Skip to content

Commit 2a9bfab

Browse files
author
easonLiangWorldedtech
committed
fix(tools): stop a post-commit failure from rolling back a landed write
Three CodeRabbit rows at head 1b09bab, all in the write_to_file teardown: - execute()'s catch called diffViewProvider.reset() directly, so a reset that rejected skipped reportRevertFailure(): the user saw only the write error while the editor still held content nobody approved. It now goes through the same resilient helper the parse-failure and partial-stream teardowns use. - The prevent-focus-disruption rejection exit returned without resetting the provider. That branch never opens a diff view, but the preflight had already adopted this call's created directories and set editType/originalContent, so the next write's open() folded them into its own createdDirs and its rollback rmdir'ed directories belonging to the rejected write. - saveChanges() persists the document and then keeps working (closing the diff views, tab bookkeeping, diagnostics), and trackFileContext() and pushToolWriteResult() run after it. A failure past that point restored the previous content, or unlinked a file the user had just approved being created. saveChanges() now signals its commit point at the document save and the rollback stands down from there; saveDirectly() commits when it returns, because performing the write is what it does. Same shape as the landed rule recorded for #41 Follow-up 11 (6092123982) in Zoo-Code-Org#1921 (1b9ae30): the commit point is where a write becomes irreversible, not where the call finished. Tests: four new cases; each is the only failure when its own guard is removed, and the DiffViewProvider pair pins both directions of the commit signal.
1 parent 1b09bab commit 2a9bfab

4 files changed

Lines changed: 126 additions & 3 deletions

File tree

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,13 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
324324

325325
const isWriteProtected = task.rooProtectedController?.isWriteProtected(relPath) || false
326326

327+
// The point of no return for this write. saveChanges() persists the document and then keeps
328+
// working (closing the diff views, tab bookkeeping, diagnostics), and trackFileContext() and
329+
// pushToolWriteResult() run after it, so a rejection past this point must not roll back a
330+
// write the user already approved: the rollback would restore the previous content, or delete
331+
// a file that was created and saved. Set only once the durable write has landed.
332+
let writeCommitted = false
333+
327334
try {
328335
// The guarded scope starts before the preflight filesystem work: a throw from
329336
// fileExistsAtPath or createDirectoriesForFile must report and tear down like any other
@@ -410,10 +417,19 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
410417
// task, which suppresses the diff preview of every later write_to_file, and
411418
// the TaskAborted listener leaks.
412419
super.resetPartialState()
420+
// This branch never opened a diff view, but the preflight above already adopted
421+
// this call's created directories and set editType/originalContent on the
422+
// per-task provider. A rejection that leaves them behind hands them to the next
423+
// write's open(), whose rollback would then rmdir directories that belong to
424+
// this rejected write - and fail with ENOTEMPTY once a later file lives in one.
425+
await this.resetDiffViewAfterWrite(task)
413426
return
414427
}
415428

416429
await task.diffViewProvider.saveDirectly(relPath, newContent, false, diagnosticsEnabled, writeDelayMs)
430+
// saveDirectly() performs the write itself and reports a failing write, so returning
431+
// means the content is on disk: from here the rollback has to stand down.
432+
writeCommitted = true
417433
} else {
418434
if (!task.diffViewProvider.isEditing) {
419435
const partialMessage = JSON.stringify(sharedMessageProps)
@@ -449,7 +465,12 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
449465
return
450466
}
451467

452-
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
468+
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs, () => {
469+
// Signalled by saveChanges() at the document save, not when it returns: the editor
470+
// bookkeeping and diagnostics that follow can still reject, and by then the file
471+
// has already landed.
472+
writeCommitted = true
473+
})
453474
}
454475

455476
if (relPath) {
@@ -490,8 +511,14 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
490511
// an existing file. Report it the same way the parse-failure teardown and
491512
// cleanupFailedPartialStream() do - after the reset, so the report is the last thing the
492513
// failed write leaves behind.
493-
const reverted = await this.revertDiffChangesBeforeReset(task)
494-
await task.diffViewProvider.reset()
514+
// After the commit point the write is durable, so restoring the previous content
515+
// (or unlinking a newly created file) would undo an approved write to clean up an
516+
// unrelated failure. Treat the rollback as done rather than performing it.
517+
const reverted = writeCommitted ? true : await this.revertDiffChangesBeforeReset(task)
518+
// The resilient helper, as in the other two teardowns: a reset that rejects must not
519+
// skip the report below, or the user sees only the write error while the editor still
520+
// holds content nobody approved.
521+
await this.resetDiffViewAfterWrite(task)
495522
super.resetPartialState()
496523

497524
if (!reverted) {

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1149,6 +1149,68 @@ describe("writeToFileTool", () => {
11491149
expect(mockCline.diffViewProvider.reset).toHaveBeenCalled()
11501150
})
11511151

1152+
it("reports the rollback failure even when the diff-view reset rejects", async () => {
1153+
// The catch used a bare diffViewProvider.reset(): when that rejected, the rollback report
1154+
// after it never ran, so the user saw only the write error while the editor still held
1155+
// content nobody approved. The teardown now goes through the same resilient helper the
1156+
// parse-failure and partial-stream teardowns already use.
1157+
mockCline.diffViewProvider.open.mockRejectedValue(new Error("open failed"))
1158+
mockCline.diffViewProvider.revertChanges.mockRejectedValue(new Error("revert failed"))
1159+
mockCline.diffViewProvider.reset.mockRejectedValue(new Error("reset failed"))
1160+
1161+
await executeWriteFileTool({})
1162+
1163+
expect(mockHandleError).toHaveBeenCalledWith("writing file", expect.any(Error))
1164+
expect(mockCline.say).toHaveBeenCalledWith("error", expect.stringContaining("could not be restored"))
1165+
})
1166+
1167+
it("resets the diff-view provider when the prevent-focus-disruption approval is rejected", async () => {
1168+
// This branch never opens a diff view, but the preflight already adopted the created
1169+
// directories and set editType/originalContent on the per-task provider. Left behind, the
1170+
// next write's open() folds those directories into its own createdDirs and its rollback
1171+
// rmdirs directories belonging to this rejected write - ENOTEMPTY once a later file lives
1172+
// in one of them.
1173+
mockCline.providerRef = {
1174+
deref: vi.fn().mockReturnValue({
1175+
getState: vi.fn().mockResolvedValue({
1176+
diagnosticsEnabled: true,
1177+
writeDelayMs: 1000,
1178+
experiments: { preventFocusDisruption: true },
1179+
}),
1180+
}),
1181+
}
1182+
mockCline.diffViewProvider.saveDirectly = vi.fn().mockResolvedValue({
1183+
newProblemsMessage: "",
1184+
userEdits: undefined,
1185+
finalContent: "final content",
1186+
})
1187+
mockAskApproval = vi.fn().mockResolvedValue(false)
1188+
1189+
await executeWriteFileTool({})
1190+
1191+
expect(mockCline.diffViewProvider.saveDirectly).not.toHaveBeenCalled()
1192+
expect(mockCline.diffViewProvider.reset).toHaveBeenCalled()
1193+
})
1194+
1195+
it("does not roll back a write that saveChanges already committed", async () => {
1196+
// saveChanges() persists the document and then keeps working, and trackFileContext() runs
1197+
// after it. A failure past that point used to restore the previous content - or unlink a
1198+
// file the user had just approved being created - to clean up an unrelated error.
1199+
mockCline.diffViewProvider.saveChanges.mockImplementation(
1200+
async (_diagnosticsEnabled: boolean, _writeDelayMs: number, onCommit?: () => void) => {
1201+
onCommit?.()
1202+
return { newProblemsMessage: "", userEdits: undefined, finalContent: "final content" }
1203+
},
1204+
)
1205+
mockCline.fileContextTracker.trackFileContext.mockRejectedValue(new Error("context tracking failed"))
1206+
1207+
await executeWriteFileTool({})
1208+
1209+
expect(mockHandleError).toHaveBeenCalledWith("writing file", expect.any(Error))
1210+
expect(mockCline.diffViewProvider.revertChanges).not.toHaveBeenCalled()
1211+
expect(mockCline.diffViewProvider.reset).toHaveBeenCalled()
1212+
})
1213+
11521214

11531215

11541216
it("swallows partial streaming errors instead of surfacing a duplicate error bubble", async () => {

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,7 @@ export class DiffViewProvider {
344344
async saveChanges(
345345
diagnosticsEnabled: boolean = true,
346346
writeDelayMs: number = DEFAULT_WRITE_DELAY_MS,
347+
onCommit?: () => void,
347348
): Promise<{
348349
newProblemsMessage: string | undefined
349350
userEdits: string | undefined
@@ -361,6 +362,12 @@ export class DiffViewProvider {
361362
await updatedDocument.save()
362363
}
363364

365+
// The write is irreversible from here: a clean document already matches disk, and a saved
366+
// one has landed. Everything below (closing the diff views, tab bookkeeping, diagnostics)
367+
// can still reject, and a caller that rolls the tool call back after this point would undo
368+
// a write the user approved - so it is told, at the commit point rather than on return.
369+
onCommit?.()
370+
364371
// Stop tracking touches and cancel any pending scroll-to-diff before any
365372
// programmatic editor activation below.
366373
this.disposeActiveEditorListener()

‎src/integrations/editor/__tests__/DiffViewProvider.spec.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -970,6 +970,33 @@ describe("DiffViewProvider", () => {
970970
expect(mockDelay).toHaveBeenCalledWith(5000)
971971
expect(vscode.languages.getDiagnostics).toHaveBeenCalled()
972972
})
973+
974+
it("signals the commit point once the document write has landed", async () => {
975+
diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined)
976+
const onCommit = vi.fn()
977+
978+
await diffViewProvider.saveChanges(false, 0, onCommit)
979+
980+
// The shared document is clean, so nothing is written: the file already matches the
981+
// buffer, which is just as irreversible. The caller stops rolling back here.
982+
expect(onCommit).toHaveBeenCalledTimes(1)
983+
})
984+
985+
it("does not signal the commit point when the document save rejects", async () => {
986+
const save = vi.fn().mockRejectedValue(new Error("save failed"))
987+
// Structural double carrying only the members saveChanges() reaches before the commit
988+
// point; the full TextEditor shape needs a live editor host - hence the assertion.
989+
diffViewProvider["activeDiffEditor"] = {
990+
document: { getText: vi.fn().mockReturnValue("new content"), isDirty: true, save },
991+
} as unknown as vscode.TextEditor
992+
const onCommit = vi.fn()
993+
994+
await expect(diffViewProvider.saveChanges(false, 0, onCommit)).rejects.toThrow("save failed")
995+
996+
// A rejected save leaves the file absent or holding the previous content: the caller has
997+
// to keep the rollback available, so signalling here would lose the write's debris.
998+
expect(onCommit).not.toHaveBeenCalled()
999+
})
9731000
})
9741001

9751002
describe("preEditScrollLine capture and restore", () => {

0 commit comments

Comments
 (0)