Skip to content

Commit 8084eab

Browse files
fix(write-to-file): keep rollback honest when the discard itself fails
CodeRabbit Persistence Integrity on Zoo-Code-Org#1929: "In DiffViewProvider.saveChanges() (src/integrations/editor/DiffViewProvider.ts:350-358), placeholderPath is cleared before the awaited document save succeeds. If a new-file save fails, WriteToFileTool.execute() only calls reset() in its catch ...; reset() clears the ownership fields without unlinking the placeholder ... The failed operation can therefore leave an empty or partially written new file. Also, handlePartial() ignores the rollback error returned by discardUnapprovedStreamBeforeReset() ... so a later user save can persist that content." Ownership now follows the write: saveChanges() releases placeholderPath only after the approved save lands, and execute()'s catch runs the discard before reset() - the only teardown that removes what this edit created - so a rejected save no longer leaves an empty or half-written new file behind. The discard failure is reported instead of dropped. Two failures get two channels: the exception the delta produced stays the primary one (BaseTool.handle() reports it unchanged - wrapping it would change the failure the caller sees), and the discard failure, which is about debris still on disk, gets its own report through task.say("error", ...). Both the streaming catch and the write teardown do this now. Open thread 4236260447: "Abandoned create leaves the target tab open, so the placeholder unlink orphans it. closeFileTab() skips tabs where tab.isDirty is true ... Lines 624-631 still unlink the placeholder. The user then sees an open dirty tab for a file that no longer exists on disk ... If the user presses Ctrl+S, VS Code recreates the file with that unapproved content." The discard now keeps the placeholder and the directories this edit created whenever the editor work failed with the buffer still dirty, and says so in the error it throws; when the buffer ended clean - or there was never an editor at all - the artifacts are debris and still go. Carried follow-up (Zoo-Code-Org#41 (comment)): closeAllDiffViews() moved after the buffer restore inside the discard. A vscode.diff tab is dirty while its modified side holds the streamed content and closeAllDiffViews() skips dirty tabs, so closing first left that tab open over the file being unlinked. Lifecycle Resource Cleanup: "A completed call then awaits createDirectoriesForFile() at :308-309 before the cleanup boundary at :335; a filesystem error such as EACCES or EROFS rejects execute() without calling releasePartialStreamBookkeeping()." The setup awaits are now inside a boundary that releases this task's entry and rethrows, so the error still travels the path it always took and nothing reports it twice. Regression Evidence: the abort test now asserts exactly one TaskAborted registration per task and deregisters that same function reference (expect.any(Function) passed even when a different callback was removed), and a new liveness test replaces the state under the same key while a delta is in flight - presence-only liveness would pass the old tests. Negative controls (Buffer snapshots, sha256 0dbb4148ab1b5011 provider / afee0b37e8ca0ecb tool, verified after every mutant): clearing placeholderPath before the save -> 1 red; keepArtifacts always false -> 3 red; keepArtifacts ignoring the buffer state -> 2 red; execute() catch not discarding -> 2 red; dropping the write-teardown report -> 1 red; dropping the streaming report -> 1 red; wrapping the primary error instead (the shape the review suggested) -> 1 red; setup boundary not releasing -> 1 red; liveness by key presence -> 1 red; re-registering the abort listener per delta -> 1 red. Local: sweep (core/tools, integrations/editor, core/task, core/webview) 97 files / 1973 passed / 5 skipped; tsc --noEmit 0 with the local @roo-code/types paths override; eslint . --ext=ts --max-warnings=0 exit 0; prettier --check clean on all four files; eslint-suppressions.json untouched; it( 48 -> 53 and 86 -> 90, no removals.
1 parent 12ec5f8 commit 8084eab

4 files changed

Lines changed: 379 additions & 58 deletions

File tree

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 70 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -293,43 +293,58 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
293293

294294
const isWriteProtected = task.rooProtectedController?.isWriteProtected(relPath) || false
295295

296+
// Declared outside the setup boundary below: the write body's try block reads it after the
297+
// setup succeeded, and a block-scoped declaration would not be visible there.
296298
let fileExists: boolean
297-
const absolutePath = path.resolve(task.cwd, relPath)
299+
let sharedMessageProps: ClineSayTool
300+
301+
// The setup below awaits before the write's own try/catch begins. A rejection there (an
302+
// EACCES/EROFS from createDirectoriesForFile, a failing filesystem probe) would otherwise
303+
// escape execute() with this task's stream entry and its TaskAborted listener still
304+
// registered, so the map would keep the task alive and a later write could reuse a stale
305+
// stream state. Release and rethrow: BaseTool.handle() still reports the error exactly
306+
// once, and no diff view is open yet, so there is no preview to discard.
307+
try {
308+
const absolutePath = path.resolve(task.cwd, relPath)
298309

299-
if (task.diffViewProvider.editType !== undefined) {
300-
fileExists = task.diffViewProvider.editType === "modify"
301-
} else {
302-
fileExists = await fileExistsAtPath(absolutePath)
303-
task.diffViewProvider.editType = fileExists ? "modify" : "create"
304-
}
310+
if (task.diffViewProvider.editType !== undefined) {
311+
fileExists = task.diffViewProvider.editType === "modify"
312+
} else {
313+
fileExists = await fileExistsAtPath(absolutePath)
314+
task.diffViewProvider.editType = fileExists ? "modify" : "create"
315+
}
305316

306-
// Create parent directories early for new files to prevent ENOENT errors
307-
// in subsequent operations (e.g., diffViewProvider.open, fs.readFile)
308-
if (!fileExists) {
309-
await createDirectoriesForFile(absolutePath)
310-
}
317+
// Create parent directories early for new files to prevent ENOENT errors
318+
// in subsequent operations (e.g., diffViewProvider.open, fs.readFile)
319+
if (!fileExists) {
320+
await createDirectoriesForFile(absolutePath)
321+
}
311322

312-
if (newContent.startsWith("```")) {
313-
newContent = newContent.split("\n").slice(1).join("\n")
314-
}
323+
if (newContent.startsWith("```")) {
324+
newContent = newContent.split("\n").slice(1).join("\n")
325+
}
315326

316-
if (newContent.endsWith("```")) {
317-
newContent = newContent.split("\n").slice(0, -1).join("\n")
318-
}
327+
if (newContent.endsWith("```")) {
328+
newContent = newContent.split("\n").slice(0, -1).join("\n")
329+
}
319330

320-
if (!task.api.getModel().id.includes("claude")) {
321-
newContent = unescapeHtmlEntities(newContent)
322-
}
331+
if (!task.api.getModel().id.includes("claude")) {
332+
newContent = unescapeHtmlEntities(newContent)
333+
}
323334

324-
const fullPath = relPath ? path.resolve(task.cwd, relPath) : ""
325-
const isOutsideWorkspace = isPathOutsideWorkspace(fullPath)
335+
const fullPath = relPath ? path.resolve(task.cwd, relPath) : ""
336+
const isOutsideWorkspace = isPathOutsideWorkspace(fullPath)
326337

327-
const sharedMessageProps: ClineSayTool = {
328-
tool: fileExists ? "editedExistingFile" : "newFileCreated",
329-
path: getReadablePath(task.cwd, relPath),
330-
content: newContent,
331-
isOutsideWorkspace,
332-
isProtected: isWriteProtected,
338+
sharedMessageProps = {
339+
tool: fileExists ? "editedExistingFile" : "newFileCreated",
340+
path: getReadablePath(task.cwd, relPath),
341+
content: newContent,
342+
isOutsideWorkspace,
343+
isProtected: isWriteProtected,
344+
}
345+
} catch (error) {
346+
this.releasePartialStreamBookkeeping(task)
347+
throw error
333348
}
334349

335350
try {
@@ -433,6 +448,20 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
433448
await this.finalizePartialToolAskAfterFailure(task, pendingPartialAsk)
434449
}
435450
await handleError("writing file", error as Error)
451+
// A preview that never got its approved write to disk holds unapproved content: discard
452+
// it before reset() drops the state the discard depends on. This is also the teardown for
453+
// a saveChanges() that rejected mid-write - the placeholder is still owned by this edit,
454+
// because saveChanges() releases ownership only once the save lands - so the discard is
455+
// what removes the empty or half-written new file.
456+
if (task.diffViewProvider.isEditing) {
457+
const discardError = await this.discardUnapprovedStreamBeforeReset(task)
458+
if (discardError) {
459+
await task.say(
460+
"error",
461+
`write_to_file could not discard the unapproved preview after the failed write: ${discardError.message}`,
462+
)
463+
}
464+
}
436465
await task.diffViewProvider.reset()
437466
this.releasePartialStreamBookkeeping(task)
438467
return
@@ -579,8 +608,19 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
579608
this.releasePartialStreamBookkeeping(task)
580609
}
581610
if (task.diffViewProvider.isEditing) {
582-
await this.discardUnapprovedStreamBeforeReset(task)
611+
const discardError = await this.discardUnapprovedStreamBeforeReset(task)
583612
await this.resetDiffViewAfterWrite(task)
613+
if (discardError) {
614+
// Two failures, two channels. The exception this delta produced stays the primary one:
615+
// BaseTool.handle() reports it unchanged, so wrapping it here would change the failure
616+
// the caller sees. The discard failure is a separate, actionable condition - the
617+
// placeholder or the created directories are still on disk and the buffer may still hold
618+
// unapproved content - so it gets its own report instead of only a console line.
619+
await task.say(
620+
"error",
621+
`write_to_file could not discard the unapproved preview after the failed stream: ${discardError.message}`,
622+
)
623+
}
584624
}
585625
throw error
586626
}

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

Lines changed: 149 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,14 @@ describe("writeToFileTool", () => {
449449
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
450450
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
451451
expect(mockCline.ask).toHaveBeenCalledTimes(1)
452-
expect(mockCline.once).toHaveBeenCalledWith(RooCodeEventName.TaskAborted, expect.any(Function))
452+
// One listener per task, not one per delta, and the teardown must deregister THAT function:
453+
// expect.any(Function) would also pass a tool that registered twice or removed a
454+
// different callback and left the real listener attached.
455+
const registrations = mockCline.once.mock.calls.filter(
456+
([event]: unknown[]) => event === RooCodeEventName.TaskAborted,
457+
)
458+
expect(registrations).toHaveLength(1)
459+
expect(mockCline.once).toHaveBeenCalledWith(RooCodeEventName.TaskAborted, abortCleanup)
453460

454461
abortCleanup?.()
455462
expect(mockCline.off).toHaveBeenCalledWith(RooCodeEventName.TaskAborted, abortCleanup)
@@ -600,6 +607,55 @@ describe("writeToFileTool", () => {
600607
expect(mockHandleError).toHaveBeenCalledWith("writing file", expect.any(Error))
601608
expect(mockCline.finalizePartialToolAsk).toHaveBeenCalledWith(expectedPartialToolMessage)
602609
})
610+
611+
it("discards the unapproved preview when the approved write itself fails", async () => {
612+
// saveChanges() releases placeholder ownership only once the write lands, so a rejected
613+
// save leaves this edit owning an empty or half-written new file. The catch has to run
614+
// the discard - the only teardown that removes what this edit created - before reset()
615+
// drops the state the discard reads.
616+
mockCline.diffViewProvider.saveChanges.mockRejectedValue(new Error("save failed"))
617+
mockCline.diffViewProvider.isEditing = true
618+
619+
await executeWriteFileTool({})
620+
621+
const discardOrder = mockCline.diffViewProvider.discardUnapprovedStream.mock.invocationCallOrder[0]
622+
const resetOrder = mockCline.diffViewProvider.reset.mock.invocationCallOrder[0]
623+
expect(mockCline.diffViewProvider.discardUnapprovedStream).toHaveBeenCalledTimes(1)
624+
expect(discardOrder).toBeLessThan(resetOrder)
625+
expect(mockHandleError).toHaveBeenCalledWith("writing file", expect.any(Error))
626+
})
627+
628+
it("reports a discard that fails during the write teardown", async () => {
629+
// The discard is the last thing standing between an abandoned create and debris on
630+
// disk. If it throws, the user still has to learn the file may be left behind - a
631+
// console line is not a report.
632+
mockCline.diffViewProvider.saveChanges.mockRejectedValue(new Error("save failed"))
633+
mockCline.diffViewProvider.isEditing = true
634+
mockCline.diffViewProvider.discardUnapprovedStream.mockRejectedValue(
635+
new Error("EPERM: operation not permitted"),
636+
)
637+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
638+
639+
try {
640+
await executeWriteFileTool({})
641+
642+
expect(mockCline.say).toHaveBeenCalledWith(
643+
"error",
644+
expect.stringContaining("could not discard the unapproved preview after the failed write"),
645+
)
646+
expect(mockCline.say).toHaveBeenCalledWith(
647+
"error",
648+
expect.stringContaining("EPERM: operation not permitted"),
649+
)
650+
// The write failure stays the reported failure; the discard failure is additional.
651+
expect(mockHandleError).toHaveBeenCalledWith(
652+
"writing file",
653+
expect.objectContaining({ message: "save failed" }),
654+
)
655+
} finally {
656+
errorSpy.mockRestore()
657+
}
658+
})
603659
})
604660

605661
describe("early-exit stream state cleanup", () => {
@@ -955,6 +1011,98 @@ describe("writeToFileTool", () => {
9551011
)
9561012
})
9571013

1014+
it("reports a discard failure without replacing the error the delta produced", async () => {
1015+
// The delta failed in the pre-streaming setup, and the discard of the preview an
1016+
// earlier delta left open failed too. Two failures, two channels: BaseTool.handle()
1017+
// must still report THIS delta's error - wrapping it would change the failure the
1018+
// caller sees - while the discard failure (debris still on disk) gets its own report.
1019+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
1020+
mockCline.providerRef.deref.mockReturnValue({
1021+
getState: vi.fn().mockRejectedValue(new Error("provider state unavailable")),
1022+
})
1023+
mockCline.diffViewProvider.isEditing = true
1024+
mockCline.diffViewProvider.discardUnapprovedStream.mockRejectedValue(
1025+
new Error("EPERM: operation not permitted"),
1026+
)
1027+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
1028+
1029+
try {
1030+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
1031+
1032+
expect(mockCline.say).toHaveBeenCalledWith(
1033+
"error",
1034+
expect.stringContaining("could not discard the unapproved preview after the failed stream"),
1035+
)
1036+
expect(mockCline.say).toHaveBeenCalledWith(
1037+
"error",
1038+
expect.stringContaining("EPERM: operation not permitted"),
1039+
)
1040+
const reported = mockHandleError.mock.calls.find(
1041+
([context]) => context === "handling partial write_to_file",
1042+
)?.[1] as Error
1043+
expect(reported.message).toBe("provider state unavailable")
1044+
expect(reported.name).toBe("Error")
1045+
} finally {
1046+
errorSpy.mockRestore()
1047+
}
1048+
})
1049+
1050+
it("leaves a replacement stream state alone when the delta it replaced resumes", async () => {
1051+
// Liveness is object identity, not key presence: a test that only clears the entry
1052+
// passes for an implementation that checks the key. Here a new stream takes over the
1053+
// same task key while the old delta awaits the filesystem, so the resumed delta must
1054+
// neither continue its side effects nor write through the replacement's entry.
1055+
let releaseGate: (() => void) | undefined
1056+
const gate = new Promise<void>((resolve) => {
1057+
releaseGate = resolve
1058+
})
1059+
// The path must be stabilized by an earlier delta before handlePartial() touches the
1060+
// filesystem, which is also what registers this task's entry.
1061+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
1062+
mockedCreateDirectoriesForFile.mockImplementationOnce(() => gate.then(() => []))
1063+
const streaming = executeWriteFileTool({}, { fileExists: false, isPartial: true })
1064+
await new Promise<void>((resolve) => setImmediate(resolve))
1065+
expect(mockedCreateDirectoriesForFile).toHaveBeenCalledTimes(1)
1066+
1067+
const key = writeToFileTool["getPartialStreamFailureKey"](mockCline as never) as string
1068+
writeToFileTool["resetTaskPartialState"](mockCline as never)
1069+
const replacement = writeToFileTool["getTaskPartialStreamState"](mockCline as never)
1070+
replacement.streamFailed = false
1071+
releaseGate?.()
1072+
await streaming
1073+
1074+
expect(mockCline.ask).not.toHaveBeenCalled()
1075+
expect(mockCline.diffViewProvider.open).not.toHaveBeenCalled()
1076+
expect(mockCline.diffViewProvider.update).not.toHaveBeenCalled()
1077+
expect(writeToFileTool["taskPartialStreamState"].get(key)).toBe(replacement)
1078+
expect(replacement.streamFailed).toBe(false)
1079+
expect(replacement.streamError).toBeUndefined()
1080+
})
1081+
1082+
it("releases the stream state when the setup before the write boundary rejects", async () => {
1083+
// execute() creates the parent directories for a new file before its write boundary
1084+
// begins. An EACCES there used to escape execute() entirely - BaseTool.handle() only
1085+
// reports it - so the map kept this task's entry and its abort listener alive, and a
1086+
// later write could inherit a stale stream state.
1087+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
1088+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
1089+
expect(writeToFileTool["taskPartialStreamState"].size).toBe(1)
1090+
const abortListener = mockCline.once.mock.calls.find(
1091+
([event]: unknown[]) => event === RooCodeEventName.TaskAborted,
1092+
)?.[1]
1093+
expect(abortListener).toBeInstanceOf(Function)
1094+
mockedCreateDirectoriesForFile.mockRejectedValueOnce(new Error("EACCES: permission denied"))
1095+
1096+
// The failure itself keeps travelling the path it always took: the boundary releases
1097+
// and rethrows, so the caller still sees the original error and nothing reports it twice.
1098+
await expect(executeWriteFileTool({})).rejects.toThrow("EACCES: permission denied")
1099+
1100+
expect(writeToFileTool["taskPartialStreamState"].size).toBe(0)
1101+
expect(mockCline.off).toHaveBeenCalledWith(RooCodeEventName.TaskAborted, abortListener)
1102+
expect(mockHandleError).not.toHaveBeenCalled()
1103+
expect(mockCline.diffViewProvider.reset).not.toHaveBeenCalled()
1104+
})
1105+
9581106
it("reports the captured stream error once when the finalized block fails to parse", async () => {
9591107
// A streaming delta already hit a fatal filesystem error; the finalized block then fails
9601108
// to parse. The stream error is what the user can act on, so it takes the report slot and

0 commit comments

Comments
 (0)