Skip to content

Commit e3c1040

Browse files
feat(tools): onParameterParseFailure teardown boundary
1 parent 4b23b6a commit e3c1040

3 files changed

Lines changed: 250 additions & 3 deletions

File tree

‎src/core/tools/BaseTool.ts‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,9 +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)
159-
const errorMessage = `Failed to parse ${this.name} parameters: ${error instanceof Error ? error.message : String(error)}`
160-
await callbacks.handleError(`parsing ${this.name} args`, new Error(errorMessage))
158+
const parseError = error instanceof Error ? error : new Error(String(error))
159+
console.error(`Error parsing parameters:`, parseError)
160+
// Final args could not be parsed (e.g. the model's tool call was truncated
161+
// mid-JSON by the output token limit), so execute() will never run. If a
162+
// streaming delta already opened a partial "tool" ask (partial: true),
163+
// finalize it here or the webview spinner stays stuck indefinitely.
164+
await task.finalizePartialToolAsk().catch((finalizeError) => {
165+
console.error(`Error finalizing ${this.name} partial tool ask:`, finalizeError)
166+
})
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+
}
161175
// Note: handleError already emits a tool_result via formatResponse.toolError in the caller.
162176
// Do NOT call pushToolResult here to avoid duplicate tool_result payloads.
163177
return
@@ -166,4 +180,23 @@ export abstract class BaseTool<TName extends ToolName> {
166180
// Execute with typed parameters
167181
await this.execute(params, task, callbacks)
168182
}
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+
}
169202
}

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,28 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
174174
* "writing file" context execute()'s catch uses, and suppress the incidental
175175
* parse error.
176176
*/
177+
override async onParameterParseFailure(task: Task, callbacks: ToolCallbacks, parseError: Error): Promise<boolean> {
178+
const state = this.taskPartialStreamState.get(this.getPartialStreamFailureKey(task))
179+
if (!state) {
180+
return false
181+
}
182+
this.resetTaskPartialState(task)
183+
// Streaming may have opened the diff view with unapproved partial content.
184+
// execute() never runs on this path, so its error cleanup (revert + reset)
185+
// never fires: restore the document here so a user save cannot persist
186+
// 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)
190+
await this.resetDiffViewAfterWrite(task)
191+
if (!state.streamError) {
192+
return false
193+
}
194+
void parseError
195+
await callbacks.handleError("writing file", state.streamError)
196+
return true
197+
}
198+
177199
override resetPartialState(): void {
178200
super.resetPartialState()
179201
for (const state of this.taskPartialStreamState.values()) {

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

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,7 +541,123 @@ describe("writeToFileTool", () => {
541541
}
542542
})
543543

544+
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 () => {
545+
// A streaming delta fails with a filesystem error (streamFailed + streamError are
546+
// captured). The final block then arrives without nativeArgs, so execute() never
547+
// runs: the parse-failure teardown boundary must report the original filesystem
548+
// error under the "writing file" context (not the incidental parse error) and tear
549+
// down the per-task state, so the next write_to_file stream in this task is not
550+
// blocked by the stale streamFailed guard and no abort listener leaks.
551+
const fsError = new Error("EACCES: permission denied")
552+
mockCline.diffViewProvider.open.mockRejectedValue(fsError)
553+
// Capture the abort listener of the state created by the first deltas: it is the
554+
// exact reference that the parse-failure teardown must detach.
555+
let abortListener: (() => void) | undefined
556+
mockCline.once.mockImplementation((event: RooCodeEventName, listener: () => void) => {
557+
if (event === RooCodeEventName.TaskAborted && abortListener === undefined) {
558+
abortListener = listener
559+
}
560+
return mockCline
561+
})
562+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
563+
try {
564+
await executeWriteFileTool({}, { isPartial: true })
565+
await executeWriteFileTool({}, { isPartial: true })
544566

567+
const toolUse: ToolUse = {
568+
type: "tool_use",
569+
name: "write_to_file",
570+
params: { path: testFilePath, content: testContent },
571+
nativeArgs: undefined,
572+
partial: false,
573+
}
574+
await writeToFileTool.handle(mockCline, toolUse as ToolUse<"write_to_file">, {
575+
askApproval: mockAskApproval,
576+
handleError: mockHandleError,
577+
pushToolResult: vi.fn(),
578+
})
579+
580+
expect(mockHandleError).toHaveBeenCalledTimes(1)
581+
expect(mockHandleError).toHaveBeenCalledWith("writing file", fsError)
582+
expect(mockHandleError).not.toHaveBeenCalledWith(
583+
expect.stringContaining("parsing write_to_file"),
584+
expect.anything(),
585+
)
586+
// The parse-failure teardown also restores the diff document: the
587+
// streaming failure above already reverted it once (revert + reset),
588+
// and the parse path runs the same cleanup again because execute()
589+
// never runs on this path.
590+
expect(mockCline.diffViewProvider.revertChanges).toHaveBeenCalledTimes(2)
591+
expect(mockCline.diffViewProvider.reset).toHaveBeenCalledTimes(2)
592+
// Per-task state torn down at this boundary: guard cleared, the exact
593+
// registered abort listener detached.
594+
expect(writeToFileTool["taskPartialStreamState"].size).toBe(0)
595+
expect(abortListener).toBeTypeOf("function")
596+
expect(mockCline.off).toHaveBeenCalledWith(RooCodeEventName.TaskAborted, abortListener)
597+
598+
// The next stream for the same task must issue a partial ask again (the stale
599+
// streamFailed guard is gone).
600+
mockCline.diffViewProvider.open.mockResolvedValue(undefined)
601+
await executeWriteFileTool({}, { isPartial: true })
602+
await executeWriteFileTool({}, { isPartial: true })
603+
expect(mockCline.ask).toHaveBeenCalledTimes(2)
604+
} finally {
605+
consoleErrorSpy.mockRestore()
606+
}
607+
})
608+
609+
it("restores the diff document when the final block fails to parse after successful streaming", async () => {
610+
// Streaming opened the diff view with unapproved partial content (open and
611+
// update both succeeded, so no streaming error was captured). The final block
612+
// then arrives without nativeArgs: execute() never runs, so its error cleanup
613+
// never fires. The parse-failure teardown must still restore the document
614+
// (revert before reset) or a user save could persist content the write never
615+
// completed, and must report the generic parse error (no streaming error to
616+
// surface instead).
617+
let abortListener: (() => void) | undefined
618+
mockCline.once.mockImplementation((event: RooCodeEventName, listener: () => void) => {
619+
if (event === RooCodeEventName.TaskAborted && abortListener === undefined) {
620+
abortListener = listener
621+
}
622+
return mockCline
623+
})
624+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
625+
try {
626+
// Delta 1 - stabilize path; delta 2 - streams the partial content into the
627+
// diff view (open + update resolve).
628+
await executeWriteFileTool({}, { isPartial: true })
629+
await executeWriteFileTool({}, { isPartial: true })
630+
expect(mockCline.diffViewProvider.open).toHaveBeenCalledTimes(1)
631+
expect(mockCline.diffViewProvider.update).toHaveBeenCalledTimes(1)
632+
633+
const toolUse: ToolUse = {
634+
type: "tool_use",
635+
name: "write_to_file",
636+
params: { path: testFilePath, content: testContent },
637+
nativeArgs: undefined,
638+
partial: false,
639+
}
640+
await writeToFileTool.handle(mockCline, toolUse as ToolUse<"write_to_file">, {
641+
askApproval: mockAskApproval,
642+
handleError: mockHandleError,
643+
pushToolResult: vi.fn(),
644+
})
645+
646+
// No streaming error was captured: the generic parse error is reported.
647+
expect(mockHandleError).toHaveBeenCalledTimes(1)
648+
expect(mockHandleError).toHaveBeenCalledWith("parsing write_to_file args", expect.any(Error))
649+
// The diff document is restored by the parse path itself (no streaming
650+
// failure happened, so this is the only revert + reset in the test).
651+
expect(mockCline.diffViewProvider.revertChanges).toHaveBeenCalledTimes(1)
652+
expect(mockCline.diffViewProvider.reset).toHaveBeenCalledTimes(1)
653+
// Per-task state torn down: guard cleared, exact listener detached.
654+
expect(writeToFileTool["taskPartialStreamState"].size).toBe(0)
655+
expect(abortListener).toBeTypeOf("function")
656+
expect(mockCline.off).toHaveBeenCalledWith(RooCodeEventName.TaskAborted, abortListener)
657+
} finally {
658+
consoleErrorSpy.mockRestore()
659+
}
660+
})
545661
})
546662

547663
describe("path stabilization predicate", () => {
@@ -755,7 +871,83 @@ describe("writeToFileTool", () => {
755871
expect(mockCline.diffViewProvider.open).toHaveBeenCalledTimes(1)
756872
})
757873

874+
it("finalizes any open partial tool ask when final args cannot be parsed", async () => {
875+
// Regression test: a write_to_file block whose final args fail to parse (e.g. the
876+
// tool call was truncated mid-JSON by the output token limit) never reaches
877+
// execute(). A streaming delta for that block may already have opened a partial
878+
// `tool` ask (partial: true) -- BaseTool.handle must finalize it, otherwise the
879+
// UI spinner stays stuck even though the parse error bubble was shown.
880+
// Delta 1 - stabilize path (no ask yet)
881+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
882+
// Delta 2 - path stabilized, partial ask issued once
883+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
884+
expect(mockCline.ask).toHaveBeenCalledTimes(1)
885+
expect(mockCline.finalizePartialToolAsk).not.toHaveBeenCalled()
758886

887+
// Final block arrives but its native args cannot be parsed, so execute() is skipped.
888+
const toolUse: ToolUse = {
889+
type: "tool_use",
890+
name: "write_to_file",
891+
params: {
892+
path: testFilePath,
893+
content: testContent,
894+
},
895+
partial: false,
896+
}
897+
await writeToFileTool.handle(mockCline, toolUse as ToolUse<"write_to_file">, {
898+
askApproval: mockAskApproval,
899+
handleError: mockHandleError,
900+
pushToolResult: mockPushToolResult,
901+
})
902+
903+
// The parse error is still reported, and the open partial ask is finalized first.
904+
// No argument: BaseTool.handle() calls finalizePartialToolAsk() with no text, so a
905+
// mutation passing wrong text would leave findLast() unmatched and the spinner
906+
// stuck. (toHaveBeenCalledWith(undefined) does not match a no-arg call under
907+
// vitest's matcher semantics: [] is not equal to [undefined].)
908+
expect(mockCline.finalizePartialToolAsk).toHaveBeenCalledTimes(1)
909+
expect(mockCline.finalizePartialToolAsk).toHaveBeenCalledWith()
910+
expect(mockHandleError).toHaveBeenCalledWith("parsing write_to_file args", expect.any(Error))
911+
})
912+
913+
it("continues parse failure cleanup when finalizing the partial ask fails", async () => {
914+
// Pins the .catch arm on task.finalizePartialToolAsk() in BaseTool.handle(): when the
915+
// final args cannot be parsed and finalizing the open partial ask also fails, the
916+
// failure must only be logged so the parse error is still reported to the user.
917+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
918+
try {
919+
mockCline.finalizePartialToolAsk.mockRejectedValue(new Error("finalize failed"))
920+
921+
// Final block arrives but its native args cannot be parsed, so execute() is skipped.
922+
const toolUse: ToolUse = {
923+
type: "tool_use",
924+
name: "write_to_file",
925+
params: {
926+
path: testFilePath,
927+
content: testContent,
928+
},
929+
partial: false,
930+
}
931+
await writeToFileTool.handle(mockCline, toolUse as ToolUse<"write_to_file">, {
932+
askApproval: mockAskApproval,
933+
handleError: mockHandleError,
934+
pushToolResult: vi.fn(),
935+
})
936+
937+
// Same no-argument contract as the sibling test above: the finalize call in
938+
// BaseTool.handle() carries no text.
939+
expect(mockCline.finalizePartialToolAsk).toHaveBeenCalledTimes(1)
940+
expect(mockCline.finalizePartialToolAsk).toHaveBeenCalledWith()
941+
expect(consoleErrorSpy).toHaveBeenCalledWith(
942+
"Error finalizing write_to_file partial tool ask:",
943+
expect.any(Error),
944+
)
945+
// The parse error is still reported despite the failed finalization.
946+
expect(mockHandleError).toHaveBeenCalledWith("parsing write_to_file args", expect.any(Error))
947+
} finally {
948+
consoleErrorSpy.mockRestore()
949+
}
950+
})
759951

760952

761953

0 commit comments

Comments
 (0)