Skip to content

Commit be0e154

Browse files
committed
fix(write-to-file): guard partial ask finalization
1 parent 16c4d48 commit be0e154

2 files changed

Lines changed: 118 additions & 83 deletions

File tree

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 77 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
6363
})
6464
}
6565

66+
private async finalizePartialToolAskAfterFailure(task: Task, text?: string): Promise<void> {
67+
await task.finalizePartialToolAsk(text).catch((finalizeError) => {
68+
console.error("Error finalizing write_to_file partial tool ask:", finalizeError)
69+
})
70+
}
71+
6672
override resetPartialState(): void {
6773
super.resetPartialState()
6874
this.partialStreamFailuresByTaskId.clear()
@@ -153,105 +159,93 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
153159
EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION,
154160
)
155161

156-
try {
157-
if (isPreventFocusDisruptionEnabled) {
158-
task.diffViewProvider.editType = fileExists ? "modify" : "create"
159-
if (fileExists) {
160-
const absolutePath = path.resolve(task.cwd, relPath)
161-
task.diffViewProvider.originalContent = await fs.readFile(absolutePath, "utf-8")
162-
} else {
163-
task.diffViewProvider.originalContent = ""
164-
}
165-
166-
let unified = fileExists
167-
? formatResponse.createPrettyPatch(relPath, task.diffViewProvider.originalContent, newContent)
168-
: convertNewFileToUnifiedDiff(newContent, relPath)
169-
unified = sanitizeUnifiedDiff(unified)
170-
const completeMessage = JSON.stringify({
171-
...sharedMessageProps,
172-
content: unified,
173-
diffStats: computeDiffStats(unified) || undefined,
174-
} satisfies ClineSayTool)
175-
176-
const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected)
177-
178-
if (!didApprove) {
179-
return
180-
}
181-
182-
await task.diffViewProvider.saveDirectly(
183-
relPath,
184-
newContent,
185-
false,
186-
diagnosticsEnabled,
187-
writeDelayMs,
188-
)
162+
if (isPreventFocusDisruptionEnabled) {
163+
task.diffViewProvider.editType = fileExists ? "modify" : "create"
164+
if (fileExists) {
165+
const absolutePath = path.resolve(task.cwd, relPath)
166+
task.diffViewProvider.originalContent = await fs.readFile(absolutePath, "utf-8")
189167
} else {
190-
if (!task.diffViewProvider.isEditing) {
191-
const partialMessage = JSON.stringify(sharedMessageProps)
192-
await task.ask("tool", partialMessage, true).catch(() => {})
193-
await task.diffViewProvider.open(relPath)
194-
}
195-
196-
await task.diffViewProvider.update(
197-
everyLineHasLineNumbers(newContent) ? stripLineNumbers(newContent) : newContent,
198-
true,
199-
)
200-
201-
await delay(300)
202-
task.diffViewProvider.scrollToFirstDiff()
203-
204-
let unified = fileExists
205-
? formatResponse.createPrettyPatch(relPath, task.diffViewProvider.originalContent, newContent)
206-
: convertNewFileToUnifiedDiff(newContent, relPath)
207-
unified = sanitizeUnifiedDiff(unified)
208-
const completeMessage = JSON.stringify({
209-
...sharedMessageProps,
210-
content: unified,
211-
diffStats: computeDiffStats(unified) || undefined,
212-
} satisfies ClineSayTool)
213-
214-
const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected)
215-
216-
if (!didApprove) {
217-
await task.diffViewProvider.revertChanges()
218-
return
219-
}
220-
221-
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
168+
task.diffViewProvider.originalContent = ""
222169
}
223170

224-
if (relPath) {
225-
await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
171+
let unified = fileExists
172+
? formatResponse.createPrettyPatch(relPath, task.diffViewProvider.originalContent, newContent)
173+
: convertNewFileToUnifiedDiff(newContent, relPath)
174+
unified = sanitizeUnifiedDiff(unified)
175+
const completeMessage = JSON.stringify({
176+
...sharedMessageProps,
177+
content: unified,
178+
diffStats: computeDiffStats(unified) || undefined,
179+
} satisfies ClineSayTool)
180+
181+
const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected)
182+
183+
if (!didApprove) {
184+
return
226185
}
227186

228-
task.didEditFile = true
187+
await task.diffViewProvider.saveDirectly(relPath, newContent, false, diagnosticsEnabled, writeDelayMs)
188+
} else {
189+
if (!task.diffViewProvider.isEditing) {
190+
const partialMessage = JSON.stringify(sharedMessageProps)
191+
await task.ask("tool", partialMessage, true).catch(() => {})
192+
await task.diffViewProvider.open(relPath)
193+
}
194+
195+
await task.diffViewProvider.update(
196+
everyLineHasLineNumbers(newContent) ? stripLineNumbers(newContent) : newContent,
197+
true,
198+
)
229199

230-
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, !fileExists)
200+
await delay(300)
201+
task.diffViewProvider.scrollToFirstDiff()
231202

232-
pushToolResult(message)
203+
let unified = fileExists
204+
? formatResponse.createPrettyPatch(relPath, task.diffViewProvider.originalContent, newContent)
205+
: convertNewFileToUnifiedDiff(newContent, relPath)
206+
unified = sanitizeUnifiedDiff(unified)
207+
const completeMessage = JSON.stringify({
208+
...sharedMessageProps,
209+
content: unified,
210+
diffStats: computeDiffStats(unified) || undefined,
211+
} satisfies ClineSayTool)
233212

234-
await this.resetDiffViewAfterWrite(task)
213+
const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected)
235214

236-
task.processQueuedMessages()
215+
if (!didApprove) {
216+
await task.diffViewProvider.revertChanges()
217+
return
218+
}
219+
220+
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
221+
}
237222

238-
return
239-
} finally {
240-
this.resetTaskPartialState(task)
223+
if (relPath) {
224+
await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
241225
}
226+
227+
task.didEditFile = true
228+
229+
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, !fileExists)
230+
231+
pushToolResult(message)
232+
233+
await this.resetDiffViewAfterWrite(task)
234+
235+
task.processQueuedMessages()
236+
237+
return
242238
} catch (error) {
243239
// Finalize any open partial tool message so the UI spinner doesn't get stuck.
244240
// The partial ask fired during streaming (handlePartial) or early in execute sets
245241
// partial: true on the webview message; without this, the spinner persists even
246242
// after the error bubble appears.
247-
try {
248-
await task.finalizePartialToolAsk()
249-
await handleError("writing file", error as Error)
250-
await this.resetDiffViewAfterWrite(task)
251-
} finally {
252-
this.resetTaskPartialState(task)
253-
}
243+
await this.finalizePartialToolAskAfterFailure(task)
244+
await handleError("writing file", error as Error)
245+
await this.resetDiffViewAfterWrite(task)
254246
return
247+
} finally {
248+
this.resetTaskPartialState(task)
255249
}
256250
}
257251

@@ -332,7 +326,7 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
332326
// Mark the stream as failed so later deltas don't re-attempt and spawn a new
333327
// partial tool message each time.
334328
this.partialStreamFailuresByTaskId.add(partialStreamFailureKey)
335-
await task.finalizePartialToolAsk(partialMessage)
329+
await this.finalizePartialToolAskAfterFailure(task, partialMessage)
336330
await this.resetDiffViewAfterWrite(task)
337331
}
338332
}

‎src/core/tools/__tests__/writeToFileTool.spec.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,26 @@ describe("writeToFileTool", () => {
610610
expect(mockCline.consecutiveMistakeCount).toBe(3)
611611
})
612612

613+
it("continues execute error cleanup when finalizing partial ask fails", async () => {
614+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
615+
mockedCreateDirectoriesForFile.mockRejectedValue(
616+
Object.assign(new Error("EACCES: permission denied, mkdir '/ro'"), { code: "EACCES" }),
617+
)
618+
mockCline.finalizePartialToolAsk.mockRejectedValue(new Error("finalize failed"))
619+
620+
await executeWriteFileTool({}, { fileExists: false })
621+
622+
expect(mockCline.finalizePartialToolAsk).toHaveBeenCalled()
623+
expect(mockHandleError).toHaveBeenCalledWith("writing file", expect.any(Error))
624+
expect(mockCline.diffViewProvider.reset).toHaveBeenCalled()
625+
expect(consoleErrorSpy).toHaveBeenCalledWith(
626+
"Error finalizing write_to_file partial tool ask:",
627+
expect.any(Error),
628+
)
629+
630+
consoleErrorSpy.mockRestore()
631+
})
632+
613633
it("keeps partial stream failures isolated per task", async () => {
614634
mockCline.diffViewProvider.open.mockRejectedValueOnce(
615635
Object.assign(new Error("EROFS: read-only file system, mkdir '/task-a'"), { code: "EROFS" }),
@@ -652,6 +672,27 @@ describe("writeToFileTool", () => {
652672
consoleErrorSpy.mockRestore()
653673
})
654674

675+
it("continues partial failure cleanup when finalizing partial ask fails", async () => {
676+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
677+
mockCline.diffViewProvider.open.mockRejectedValue(
678+
Object.assign(new Error("EROFS: read-only file system, mkdir '/scratch'"), { code: "EROFS" }),
679+
)
680+
mockCline.finalizePartialToolAsk.mockRejectedValue(new Error("finalize failed"))
681+
682+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
683+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
684+
685+
expect(mockCline.finalizePartialToolAsk).toHaveBeenCalled()
686+
expect(mockCline.diffViewProvider.reset).toHaveBeenCalled()
687+
expect(mockHandleError).not.toHaveBeenCalled()
688+
expect(consoleErrorSpy).toHaveBeenCalledWith(
689+
"Error finalizing write_to_file partial tool ask:",
690+
expect.any(Error),
691+
)
692+
693+
consoleErrorSpy.mockRestore()
694+
})
695+
655696
it.skipIf(process.platform === "win32")(
656697
"EROFS in handlePartial does not stall agent loop -- createDirectoriesForFile is not called",
657698
async () => {

0 commit comments

Comments
 (0)