Skip to content

Commit 2fa500a

Browse files
fix(write-to-file): close the parse-failure and post-commit teardown gaps
This is the U3 unit content re-based onto main's tip 73931fe (sha from ls-remote of upstream refs/heads/main at the moment of re-basing, not a rev-parse of a local ref), not merged into it. The parent is main, so this branch is an ancestor of main and the PR diff is the unit's own work: 10 paths, no merge commit, no 105-file refresh riding along. Why re-base rather than merge. The unit's nine spec hunks land inside src/integrations/editor/ __tests__/DiffViewProvider.spec.ts, which main rewrote onto its typed test harness (main's copy: 1780 lines, 71 titles, 0 'as any', 56 makeTextEditor calls; the branch's copy: 2670 lines, 99 titles, 293 'as any', 3 makeTextEditor calls). Merging forced the two harnesses to coexist; re-basing keeps main's helper form and ports the unit's assertions onto it, which is what main's rewrite asks for. What the port changed, so the diff is not a mystery: - The shared double builder gained a construction-time dirty flag: buildActiveDiffEditor(docOverrides) passes docOverrides.isDirty into makeTextDocument. The five tests that needed a dirty document now build one with buildActiveDiffEditor({ isDirty: true }) instead of writing editor.document.isDirty = true after the fact. That is main's own idiom for a dirty document (its spec passes { isDirty: true } into makeTextDocument, and its harness has no setter because the type's isDirty is readonly), and it is equivalent here: the double is not handed to the code under test until after the fixture lines, so no read of isDirty can observe the difference between constructed-dirty and made-dirty. - 29 'as any' casts on the branch's copy became bracket writes or typed doubles; the file now has 0. - The 5 remaining type errors from the merge attempt (TS2540 on the readonly isDirty) are gone. Verification on this head, all with the pinned pnpm 10.8.1 and hooks running: - eslint --max-warnings=0 --no-warn-ignored over all 10 paths: exit 0 each, with src/eslint-suppressions restored to main's blob and no --prune-suppressions, so the claim 'byte-identical to main's suppressions' is a diffed fact and not an inference. - pnpm --dir src exec tsc --noEmit: exit 0, 0 errors. - DiffViewProvider.spec.ts 99 passed (99) - all 99 branch titles survive, 0 lost; writeToFileTool.spec.ts 64 passed | 5 skipped (69); writeToFileTool-partial-state-cleanup.spec.ts 9 passed (9); removeClineFromStack-delegation.spec.ts 24 passed (24); ClineProvider.spec.ts 339 passed (339). Branch intent, unchanged by the port - read from the unit's own commit subjects: fail the approved save when document.save reports false (b97f68e), fail the rollback when the pre-stream restore edit is not applied (3daf338), fail the existing-file rollback when the revert edit or save reports false (23213ef), stop a post-commit failure from rolling back a landed write (2a9bfab), plus the parse-failure and post-commit teardown gaps (5adf7ec).
1 parent 73931fe commit 2fa500a

10 files changed

Lines changed: 3024 additions & 134 deletions

File tree

‎src/__tests__/removeClineFromStack-delegation.spec.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { ClineProvider } from "../core/webview/ClineProvider"
55
import { TaskRegistry } from "../core/task/TaskRegistry"
66
import { PendingActionSettlementError, type Task } from "../core/task/Task"
77
import { makeProviderStub } from "./helpers/provider-stub"
8+
import { writeToFileTool } from "../core/tools/WriteToFileTool"
89

910
type PrivateClineProviderMethods = {
1011
removeClineFromStack: (this: ClineProvider) => ReturnType<ClineProvider["removeClineFromStack"]>
@@ -202,6 +203,46 @@ describe("ClineProvider failed history restoration cleanup", () => {
202203
expect(task.dispose).toHaveBeenCalledOnce()
203204
})
204205

206+
it("releases the tool's per-task state before a directly disposed task loses its listeners", async () => {
207+
const key = "failed-history-task.inst-1"
208+
const order: string[] = []
209+
const task = {
210+
taskId: "failed-history-task",
211+
instanceId: "inst-1",
212+
emit: vi.fn(),
213+
once: vi.fn(),
214+
off: vi.fn(),
215+
dispose: vi.fn().mockImplementation(() => {
216+
// Dispose removes every listener, so this is the last moment the abort
217+
// cleanup could still have run; the entry must already be gone here.
218+
order.push(writeToFileTool["taskPartialStreamState"].has(key) ? "state-retained" : "state-cleared")
219+
order.push("dispose")
220+
return Promise.resolve()
221+
}),
222+
} as unknown as Task
223+
// Fixture: the state entry the tool would have created during a partial stream.
224+
writeToFileTool["taskPartialStreamState"].set(key, {
225+
lastSeenPartialPath: undefined,
226+
streamFailed: false,
227+
streamError: undefined,
228+
task,
229+
abortCleanup: () => {},
230+
})
231+
const taskEventListeners = new Map([[task, [vi.fn()]]])
232+
const taskRegistry = new TaskRegistry()
233+
taskRegistry.push(task)
234+
const provider = { taskRegistry, taskEventListeners, log: vi.fn() } as unknown as ClineProvider
235+
236+
await privateClineProvider.cleanupFailedHistoryTask.call(
237+
provider,
238+
task,
239+
new PendingActionSettlementError("settlement failed"),
240+
)
241+
242+
expect(order).toEqual(["state-cleared", "dispose"])
243+
expect(writeToFileTool["taskPartialStreamState"].size).toBe(0)
244+
})
245+
205246
it("keeps the task active after an unrelated history resume failure", async () => {
206247
const cleanupListener = vi.fn()
207248
const task = {

‎src/core/assistant-message/presentAssistantMessage.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -577,15 +577,34 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request
577577
// Best-effort only
578578
}
579579

580+
// A streaming delta may have captured a fatal filesystem error for this task.
581+
// handle() never runs on this path, and clearTaskState() (below) releases the
582+
// state holding it, so the model must learn about it from this single result.
583+
const retainedStreamError =
584+
block.name === "write_to_file" ? writeToFileTool.getRetainedStreamError(cline) : undefined
585+
const reportedMessage = retainedStreamError
586+
? `${retainedStreamError.message}\n${errorMessage}`
587+
: errorMessage
588+
580589
// Push tool_result directly without setting didAlreadyUseTool so streaming can
581590
// continue gracefully.
582591
cline.pushToolResultToUserContent({
583592
type: "tool_result",
584593
tool_use_id: sanitizeToolUseId(toolCallId),
585-
content: formatResponse.toolError(errorMessage),
594+
content: formatResponse.toolError(reportedMessage),
586595
is_error: true,
587596
})
588597

598+
// handle() is never reached on this path, so the parse-failure teardown it
599+
// performs must run here instead: a streaming delta may already have opened a
600+
// partial write_to_file ask and left per-task failure state behind.
601+
if (block.name === "write_to_file") {
602+
writeToFileTool.clearTaskState(cline)
603+
await cline.finalizePartialToolAsk().catch((finalizeError) => {
604+
console.error("Error finalizing write_to_file partial ask:", finalizeError)
605+
})
606+
}
607+
589608
break
590609
}
591610
}

‎src/core/tools/BaseTool.ts‎

Lines changed: 40 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,27 @@ 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(
200+
_task: Task,
201+
_callbacks: ToolCallbacks,
202+
_parseError: Error,
203+
): Promise<boolean> {
204+
return false
205+
}
169206
}

0 commit comments

Comments
 (0)