Skip to content

Commit

Permalink
Checkbox to experiment with letting Cline edit through diffs (#48)
Browse files Browse the repository at this point in the history
Co-authored-by: Jozi <[email protected]>
  • Loading branch information
mrubens and JoziGila authored Dec 7, 2024
1 parent dafe286 commit 5d9d36c
Show file tree
Hide file tree
Showing 15 changed files with 174 additions and 14 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Roo Cline Changelog

## [2.1.12]

- Incorporate JoziGila's [PR](https://github.com/cline/cline/pull/158) to add support for editing through diffs

## [2.1.11]

- Incorporate lloydchang's [PR](https://github.com/RooVetGit/Roo-Cline/pull/42) to add support for OpenRouter compression
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"displayName": "Roo Cline",
"description": "A fork of Cline, an autonomous coding agent, with some added experimental configuration and automation features.",
"publisher": "RooVeterinaryInc",
"version": "2.1.11",
"version": "2.1.12",
"icon": "assets/icons/rocket.png",
"galleryBanner": {
"color": "#617A91",
Expand Down
98 changes: 96 additions & 2 deletions src/core/Cline.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Anthropic } from "@anthropic-ai/sdk"
import * as diff from "diff"
import cloneDeep from "clone-deep"
import delay from "delay"
import fs from "fs/promises"
Expand Down Expand Up @@ -64,6 +65,7 @@ export class Cline {
private browserSession: BrowserSession
private didEditFile: boolean = false
customInstructions?: string
diffEnabled?: boolean

apiConversationHistory: Anthropic.MessageParam[] = []
clineMessages: ClineMessage[] = []
Expand Down Expand Up @@ -93,6 +95,7 @@ export class Cline {
provider: ClineProvider,
apiConfiguration: ApiConfiguration,
customInstructions?: string,
diffEnabled?: boolean,
task?: string,
images?: string[],
historyItem?: HistoryItem,
Expand All @@ -104,7 +107,7 @@ export class Cline {
this.browserSession = new BrowserSession(provider.context)
this.diffViewProvider = new DiffViewProvider(cwd)
this.customInstructions = customInstructions

this.diffEnabled = diffEnabled
if (historyItem) {
this.taskId = historyItem.id
this.resumeTaskFromHistory()
Expand Down Expand Up @@ -749,7 +752,7 @@ export class Cline {
}

async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
const systemPrompt = await SYSTEM_PROMPT(cwd, this.api.getModel().info.supportsComputerUse ?? false) + await addCustomInstructions(this.customInstructions ?? '', cwd)
const systemPrompt = await SYSTEM_PROMPT(cwd, this.api.getModel().info.supportsComputerUse ?? false, !!this.diffEnabled) + await addCustomInstructions(this.customInstructions ?? '', cwd)

// If the previous API request's total token usage is close to the context window, truncate the conversation history to free up space for the new request
if (previousApiReqIndex >= 0) {
Expand Down Expand Up @@ -876,6 +879,8 @@ export class Cline {
return `[${block.name} for '${block.params.path}']`
case "write_to_file":
return `[${block.name} for '${block.params.path}']`
case "apply_diff":
return `[${block.name} for '${block.params.path}']`
case "search_files":
return `[${block.name} for '${block.params.regex}'${
block.params.file_pattern ? ` in '${block.params.file_pattern}'` : ""
Expand Down Expand Up @@ -1150,6 +1155,95 @@ export class Cline {
break
}
}
case "apply_diff": {
const relPath: string | undefined = block.params.path
const diffContent: string | undefined = block.params.diff

const sharedMessageProps: ClineSayTool = {
tool: "appliedDiff",
path: getReadablePath(cwd, removeClosingTag("path", relPath)),
}

try {
if (block.partial) {
// update gui message
const partialMessage = JSON.stringify(sharedMessageProps)
await this.ask("tool", partialMessage, block.partial).catch(() => {})
break
} else {
if (!relPath) {
this.consecutiveMistakeCount++
pushToolResult(await this.sayAndCreateMissingParamError("apply_diff", "path"))
break
}
if (!diffContent) {
this.consecutiveMistakeCount++
pushToolResult(await this.sayAndCreateMissingParamError("apply_diff", "diff"))
break
}
this.consecutiveMistakeCount = 0

const absolutePath = path.resolve(cwd, relPath)
const fileExists = await fileExistsAtPath(absolutePath)

if (!fileExists) {
await this.say("error", `File does not exist at path: ${absolutePath}`)
pushToolResult(`Error: File does not exist at path: ${absolutePath}`)
break
}

const originalContent = await fs.readFile(absolutePath, "utf-8")

// Apply the diff to the original content
let newContent = diff.applyPatch(originalContent, diffContent) as string | false
if (newContent === false) {
await this.say("error", `Error applying diff to file: ${absolutePath}`)
pushToolResult(`Error applying diff to file: ${absolutePath}`)
break
}

// Create a diff for display purposes
const diffRepresentation = diff
.diffLines(originalContent, newContent)
.map((part) => {
const prefix = part.added ? "+" : part.removed ? "-" : " "
return (part.value || "")
.split("\n")
.map((line) => (line ? prefix + line : ""))
.join("\n")
})
.join("")

// Show diff view before asking for approval
this.diffViewProvider.editType = "modify"
await this.diffViewProvider.open(relPath);
await this.diffViewProvider.update(newContent, true);
await this.diffViewProvider.scrollToFirstDiff();

const completeMessage = JSON.stringify({
...sharedMessageProps,
diff: diffRepresentation,
} satisfies ClineSayTool)

const didApprove = await askApproval("tool", completeMessage)
if (!didApprove) {
await this.diffViewProvider.revertChanges() // This likely handles closing the diff view
break
}

await fs.writeFile(absolutePath, newContent)
await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), { preview: false })
await this.diffViewProvider.reset()

pushToolResult(`Changes successfully applied to ${relPath.toPosix()}:\n\n${diffRepresentation}`)
break
}
} catch (error) {
await handleError("applying diff", error)
await this.diffViewProvider.reset()
break
}
}
case "read_file": {
const relPath: string | undefined = block.params.path
const sharedMessageProps: ClineSayTool = {
Expand Down
1 change: 1 addition & 0 deletions src/core/__tests__/Cline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ describe('Cline', () => {
mockProvider,
mockApiConfig,
'custom instructions',
false,
'test task'
);

Expand Down
2 changes: 2 additions & 0 deletions src/core/assistant-message/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const toolUseNames = [
"execute_command",
"read_file",
"write_to_file",
"apply_diff",
"search_files",
"list_files",
"list_code_definition_names",
Expand All @@ -36,6 +37,7 @@ export const toolParamNames = [
"text",
"question",
"result",
"diff",
] as const

export type ToolParamName = (typeof toolParamNames)[number]
Expand Down
22 changes: 20 additions & 2 deletions src/core/prompts/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import path from 'path'
export const SYSTEM_PROMPT = async (
cwd: string,
supportsComputerUse: boolean,
diffEnabled: boolean
) => `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
====
Expand Down Expand Up @@ -54,7 +55,7 @@ Usage:
</read_file>
## write_to_file
Description: Request to write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
Description: Request to write full content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
Parameters:
- path: (required) The path of the file to write to (relative to the current working directory ${cwd.toPosix()})
- content: (required) The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified.
Expand All @@ -66,6 +67,22 @@ Your file content here
</content>
</write_to_file>
${diffEnabled ? `
## apply_diff
Description: Apply a diff to a file at the specified path. The diff should be in unified format (diff -u) and can be used to apply changes to a file. This tool is useful when you need to make specific modifications to a file based on a set of changes provided in a diff.
Parameters:
- path: (required) The path of the file to apply the diff to (relative to the current working directory ${cwd.toPosix()})
- diff: (required) The diff in unified format (diff -u) to apply to the file.
Usage:
<apply_diff>
<path>File path here</path>
<diff>
Your diff here
</diff>
</apply_diff>`
: ""
}
## search_files
Description: Request to perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.
Parameters:
Expand Down Expand Up @@ -221,7 +238,7 @@ CAPABILITIES
- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('${cwd.toPosix()}') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
- You can use search_files to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
- You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
- For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the write_to_file tool to implement changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
- For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the write_to_file ${diffEnabled ? "or apply_diff " : ""}tool to apply the changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
- You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.${
supportsComputerUse
? "\n- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.\n - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser."
Expand All @@ -238,6 +255,7 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '${cwd.toPosix()}', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '${cwd.toPosix()}'). For example, if you needed to run \`npm install\` in a project outside of '${cwd.toPosix()}', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
${diffEnabled ? "- Prefer to use apply_diff over write_to_file when making changes to existing files, particularly when editing files more than 200 lines of code, as it allows you to apply specific modifications based on a set of changes provided in a diff. This is particularly useful when you need to make targeted edits or updates to a file without overwriting the entire content." : ""}
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool.
Expand Down
22 changes: 18 additions & 4 deletions src/core/webview/ClineProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ type GlobalStateKey =
| "openRouterUseMiddleOutTransform"
| "allowedCommands"
| "soundEnabled"
| "diffEnabled"

export const GlobalFileNames = {
apiConversationHistory: "api_conversation_history.json",
Expand Down Expand Up @@ -201,12 +202,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
const {
apiConfiguration,
customInstructions,
diffEnabled,
} = await this.getState()

this.cline = new Cline(
this,
apiConfiguration,
customInstructions,
diffEnabled,
task,
images
)
Expand All @@ -217,12 +220,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
const {
apiConfiguration,
customInstructions,
diffEnabled,
} = await this.getState()

this.cline = new Cline(
this,
apiConfiguration,
customInstructions,
diffEnabled,
undefined,
undefined,
historyItem,
Expand Down Expand Up @@ -532,9 +537,13 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
break
case "soundEnabled":
const enabled = message.bool ?? true
await this.updateGlobalState("soundEnabled", enabled)
setSoundEnabled(enabled)
const soundEnabled = message.bool ?? true
await this.updateGlobalState("soundEnabled", soundEnabled)
await this.postStateToWebview()
break
case "diffEnabled":
const diffEnabled = message.bool ?? true
await this.updateGlobalState("diffEnabled", diffEnabled)
await this.postStateToWebview()
break
}
Expand Down Expand Up @@ -843,6 +852,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
alwaysAllowExecute,
alwaysAllowBrowser,
soundEnabled,
diffEnabled,
taskHistory,
} = await this.getState()

Expand All @@ -863,7 +873,8 @@ export class ClineProvider implements vscode.WebviewViewProvider {
taskHistory: (taskHistory || [])
.filter((item) => item.ts && item.task)
.sort((a, b) => b.ts - a.ts),
soundEnabled: soundEnabled ?? true,
soundEnabled: soundEnabled ?? false,
diffEnabled: diffEnabled ?? false,
shouldShowAnnouncement: lastShownAnnouncementId !== this.latestAnnouncementId,
allowedCommands,
}
Expand Down Expand Up @@ -956,6 +967,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
taskHistory,
allowedCommands,
soundEnabled,
diffEnabled,
] = await Promise.all([
this.getGlobalState("apiProvider") as Promise<ApiProvider | undefined>,
this.getGlobalState("apiModelId") as Promise<string | undefined>,
Expand Down Expand Up @@ -991,6 +1003,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getGlobalState("taskHistory") as Promise<HistoryItem[] | undefined>,
this.getGlobalState("allowedCommands") as Promise<string[] | undefined>,
this.getGlobalState("soundEnabled") as Promise<boolean | undefined>,
this.getGlobalState("diffEnabled") as Promise<boolean | undefined>,
])

let apiProvider: ApiProvider
Expand Down Expand Up @@ -1044,6 +1057,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
taskHistory,
allowedCommands,
soundEnabled,
diffEnabled,
}
}

Expand Down
Loading

0 comments on commit 5d9d36c

Please sign in to comment.