Skip to content

Commit e03fdd7

Browse files
JoziGilamrubens
authored andcommitted
Allow Claude to produce diff files directly when editing
1 parent dafe286 commit e03fdd7

File tree

6 files changed

+124
-5
lines changed

6 files changed

+124
-5
lines changed

src/core/Cline.ts

Lines changed: 97 additions & 1 deletion
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"
@@ -749,7 +750,7 @@ export class Cline {
749750
}
750751

751752
async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
752-
const systemPrompt = await SYSTEM_PROMPT(cwd, this.api.getModel().info.supportsComputerUse ?? false) + await addCustomInstructions(this.customInstructions ?? '', cwd)
753+
const systemPrompt = await SYSTEM_PROMPT(cwd, this.api.getModel().info.supportsComputerUse ?? false, true) + await addCustomInstructions(this.customInstructions ?? '', cwd)
753754

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

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+
supportsDiff: 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+
${supportsDiff ? `
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 ${supportsDiff ? "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+
${supportsDiff ? "- 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/shared/ExtensionMessage.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ export type ClineSay =
8686
export interface ClineSayTool {
8787
tool:
8888
| "editedExistingFile"
89+
| "appliedDiff"
8990
| "newFileCreated"
9091
| "readFile"
9192
| "listFilesTopLevel"

webview-ui/src/components/chat/ChatRow.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,10 +213,11 @@ export const ChatRowContent = ({
213213

214214
switch (tool.tool) {
215215
case "editedExistingFile":
216+
case "appliedDiff":
216217
return (
217218
<>
218219
<div style={headerStyle}>
219-
{toolIcon("edit")}
220+
{toolIcon(tool.tool === "appliedDiff" ? "diff" : "edit")}
220221
<span style={{ fontWeight: "bold" }}>Cline wants to edit this file:</span>
221222
</div>
222223
<CodeAccordian

webview-ui/src/components/chat/ChatView.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
121121
const tool = JSON.parse(lastMessage.text || "{}") as ClineSayTool
122122
switch (tool.tool) {
123123
case "editedExistingFile":
124+
case "appliedDiff":
124125
case "newFileCreated":
125126
setPrimaryButtonText("Save")
126127
setSecondaryButtonText("Reject")
@@ -747,7 +748,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
747748
const lastMessage = messages.at(-1)
748749
if (lastMessage?.type === "ask" && lastMessage.text) {
749750
const tool = JSON.parse(lastMessage.text)
750-
return ["editedExistingFile", "newFileCreated"].includes(tool.tool)
751+
return ["editedExistingFile", "appliedDiff", "newFileCreated"].includes(tool.tool)
751752
}
752753
return false
753754
}

0 commit comments

Comments
 (0)