Skip to content

Commit 5d9d36c

Browse files
mrubensJoziGila
andauthored
Checkbox to experiment with letting Cline edit through diffs (#48)
Co-authored-by: Jozi <[email protected]>
1 parent dafe286 commit 5d9d36c

File tree

15 files changed

+174
-14
lines changed

15 files changed

+174
-14
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Roo Cline Changelog
22

3+
## [2.1.12]
4+
5+
- Incorporate JoziGila's [PR](https://github.com/cline/cline/pull/158) to add support for editing through diffs
6+
37
## [2.1.11]
48

59
- Incorporate lloydchang's [PR](https://github.com/RooVetGit/Roo-Cline/pull/42) to add support for OpenRouter compression

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"displayName": "Roo Cline",
44
"description": "A fork of Cline, an autonomous coding agent, with some added experimental configuration and automation features.",
55
"publisher": "RooVeterinaryInc",
6-
"version": "2.1.11",
6+
"version": "2.1.12",
77
"icon": "assets/icons/rocket.png",
88
"galleryBanner": {
99
"color": "#617A91",

src/core/Cline.ts

Lines changed: 96 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Anthropic } from "@anthropic-ai/sdk"
2+
import * as diff from "diff"
23
import cloneDeep from "clone-deep"
34
import delay from "delay"
45
import fs from "fs/promises"
@@ -64,6 +65,7 @@ export class Cline {
6465
private browserSession: BrowserSession
6566
private didEditFile: boolean = false
6667
customInstructions?: string
68+
diffEnabled?: boolean
6769

6870
apiConversationHistory: Anthropic.MessageParam[] = []
6971
clineMessages: ClineMessage[] = []
@@ -93,6 +95,7 @@ export class Cline {
9395
provider: ClineProvider,
9496
apiConfiguration: ApiConfiguration,
9597
customInstructions?: string,
98+
diffEnabled?: boolean,
9699
task?: string,
97100
images?: string[],
98101
historyItem?: HistoryItem,
@@ -104,7 +107,7 @@ export class Cline {
104107
this.browserSession = new BrowserSession(provider.context)
105108
this.diffViewProvider = new DiffViewProvider(cwd)
106109
this.customInstructions = customInstructions
107-
110+
this.diffEnabled = diffEnabled
108111
if (historyItem) {
109112
this.taskId = historyItem.id
110113
this.resumeTaskFromHistory()
@@ -749,7 +752,7 @@ export class Cline {
749752
}
750753

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

754757
// 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
755758
if (previousApiReqIndex >= 0) {
@@ -876,6 +879,8 @@ export class Cline {
876879
return `[${block.name} for '${block.params.path}']`
877880
case "write_to_file":
878881
return `[${block.name} for '${block.params.path}']`
882+
case "apply_diff":
883+
return `[${block.name} for '${block.params.path}']`
879884
case "search_files":
880885
return `[${block.name} for '${block.params.regex}'${
881886
block.params.file_pattern ? ` in '${block.params.file_pattern}'` : ""
@@ -1150,6 +1155,95 @@ export class Cline {
11501155
break
11511156
}
11521157
}
1158+
case "apply_diff": {
1159+
const relPath: string | undefined = block.params.path
1160+
const diffContent: string | undefined = block.params.diff
1161+
1162+
const sharedMessageProps: ClineSayTool = {
1163+
tool: "appliedDiff",
1164+
path: getReadablePath(cwd, removeClosingTag("path", relPath)),
1165+
}
1166+
1167+
try {
1168+
if (block.partial) {
1169+
// update gui message
1170+
const partialMessage = JSON.stringify(sharedMessageProps)
1171+
await this.ask("tool", partialMessage, block.partial).catch(() => {})
1172+
break
1173+
} else {
1174+
if (!relPath) {
1175+
this.consecutiveMistakeCount++
1176+
pushToolResult(await this.sayAndCreateMissingParamError("apply_diff", "path"))
1177+
break
1178+
}
1179+
if (!diffContent) {
1180+
this.consecutiveMistakeCount++
1181+
pushToolResult(await this.sayAndCreateMissingParamError("apply_diff", "diff"))
1182+
break
1183+
}
1184+
this.consecutiveMistakeCount = 0
1185+
1186+
const absolutePath = path.resolve(cwd, relPath)
1187+
const fileExists = await fileExistsAtPath(absolutePath)
1188+
1189+
if (!fileExists) {
1190+
await this.say("error", `File does not exist at path: ${absolutePath}`)
1191+
pushToolResult(`Error: File does not exist at path: ${absolutePath}`)
1192+
break
1193+
}
1194+
1195+
const originalContent = await fs.readFile(absolutePath, "utf-8")
1196+
1197+
// Apply the diff to the original content
1198+
let newContent = diff.applyPatch(originalContent, diffContent) as string | false
1199+
if (newContent === false) {
1200+
await this.say("error", `Error applying diff to file: ${absolutePath}`)
1201+
pushToolResult(`Error applying diff to file: ${absolutePath}`)
1202+
break
1203+
}
1204+
1205+
// Create a diff for display purposes
1206+
const diffRepresentation = diff
1207+
.diffLines(originalContent, newContent)
1208+
.map((part) => {
1209+
const prefix = part.added ? "+" : part.removed ? "-" : " "
1210+
return (part.value || "")
1211+
.split("\n")
1212+
.map((line) => (line ? prefix + line : ""))
1213+
.join("\n")
1214+
})
1215+
.join("")
1216+
1217+
// Show diff view before asking for approval
1218+
this.diffViewProvider.editType = "modify"
1219+
await this.diffViewProvider.open(relPath);
1220+
await this.diffViewProvider.update(newContent, true);
1221+
await this.diffViewProvider.scrollToFirstDiff();
1222+
1223+
const completeMessage = JSON.stringify({
1224+
...sharedMessageProps,
1225+
diff: diffRepresentation,
1226+
} satisfies ClineSayTool)
1227+
1228+
const didApprove = await askApproval("tool", completeMessage)
1229+
if (!didApprove) {
1230+
await this.diffViewProvider.revertChanges() // This likely handles closing the diff view
1231+
break
1232+
}
1233+
1234+
await fs.writeFile(absolutePath, newContent)
1235+
await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), { preview: false })
1236+
await this.diffViewProvider.reset()
1237+
1238+
pushToolResult(`Changes successfully applied to ${relPath.toPosix()}:\n\n${diffRepresentation}`)
1239+
break
1240+
}
1241+
} catch (error) {
1242+
await handleError("applying diff", error)
1243+
await this.diffViewProvider.reset()
1244+
break
1245+
}
1246+
}
11531247
case "read_file": {
11541248
const relPath: string | undefined = block.params.path
11551249
const sharedMessageProps: ClineSayTool = {

src/core/__tests__/Cline.test.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ describe('Cline', () => {
236236
mockProvider,
237237
mockApiConfig,
238238
'custom instructions',
239+
false,
239240
'test task'
240241
);
241242

src/core/assistant-message/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ export const toolUseNames = [
1212
"execute_command",
1313
"read_file",
1414
"write_to_file",
15+
"apply_diff",
1516
"search_files",
1617
"list_files",
1718
"list_code_definition_names",
@@ -36,6 +37,7 @@ export const toolParamNames = [
3637
"text",
3738
"question",
3839
"result",
40+
"diff",
3941
] as const
4042

4143
export type ToolParamName = (typeof toolParamNames)[number]

src/core/prompts/system.ts

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import path from 'path'
77
export const SYSTEM_PROMPT = async (
88
cwd: string,
99
supportsComputerUse: boolean,
10+
diffEnabled: boolean
1011
) => `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
1112
1213
====
@@ -54,7 +55,7 @@ Usage:
5455
</read_file>
5556
5657
## write_to_file
57-
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.
58+
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.
5859
Parameters:
5960
- path: (required) The path of the file to write to (relative to the current working directory ${cwd.toPosix()})
6061
- 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.
@@ -66,6 +67,22 @@ Your file content here
6667
</content>
6768
</write_to_file>
6869
70+
${diffEnabled ? `
71+
## apply_diff
72+
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.
73+
Parameters:
74+
- path: (required) The path of the file to apply the diff to (relative to the current working directory ${cwd.toPosix()})
75+
- diff: (required) The diff in unified format (diff -u) to apply to the file.
76+
Usage:
77+
<apply_diff>
78+
<path>File path here</path>
79+
<diff>
80+
Your diff here
81+
</diff>
82+
</apply_diff>`
83+
: ""
84+
}
85+
6986
## search_files
7087
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.
7188
Parameters:
@@ -221,7 +238,7 @@ CAPABILITIES
221238
- 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.
222239
- 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.
223240
- 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.
224-
- 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.
241+
- 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.
225242
- 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.${
226243
supportsComputerUse
227244
? "\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."
@@ -238,6 +255,7 @@ RULES
238255
- 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)\`.
239256
- 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.
240257
- 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.
258+
${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." : ""}
241259
- 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.
242260
- 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.
243261
- 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.

src/core/webview/ClineProvider.ts

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ type GlobalStateKey =
6464
| "openRouterUseMiddleOutTransform"
6565
| "allowedCommands"
6666
| "soundEnabled"
67+
| "diffEnabled"
6768

6869
export const GlobalFileNames = {
6970
apiConversationHistory: "api_conversation_history.json",
@@ -201,12 +202,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
201202
const {
202203
apiConfiguration,
203204
customInstructions,
205+
diffEnabled,
204206
} = await this.getState()
205207

206208
this.cline = new Cline(
207209
this,
208210
apiConfiguration,
209211
customInstructions,
212+
diffEnabled,
210213
task,
211214
images
212215
)
@@ -217,12 +220,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
217220
const {
218221
apiConfiguration,
219222
customInstructions,
223+
diffEnabled,
220224
} = await this.getState()
221225

222226
this.cline = new Cline(
223227
this,
224228
apiConfiguration,
225229
customInstructions,
230+
diffEnabled,
226231
undefined,
227232
undefined,
228233
historyItem,
@@ -532,9 +537,13 @@ export class ClineProvider implements vscode.WebviewViewProvider {
532537
}
533538
break
534539
case "soundEnabled":
535-
const enabled = message.bool ?? true
536-
await this.updateGlobalState("soundEnabled", enabled)
537-
setSoundEnabled(enabled)
540+
const soundEnabled = message.bool ?? true
541+
await this.updateGlobalState("soundEnabled", soundEnabled)
542+
await this.postStateToWebview()
543+
break
544+
case "diffEnabled":
545+
const diffEnabled = message.bool ?? true
546+
await this.updateGlobalState("diffEnabled", diffEnabled)
538547
await this.postStateToWebview()
539548
break
540549
}
@@ -843,6 +852,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
843852
alwaysAllowExecute,
844853
alwaysAllowBrowser,
845854
soundEnabled,
855+
diffEnabled,
846856
taskHistory,
847857
} = await this.getState()
848858

@@ -863,7 +873,8 @@ export class ClineProvider implements vscode.WebviewViewProvider {
863873
taskHistory: (taskHistory || [])
864874
.filter((item) => item.ts && item.task)
865875
.sort((a, b) => b.ts - a.ts),
866-
soundEnabled: soundEnabled ?? true,
876+
soundEnabled: soundEnabled ?? false,
877+
diffEnabled: diffEnabled ?? false,
867878
shouldShowAnnouncement: lastShownAnnouncementId !== this.latestAnnouncementId,
868879
allowedCommands,
869880
}
@@ -956,6 +967,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
956967
taskHistory,
957968
allowedCommands,
958969
soundEnabled,
970+
diffEnabled,
959971
] = await Promise.all([
960972
this.getGlobalState("apiProvider") as Promise<ApiProvider | undefined>,
961973
this.getGlobalState("apiModelId") as Promise<string | undefined>,
@@ -991,6 +1003,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
9911003
this.getGlobalState("taskHistory") as Promise<HistoryItem[] | undefined>,
9921004
this.getGlobalState("allowedCommands") as Promise<string[] | undefined>,
9931005
this.getGlobalState("soundEnabled") as Promise<boolean | undefined>,
1006+
this.getGlobalState("diffEnabled") as Promise<boolean | undefined>,
9941007
])
9951008

9961009
let apiProvider: ApiProvider
@@ -1044,6 +1057,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
10441057
taskHistory,
10451058
allowedCommands,
10461059
soundEnabled,
1060+
diffEnabled,
10471061
}
10481062
}
10491063

0 commit comments

Comments
 (0)