Skip to content

Commit 52c6cb0

Browse files
committed
fix(checkpoints): flush recorded writes when post-write bookkeeping throws
ApplyPatchTool records each write through an onWrote callback at the moment it lands on disk, and the catch path flushes the accumulated checkpoint/journal metadata (awaited, guarded by writeMetadataFlushed against double flush) so a throw from post-write bookkeeping cannot lose the journal entry and change card for a completed write. A journal failure in the success path keeps the documented drop-buffered-results behavior. Also clarify the perWrite checkpoint setting description: a multi-file patch produces a single checkpoint (all 18 locales).
1 parent d31ac8e commit 52c6cb0

20 files changed

Lines changed: 106 additions & 50 deletions

‎src/core/tools/ApplyPatchTool.ts‎

Lines changed: 62 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,26 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
8181
// messages when a write succeeded but the post-patch checkpoint failed.
8282
const successfulChanges: ApplyPatchFileChange[] = []
8383
const bufferedResults: string[] = []
84+
// Set once the success-path checkpoint/journal flush has been attempted
85+
// so the catch below does not persist the same writes twice.
86+
let writeMetadataFlushed = false
87+
// Journal payload builder shared by the success-path flush and the
88+
// catch-path flush for writes recorded before an unexpected throw.
89+
const journalEntries = () =>
90+
successfulChanges.map((change) => ({
91+
path: change.movePath ?? change.path,
92+
operation: change.type === "add" ? ("create" as const) : change.type,
93+
...(change.diffStats
94+
? {
95+
diffStats: {
96+
additions: change.diffStats.added,
97+
deletions: change.diffStats.removed,
98+
},
99+
}
100+
: {}),
101+
...(change.diff ? { diff: change.diff } : {}),
102+
...(change.autoApproved ? { autoApproved: true } : {}),
103+
}))
84104

85105
try {
86106
// Validate required parameters
@@ -129,10 +149,12 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
129149
}
130150

131151
// Process each file change. The handlers report whether their file
132-
// operation succeeded (which controls the whole-patch checkpoint) and
133-
// whether it actually wrote a file (which controls the change journal
134-
// — a no-op update must not be journaled). A rejected approval or a
135-
// failed local write never gets checkpointed as a success.
152+
// operation succeeded (which controls the whole-patch checkpoint); each
153+
// write is recorded through the onWrote callback at the moment it lands
154+
// on disk, so a throw from post-write bookkeeping cannot lose the
155+
// journal entry and change card for a completed write (a no-op update
156+
// never calls the callback). A rejected approval or a failed local
157+
// write never gets checkpointed as a success.
136158
let patchSucceeded = true
137159
for (const change of changes) {
138160
const relPath = change.path
@@ -163,11 +185,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
163185
task,
164186
callbacks,
165187
isWriteProtected,
188+
() => successfulChanges.push(change),
166189
)
167190
patchSucceeded = addResult.succeeded && patchSucceeded
168-
if (addResult.wrote) {
169-
successfulChanges.push(change)
170-
}
171191
if (addResult.resultMessage) {
172192
bufferedResults.push(addResult.resultMessage)
173193
}
@@ -180,11 +200,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
180200
task,
181201
callbacks,
182202
isWriteProtected,
203+
() => successfulChanges.push(change),
183204
)
184205
patchSucceeded = deleteResult.succeeded && patchSucceeded
185-
if (deleteResult.wrote) {
186-
successfulChanges.push(change)
187-
}
188206
if (deleteResult.resultMessage) {
189207
bufferedResults.push(deleteResult.resultMessage)
190208
}
@@ -197,11 +215,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
197215
task,
198216
callbacks,
199217
isWriteProtected,
218+
() => successfulChanges.push(change),
200219
)
201220
patchSucceeded = updateResult.succeeded && patchSucceeded
202-
if (updateResult.wrote) {
203-
successfulChanges.push(change)
204-
}
205221
if (updateResult.resultMessage) {
206222
bufferedResults.push(updateResult.resultMessage)
207223
}
@@ -226,6 +242,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
226242
// pushToolResult. A fully failed patch (nothing written) leaves no
227243
// checkpoint behind.
228244
if (patchSucceeded || successfulChanges.length > 0) {
245+
writeMetadataFlushed = true
229246
const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints
230247
if (perWriteCheckpoints !== false) {
231248
// B2: one journal entry per file that was actually written by
@@ -239,25 +256,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
239256
// staging/commit/journal/change-card work. checkpointSave rejects with a
240257
// CheckpointPartialPersistenceError when a committed checkpoint's
241258
// journal update fails; the catch below reports it.
242-
await checkpointSave(
243-
task,
244-
false,
245-
true,
246-
successfulChanges.map((change) => ({
247-
path: change.movePath ?? change.path,
248-
operation: change.type === "add" ? "create" : change.type,
249-
...(change.diffStats
250-
? {
251-
diffStats: {
252-
additions: change.diffStats.added,
253-
deletions: change.diffStats.removed,
254-
},
255-
}
256-
: {}),
257-
...(change.diff ? { diff: change.diff } : {}),
258-
...(change.autoApproved ? { autoApproved: true } : {}),
259-
})),
260-
)
259+
await checkpointSave(task, false, true, journalEntries())
261260
}
262261
}
263262

@@ -270,6 +269,18 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
270269
pushToolResult(message)
271270
}
272271
} catch (error) {
272+
// A handler that throws after recording its write (post-write
273+
// bookkeeping such as trackFileContext) skips the success-path flush
274+
// above. Persist the recorded writes here, awaited, before the generic
275+
// error handling: the writes are on disk and the journal must document
276+
// them. A flush already attempted above is not repeated, so a journal
277+
// failure keeps the documented drop-buffered-results behavior.
278+
if (!writeMetadataFlushed && successfulChanges.length > 0) {
279+
const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints
280+
if (perWriteCheckpoints !== false) {
281+
await checkpointSave(task, false, true, journalEntries()).catch(() => {})
282+
}
283+
}
273284
await handleError("apply patch", error as Error)
274285
await task.diffViewProvider.reset()
275286
} finally {
@@ -291,6 +302,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
291302
task: Task,
292303
callbacks: ToolCallbacks,
293304
isWriteProtected: boolean,
305+
onWrote?: () => void,
294306
): Promise<ApplyPatchFileOpResult> {
295307
const { askApproval, pushToolResult } = callbacks
296308

@@ -381,6 +393,11 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
381393
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
382394
}
383395

396+
// Record the completed write before post-write bookkeeping can fail:
397+
// a throw from trackFileContext must not lose the journal entry (and
398+
// change card) for a file that is already on disk.
399+
onWrote?.()
400+
384401
// Track file edit operation
385402
await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
386403
task.didEditFile = true
@@ -397,6 +414,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
397414
task: Task,
398415
callbacks: ToolCallbacks,
399416
isWriteProtected: boolean,
417+
onWrote?: () => void,
400418
): Promise<ApplyPatchFileOpResult> {
401419
const { askApproval, pushToolResult } = callbacks
402420

@@ -456,6 +474,10 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
456474
return { succeeded: false, wrote: false }
457475
}
458476

477+
// The deletion is complete; record it before the buffered result can be
478+
// dropped by a later failure.
479+
onWrote?.()
480+
459481
task.didEditFile = true
460482
return { succeeded: true, wrote: true, resultMessage: `Successfully deleted ${relPath}` }
461483
}
@@ -467,6 +489,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
467489
task: Task,
468490
callbacks: ToolCallbacks,
469491
isWriteProtected: boolean,
492+
onWrote?: () => void,
470493
): Promise<ApplyPatchFileOpResult> {
471494
const { askApproval, pushToolResult } = callbacks
472495

@@ -633,6 +656,10 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
633656
pushToolResult(formatResponse.toolError(errorMessage))
634657
}
635658

659+
// The destination write is on disk whether or not the source unlink
660+
// succeeded; record it before bookkeeping can fail.
661+
onWrote?.()
662+
636663
await task.fileContextTracker.trackFileContext(change.movePath, "roo_edited" as RecordSource)
637664
} else {
638665
// Save changes to the same file
@@ -642,6 +669,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
642669
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
643670
}
644671

672+
// Record the completed write before post-write bookkeeping can fail.
673+
onWrote?.()
674+
645675
await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
646676
}
647677

‎src/core/tools/__tests__/applyPatchTool.execute.spec.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,32 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
616616
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
617617
})
618618

619+
it("journals the recorded write when a handler throws after its write", async () => {
620+
// Post-write bookkeeping (trackFileContext) fails after the file is
621+
// already on disk: the write recorded at write time must still receive
622+
// its checkpoint and journal entry through the catch-path flush; the
623+
// buffered success result is dropped in favor of the failure result.
624+
vi.mocked(mockTask.fileContextTracker.trackFileContext).mockRejectedValueOnce(new Error("tracker boom"))
625+
await tool.execute({ patch: updatePatch }, mockTask as Task, {
626+
askApproval: mockAskApproval,
627+
handleError: mockHandleError,
628+
pushToolResult: mockPushToolResult,
629+
toolCallId: "test-tool-call-id",
630+
})
631+
632+
expect(mockedCheckpointSave).toHaveBeenCalledTimes(1)
633+
expect(mockedCheckpointSave).toHaveBeenCalledWith(
634+
mockTask as Task,
635+
false,
636+
true,
637+
expect.arrayContaining([expect.objectContaining({ path: "src/test.ts", operation: "update" })]),
638+
)
639+
expect(mockPushToolResult).not.toHaveBeenCalledWith("File saved successfully")
640+
expect(mockHandleError).toHaveBeenCalledWith("apply patch", expect.anything())
641+
// The finally-block handoff still runs for the recorded write.
642+
expect(mockTask.processQueuedMessages).toHaveBeenCalled()
643+
})
644+
619645
it("records one journal write per file change for a multi-file patch", async () => {
620646
// src/a.ts does not exist (add); src/b.ts does (update).
621647
mockedFileExistsAtPath.mockImplementation((filePath: string) =>

‎webview-ui/src/i18n/locales/ca/settings.json‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webview-ui/src/i18n/locales/de/settings.json‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webview-ui/src/i18n/locales/en/settings.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -817,7 +817,7 @@
817817
},
818818
"perWrite": {
819819
"label": "Checkpoint after each file write",
820-
"description": "Record a checkpoint snapshot after every successful file write by the agent"
820+
"description": "Record a checkpoint snapshot after each successful write operation; a multi-file patch produces a single checkpoint."
821821
},
822822
"changeCardDetail": {
823823
"label": "Show full diff in change cards",

‎webview-ui/src/i18n/locales/es/settings.json‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webview-ui/src/i18n/locales/fr/settings.json‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webview-ui/src/i18n/locales/hi/settings.json‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webview-ui/src/i18n/locales/id/settings.json‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webview-ui/src/i18n/locales/it/settings.json‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)