Skip to content

Commit 8415547

Browse files
fix(per-write-checkpoints): lock restores, track retained writes, name the tools
CodeRabbit round against 7f9ebb4 on #1404: - checkpointRestore now runs through the same per-task queue the saves use, so a queued save can never stage + commit while a restore is resetting the workspace, and a restore asked for during a save waits for it (thread 7pkO). - handleAddFile records the mutation at the write boundary and untracks it only when the save left no file behind, so an add whose save rejects after its bytes landed still gets the partial-state checkpoint before the queued-message handoff (thread 7pkV). - The move write-catch reports where the destination's bytes survived when the restore rename fails as well, and treats the missing destination as a workspace mutation (thread 7pkb). - The perWrite description names write_to_file, edit_file and apply_patch and says that saving from the editor records no checkpoint, in all 18 locales (thread 7pkh). Rows: 1 in checkpoint.test.ts, 2 in applyPatchTool.execute.spec.ts, 19 in CheckpointSettings.spec.tsx; each one fails against 7f9ebb4 on its own.
1 parent 7f9ebb4 commit 8415547

23 files changed

Lines changed: 273 additions & 43 deletions

‎src/core/checkpoints/__tests__/checkpoint.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,37 @@ describe("Checkpoint functionality", () => {
308308
expect(mockCheckpointService.restoreCheckpoint).not.toHaveBeenCalled()
309309
})
310310

311+
it("serializes a restore against a queued save so no save stages over a restore", async () => {
312+
const order: string[] = []
313+
let resolveRestore: () => void = () => {}
314+
mockCheckpointService.restoreCheckpoint.mockImplementationOnce(
315+
() =>
316+
new Promise((resolve) => {
317+
order.push("restore:start")
318+
resolveRestore = resolve as () => void
319+
}),
320+
)
321+
mockCheckpointService.saveCheckpoint.mockImplementationOnce(async () => {
322+
order.push("save:start")
323+
return { commit: "queued-commit" }
324+
})
325+
326+
const restore = checkpointRestore(mockTask, { ts: 2, commitHash: RESTORE_HASH, mode: "preview" })
327+
// Let the restore reach the shadow-git reset.
328+
await new Promise((resolve) => setTimeout(resolve, 10))
329+
330+
const save = checkpointSave(mockTask, false, true)
331+
// The save must not reach stageAll + commit while the restore is resetting the
332+
// workspace: that commit would record the restored bytes and drop the write's own
333+
// checkpoint.
334+
await new Promise((resolve) => setTimeout(resolve, 10))
335+
expect(order).toEqual(["restore:start"])
336+
337+
resolveRestore()
338+
await Promise.all([restore, save])
339+
expect(order).toEqual(["restore:start", "save:start"])
340+
})
341+
311342
it.each(["delete", "edit"] as const)(
312343
"propagates restore failures for %s without rewinding",
313344
async (operation) => {

‎src/core/checkpoints/index.ts‎

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -224,24 +224,26 @@ async function checkGitInstallation(
224224
}
225225
}
226226

227-
// Serialize checkpoint saves per task. saveCheckpoint() runs stageAll + commit, so two
228-
// concurrent saves for the same task (for example the task-start baseline racing the first
229-
// per-write save after the baseline timeout) can stage each other's writes or interleave
230-
// commits. A per-task promise queue makes every save wait for the previous one, including
231-
// a baseline that is still running.
232-
const checkpointSaveQueues = new Map<string, Promise<unknown>>()
233-
234-
function enqueueCheckpointSave<T>(taskId: string, operation: () => Promise<T>): Promise<T> {
235-
const previous = checkpointSaveQueues.get(taskId) ?? Promise.resolve()
227+
// Serialize checkpoint work per task. saveCheckpoint() runs stageAll + commit and
228+
// restoreCheckpoint() resets the workspace through the same shadow git, so two concurrent
229+
// operations for the same task (for example the task-start baseline racing the first
230+
// per-write save after the baseline timeout, or a restore while a per-write save is still
231+
// queued) can stage each other's writes or interleave commits. A per-task promise queue
232+
// makes every save and every restore wait for the previous one, including a baseline that
233+
// is still running.
234+
const checkpointWorkQueues = new Map<string, Promise<unknown>>()
235+
236+
function enqueueCheckpointWork<T>(taskId: string, operation: () => Promise<T>): Promise<T> {
237+
const previous = checkpointWorkQueues.get(taskId) ?? Promise.resolve()
236238
const next = previous.then(operation, operation)
237239
const tail = next.then(
238240
() => undefined,
239241
() => undefined,
240242
)
241-
checkpointSaveQueues.set(taskId, tail)
243+
checkpointWorkQueues.set(taskId, tail)
242244
void tail.finally(() => {
243-
if (checkpointSaveQueues.get(taskId) === tail) {
244-
checkpointSaveQueues.delete(taskId)
245+
if (checkpointWorkQueues.get(taskId) === tail) {
246+
checkpointWorkQueues.delete(taskId)
245247
}
246248
})
247249
return next
@@ -256,9 +258,9 @@ export async function checkpointSave(task: Task, force = false, suppressMessage
256258

257259
TelemetryService.instance.captureCheckpointCreated(task.taskId)
258260

259-
// Start the checkpoint process in the background, queued behind any save already
260-
// running for this task so stageAll + commit never overlap.
261-
return enqueueCheckpointSave(task.taskId, () =>
261+
// Start the checkpoint process in the background, queued behind any checkpoint work
262+
// already running for this task so stageAll + commit never overlap.
263+
return enqueueCheckpointWork(task.taskId, () =>
262264
service.saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, { allowEmpty: force, suppressMessage }),
263265
).catch((err) => {
264266
console.error("[Task#checkpointSave] caught unexpected error, disabling checkpoints", err)
@@ -294,7 +296,11 @@ export async function checkpointRestore(
294296
const provider = task.providerRef.deref()
295297

296298
try {
297-
await service.restoreCheckpoint(commitHash)
299+
// The same per-task lock the saves use, in both directions: a restore resets the
300+
// workspace through shadow git, so a queued save must not stage and commit while it
301+
// is running (that save would record the restored bytes and drop the write's own
302+
// checkpoint), and a restore requested during a save waits for that save to settle.
303+
await enqueueCheckpointWork(task.taskId, () => service.restoreCheckpoint(commitHash))
298304
TelemetryService.instance.captureCheckpointRestored(task.taskId)
299305
await provider?.postMessageToWebview({ type: "currentCheckpointUpdated", text: commitHash })
300306

‎src/core/tools/ApplyPatchTool.ts‎

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -311,17 +311,32 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
311311
return { ok: false, mutated }
312312
}
313313

314-
// Save the changes
315-
if (isPreventFocusDisruptionEnabled) {
316-
await task.diffViewProvider.saveDirectly(relPath, newContent, true, diagnosticsEnabled, writeDelayMs)
317-
} else {
318-
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
314+
// The write lands inside the save call below, which can still reject afterwards
315+
// (opening the document, collecting diagnostics) once the new file is on disk. The
316+
// mutation is therefore recorded at the write boundary: this handler never returns in
317+
// that case, and without the flag the retained file would hand off the queued turn
318+
// with no partial-state checkpoint (see the catch and finally in execute()).
319+
mutated = true
320+
mutation.committed = true
321+
try {
322+
if (isPreventFocusDisruptionEnabled) {
323+
await task.diffViewProvider.saveDirectly(relPath, newContent, true, diagnosticsEnabled, writeDelayMs)
324+
} else {
325+
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
326+
}
327+
} catch (error) {
328+
// A save that failed before writing any bytes left no file behind, so the add did
329+
// not mutate the workspace after all and must not be checkpointed as a retained
330+
// write. Untrack it and let the outer error path report the failure.
331+
if (!(await fileExistsAtPath(absolutePath))) {
332+
mutated = false
333+
mutation.committed = false
334+
}
335+
throw error
319336
}
320337

321338
// Track file edit operation
322339
await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
323-
mutated = true
324-
mutation.committed = true
325340
task.didEditFile = true
326341

327342
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, true)
@@ -594,12 +609,29 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
594609
if (destinationCommitted) {
595610
await fs.rm(moveAbsolutePath, { force: true }).catch(() => {})
596611
}
612+
let destinationMissing = false
597613
if (destinationBackup !== undefined) {
598-
await fs.rename(backupPath, moveAbsolutePath).catch(() => {})
614+
// Put the captured destination bytes back with one rename. If that rename
615+
// fails as well, the destination is missing and its content survives only
616+
// under the backup name, so the report has to say where it is.
617+
await fs.rename(backupPath, moveAbsolutePath).catch(() => {
618+
destinationMissing = true
619+
})
620+
}
621+
if (destinationMissing) {
622+
// A missing destination is a workspace mutation: record it so the
623+
// partial-state checkpoint runs before the queued-message handoff, exactly
624+
// as the failed source deletion below does.
625+
mutated = true
626+
mutation.committed = true
599627
}
600628
task.consecutiveMistakeCount++
601629
task.recordToolError("apply_patch")
602-
const writeErrorMessage = `Failed to write move destination '${change.movePath}': ${writeError instanceof Error ? writeError.message : String(writeError)}`
630+
const writeErrorMessage =
631+
`Failed to write move destination '${change.movePath}': ${writeError instanceof Error ? writeError.message : String(writeError)}` +
632+
(destinationMissing && backupPath !== undefined
633+
? ` The original content is preserved at '${getReadablePath(task.cwd, path.relative(task.cwd, backupPath))}'.`
634+
: "")
603635
await task.say("error", writeErrorMessage)
604636
pushToolResult(formatResponse.toolError(writeErrorMessage))
605637
await task.diffViewProvider.reset()

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

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,56 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
285285
mockedFsPromises.default.readFile.mockResolvedValue("original file content\n")
286286
})
287287

288+
it("names the retained backup and records a checkpoint when the move write fails and the restore rename fails", async () => {
289+
const patch = `*** Begin Patch
290+
*** Update File: src/old.ts
291+
*** Move to: src/new.ts
292+
@@
293+
-original file content
294+
+new content
295+
*** End Patch`
296+
// The destination exists, so the write-catch path puts it back by renaming the
297+
// on-disk backup over the destination.
298+
mockedFsPromises.default.readFile.mockImplementation(async (p: unknown) => {
299+
if (String(p).includes("new.ts")) {
300+
return "existing destination content"
301+
}
302+
return "original file content\n"
303+
})
304+
// The staging write succeeds, the staging -> destination rename fails, and the
305+
// backup -> destination restore rename fails as well: the destination is now
306+
// missing and its content survives only under the backup name.
307+
mockedFsPromises.default.rename.mockImplementation(async (from: unknown, to: unknown) => {
308+
const source = String(from)
309+
const target = String(to)
310+
if (target.includes("new.ts") && source.includes(".staging")) {
311+
throw Object.assign(new Error("EACCES: permission denied, rename"), { code: "EACCES" })
312+
}
313+
if (target.includes("new.ts") && source.includes(".backup")) {
314+
throw Object.assign(new Error("EPERM: operation not permitted, restore"), { code: "EPERM" })
315+
}
316+
return undefined
317+
})
318+
319+
await tool.execute({ patch }, mockTask as Task, {
320+
askApproval: mockAskApproval,
321+
handleError: mockHandleError,
322+
pushToolResult: mockPushToolResult,
323+
toolCallId: "test-tool-call-id",
324+
})
325+
326+
expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Failed to write move destination"))
327+
// A user who lost the destination has to be told where its bytes are.
328+
expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringMatching(/preserved at '[^']*\.backup[^']*'/))
329+
// A missing destination is a workspace mutation: the partial-state checkpoint and
330+
// the queued-message handoff both have to run.
331+
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask, false, true)
332+
expect(mockTask.processQueuedMessages).toHaveBeenCalledOnce()
333+
// Restore the default mock behavior for later tests.
334+
mockedFsPromises.default.readFile.mockResolvedValue("original file content\n")
335+
mockedFsPromises.default.rename.mockResolvedValue(undefined)
336+
})
337+
288338
it("refuses the move before writing when the destination cannot be inspected", async () => {
289339
const patch = `*** Begin Patch
290340
*** Update File: src/old.ts
@@ -381,6 +431,41 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
381431
expect(checkpointAt).toBeLessThan(handoffAt)
382432
expect(mockHandleError).toHaveBeenCalled()
383433
})
434+
it("records the partial-state checkpoint when the add save rejects after its bytes landed", async () => {
435+
const patch = `*** Begin Patch
436+
*** Add File: src/new.ts
437+
+file content
438+
*** End Patch`
439+
// The add does not exist yet, and the focus-preserving save path is enabled, so the
440+
// bytes are written by saveDirectly.
441+
mockedFileExistsAtPath.mockResolvedValueOnce(false)
442+
const provider = {
443+
getState: vi.fn().mockResolvedValue({ experiments: { preventFocusDisruption: true } }),
444+
}
445+
mockTask.providerRef = { deref: () => provider } as unknown as Task["providerRef"]
446+
// The file lands on disk inside the save, which then rejects while finishing the
447+
// document, so the handler never returns and never reaches its own tracking lines.
448+
vi.mocked(mockTask.diffViewProvider.saveDirectly).mockRejectedValueOnce(
449+
new Error("EPERM: operation not permitted, open 'src/new.ts'"),
450+
)
451+
452+
await tool.execute({ patch }, mockTask as Task, {
453+
askApproval: mockAskApproval,
454+
handleError: mockHandleError,
455+
pushToolResult: mockPushToolResult,
456+
toolCallId: "test-tool-call-id",
457+
})
458+
459+
expect(mockTask.diffViewProvider.saveDirectly).toHaveBeenCalledOnce()
460+
// The failure is the save itself, not the bookkeeping after it.
461+
expect(mockTask.diffViewProvider.pushToolWriteResult).not.toHaveBeenCalled()
462+
expect(mockHandleError).toHaveBeenCalledWith("apply patch", expect.any(Error))
463+
// The retained file is a workspace mutation, so the partial-state checkpoint runs
464+
// before the queued-message handoff even though the patch reports failure.
465+
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask, false, true)
466+
expect(mockTask.processQueuedMessages).toHaveBeenCalledOnce()
467+
})
468+
384469
it("records one suppressed checkpoint for the whole patch (default-on)", async () => {
385470
await tool.execute({ patch: deletePatch }, mockTask as Task, {
386471
askApproval: mockAskApproval,

‎webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,60 @@
22

33
import { render, screen, fireEvent } from "@/utils/test-utils"
44
import { CheckpointSettings } from "../CheckpointSettings"
5+
import enSettings from "@/i18n/locales/en/settings.json"
6+
import caSettings from "@/i18n/locales/ca/settings.json"
7+
import deSettings from "@/i18n/locales/de/settings.json"
8+
import esSettings from "@/i18n/locales/es/settings.json"
9+
import frSettings from "@/i18n/locales/fr/settings.json"
10+
import hiSettings from "@/i18n/locales/hi/settings.json"
11+
import idSettings from "@/i18n/locales/id/settings.json"
12+
import itSettings from "@/i18n/locales/it/settings.json"
13+
import jaSettings from "@/i18n/locales/ja/settings.json"
14+
import koSettings from "@/i18n/locales/ko/settings.json"
15+
import nlSettings from "@/i18n/locales/nl/settings.json"
16+
import plSettings from "@/i18n/locales/pl/settings.json"
17+
import ptBRSettings from "@/i18n/locales/pt-BR/settings.json"
18+
import ruSettings from "@/i18n/locales/ru/settings.json"
19+
import trSettings from "@/i18n/locales/tr/settings.json"
20+
import viSettings from "@/i18n/locales/vi/settings.json"
21+
import zhCNSettings from "@/i18n/locales/zh-CN/settings.json"
22+
import zhTWSettings from "@/i18n/locales/zh-TW/settings.json"
23+
// The per-write checkpoint setting ships a description in every locale file, and the render
24+
// above mocks the translation hook, so the shipped copy is asserted against the locale
25+
// resources themselves. Access goes through a guard rather than a cast so a missing key
26+
// fails loudly instead of comparing undefined.
27+
// The three tools whose successful writes record a checkpoint.
28+
const WRITE_TOOLS = ["write_to_file", "edit_file", "apply_patch"]
29+
30+
const localeSettings: Record<string, unknown> = {
31+
en: enSettings,
32+
ca: caSettings,
33+
de: deSettings,
34+
es: esSettings,
35+
fr: frSettings,
36+
hi: hiSettings,
37+
id: idSettings,
38+
it: itSettings,
39+
ja: jaSettings,
40+
ko: koSettings,
41+
nl: nlSettings,
42+
pl: plSettings,
43+
"pt-BR": ptBRSettings,
44+
ru: ruSettings,
45+
tr: trSettings,
46+
vi: viSettings,
47+
"zh-CN": zhCNSettings,
48+
"zh-TW": zhTWSettings,
49+
}
50+
51+
function perWriteDescription(settings: unknown): string {
52+
const resources = settings as { checkpoints?: { perWrite?: { description?: unknown } } }
53+
const description = resources.checkpoints?.perWrite?.description
54+
if (typeof description !== "string") {
55+
throw new Error("settings.checkpoints.perWrite.description is missing")
56+
}
57+
return description
58+
}
559

660
// Mock the translation hook
761
vi.mock("@/i18n/TranslationContext", () => ({
@@ -122,4 +176,26 @@ describe("CheckpointSettings", () => {
122176

123177
expect(setCachedStateField).toHaveBeenCalledWith("perWriteCheckpoints", false)
124178
})
179+
180+
it.each(Object.entries(localeSettings).map(([locale, settings]) => ({ locale, settings })))(
181+
"names the three writing tools in the $locale per-write checkpoint description",
182+
({ locale, settings }) => {
183+
const description = perWriteDescription(settings)
184+
// The tool identifiers are language-neutral, so every locale can be held to the same
185+
// names: the setting records a checkpoint for these tools only, and the copy has to
186+
// say so instead of promising a snapshot after every write operation.
187+
expect(WRITE_TOOLS.filter((toolName) => !description.includes(toolName))).toEqual([])
188+
if (locale !== "en") {
189+
// The description is genuinely localized: a locale left on the English copy is a
190+
// missing translation, not a parity match.
191+
expect(description).not.toBe(perWriteDescription(localeSettings.en))
192+
}
193+
},
194+
)
195+
196+
it("states that saving from the editor records no checkpoint", () => {
197+
// The checkpoint call sites are the agent's three writing tools; an editor save does
198+
// not go through them, so the copy must not imply that it does.
199+
expect(perWriteDescription(localeSettings.en)).toContain("Saving a file from the editor does not record one")
200+
})
125201
})

‎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
@@ -771,7 +771,7 @@
771771
},
772772
"perWrite": {
773773
"label": "Checkpoint after each file write",
774-
"description": "Record a checkpoint snapshot after each successful write operation; a multi-file patch produces a single checkpoint."
774+
"description": "Record a checkpoint after each successful write by the agent's write_to_file, edit_file or apply_patch tools; a multi-file patch produces a single checkpoint. Saving a file from the editor does not record one."
775775
}
776776
},
777777
"notifications": {

‎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.

0 commit comments

Comments
 (0)