Skip to content

Commit 0dc92ca

Browse files
author
easonLiangWorldedtech
committed
fix(tools): do not report a completed teardown when the diff revert fails
onParameterParseFailure() tore down the per-task stream state first, then reverted the diff document with the failure logged and swallowed, then reset the diff provider. A failed revert therefore looked like a completed teardown even though the editor can still hold the unapproved partial content - and a user save of that editor lands a write the task never approved, with nothing in the UI saying so. The revert now runs while the recovery state still exists, revertDiffChangesBeforeReset returns whether it succeeded, and a failed revert is surfaced with task.say("error", ...) naming the hazard. The remaining cleanup (reset + per-task teardown) still runs, so the task is never left half-torn-down. Test: the seeded per-task state is observed from inside the failing revertChanges double, so the ordering is pinned (state present during rollback, gone afterwards), and the error say is asserted. Without the fix the test fails (1 failed / 5 passed); with it 6 pass. The streaming-failure cleanup keeps its existing log-only behaviour: that path's error is reported by the authoritative non-partial block in execute(), as its comment states, so adding a second message there would double-report the same failure. Local: writeToFileTool-partial-state-cleanup.spec.ts 6 passed, eslint clean with --prune-suppressions (no suppression change), package tsc clean.
1 parent b04e224 commit 0dc92ca

2 files changed

Lines changed: 62 additions & 10 deletions

File tree

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -144,13 +144,19 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
144144
* streamed content; a user save would then persist a write the task never completed
145145
* (denied or failed before approval). Must run BEFORE resetDiffViewAfterWrite(),
146146
* since reset() clears the state revertChanges() relies on. No-op when no diff view
147-
* is open. Failures are logged and swallowed so the remaining cleanup (reset,
148-
* per-task state teardown) always continues.
147+
* is open. Failures are logged and reported through the return value: the caller
148+
* must not treat the teardown as complete when this returns false, because the
149+
* document may still hold the unapproved content, but the remaining cleanup (reset,
150+
* per-task state teardown) still runs so the task is not left half-torn-down.
149151
*/
150-
private async revertDiffChangesBeforeReset(task: Task): Promise<void> {
151-
await task.diffViewProvider.revertChanges().catch((revertError) => {
152+
private async revertDiffChangesBeforeReset(task: Task): Promise<boolean> {
153+
try {
154+
await task.diffViewProvider.revertChanges()
155+
return true
156+
} catch (revertError) {
152157
console.error("Error reverting write_to_file diff view changes:", revertError)
153-
})
158+
return false
159+
}
154160
}
155161

156162
private async finalizePartialToolAskAfterFailure(task: Task, text?: string): Promise<void> {
@@ -179,15 +185,26 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
179185
if (!state) {
180186
return false
181187
}
182-
this.resetTaskPartialState(task)
183188
// Streaming may have opened the diff view with unapproved partial content.
184189
// execute() never runs on this path, so its error cleanup (revert + reset)
185190
// never fires: restore the document here so a user save cannot persist
186191
// content the write never completed (the same invariant the denial and
187-
// streaming-failure paths maintain). Both helpers no-op when no view is
188-
// open.
189-
await this.revertDiffChangesBeforeReset(task)
192+
// streaming-failure paths maintain). Both helpers no-op when no view is open.
193+
// The revert runs BEFORE the per-task state is torn down: when it fails, the
194+
// document can still hold that unapproved content, and the recovery state has
195+
// to exist while the outcome is decided and reported.
196+
const reverted = await this.revertDiffChangesBeforeReset(task)
197+
this.resetTaskPartialState(task)
190198
await this.resetDiffViewAfterWrite(task)
199+
if (!reverted) {
200+
// Do not report a completed teardown: the editor may still show content this
201+
// task never approved, and saving it would land a write the user never
202+
// authorized. The user has to be able to tell that from the UI.
203+
await task.say(
204+
"error",
205+
"write_to_file: the diff editor could not be restored after the failed tool call, so it may still show unapproved content. Do not save that editor.",
206+
)
207+
}
191208
if (!state.streamError) {
192209
return false
193210
}

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

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ interface CleanupTask {
1919
revertChanges: MockedFunction<() => Promise<void>>
2020
}
2121
finalizePartialToolAsk: MockedFunction<() => Promise<void>>
22+
say: MockedFunction<(...args: unknown[]) => Promise<void>>
2223
}
2324

2425
function buildTask(taskId: string, instanceId: string): Task {
@@ -32,6 +33,7 @@ function buildTask(taskId: string, instanceId: string): Task {
3233
revertChanges: vi.fn().mockResolvedValue(undefined),
3334
},
3435
finalizePartialToolAsk: vi.fn().mockResolvedValue(undefined),
36+
say: vi.fn().mockResolvedValue(undefined),
3537
}
3638
return task as unknown as Task
3739
}
@@ -87,8 +89,41 @@ describe("WriteToFileTool per-task partial-state cleanup", () => {
8789
expect(errorSpy).toHaveBeenCalledWith("Error reverting write_to_file diff view changes:", expect.any(Error))
8890
})
8991

92+
it("reverts while the recovery state exists and reports the hazard when the revert fails", async () => {
93+
const task = buildTask("revert-fails-teardown", "inst-5")
94+
const t = task as unknown as CleanupTask
95+
let stateSizeDuringRevert = -1
96+
t.diffViewProvider.revertChanges = vi.fn(async () => {
97+
// The recovery state must still be present while the rollback runs.
98+
stateSizeDuringRevert = writeToFileTool["taskPartialStreamState"].size
99+
throw new Error("revert failed")
100+
})
101+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
102+
// Seed the per-task stream state so this teardown boundary is taken at all.
103+
writeToFileTool["getTaskPartialStreamState"](task)
104+
expect(writeToFileTool["taskPartialStreamState"].size).toBe(1)
105+
106+
const handled = await writeToFileTool["onParameterParseFailure"](
107+
task,
108+
// Only handleError is reached when no streaming error was recorded; the
109+
// structural double is the existing pattern in this file.
110+
{ handleError: vi.fn().mockResolvedValue(undefined) } as unknown as Parameters<typeof writeToFileTool["onParameterParseFailure"]>[1],
111+
new Error("parameter parse failed"),
112+
)
113+
114+
// A failed rollback is not a completed teardown: the user is told the editor may
115+
// still hold content the task never approved.
116+
expect(t.say).toHaveBeenCalledWith("error", expect.stringContaining("unapproved"))
117+
expect(stateSizeDuringRevert).toBe(1)
118+
// The teardown still finished.
119+
expect(writeToFileTool["taskPartialStreamState"].size).toBe(0)
120+
expect(t.diffViewProvider.reset).toHaveBeenCalled()
121+
expect(handled).toBe(false)
122+
errorSpy.mockRestore()
123+
})
124+
90125
it("logs and continues when finalizing the open partial ask fails", async () => {
91-
const task = buildTask("finalize-fails", "inst-5")
126+
const task = buildTask("finalize-fails", "inst-6")
92127
const t = task as unknown as CleanupTask
93128
t.finalizePartialToolAsk = vi.fn().mockRejectedValue(new Error("finalize failed"))
94129
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})

0 commit comments

Comments
 (0)