Skip to content

Commit 19e8512

Browse files
fix(write-to-file): cover the pre-streaming window and discard without saving
CodeRabbit Lifecycle Resource Cleanup on Zoo-Code-Org#1932: "handlePartial() then awaits provider?.getState() at lines 510-511 outside its local cleanup try. If that await, or a later synchronous operation, rejects, BaseTool.handle() only calls callbacks.handleError() ... it does not clear the map entry or remove the listener", and "if the task is aborted while diffViewProvider.open() is pending and open() then rejects, the abort listener has already cleared the state and task disposal can already start diff cleanup, but the catch still unconditionally finalizes the ask and calls revert/reset cleanup. This duplicates cleanup after cancellation." Everything after the entry is registered now runs inside a boundary that releases it: the pre-streaming window is wrapped, its catch releases this delta's entry (identity-guarded, so a newer stream's entry survives) and rethrows; the streaming catch checks liveness before it marks, finalizes, or restores, and again between the two cleanup awaits, so a cancellation that lands in either gap stops instead of running a second cleanup over a view disposal already owns. This is the mirror image of U4/Zoo-Code-Org#1929 61dd05a: that unit wrapped the setup work and left open()/update() outside, this one wrapped open()/update() and left provider.getState() outside. The rule is recorded in #41 (Zoo-Code-Org#41 (comment)): an await that happens after per-task state is registered belongs inside the boundary that releases it, including awaits that look like read-only setup. CodeRabbit Persistence Integrity on Zoo-Code-Org#1932: "revertChanges() now avoids saving activeDiffEditor.document and calls discardFileTab() ... That helper only finds TabInputText tabs (lines 912-920), but openDiffEditor() creates a vscode.diff tab with TabInputTextDiff ... A user can later save the still-open dirty modified-side buffer and recreate the unapproved streamed file." The rollback of an unapproved stream now goes through discardUnapprovedStream(), ported from the earliest unit that defines it (U7/Zoo-Code-Org#1928 f8f7ce1), together with the placeholderPath ownership tracking that keeps the discard from deleting a file the user approved, and with the discard's own suite. It empties or restores the buffer in memory, closes the tab only once it is clean, and then removes the placeholder and the directories this edit created; the target file is never written, so nothing the user did not approve reaches disk. One deliberate change to the ported shape: closeAllDiffViews() now runs AFTER the buffer restore instead of before it. A vscode.diff tab is dirty while its modified side holds the streamed content and closeAllDiffViews() deliberately skips dirty tabs, so calling it first left exactly the tab the row names open over a file the discard then unlinked. The same one-line move has to land in Zoo-Code-Org#1928 and Zoo-Code-Org#1929 so the primitive stays identical across the chain; it is called out here rather than silently diverging. Out of Scope Changes was answered before this commit: the per-file declaration is in #41 (Zoo-Code-Org#41 (comment)) and appended to Zoo-Code-Org#1937's body. BaseTool.ts belongs to U3/Zoo-Code-Org#1931 (e3c1040) and ClineProvider.ts to U4/Zoo-Code-Org#1929 (d172c95) and only appear in this PR's file list because the chain is opened against main; DiffViewProvider.ts and its spec are this unit's own, because the cleanup that U6's finally invokes is that code. Negative controls (Buffer snapshots, sha256 cd36a1095acd4c72 / 39863d8ea2df56c8 / 781972c962cf3882 verified after every mutant): outer catch not releasing -> 1 red; no liveness check at the top of the streaming catch -> 1 red; no liveness check between the two cleanup awaits -> 1 red; rollback routed back through revertChanges -> 16 red; closeAllDiffViews moved back before the restore -> 3 red; placeholder ownership guard removed -> 3 red. Local: sweep (core/tools, integrations/editor, core/task, core/webview) 97 files / 1994 passed / 5 skipped; tsc --noEmit 0 with the local @roo-code/types paths override; eslint . --ext=ts --max-warnings=0 exit 0; eslint-suppressions.json untouched.
1 parent 443993e commit 19e8512

5 files changed

Lines changed: 831 additions & 86 deletions

File tree

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 104 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -150,23 +150,31 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
150150
}
151151

152152
/**
153-
* Restore the diff editor document to its pre-streaming state and close the view.
153+
* Release the diff view of a write that was never approved, then let the caller reset it.
154154
*
155155
* reset() clears the provider's state but leaves the diff document dirty with the
156156
* streamed content; a user save would then persist a write the task never completed
157157
* (denied or failed before approval). Must run BEFORE resetDiffViewAfterWrite(),
158-
* since reset() clears the state revertChanges() relies on. No-op when no diff view
158+
* since reset() clears the state the discard relies on. No-op when no diff view
159159
* is open. Failures are logged and reported through the return value: the caller
160160
* must not treat the teardown as complete when this returns false, because the
161161
* document may still hold the unapproved content, but the remaining cleanup (reset,
162162
* per-task state teardown) still runs so the task is not left half-torn-down.
163+
*
164+
* This is deliberately not revertChanges(): that method SAVES. For a new file it writes
165+
* the streamed partial output into the placeholder before deleting it, and for an
166+
* existing file it writes the restored original back to a file this stream never
167+
* changed. discardUnapprovedStream() empties or restores the buffer in memory and
168+
* closes the tab only once it is clean, so nothing the user did not approve reaches
169+
* disk and the modified side of the vscode.diff tab - a TabInputTextDiff, which
170+
* discardFileTab() cannot see - is what actually gets discarded.
163171
*/
164-
private async revertDiffChangesBeforeReset(task: Task): Promise<boolean> {
172+
private async discardUnapprovedStreamBeforeReset(task: Task): Promise<boolean> {
165173
try {
166-
await task.diffViewProvider.revertChanges()
174+
await task.diffViewProvider.discardUnapprovedStream()
167175
return true
168-
} catch (revertError) {
169-
console.error("Error reverting write_to_file diff view changes:", revertError)
176+
} catch (discardError) {
177+
console.error("Error discarding the unapproved write_to_file diff view:", discardError)
170178
return false
171179
}
172180
}
@@ -204,7 +212,7 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
204212
* cleanup is a different failure and is reported elsewhere.
205213
*/
206214
private async cleanupFailedPartialStream(task: Task): Promise<void> {
207-
const reverted = await this.revertDiffChangesBeforeReset(task)
215+
const reverted = await this.discardUnapprovedStreamBeforeReset(task)
208216
await this.resetDiffViewAfterWrite(task)
209217
if (!reverted) {
210218
await this.reportRevertFailure(task)
@@ -239,7 +247,7 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
239247
// The revert runs BEFORE the per-task state is torn down: when it fails, the
240248
// document can still hold that unapproved content, and the recovery state has
241249
// to exist while the outcome is decided and reported.
242-
const reverted = await this.revertDiffChangesBeforeReset(task)
250+
const reverted = await this.discardUnapprovedStreamBeforeReset(task)
243251
this.resetTaskPartialState(task)
244252
await this.resetDiffViewAfterWrite(task)
245253
if (!reverted) {
@@ -470,7 +478,7 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
470478
// save it manually.
471479
let reverted = true
472480
if (!writeApproved) {
473-
reverted = await this.revertDiffChangesBeforeReset(task)
481+
reverted = await this.discardUnapprovedStreamBeforeReset(task)
474482
}
475483
await this.resetDiffViewAfterWrite(task)
476484
if (!reverted) {
@@ -507,65 +515,89 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
507515
return
508516
}
509517

510-
const provider = task.providerRef.deref()
511-
const state = await provider?.getState()
512-
// Cancelled while provider state was in flight: the teardown already released this
513-
// task's stream state, so this delta must not go on to ask or open a diff view.
514-
if (!this.isPartialStreamStillLive(task, partialStreamState)) {
515-
return
516-
}
518+
// Everything below runs after getTaskPartialStreamState() registered this task's entry and its
519+
// TaskAborted listener, so it belongs inside a boundary that releases them. The awaits here look
520+
// like reads and are not: provider.getState() is an await into the extension host and the
521+
// filesystem probe can reject. If either does, this delta reaches neither the streaming block
522+
// nor execute()'s teardown, and BaseTool.handle() only reports the error - which would leave
523+
// the singleton holding a task that nothing else ever releases.
517524

518-
const isPreventFocusDisruptionEnabled = experiments.isEnabled(
519-
state?.experiments ?? {},
520-
EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION,
521-
)
525+
// Declared outside the try: the streaming catch below reads it, and a try block's
526+
// own scope is not visible to code that runs after the try.
527+
let partialMessage: string | undefined
522528

523-
if (isPreventFocusDisruptionEnabled) {
524-
// The preview is suppressed for this stream: release the entry registered above so the
525-
// abort listener and any failure mark do not outlive a delta that never shows a diff
526-
// view and never reaches execute()'s teardown.
527-
super.resetPartialState()
528-
this.resetTaskPartialState(task)
529-
return
530-
}
529+
try {
530+
const provider = task.providerRef.deref()
531+
const state = await provider?.getState()
532+
// Cancelled while provider state was in flight: the teardown already released this
533+
// task's stream state, so this delta must not go on to ask or open a diff view.
534+
if (!this.isPartialStreamStillLive(task, partialStreamState)) {
535+
return
536+
}
531537

532-
// relPath is guaranteed non-null after hasPathStabilized
533-
let fileExists: boolean
534-
const absolutePath = path.resolve(task.cwd, relPath!)
538+
const isPreventFocusDisruptionEnabled = experiments.isEnabled(
539+
state?.experiments ?? {},
540+
EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION,
541+
)
535542

536-
if (task.diffViewProvider.editType !== undefined) {
537-
fileExists = task.diffViewProvider.editType === "modify"
538-
} else {
539-
fileExists = await fileExistsAtPath(absolutePath)
540-
task.diffViewProvider.editType = fileExists ? "modify" : "create"
541-
}
543+
if (isPreventFocusDisruptionEnabled) {
544+
// The preview is suppressed for this stream: release the entry registered above so the
545+
// abort listener and any failure mark do not outlive a delta that never shows a diff
546+
// view and never reaches execute()'s teardown.
547+
super.resetPartialState()
548+
this.resetTaskPartialState(task)
549+
return
550+
}
542551

543-
// Cancelled during the filesystem probe: stop before the partial ask and the diff view.
544-
// (The probe above is the only await in this branch.)
545-
if (!this.isPartialStreamStillLive(task, partialStreamState)) {
546-
return
547-
}
552+
// relPath is guaranteed non-null after hasPathStabilized
553+
let fileExists: boolean
554+
const absolutePath = path.resolve(task.cwd, relPath!)
548555

549-
const isWriteProtected = task.rooProtectedController?.isWriteProtected(relPath!) || false
550-
const isOutsideWorkspace = isPathOutsideWorkspace(absolutePath)
556+
if (task.diffViewProvider.editType !== undefined) {
557+
fileExists = task.diffViewProvider.editType === "modify"
558+
} else {
559+
fileExists = await fileExistsAtPath(absolutePath)
560+
task.diffViewProvider.editType = fileExists ? "modify" : "create"
561+
}
551562

552-
const sharedMessageProps: ClineSayTool = {
553-
tool: fileExists ? "editedExistingFile" : "newFileCreated",
554-
path: getReadablePath(task.cwd, relPath!),
555-
content: newContent || "",
556-
isOutsideWorkspace,
557-
isProtected: isWriteProtected,
558-
}
563+
// Cancelled during the filesystem probe: stop before the partial ask and the diff view.
564+
// (The probe above is the only await in this branch.)
565+
if (!this.isPartialStreamStillLive(task, partialStreamState)) {
566+
return
567+
}
559568

560-
const partialMessage = JSON.stringify(sharedMessageProps)
561-
await task.ask("tool", partialMessage, block.partial).catch(() => {})
569+
const isWriteProtected = task.rooProtectedController?.isWriteProtected(relPath!) || false
570+
const isOutsideWorkspace = isPathOutsideWorkspace(absolutePath)
562571

563-
// Cancelled while the partial ask was in flight: the teardown released this task's
564-
// state, so this delta must not touch the diff view.
565-
if (!this.isPartialStreamStillLive(task, partialStreamState)) {
566-
return
572+
const sharedMessageProps: ClineSayTool = {
573+
tool: fileExists ? "editedExistingFile" : "newFileCreated",
574+
path: getReadablePath(task.cwd, relPath!),
575+
content: newContent || "",
576+
isOutsideWorkspace,
577+
isProtected: isWriteProtected,
578+
}
579+
580+
partialMessage = JSON.stringify(sharedMessageProps)
581+
await task.ask("tool", partialMessage, block.partial).catch(() => {})
582+
583+
// Cancelled while the partial ask was in flight: the teardown released this task's
584+
// state, so this delta must not touch the diff view.
585+
if (!this.isPartialStreamStillLive(task, partialStreamState)) {
586+
return
587+
}
588+
} catch (error) {
589+
// Unexpected failure in the pre-streaming window: nothing was streamed and nothing was shown,
590+
// so this is not the retained-streaming-failure case the inner catch below keeps state for.
591+
// Release this delta's entry and its listener before the error reaches BaseTool.handle(),
592+
// then rethrow so the delta is still reported. Identity-guarded: if a cancellation already
593+
// released the entry and a newer stream re-created it under the same key, that entry stays.
594+
if (this.isPartialStreamStillLive(task, partialStreamState)) {
595+
this.resetTaskPartialState(task)
596+
}
597+
throw error
567598
}
568599

600+
569601
if (newContent) {
570602
try {
571603
if (!task.diffViewProvider.isEditing) {
@@ -583,6 +615,14 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
583615
false,
584616
)
585617
} catch (error) {
618+
// The task may have been aborted while open() or update() was in flight. The teardown
619+
// already released this entry and the disposal path already owns the diff cleanup, so
620+
// marking, finalizing and restoring here would be a second cleanup of the same stream:
621+
// a second partial-tool row and a second restore racing the first.
622+
if (!this.isPartialStreamStillLive(task, partialStreamState)) {
623+
return
624+
}
625+
586626
// Opening or updating the diff view can throw on filesystem errors
587627
// (EACCES/EROFS on read-only paths). Finalize the partial tool message
588628
// so the UI spinner doesn't get stuck and reset the diff view. Do NOT
@@ -599,6 +639,13 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
599639
partialStreamState.streamFailed = true
600640
partialStreamState.streamError = error instanceof Error ? error : new Error(String(error))
601641
await this.finalizePartialToolAskAfterFailure(task, partialMessage)
642+
643+
// Finalizing is an await: a cancellation during it has already run the teardown and the
644+
// disposal cleanup, so the restore below must not run a second time over the same view.
645+
if (!this.isPartialStreamStillLive(task, partialStreamState)) {
646+
return
647+
}
648+
602649
// The write was never approved: restore the document so a user save cannot
603650
// persist the failed streamed content (reset() alone leaves it dirty), and
604651
// surface the hazard if that restore itself failed. The stream error is

‎src/core/tools/__tests__/writeToFileTool-partial-state-cleanup.spec.ts‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ interface CleanupTask {
1616
off: MockedFunction<(...args: unknown[]) => unknown>
1717
diffViewProvider: {
1818
reset: MockedFunction<() => Promise<void>>
19+
discardUnapprovedStream: MockedFunction<() => Promise<void>>
1920
revertChanges: MockedFunction<() => Promise<void>>
2021
}
2122
finalizePartialToolAsk: MockedFunction<() => Promise<void>>
@@ -31,6 +32,7 @@ function buildTask(taskId: string, instanceId: string): Task {
3132
diffViewProvider: {
3233
reset: vi.fn().mockResolvedValue(undefined),
3334
revertChanges: vi.fn().mockResolvedValue(undefined),
35+
discardUnapprovedStream: vi.fn().mockResolvedValue(undefined),
3436
},
3537
finalizePartialToolAsk: vi.fn().mockResolvedValue(undefined),
3638
say: vi.fn().mockResolvedValue(undefined),
@@ -78,22 +80,22 @@ describe("WriteToFileTool per-task partial-state cleanup", () => {
7880
expect(errorSpy).toHaveBeenCalledWith("Error resetting write_to_file diff view:", expect.any(Error))
7981
})
8082

81-
it("logs and continues when reverting the diff document fails", async () => {
83+
it("logs and continues when discarding the unapproved diff view fails", async () => {
8284
const task = buildTask("revert-fails", "inst-4")
8385
const t = task as unknown as CleanupTask
84-
t.diffViewProvider.revertChanges = vi.fn().mockRejectedValue(new Error("revert failed"))
86+
t.diffViewProvider.discardUnapprovedStream = vi.fn().mockRejectedValue(new Error("revert failed"))
8587
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
8688

87-
await writeToFileTool["revertDiffChangesBeforeReset"](task)
89+
await writeToFileTool["discardUnapprovedStreamBeforeReset"](task)
8890

89-
expect(errorSpy).toHaveBeenCalledWith("Error reverting write_to_file diff view changes:", expect.any(Error))
91+
expect(errorSpy).toHaveBeenCalledWith("Error discarding the unapproved write_to_file diff view:", expect.any(Error))
9092
})
9193

92-
it("reverts while the recovery state exists and reports the hazard when the revert fails", async () => {
94+
it("discards while the recovery state exists and reports the hazard when the discard fails", async () => {
9395
const task = buildTask("revert-fails-teardown", "inst-6")
9496
const t = task as unknown as CleanupTask
9597
let stateSizeDuringRevert = -1
96-
t.diffViewProvider.revertChanges = vi.fn(async () => {
98+
t.diffViewProvider.discardUnapprovedStream = vi.fn(async () => {
9799
// The recovery state must still be present while the rollback runs.
98100
stateSizeDuringRevert = writeToFileTool["taskPartialStreamState"].size
99101
throw new Error("revert failed")
@@ -125,7 +127,7 @@ describe("WriteToFileTool per-task partial-state cleanup", () => {
125127
it("reports the rollback hazard AND the retained streaming error, and returns true", async () => {
126128
const task = buildTask("revert-fails-with-stream-error", "inst-7")
127129
const t = task as unknown as CleanupTask
128-
t.diffViewProvider.revertChanges = vi.fn().mockRejectedValue(new Error("revert failed"))
130+
t.diffViewProvider.discardUnapprovedStream = vi.fn().mockRejectedValue(new Error("revert failed"))
129131
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
130132
const state = writeToFileTool["getTaskPartialStreamState"](task)
131133
const streamError = new Error("filesystem failure while streaming")
@@ -149,7 +151,7 @@ describe("WriteToFileTool per-task partial-state cleanup", () => {
149151
it("still reports the streaming error when the rollback warning itself fails", async () => {
150152
const task = buildTask("rollback-warning-fails", "inst-8")
151153
const t = task as unknown as CleanupTask
152-
t.diffViewProvider.revertChanges = vi.fn().mockRejectedValue(new Error("revert failed"))
154+
t.diffViewProvider.discardUnapprovedStream = vi.fn().mockRejectedValue(new Error("revert failed"))
153155
t.say = vi.fn().mockRejectedValue(new Error("say failed"))
154156
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
155157
const state = writeToFileTool["getTaskPartialStreamState"](task)
@@ -174,7 +176,7 @@ describe("WriteToFileTool per-task partial-state cleanup", () => {
174176
it("surfaces the rollback hazard from the failed-stream cleanup as well", async () => {
175177
const task = buildTask("failed-stream-cleanup", "inst-9")
176178
const t = task as unknown as CleanupTask
177-
t.diffViewProvider.revertChanges = vi.fn().mockRejectedValue(new Error("revert failed"))
179+
t.diffViewProvider.discardUnapprovedStream = vi.fn().mockRejectedValue(new Error("revert failed"))
178180
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
179181

180182
await writeToFileTool["cleanupFailedPartialStream"](task)

0 commit comments

Comments
 (0)