-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathApplyDiffTool.ts
More file actions
303 lines (246 loc) · 9.99 KB
/
ApplyDiffTool.ts
File metadata and controls
303 lines (246 loc) · 9.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import path from "path"
import fs from "fs/promises"
import { TelemetryService } from "@roo-code/telemetry"
import { DEFAULT_WRITE_DELAY_MS } from "@roo-code/types"
import { ClineSayTool } from "../../shared/ExtensionMessage"
import { getReadablePath } from "../../utils/path"
import { Task } from "../task/Task"
import { formatResponse } from "../prompts/responses"
import { fileExistsAtPath } from "../../utils/fs"
import { RecordSource } from "../context-tracking/FileContextTrackerTypes"
import { unescapeHtmlEntities } from "../../utils/text-normalization"
import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
import { computeDiffStats, sanitizeUnifiedDiff } from "../diff/stats"
import { BaseTool, ToolCallbacks } from "./BaseTool"
import type { ToolUse } from "../../shared/tools"
interface ApplyDiffParams {
path: string
diff: string
}
export class ApplyDiffTool extends BaseTool<"apply_diff"> {
readonly name = "apply_diff" as const
parseLegacy(params: Partial<Record<string, string>>): ApplyDiffParams {
return {
path: params.path || "",
diff: params.diff || "",
}
}
async execute(params: ApplyDiffParams, task: Task, callbacks: ToolCallbacks): Promise<void> {
const { askApproval, handleError, pushToolResult, toolProtocol } = callbacks
let { path: relPath, diff: diffContent } = params
if (diffContent && !task.api.getModel().id.includes("claude")) {
diffContent = unescapeHtmlEntities(diffContent)
}
try {
if (!relPath) {
task.consecutiveMistakeCount++
task.recordToolError("apply_diff")
pushToolResult(await task.sayAndCreateMissingParamError("apply_diff", "path"))
return
}
if (!diffContent) {
task.consecutiveMistakeCount++
task.recordToolError("apply_diff")
pushToolResult(await task.sayAndCreateMissingParamError("apply_diff", "diff"))
return
}
const accessAllowed = task.rooIgnoreController?.validateAccess(relPath)
if (!accessAllowed) {
await task.say("rooignore_error", relPath)
pushToolResult(formatResponse.rooIgnoreError(relPath, toolProtocol))
return
}
const absolutePath = path.resolve(task.cwd, relPath)
const fileExists = await fileExistsAtPath(absolutePath)
if (!fileExists) {
task.consecutiveMistakeCount++
task.recordToolError("apply_diff")
const formattedError = `File does not exist at path: ${absolutePath}\n\n<error_details>\nThe specified file could not be found. Please verify the file path and try again.\n</error_details>`
await task.say("error", formattedError)
task.didToolFailInCurrentTurn = true
pushToolResult(formattedError)
return
}
const originalContent: string = await fs.readFile(absolutePath, "utf-8")
// Apply the diff to the original content
const diffResult = (await task.diffStrategy?.applyDiff(
originalContent,
diffContent,
parseInt(params.diff.match(/:start_line:(\d+)/)?.[1] ?? ""),
)) ?? {
success: false,
error: "No diff strategy available",
}
if (!diffResult.success) {
task.consecutiveMistakeCount++
const currentCount = (task.consecutiveMistakeCountForApplyDiff.get(relPath) || 0) + 1
task.consecutiveMistakeCountForApplyDiff.set(relPath, currentCount)
let formattedError = ""
TelemetryService.instance.captureDiffApplicationError(task.taskId, currentCount)
if (diffResult.failParts && diffResult.failParts.length > 0) {
for (const failPart of diffResult.failParts) {
if (failPart.success) {
continue
}
const errorDetails = failPart.details ? JSON.stringify(failPart.details, null, 2) : ""
formattedError = `<error_details>\n${
failPart.error
}${errorDetails ? `\n\nDetails:\n${errorDetails}` : ""}\n</error_details>`
}
} else {
const errorDetails = diffResult.details ? JSON.stringify(diffResult.details, null, 2) : ""
formattedError = `Unable to apply diff to file: ${absolutePath}\n\n<error_details>\n${
diffResult.error
}${errorDetails ? `\n\nDetails:\n${errorDetails}` : ""}\n</error_details>`
}
if (currentCount >= 2) {
await task.say("diff_error", formattedError)
}
task.recordToolError("apply_diff", formattedError)
pushToolResult(formattedError)
return
}
task.consecutiveMistakeCount = 0
task.consecutiveMistakeCountForApplyDiff.delete(relPath)
// Generate backend-unified diff for display in chat/webview
const unifiedPatchRaw = formatResponse.createPrettyPatch(relPath, originalContent, diffResult.content)
const unifiedPatch = sanitizeUnifiedDiff(unifiedPatchRaw)
const diffStats = computeDiffStats(unifiedPatch) || undefined
// Check if preventFocusDisruption experiment is enabled
const provider = task.providerRef.deref()
const state = await provider?.getState()
const diagnosticsEnabled = state?.diagnosticsEnabled ?? true
const writeDelayMs = state?.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS
const isPreventFocusDisruptionEnabled = experiments.isEnabled(
state?.experiments ?? {},
EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION,
)
// Check if file is write-protected
const isWriteProtected = task.rooProtectedController?.isWriteProtected(relPath) || false
const sharedMessageProps: ClineSayTool = {
tool: "appliedDiff",
path: getReadablePath(task.cwd, relPath),
diff: diffContent,
}
if (isPreventFocusDisruptionEnabled) {
// Show progress indicator in UI while preparing the file
const partialMessage = JSON.stringify(sharedMessageProps)
await task.ask("tool", partialMessage, true).catch(() => {})
// Direct file write without diff view
const completeMessage = JSON.stringify({
...sharedMessageProps,
diff: diffContent,
content: unifiedPatch,
diffStats,
isProtected: isWriteProtected,
} satisfies ClineSayTool)
let toolProgressStatus
if (task.diffStrategy && task.diffStrategy.getProgressStatus) {
const block: ToolUse<"apply_diff"> = {
type: "tool_use",
name: "apply_diff",
params: { path: relPath, diff: diffContent },
partial: false,
}
toolProgressStatus = task.diffStrategy.getProgressStatus(block, diffResult)
}
const didApprove = await askApproval("tool", completeMessage, toolProgressStatus, isWriteProtected)
if (!didApprove) {
return
}
// Save directly without showing diff view or opening the file
task.diffViewProvider.editType = "modify"
task.diffViewProvider.originalContent = originalContent
await task.diffViewProvider.saveDirectly(
relPath,
diffResult.content,
false,
diagnosticsEnabled,
writeDelayMs,
)
} else {
// Original behavior with diff view
// Show diff view before asking for approval
task.diffViewProvider.editType = "modify"
await task.diffViewProvider.open(relPath)
await task.diffViewProvider.update(diffResult.content, true)
task.diffViewProvider.scrollToFirstDiff()
const completeMessage = JSON.stringify({
...sharedMessageProps,
diff: diffContent,
content: unifiedPatch,
diffStats,
isProtected: isWriteProtected,
} satisfies ClineSayTool)
let toolProgressStatus
if (task.diffStrategy && task.diffStrategy.getProgressStatus) {
const block: ToolUse<"apply_diff"> = {
type: "tool_use",
name: "apply_diff",
params: { path: relPath, diff: diffContent },
partial: false,
}
toolProgressStatus = task.diffStrategy.getProgressStatus(block, diffResult)
}
const didApprove = await askApproval("tool", completeMessage, toolProgressStatus, isWriteProtected)
if (!didApprove) {
await task.diffViewProvider.revertChanges()
task.processQueuedMessages()
return
}
// Call saveChanges to update the DiffViewProvider properties
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
}
// Track file edit operation
if (relPath) {
await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
}
// Used to determine if we should wait for busy terminal to update before sending api request
task.didEditFile = true
let partFailHint = ""
if (diffResult.failParts && diffResult.failParts.length > 0) {
partFailHint = `But unable to apply all diff parts to file: ${absolutePath}, silently use <read_file> tool to check newest file version and re-apply diffs\n`
}
// Get the formatted response message
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, !fileExists)
// Check for single SEARCH/REPLACE block warning
const searchBlocks = (diffContent.match(/<<<<<<< SEARCH/g) || []).length
const singleBlockNotice =
searchBlocks === 1
? "\n<notice>Making multiple related changes in a single apply_diff is more efficient. If other changes are needed in this file, please include them as additional SEARCH/REPLACE blocks.</notice>"
: ""
if (partFailHint) {
pushToolResult(partFailHint + message + singleBlockNotice)
} else {
pushToolResult(message + singleBlockNotice)
}
await task.diffViewProvider.reset()
// Process any queued messages after file edit completes
task.processQueuedMessages()
return
} catch (error) {
await handleError("applying diff", error as Error)
await task.diffViewProvider.reset()
task.processQueuedMessages()
return
}
}
override async handlePartial(task: Task, block: ToolUse<"apply_diff">): Promise<void> {
const relPath: string | undefined = block.params.path
const diffContent: string | undefined = block.params.diff
const sharedMessageProps: ClineSayTool = {
tool: "appliedDiff",
path: getReadablePath(task.cwd, relPath || ""),
diff: diffContent,
}
let toolProgressStatus
if (task.diffStrategy && task.diffStrategy.getProgressStatus) {
toolProgressStatus = task.diffStrategy.getProgressStatus(block)
}
if (toolProgressStatus && Object.keys(toolProgressStatus).length === 0) {
return
}
await task.ask("tool", JSON.stringify(sharedMessageProps), block.partial, toolProgressStatus).catch(() => {})
}
}
export const applyDiffTool = new ApplyDiffTool()