Skip to content

Commit feedc5d

Browse files
author
easonLiangWorldedtech
committed
fix(write-to-file): capture streaming failure once, report it once
1 parent 9d78a76 commit feedc5d

2 files changed

Lines changed: 267 additions & 16 deletions

File tree

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,14 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
353353
const relPath: string | undefined = block.params.path
354354
const newContent: string | undefined = block.params.content
355355

356+
const partialStreamFailureKey = this.getPartialStreamFailureKey(task)
357+
358+
// A prior streaming delta for this task already hit a fatal filesystem error.
359+
// Skip further streaming work so we don't create a new partial tool message on every
360+
// subsequent delta. execute() will report the error once when the block completes.
361+
if (this.taskPartialStreamState.get(partialStreamFailureKey)?.streamFailed) {
362+
return
363+
}
356364

357365
// Get (or create) this task's state; registers the TaskAborted teardown listener
358366
// once, so abandoned streams are torn down even if execute() never runs.
@@ -385,12 +393,6 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
385393
task.diffViewProvider.editType = fileExists ? "modify" : "create"
386394
}
387395

388-
// Create parent directories early for new files to prevent ENOENT errors
389-
// in subsequent operations (e.g., diffViewProvider.open)
390-
if (!fileExists) {
391-
await createDirectoriesForFile(absolutePath)
392-
}
393-
394396
const isWriteProtected = task.rooProtectedController?.isWriteProtected(relPath!) || false
395397
const isOutsideWorkspace = isPathOutsideWorkspace(absolutePath)
396398

@@ -406,14 +408,37 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
406408
await task.ask("tool", partialMessage, block.partial).catch(() => {})
407409

408410
if (newContent) {
409-
if (!task.diffViewProvider.isEditing) {
410-
await task.diffViewProvider.open(relPath!)
411-
}
411+
try {
412+
if (!task.diffViewProvider.isEditing) {
413+
await task.diffViewProvider.open(relPath!)
414+
}
412415

413-
await task.diffViewProvider.update(
414-
everyLineHasLineNumbers(newContent) ? stripLineNumbers(newContent) : newContent,
415-
false,
416-
)
416+
await task.diffViewProvider.update(
417+
everyLineHasLineNumbers(newContent) ? stripLineNumbers(newContent) : newContent,
418+
false,
419+
)
420+
} catch (error) {
421+
// Opening or updating the diff view can throw on filesystem errors
422+
// (EACCES/EROFS on read-only paths). Finalize the partial tool message
423+
// so the UI spinner doesn't get stuck and reset the diff view. Do NOT
424+
// rethrow: the same filesystem operation is retried in execute() once the
425+
// block completes, and that authoritative non-partial path reports the
426+
// error to the user. Surfacing it here too would show the same error twice.
427+
// Swallowing it here is safe because the agent loop advances naturally when
428+
// the non-partial block arrives (it does not depend on this throw).
429+
console.error(`Error streaming write_to_file diff view:`, error)
430+
// Mark the stream as failed so later deltas don't re-attempt and spawn a new
431+
// partial tool message each time. Retain the original error: if the final
432+
// block later fails to parse, execute() never runs and only
433+
// onParameterParseFailure() can report this failure to the user.
434+
partialStreamState.streamFailed = true
435+
partialStreamState.streamError = error instanceof Error ? error : new Error(String(error))
436+
await this.finalizePartialToolAskAfterFailure(task, partialMessage)
437+
// The write was never approved: restore the document so a user save cannot
438+
// persist the failed streamed content (reset() alone leaves it dirty).
439+
await this.revertDiffChangesBeforeReset(task)
440+
await this.resetDiffViewAfterWrite(task)
441+
}
417442
}
418443
}
419444
}

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

Lines changed: 229 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,19 @@ describe("writeToFileTool", () => {
9797
const testContent = "Line 1\nLine 2\nLine 3"
9898
const testContentWithMarkdown = "```javascript\nLine 1\nLine 2\n```"
9999

100+
// The exact payload handlePartial() streams as the partial `tool` ask for the default
101+
// test scenario (new file, readable path, in-workspace, not write-protected).
102+
// finalizePartialToolAsk() no-ops on a text mismatch, so finalize assertions must
103+
// match this exactly: a weaker matcher (e.g. expect.any(String), which a relPath also
104+
// satisfies) would pass a mutant that passes the wrong text and leaves the spinner stuck.
105+
const expectedPartialToolMessage = JSON.stringify({
106+
tool: "newFileCreated",
107+
path: "test/path.txt",
108+
content: testContent,
109+
isOutsideWorkspace: false,
110+
isProtected: false,
111+
})
112+
100113
// Mocked functions with correct types
101114
const mockedFileExistsAtPath = fileExistsAtPath as MockedFunction<typeof fileExistsAtPath>
102115
const mockedCreateDirectoriesForFile = createDirectoriesForFile as MockedFunction<typeof createDirectoriesForFile>
@@ -429,6 +442,25 @@ describe("writeToFileTool", () => {
429442
expect(mockCline.diffViewProvider.open).toHaveBeenCalledWith(testFilePath)
430443
expect(mockCline.diffViewProvider.update).toHaveBeenCalledWith(testContent, false)
431444
})
445+
it("does not share path stabilization between tasks with the same path", async () => {
446+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
447+
expect(mockCline.ask).not.toHaveBeenCalled()
448+
449+
mockCline.taskId = "task-2"
450+
mockCline.instanceId = "instance-2"
451+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
452+
expect(mockCline.ask).not.toHaveBeenCalled()
453+
454+
mockCline.taskId = "task-1"
455+
mockCline.instanceId = "instance-1"
456+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
457+
expect(mockCline.ask).toHaveBeenCalledTimes(1)
458+
459+
mockCline.taskId = "task-2"
460+
mockCline.instanceId = "instance-2"
461+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
462+
expect(mockCline.ask).toHaveBeenCalledTimes(2)
463+
})
432464

433465
it("cleans per-task partial state when the task aborts before execute finalization", async () => {
434466
let abortCleanup: (() => void) | undefined
@@ -465,8 +497,49 @@ describe("writeToFileTool", () => {
465497
expect(mockCline.diffViewProvider.open).not.toHaveBeenCalled()
466498
})
467499

500+
it("does not issue a partial ask when content is undefined after path stabilization", async () => {
501+
// Delta 1 stabilizes the path. Delta 2 repeats it but carries no content yet: the
502+
// `newContent === undefined` clause must short-circuit the ask even though the path itself has
503+
// stabilized.
504+
await executeWriteFileTool({}, { isPartial: true })
505+
await executeWriteFileTool({ content: undefined }, { isPartial: true })
506+
507+
expect(mockCline.ask).not.toHaveBeenCalled()
508+
expect(mockCline.diffViewProvider.update).not.toHaveBeenCalled()
509+
})
510+
511+
it("does not reopen an already open diff view during streaming", async () => {
512+
// The diff view is already open for this task (isEditing). A stabilized delta must still update
513+
// the streamed content but must not call open() again -- reopening would discard the view's
514+
// current state.
515+
mockCline.diffViewProvider.isEditing = true
468516

517+
await executeWriteFileTool({}, { isPartial: true })
518+
await executeWriteFileTool({}, { isPartial: true })
519+
520+
expect(mockCline.ask).toHaveBeenCalledTimes(1)
521+
expect(mockCline.diffViewProvider.open).not.toHaveBeenCalled()
522+
expect(mockCline.diffViewProvider.update).toHaveBeenCalledWith(testContent, false)
523+
})
469524

525+
it("logs the streaming diff view failure with the write_to_file context", async () => {
526+
// The catch arm logs a context-specific message before swallowing the error (execute() reports
527+
// the authoritative one). The message must keep the write_to_file context so the log is
528+
// actionable.
529+
mockCline.diffViewProvider.open.mockRejectedValue(new Error("EACCES: permission denied"))
530+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
531+
try {
532+
await executeWriteFileTool({}, { isPartial: true })
533+
await executeWriteFileTool({}, { isPartial: true })
534+
535+
expect(consoleErrorSpy).toHaveBeenCalledWith(
536+
"Error streaming write_to_file diff view:",
537+
expect.anything(),
538+
)
539+
} finally {
540+
consoleErrorSpy.mockRestore()
541+
}
542+
})
470543

471544

472545
})
@@ -575,17 +648,170 @@ describe("writeToFileTool", () => {
575648
expect(mockCline.diffViewProvider.reset).toHaveBeenCalled()
576649
})
577650

578-
it("handles partial streaming errors after path stabilizes", async () => {
651+
652+
653+
it("swallows partial streaming errors instead of surfacing a duplicate error bubble", async () => {
654+
// The same filesystem operation is retried in execute() once the block completes,
655+
// and that authoritative non-partial path reports the error to the user. Surfacing
656+
// it during streaming too would show the same error twice, so handlePartial must NOT
657+
// route streaming errors through handleError.
579658
mockCline.diffViewProvider.open.mockRejectedValue(new Error("Open failed"))
580659

581660
// First call - path not yet stabilized, no error yet
582661
await executeWriteFileTool({}, { isPartial: true })
583662
expect(mockHandleError).not.toHaveBeenCalled()
584663

585-
// Second call with same path - path is now stabilized, error occurs
664+
// Second call with same path - path is now stabilized, error occurs but is swallowed
665+
await executeWriteFileTool({}, { isPartial: true })
666+
expect(mockHandleError).not.toHaveBeenCalled()
667+
})
668+
669+
it("finalizes partial tool message and resets diff view when handlePartial open() fails", async () => {
670+
// Regression test: when diffViewProvider.open() throws during streaming (e.g. EACCES/EROFS
671+
// on a read-only path), the partial tool ask created at the top of handlePartial leaves the
672+
// UI spinner stuck. handlePartial must finalize the partial message and reset the diff view,
673+
// and must NOT surface a duplicate error (execute() reports the authoritative one).
674+
mockCline.diffViewProvider.open.mockRejectedValue(
675+
Object.assign(new Error("EACCES: permission denied, open '/ro/test.py'"), { code: "EACCES" }),
676+
)
677+
// Record the relative order of revertChanges() and reset() (vitest mocks expose
678+
// no invocationCallOrder).
679+
const diffViewCallOrder: string[] = []
680+
mockCline.diffViewProvider.revertChanges.mockImplementation(async () => {
681+
diffViewCallOrder.push("revert")
682+
})
683+
mockCline.diffViewProvider.reset.mockImplementation(async () => {
684+
diffViewCallOrder.push("reset")
685+
})
686+
687+
// First call - path not yet stabilized
586688
await executeWriteFileTool({}, { isPartial: true })
587-
expect(mockHandleError).toHaveBeenCalledWith("handling partial write_to_file", expect.any(Error))
689+
expect(mockCline.finalizePartialToolAsk).not.toHaveBeenCalled()
588690

691+
// Second call - path stabilized, open() rejects
692+
await executeWriteFileTool({}, { isPartial: true })
693+
694+
// Exact streamed payload: finalizePartialToolAsk() no-ops on a text mismatch, so
695+
// a wrong argument (e.g. relPath) would leave the spinner stuck.
696+
expect(mockCline.finalizePartialToolAsk).toHaveBeenCalledWith(expectedPartialToolMessage)
697+
// The failed write's streamed content must be reverted before reset() clears the
698+
// state revertChanges() relies on.
699+
expect(diffViewCallOrder).toEqual(["revert", "reset"])
700+
expect(mockHandleError).not.toHaveBeenCalled()
589701
})
702+
703+
it("finalizes partial tool message and resets diff view when handlePartial update() fails", async () => {
704+
// Same regression as above but for the streaming update() call failing after open() succeeds.
705+
mockCline.diffViewProvider.update.mockRejectedValue(
706+
Object.assign(new Error("EROFS: read-only file system, write '/ro/test.py'"), { code: "EROFS" }),
707+
)
708+
// Record the relative order of revertChanges() and reset() (vitest mocks expose
709+
// no invocationCallOrder).
710+
const diffViewCallOrder: string[] = []
711+
mockCline.diffViewProvider.revertChanges.mockImplementation(async () => {
712+
diffViewCallOrder.push("revert")
713+
})
714+
mockCline.diffViewProvider.reset.mockImplementation(async () => {
715+
diffViewCallOrder.push("reset")
716+
})
717+
718+
// First call - path not yet stabilized
719+
await executeWriteFileTool({}, { isPartial: true })
720+
721+
// Second call - path stabilized, update() rejects
722+
await executeWriteFileTool({}, { isPartial: true })
723+
724+
// Exact streamed payload: finalizePartialToolAsk() no-ops on a text mismatch, so
725+
// a wrong argument (e.g. relPath) would leave the spinner stuck.
726+
expect(mockCline.finalizePartialToolAsk).toHaveBeenCalledWith(expectedPartialToolMessage)
727+
// The failed write's streamed content must be reverted before reset() clears the
728+
// state revertChanges() relies on.
729+
expect(diffViewCallOrder).toEqual(["revert", "reset"])
730+
expect(mockHandleError).not.toHaveBeenCalled()
731+
})
732+
733+
it("does not spawn a new partial tool message on each streaming delta after a failure", async () => {
734+
// Regression test: after diffViewProvider.open() throws and the partial message is
735+
// finalized + diff view reset, the next streaming delta saw a non-partial last message
736+
// and created a brand new "Zoo wants to edit this file" message -- repeating once per
737+
// delta. After the fix, partialStreamFailed short-circuits subsequent deltas so only
738+
// the single initial partial ask is issued.
739+
mockCline.diffViewProvider.open.mockRejectedValue(
740+
Object.assign(new Error("EROFS: read-only file system, mkdir '/scratch'"), { code: "EROFS" }),
741+
)
742+
743+
// Delta 1 - stabilize path (no ask yet)
744+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
745+
// Delta 2 - path stabilized, ask issued once, open() fails, stream marked failed
746+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
747+
// Deltas 3..5 - must be short-circuited, no further asks
748+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
749+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
750+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
751+
752+
// Only the single partial ask from delta 2 should have been issued
753+
expect(mockCline.ask).toHaveBeenCalledTimes(1)
754+
// open() must not be retried after the first failure
755+
expect(mockCline.diffViewProvider.open).toHaveBeenCalledTimes(1)
756+
})
757+
758+
759+
760+
761+
762+
763+
764+
765+
766+
it("keeps partial stream failures isolated per task", async () => {
767+
mockCline.diffViewProvider.open.mockRejectedValueOnce(
768+
Object.assign(new Error("EROFS: read-only file system, mkdir '/task-a'"), { code: "EROFS" }),
769+
)
770+
771+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
772+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
773+
expect(mockCline.ask).toHaveBeenCalledTimes(1)
774+
775+
mockCline.taskId = "task-2"
776+
mockCline.instanceId = "instance-2"
777+
mockCline.diffViewProvider.open.mockResolvedValue(undefined)
778+
mockCline.diffViewProvider.update.mockResolvedValue(undefined)
779+
mockCline.diffViewProvider.editType = undefined
780+
781+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
782+
expect(mockCline.ask).toHaveBeenCalledTimes(1)
783+
784+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
785+
786+
expect(mockCline.ask).toHaveBeenCalledTimes(2)
787+
expect(mockCline.diffViewProvider.open).toHaveBeenCalledTimes(2)
788+
})
789+
790+
791+
792+
it("EROFS in handlePartial does not stall agent loop -- createDirectoriesForFile is not called", async () => {
793+
// Regression test: before the fix, createDirectoriesForFile was called in handlePartial
794+
// with no .catch() guard. An EROFS throw escaped to BaseTool.handle(), which called
795+
// handleError but did not set didRejectTool/didAlreadyUseTool, so the advancement gate
796+
// in presentAssistantMessage was never reached and the agent loop stalled permanently.
797+
// After the fix the call is removed entirely -- handlePartial never touches the filesystem.
798+
mockedCreateDirectoriesForFile.mockRejectedValue(
799+
Object.assign(new Error("EROFS: read-only file system, mkdir '/scratch'"), { code: "EROFS" }),
800+
)
801+
802+
// First call -- path not yet stabilized, returns early
803+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
804+
expect(mockHandleError).not.toHaveBeenCalled()
805+
806+
// Second call -- path stabilized; createDirectoriesForFile must NOT be called from
807+
// handlePartial, so the mock rejection must not trigger and handleError must not be called
808+
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
809+
expect(mockedCreateDirectoriesForFile).not.toHaveBeenCalled()
810+
expect(mockHandleError).not.toHaveBeenCalled()
811+
})
812+
813+
814+
815+
590816
})
591817
})

0 commit comments

Comments
 (0)