-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathWriteToFileTool.ts
More file actions
363 lines (299 loc) · 13 KB
/
Copy pathWriteToFileTool.ts
File metadata and controls
363 lines (299 loc) · 13 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import path from "path"
import delay from "delay"
import fs from "fs/promises"
import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS, RooCodeEventName } from "@roo-code/types"
import { Task } from "../task/Task"
import { formatResponse } from "../prompts/responses"
import { RecordSource } from "../context-tracking/FileContextTrackerTypes"
import { fileExistsAtPath, createDirectoriesForFile } from "../../utils/fs"
import { stripLineNumbers, everyLineHasLineNumbers } from "../../integrations/misc/extract-text"
import { getReadablePath } from "../../utils/path"
import { isPathOutsideWorkspace } from "../../utils/pathUtils"
import { unescapeHtmlEntities } from "../../utils/text-normalization"
import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
import { convertNewFileToUnifiedDiff, computeDiffStats, sanitizeUnifiedDiff } from "../diff/stats"
import type { ToolUse } from "../../shared/tools"
import { BaseTool, ToolCallbacks } from "./BaseTool"
interface WriteToFileParams {
path: string
content: string
}
export class WriteToFileTool extends BaseTool<"write_to_file"> {
readonly name = "write_to_file" as const
/**
* Tracks filesystem failures from diff-view streaming by task id. Tool instances are
* singletons, so this state must be keyed per task to avoid one task's failing partial
* stream suppressing another task's streaming deltas.
*/
private partialStreamFailuresByTaskId = new Set<string>()
/**
* Tracks partial path stabilization by task id. The tool is a singleton, so using the
* BaseTool singleton path state lets concurrent tasks incorrectly stabilize each other.
*/
private lastSeenPartialPathByTaskId = new Map<string, string | undefined>()
/**
* Tracks abort cleanup listeners for per-task partial state so normal execute()
* finalization can unregister them and abandoned streams are torn down on abort.
*/
private partialStateAbortCleanupByTaskId = new Map<string, { task: Task; cleanup: () => void }>()
private getPartialStreamFailureKey(task: Task): string {
return `${task.taskId}.${task.instanceId}`
}
private registerTaskPartialStateCleanup(task: Task): void {
const key = this.getPartialStreamFailureKey(task)
if (this.partialStateAbortCleanupByTaskId.has(key)) {
return
}
const cleanup = () => this.resetTaskPartialState(task)
this.partialStateAbortCleanupByTaskId.set(key, { task, cleanup })
task.once(RooCodeEventName.TaskAborted, cleanup)
}
private hasPathStabilizedForTask(task: Task, partialPath: string | undefined): boolean {
this.registerTaskPartialStateCleanup(task)
const key = this.getPartialStreamFailureKey(task)
const lastSeenPath = this.lastSeenPartialPathByTaskId.get(key)
const pathHasStabilized = lastSeenPath !== undefined && lastSeenPath === partialPath
this.lastSeenPartialPathByTaskId.set(key, partialPath)
return pathHasStabilized && !!partialPath
}
private resetTaskPartialState(task: Task): void {
const key = this.getPartialStreamFailureKey(task)
const abortCleanup = this.partialStateAbortCleanupByTaskId.get(key)
if (abortCleanup) {
task.off(RooCodeEventName.TaskAborted, abortCleanup.cleanup)
this.partialStateAbortCleanupByTaskId.delete(key)
}
this.lastSeenPartialPathByTaskId.delete(key)
this.partialStreamFailuresByTaskId.delete(key)
}
private async resetDiffViewAfterWrite(task: Task): Promise<void> {
await task.diffViewProvider.reset().catch((resetError) => {
console.error("Error resetting write_to_file diff view:", resetError)
})
}
private async finalizePartialToolAskAfterFailure(task: Task, text?: string): Promise<void> {
await task.finalizePartialToolAsk(text).catch((finalizeError) => {
console.error("Error finalizing write_to_file partial tool ask:", finalizeError)
})
}
override resetPartialState(): void {
super.resetPartialState()
for (const { task, cleanup } of this.partialStateAbortCleanupByTaskId.values()) {
task.off(RooCodeEventName.TaskAborted, cleanup)
}
this.partialStreamFailuresByTaskId.clear()
this.lastSeenPartialPathByTaskId.clear()
this.partialStateAbortCleanupByTaskId.clear()
}
async execute(params: WriteToFileParams, task: Task, callbacks: ToolCallbacks): Promise<void> {
const { pushToolResult, handleError, askApproval } = callbacks
const relPath = params.path
let newContent = params.content
const partialStreamFailureKey = this.getPartialStreamFailureKey(task)
if (!relPath) {
task.consecutiveMistakeCount++
task.recordToolError("write_to_file")
pushToolResult(await task.sayAndCreateMissingParamError("write_to_file", "path"))
await task.diffViewProvider.reset()
return
}
if (newContent === undefined) {
task.consecutiveMistakeCount++
task.recordToolError("write_to_file")
pushToolResult(await task.sayAndCreateMissingParamError("write_to_file", "content"))
await task.diffViewProvider.reset()
return
}
const accessAllowed = task.rooIgnoreController?.validateAccess(relPath)
if (!accessAllowed) {
await task.say("rooignore_error", relPath)
pushToolResult(formatResponse.rooIgnoreError(relPath))
return
}
const isWriteProtected = task.rooProtectedController?.isWriteProtected(relPath) || false
let fileExists: boolean
const absolutePath = path.resolve(task.cwd, relPath)
if (task.diffViewProvider.editType !== undefined) {
fileExists = task.diffViewProvider.editType === "modify"
} else {
fileExists = await fileExistsAtPath(absolutePath)
task.diffViewProvider.editType = fileExists ? "modify" : "create"
}
if (newContent.startsWith("```")) {
newContent = newContent.split("\n").slice(1).join("\n")
}
if (newContent.endsWith("```")) {
newContent = newContent.split("\n").slice(0, -1).join("\n")
}
if (!task.api.getModel().id.includes("claude")) {
newContent = unescapeHtmlEntities(newContent)
}
const fullPath = relPath ? path.resolve(task.cwd, relPath) : ""
const isOutsideWorkspace = isPathOutsideWorkspace(fullPath)
const sharedMessageProps: ClineSayTool = {
tool: fileExists ? "editedExistingFile" : "newFileCreated",
path: getReadablePath(task.cwd, relPath),
content: newContent,
isOutsideWorkspace,
isProtected: isWriteProtected,
}
try {
// Create parent directories for new files inside the try block so filesystem
// errors (EROFS, EACCES, etc.) route through handleError with proper cleanup
// and consecutive-mistake counting, rather than escaping unhandled.
if (!fileExists) {
await createDirectoriesForFile(absolutePath)
}
task.consecutiveMistakeCount = 0
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,
)
if (isPreventFocusDisruptionEnabled) {
task.diffViewProvider.editType = fileExists ? "modify" : "create"
if (fileExists) {
const absolutePath = path.resolve(task.cwd, relPath)
task.diffViewProvider.originalContent = await fs.readFile(absolutePath, "utf-8")
} else {
task.diffViewProvider.originalContent = ""
}
let unified = fileExists
? formatResponse.createPrettyPatch(relPath, task.diffViewProvider.originalContent, newContent)
: convertNewFileToUnifiedDiff(newContent, relPath)
unified = sanitizeUnifiedDiff(unified)
const completeMessage = JSON.stringify({
...sharedMessageProps,
content: unified,
diffStats: computeDiffStats(unified) || undefined,
} satisfies ClineSayTool)
const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected)
if (!didApprove) {
return
}
await task.diffViewProvider.saveDirectly(relPath, newContent, false, diagnosticsEnabled, writeDelayMs)
} else {
if (!task.diffViewProvider.isEditing) {
const partialMessage = JSON.stringify(sharedMessageProps)
await task.ask("tool", partialMessage, true).catch(() => {})
await task.diffViewProvider.open(relPath)
}
await task.diffViewProvider.update(
everyLineHasLineNumbers(newContent) ? stripLineNumbers(newContent) : newContent,
true,
)
await delay(300)
task.diffViewProvider.scrollToFirstDiff()
let unified = fileExists
? formatResponse.createPrettyPatch(relPath, task.diffViewProvider.originalContent, newContent)
: convertNewFileToUnifiedDiff(newContent, relPath)
unified = sanitizeUnifiedDiff(unified)
const completeMessage = JSON.stringify({
...sharedMessageProps,
content: unified,
diffStats: computeDiffStats(unified) || undefined,
} satisfies ClineSayTool)
const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected)
if (!didApprove) {
await task.diffViewProvider.revertChanges()
return
}
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
}
if (relPath) {
await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
}
task.didEditFile = true
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, !fileExists)
pushToolResult(message)
await this.resetDiffViewAfterWrite(task)
task.processQueuedMessages()
return
} catch (error) {
// Finalize any open partial tool message so the UI spinner doesn't get stuck.
// The partial ask fired during streaming (handlePartial) or early in execute sets
// partial: true on the webview message; without this, the spinner persists even
// after the error bubble appears.
await this.finalizePartialToolAskAfterFailure(task)
await handleError("writing file", error as Error)
await this.resetDiffViewAfterWrite(task)
return
} finally {
this.resetTaskPartialState(task)
}
}
override async handlePartial(task: Task, block: ToolUse<"write_to_file">): Promise<void> {
const relPath: string | undefined = block.params.path
const newContent: string | undefined = block.params.content
const partialStreamFailureKey = this.getPartialStreamFailureKey(task)
// A prior streaming delta for this task already hit a fatal filesystem error.
// Skip further streaming work so we don't create a new partial tool message on every
// subsequent delta. execute() will report the error once when the block completes.
if (this.partialStreamFailuresByTaskId.has(partialStreamFailureKey)) {
return
}
// Wait for path to stabilize before showing UI (prevents truncated paths)
if (!this.hasPathStabilizedForTask(task, relPath) || newContent === undefined) {
return
}
const provider = task.providerRef.deref()
const state = await provider?.getState()
const isPreventFocusDisruptionEnabled = experiments.isEnabled(
state?.experiments ?? {},
EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION,
)
if (isPreventFocusDisruptionEnabled) {
return
}
// relPath is guaranteed non-null after hasPathStabilized
let fileExists: boolean
const absolutePath = path.resolve(task.cwd, relPath!)
if (task.diffViewProvider.editType !== undefined) {
fileExists = task.diffViewProvider.editType === "modify"
} else {
fileExists = await fileExistsAtPath(absolutePath)
task.diffViewProvider.editType = fileExists ? "modify" : "create"
}
const isWriteProtected = task.rooProtectedController?.isWriteProtected(relPath!) || false
const isOutsideWorkspace = isPathOutsideWorkspace(absolutePath)
const sharedMessageProps: ClineSayTool = {
tool: fileExists ? "editedExistingFile" : "newFileCreated",
path: getReadablePath(task.cwd, relPath!),
content: newContent || "",
isOutsideWorkspace,
isProtected: isWriteProtected,
}
const partialMessage = JSON.stringify(sharedMessageProps)
await task.ask("tool", partialMessage, block.partial).catch(() => {})
if (newContent) {
try {
if (!task.diffViewProvider.isEditing) {
await task.diffViewProvider.open(relPath!)
}
await task.diffViewProvider.update(
everyLineHasLineNumbers(newContent) ? stripLineNumbers(newContent) : newContent,
false,
)
} catch (error) {
// Opening or updating the diff view can throw on filesystem errors
// (EACCES/EROFS on read-only paths). Finalize the partial tool message
// so the UI spinner doesn't get stuck and reset the diff view. Do NOT
// rethrow: the same filesystem operation is retried in execute() once the
// block completes, and that authoritative non-partial path reports the
// error to the user. Surfacing it here too would show the same error twice.
// Swallowing it here is safe because the agent loop advances naturally when
// the non-partial block arrives (it does not depend on this throw).
console.error(`Error streaming write_to_file diff view:`, error)
// Mark the stream as failed so later deltas don't re-attempt and spawn a new
// partial tool message each time.
this.partialStreamFailuresByTaskId.add(partialStreamFailureKey)
await this.finalizePartialToolAskAfterFailure(task, partialMessage)
await this.resetDiffViewAfterWrite(task)
}
}
}
}
export const writeToFileTool = new WriteToFileTool()