Skip to content

Commit a704b15

Browse files
committed
fix(write_to_file): report captured streaming error on parse failure; clear provider state on prevent-focus denial
Address two CodeRabbit findings on the merged head: - BaseTool.handle(): when nativeArgs are missing or malformed, execute() never runs, so per-task state registered outside execute() was never torn down. Add the onParameterParseFailure() teardown boundary; WriteToFileTool overrides it to report the captured streaming filesystem error under the "writing file" context (suppressing the incidental parse error) and to clear the per-task state (streamFailed guard + abort listener). - WriteToFileTool.execute(): the prevent-focus branch stamped editType/originalContent on the provider before asking; on denial it now resets the provider state so a later write re-checks the file system instead of reusing the stale editType. Adds regression tests for both paths.
1 parent b9e2bda commit a704b15

3 files changed

Lines changed: 137 additions & 4 deletions

File tree

‎src/core/tools/BaseTool.ts‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,16 +155,23 @@ export abstract class BaseTool<TName extends ToolName> {
155155
throw new Error("Tool call is missing native arguments (nativeArgs).")
156156
}
157157
} catch (error) {
158-
console.error(`Error parsing parameters:`, error)
158+
const parseError = error instanceof Error ? error : new Error(String(error))
159+
console.error(`Error parsing parameters:`, parseError)
159160
// Final args could not be parsed (e.g. the model's tool call was truncated
160161
// mid-JSON by the output token limit), so execute() will never run. If a
161162
// streaming delta already opened a partial "tool" ask (partial: true),
162163
// finalize it here or the webview spinner stays stuck indefinitely.
163164
await task.finalizePartialToolAsk().catch((finalizeError) => {
164165
console.error(`Error finalizing ${this.name} partial tool ask:`, finalizeError)
165166
})
166-
const errorMessage = `Failed to parse ${this.name} parameters: ${error instanceof Error ? error.message : String(error)}`
167-
await callbacks.handleError(`parsing ${this.name} args`, new Error(errorMessage))
167+
// execute() never runs on this path, so tools that keep per-task state
168+
// outside execute() (streaming failure marks, abort listeners) get their
169+
// one remaining teardown boundary here.
170+
const reportedStreamingFailure = await this.onParameterParseFailure(task, callbacks, parseError)
171+
if (!reportedStreamingFailure) {
172+
const errorMessage = `Failed to parse ${this.name} parameters: ${parseError.message}`
173+
await callbacks.handleError(`parsing ${this.name} args`, new Error(errorMessage))
174+
}
168175
// Note: handleError already emits a tool_result via formatResponse.toolError in the caller.
169176
// Do NOT call pushToolResult here to avoid duplicate tool_result payloads.
170177
return
@@ -173,4 +180,23 @@ export abstract class BaseTool<TName extends ToolName> {
173180
// Execute with typed parameters
174181
await this.execute(params, task, callbacks)
175182
}
183+
184+
/**
185+
* Teardown boundary for the native-argument parse-failure path in handle().
186+
*
187+
* When nativeArgs are missing or malformed, execute() never runs, so per-task
188+
* state a tool registered outside execute() (streaming failure marks, abort
189+
* listeners) is never torn down there. Streaming tools override this to tear
190+
* that state down and, when a streaming delta already failed, to report the
191+
* captured streaming error instead of the generic parse error.
192+
*
193+
* @param task - Task instance
194+
* @param callbacks - Tool execution callbacks
195+
* @param parseError - The native-argument parse error
196+
* @returns true when the override already reported the failure to the user,
197+
* so handle() suppresses the generic parse error
198+
*/
199+
protected async onParameterParseFailure(task: Task, callbacks: ToolCallbacks, parseError: Error): Promise<boolean> {
200+
return false
201+
}
176202
}

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ interface TaskPartialStreamState {
3131
lastSeenPartialPath: string | undefined
3232
/** True once a streaming delta hit a fatal filesystem error. */
3333
streamFailed: boolean
34+
/** The original filesystem error of the failed streaming delta, reported once
35+
* by onParameterParseFailure() when the final block fails to parse (so
36+
* execute() never runs and would never report it). */
37+
streamError: Error | undefined
3438
/** The task that owns this state; target for abort-listener deregistration. */
3539
task: Task
3640
/** TaskAborted listener that tears this state down; registered once per task. */
@@ -89,6 +93,7 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
8993
const state: TaskPartialStreamState = {
9094
lastSeenPartialPath: undefined,
9195
streamFailed: false,
96+
streamError: undefined,
9297
task,
9398
abortCleanup: () => this.resetTaskPartialState(task),
9499
}
@@ -144,6 +149,31 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
144149
})
145150
}
146151

152+
/**
153+
* Teardown boundary for the handle() parse-failure path, where execute() never
154+
* runs and therefore its finally (resetTaskPartialState) never runs either.
155+
*
156+
* Tears down the per-task stream state: otherwise the abort listener leaks for
157+
* the task's lifetime, and when a streaming delta had failed, the streamFailed
158+
* guard would suppress the diff preview of every later write_to_file in this
159+
* task. When a streaming delta already hit a fatal filesystem error, that error
160+
* is what the user can act on, so report it with the same "writing file"
161+
* context execute()'s catch uses, and suppress the incidental parse error.
162+
*/
163+
override async onParameterParseFailure(task: Task, callbacks: ToolCallbacks, parseError: Error): Promise<boolean> {
164+
const state = this.taskPartialStreamState.get(this.getPartialStreamFailureKey(task))
165+
if (!state) {
166+
return false
167+
}
168+
this.resetTaskPartialState(task)
169+
if (!state.streamError) {
170+
return false
171+
}
172+
void parseError
173+
await callbacks.handleError("writing file", state.streamError)
174+
return true
175+
}
176+
147177
override resetPartialState(): void {
148178
super.resetPartialState()
149179
for (const state of this.taskPartialStreamState.values()) {
@@ -287,6 +317,12 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
287317
const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected)
288318

289319
if (!didApprove) {
320+
// The prevent-focus branch set editType/originalContent on the provider
321+
// before asking. Clear them on denial (no diff document was opened in
322+
// this branch, so reset() is sufficient; the non-prevent-focus denial
323+
// branch resets through revertChanges()), so a later write re-checks
324+
// the file system instead of reusing the stale editType.
325+
await this.resetDiffViewAfterWrite(task)
290326
return
291327
}
292328

@@ -444,8 +480,11 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
444480
// the non-partial block arrives (it does not depend on this throw).
445481
console.error(`Error streaming write_to_file diff view:`, error)
446482
// Mark the stream as failed so later deltas don't re-attempt and spawn a new
447-
// partial tool message each time.
483+
// partial tool message each time. Retain the original error: if the final
484+
// block later fails to parse, execute() never runs and only
485+
// onParameterParseFailure() can report this failure to the user.
448486
partialStreamState.streamFailed = true
487+
partialStreamState.streamError = error instanceof Error ? error : new Error(String(error))
449488
await this.finalizePartialToolAskAfterFailure(task, partialMessage)
450489
// The write was never approved: restore the document so a user save cannot
451490
// persist the failed streamed content (reset() alone leaves it dirty).

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

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -715,6 +715,54 @@ describe("writeToFileTool", () => {
715715
consoleErrorSpy.mockRestore()
716716
}
717717
})
718+
719+
it("reports the captured streaming error instead of the parse error when the final block fails to parse, and clears the per-task state", async () => {
720+
// A streaming delta fails with a filesystem error (streamFailed + streamError are
721+
// captured). The final block then arrives without nativeArgs, so execute() never
722+
// runs: the parse-failure teardown boundary must report the original filesystem
723+
// error under the "writing file" context (not the incidental parse error) and tear
724+
// down the per-task state, so the next write_to_file stream in this task is not
725+
// blocked by the stale streamFailed guard and no abort listener leaks.
726+
const fsError = new Error("EACCES: permission denied")
727+
mockCline.diffViewProvider.open.mockRejectedValue(fsError)
728+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
729+
try {
730+
await executeWriteFileTool({}, { isPartial: true })
731+
await executeWriteFileTool({}, { isPartial: true })
732+
733+
const toolUse: ToolUse = {
734+
type: "tool_use",
735+
name: "write_to_file",
736+
params: { path: testFilePath, content: testContent },
737+
nativeArgs: undefined,
738+
partial: false,
739+
}
740+
await writeToFileTool.handle(mockCline, toolUse as ToolUse<"write_to_file">, {
741+
askApproval: mockAskApproval,
742+
handleError: mockHandleError,
743+
pushToolResult: vi.fn(),
744+
})
745+
746+
expect(mockHandleError).toHaveBeenCalledTimes(1)
747+
expect(mockHandleError).toHaveBeenCalledWith("writing file", fsError)
748+
expect(mockHandleError).not.toHaveBeenCalledWith(
749+
expect.stringContaining("parsing write_to_file"),
750+
expect.anything(),
751+
)
752+
// Per-task state torn down at this boundary: guard cleared, listener detached.
753+
expect(writeToFileTool["taskPartialStreamState"].size).toBe(0)
754+
expect(mockCline.off).toHaveBeenCalledWith(RooCodeEventName.TaskAborted, expect.any(Function))
755+
756+
// The next stream for the same task must issue a partial ask again (the stale
757+
// streamFailed guard is gone).
758+
mockCline.diffViewProvider.open.mockResolvedValue(undefined)
759+
await executeWriteFileTool({}, { isPartial: true })
760+
await executeWriteFileTool({}, { isPartial: true })
761+
expect(mockCline.ask).toHaveBeenCalledTimes(2)
762+
} finally {
763+
consoleErrorSpy.mockRestore()
764+
}
765+
})
718766
})
719767

720768
describe("path stabilization predicate", () => {
@@ -725,6 +773,7 @@ describe("writeToFileTool", () => {
725773
return {
726774
lastSeenPartialPath,
727775
streamFailed: false,
776+
streamError: undefined,
728777
task: mockCline,
729778
abortCleanup: () => {},
730779
}
@@ -1388,5 +1437,24 @@ describe("writeToFileTool", () => {
13881437
expect(mockCline.diffViewProvider.open).not.toHaveBeenCalled()
13891438
expect(mockCline.diffViewProvider.update).not.toHaveBeenCalled()
13901439
})
1440+
1441+
it("clears the provider state when prevent-focus approval is denied", async () => {
1442+
// The prevent-focus branch stamps editType/originalContent on the provider before
1443+
// asking. On denial nothing was approved and no diff document was opened, so the
1444+
// provider state must be cleared (reset) to make a later write re-check the file
1445+
// system instead of reusing the stale editType. The non-prevent-focus denial branch
1446+
// resets through revertChanges(); this branch must not call it (no document to
1447+
// revert).
1448+
enablePreventFocusDisruption()
1449+
mockAskApproval.mockResolvedValue(false)
1450+
1451+
await executeWriteFileTool({}, { fileExists: false })
1452+
1453+
expect(mockAskApproval).toHaveBeenCalledTimes(1)
1454+
expect(mockCline.diffViewProvider.saveDirectly).not.toHaveBeenCalled()
1455+
expect(mockCline.diffViewProvider.reset).toHaveBeenCalledTimes(1)
1456+
expect(mockCline.diffViewProvider.revertChanges).not.toHaveBeenCalled()
1457+
expect(mockCline.didEditFile).toBe(false)
1458+
})
13911459
})
13921460
})

0 commit comments

Comments
 (0)