From bbaeb3df04f6c4da809452b27222de00b8285dc4 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Thu, 27 Aug 2026 19:59:46 +0800 Subject: [PATCH 01/52] feat(checkpoints): per-write checkpoints, task-start baseline, and perWriteCheckpoints setting (B1, #1375) --- packages/types/src/global-settings.ts | 13 + packages/types/src/vscode-extension-host.ts | 1 + src/core/task/Task.ts | 14 + src/core/task/__tests__/Task.spec.ts | 92 +++++ src/core/tools/ApplyPatchTool.ts | 67 +++- src/core/tools/EditFileTool.ts | 6 + src/core/tools/WriteToFileTool.ts | 8 + .../__tests__/applyPatchTool.execute.spec.ts | 331 ++++++++++++++++++ src/core/tools/__tests__/editFileTool.spec.ts | 42 +++ .../tools/__tests__/writeToFileTool.spec.ts | 77 ++++ src/core/webview/ClineProvider.ts | 4 + .../webview/__tests__/ClineProvider.spec.ts | 43 +++ .../settings/CheckpointSettings.tsx | 21 +- .../src/components/settings/SettingsView.tsx | 4 + .../__tests__/CheckpointSettings.spec.tsx | 125 +++++++ .../src/context/ExtensionStateContext.tsx | 1 + .../__tests__/ExtensionStateContext.spec.tsx | 2 + webview-ui/src/i18n/locales/ca/settings.json | 4 + webview-ui/src/i18n/locales/de/settings.json | 4 + webview-ui/src/i18n/locales/en/settings.json | 4 + webview-ui/src/i18n/locales/es/settings.json | 4 + webview-ui/src/i18n/locales/fr/settings.json | 4 + webview-ui/src/i18n/locales/hi/settings.json | 4 + webview-ui/src/i18n/locales/id/settings.json | 4 + webview-ui/src/i18n/locales/it/settings.json | 4 + webview-ui/src/i18n/locales/ja/settings.json | 4 + webview-ui/src/i18n/locales/ko/settings.json | 4 + webview-ui/src/i18n/locales/nl/settings.json | 4 + webview-ui/src/i18n/locales/pl/settings.json | 4 + .../src/i18n/locales/pt-BR/settings.json | 4 + webview-ui/src/i18n/locales/ru/settings.json | 4 + webview-ui/src/i18n/locales/tr/settings.json | 4 + webview-ui/src/i18n/locales/vi/settings.json | 4 + .../src/i18n/locales/zh-CN/settings.json | 4 + .../src/i18n/locales/zh-TW/settings.json | 4 + 35 files changed, 904 insertions(+), 19 deletions(-) create mode 100644 webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index 2bd5573039..8d1898a944 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -117,6 +117,13 @@ export const MAX_CHECKPOINT_TIMEOUT_SECONDS = 60 */ export const DEFAULT_CHECKPOINT_TIMEOUT_SECONDS = 15 +/** + * Whether per-write checkpoints and task-start baseline are enabled by default. + * Master switch for the B cluster of checkpoint features. + * @default true + */ +export const DEFAULT_PER_WRITE_CHECKPOINTS = true + /** * GlobalSettings */ @@ -226,6 +233,12 @@ export const globalSettingsSchema = z.object({ .min(MIN_CHECKPOINT_TIMEOUT_SECONDS) .max(MAX_CHECKPOINT_TIMEOUT_SECONDS) .optional(), + /** + * Whether to record a shadow-git checkpoint after every successful write_to_file, + * edit_file, and apply_patch (per-write checkpoints), plus a task-start baseline. + * @default true + */ + perWriteCheckpoints: z.boolean().optional(), ttsEnabled: z.boolean().optional(), ttsSpeed: z.number().optional(), diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 02fc7b0463..255625f290 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -372,6 +372,7 @@ export type ExtensionState = Pick< enableCheckpoints: boolean checkpointTimeout: number // Timeout for checkpoint initialization in seconds (default: 15) + perWriteCheckpoints: boolean maxOpenTabsContext: number // Maximum number of VSCode open tabs to include in context (0-500) maxWorkspaceFiles: number // Maximum number of files to include in current working directory details (0-500) showRooIgnoredFiles: boolean // Whether to show .rooignore'd files in listings diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 77a1333b39..aa15afbd85 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -480,6 +480,9 @@ export class Task extends EventEmitter implements TaskLike { public lastMessageTs?: number private autoApprovalTimeoutRef?: NodeJS.Timeout + // B1: task-start baseline, recorded at most once (initiateTaskLoop also runs on resume). + private taskStartBaselineDone = false + // Tool Use consecutiveMistakeCount: number = 0 consecutiveMistakeLimit: number @@ -3930,6 +3933,17 @@ export class Task extends EventEmitter implements TaskLike { // arm needed. void getCheckpointService(this) + // B1 task-start baseline: a suppressed pre-task root commit (default-on). + if (!this.taskStartBaselineDone) { + this.taskStartBaselineDone = true + const baselineEnabled = (await this.providerRef.deref()?.getState())?.perWriteCheckpoints + if (baselineEnabled !== false) { + // allowEmpty=true so a clean workspace still produces the baseline + // commit; awaited so the first per-write checkpoint cannot interleave. + await this.checkpointSave(true, true) + } + } + let nextUserContent = userContent let includeFileDetails = true diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 765dd1b2b6..ac2e356553 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7248,6 +7248,98 @@ describe("Cline", () => { }) }) + describe("task-start baseline (B1 perWriteCheckpoints)", () => { + it("records one suppressed baseline checkpoint per Task instance at loop start", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "baseline task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue(undefined) + const state = await mockProvider.getState() + vi.spyOn(mockProvider, "getState").mockResolvedValue(state) + + task.abort = true + + await taskAccess.initiateTaskLoop([]) + await taskAccess.initiateTaskLoop([]) + + expect(saveSpy).toHaveBeenCalledOnce() + expect(saveSpy).toHaveBeenCalledWith(true, true) + }) + + it("records the baseline checkpoint when the setting is unset (default-on)", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "baseline unset task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue(undefined) + const state = await mockProvider.getState() + // Unset: the property is absent from the state, so default-on applies. + const unsetState = { ...state } + Reflect.deleteProperty(unsetState, "perWriteCheckpoints") + vi.spyOn(mockProvider, "getState").mockResolvedValue(unsetState as typeof state) + + task.abort = true + + await taskAccess.initiateTaskLoop([]) + + expect(saveSpy).toHaveBeenCalledOnce() + expect(saveSpy).toHaveBeenCalledWith(true, true) + }) + + it("does not record a baseline checkpoint when perWriteCheckpoints is disabled", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "baseline disabled task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue(undefined) + const state = await mockProvider.getState() + vi.spyOn(mockProvider, "getState").mockResolvedValue({ ...state, perWriteCheckpoints: false }) + + task.abort = true + + await taskAccess.initiateTaskLoop([]) + + expect(saveSpy).not.toHaveBeenCalled() + }) + + it("awaits the baseline checkpoint before entering the request loop", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "baseline await task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + type SaveResult = Awaited> + let resolveSave: (value: SaveResult | PromiseLike) => void = () => {} + const saveSpy = vi + .spyOn(task, "checkpointSave") + .mockImplementation(() => new Promise((resolve) => (resolveSave = resolve))) + const requestSpy = vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true) + vi.spyOn(mockProvider, "getState").mockResolvedValue({ ...(await mockProvider.getState()) }) + const loopPromise = taskAccess.initiateTaskLoop([]) + + // The loop must not enter while the baseline checkpoint is still in flight. + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(saveSpy).toHaveBeenCalledOnce() + expect(requestSpy).not.toHaveBeenCalled() + + resolveSave() + await loopPromise + expect(requestSpy).toHaveBeenCalled() + }) + }) + describe("start()", () => { it("should be a no-op if the task was already started in the constructor", () => { const task = new Task({ diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 2713e08ffe..a9887e6cc0 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -6,6 +6,7 @@ import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { getReadablePath } from "../../utils/path" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { Task } from "../task/Task" +import { checkpointSave } from "../checkpoints" import { formatResponse } from "../prompts/responses" import { RecordSource } from "../context-tracking/FileContextTrackerTypes" import { fileExistsAtPath } from "../../utils/fs" @@ -102,7 +103,10 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { return } - // Process each file change + // Process each file change. The handlers report whether their file + // operation succeeded, so a rejected approval or a failed local write + // does not get checkpointed as if the patch had succeeded. + let patchSucceeded = true for (const change of changes) { const relPath = change.path const absolutePath = path.resolve(task.cwd, relPath) @@ -120,17 +124,39 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (change.type === "add") { // Create new file - await this.handleAddFile(change, absolutePath, relPath, task, callbacks, isWriteProtected) + patchSucceeded = + (await this.handleAddFile(change, absolutePath, relPath, task, callbacks, isWriteProtected)) && + patchSucceeded } else if (change.type === "delete") { // Delete file - await this.handleDeleteFile(absolutePath, relPath, task, callbacks, isWriteProtected) + patchSucceeded = + (await this.handleDeleteFile(absolutePath, relPath, task, callbacks, isWriteProtected)) && + patchSucceeded } else if (change.type === "update") { // Update file - await this.handleUpdateFile(change, absolutePath, relPath, task, callbacks, isWriteProtected) + patchSucceeded = + (await this.handleUpdateFile( + change, + absolutePath, + relPath, + task, + callbacks, + isWriteProtected, + )) && patchSucceeded } } task.consecutiveMistakeCount = 0 + + // B1: one checkpoint for the whole patch (not per file), and only when + // every file operation succeeded. Live setting with default-on + // semantics: skip only when explicitly false. + if (patchSucceeded) { + const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints + if (perWriteCheckpoints !== false) { + void checkpointSave(task, false, true).catch(() => {}) + } + } } catch (error) { await handleError("apply patch", error as Error) await task.diffViewProvider.reset() @@ -144,7 +170,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task: Task, callbacks: ToolCallbacks, isWriteProtected: boolean, - ): Promise { + ): Promise { const { askApproval, pushToolResult } = callbacks // Check if file already exists @@ -155,7 +181,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const errorMessage = `File already exists: ${relPath}. Use Update File instead.` await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) - return + return false } const newContent = change.newContent || "" @@ -209,7 +235,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } pushToolResult("Changes were rejected by the user.") await task.diffViewProvider.reset() - return + return false } // Save the changes @@ -227,6 +253,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { pushToolResult(message) await task.diffViewProvider.reset() task.processQueuedMessages() + return true } private async handleDeleteFile( @@ -235,7 +262,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task: Task, callbacks: ToolCallbacks, isWriteProtected: boolean, - ): Promise { + ): Promise { const { askApproval, pushToolResult } = callbacks // Check if file exists @@ -246,7 +273,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const errorMessage = `File not found: ${relPath}. Cannot delete a non-existent file.` await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) - return + return false } const isOutsideWorkspace = isPathOutsideWorkspace(absolutePath) @@ -268,7 +295,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (!didApprove) { pushToolResult("Delete operation was rejected by the user.") - return + return false } // Delete the file @@ -278,12 +305,13 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const errorMessage = `Failed to delete file '${relPath}': ${error instanceof Error ? error.message : String(error)}` await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) - return + return false } task.didEditFile = true pushToolResult(`Successfully deleted ${relPath}`) task.processQueuedMessages() + return true } private async handleUpdateFile( @@ -293,7 +321,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task: Task, callbacks: ToolCallbacks, isWriteProtected: boolean, - ): Promise { + ): Promise { const { askApproval, pushToolResult } = callbacks // Check if file exists @@ -304,7 +332,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const errorMessage = `File not found: ${relPath}. Cannot update a non-existent file.` await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) - return + return false } const originalContent = change.originalContent || "" @@ -318,9 +346,11 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // Generate and validate diff const diff = formatResponse.createPrettyPatch(relPath, originalContent, newContent) if (!diff) { + // A no-op change is not a failure: the patch processed cleanly and + // nothing was written, so the whole-patch success state is kept. pushToolResult(`No changes needed for '${relPath}'`) await task.diffViewProvider.reset() - return + return true } // Check experiment settings @@ -366,7 +396,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } pushToolResult("Changes were rejected by the user.") await task.diffViewProvider.reset() - return + return false } // Handle file move if specified @@ -379,7 +409,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await task.say("rooignore_error", change.movePath) pushToolResult(formatResponse.rooIgnoreError(change.movePath)) await task.diffViewProvider.reset() - return + return false } // Check if destination path is write-protected @@ -391,7 +421,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) await task.diffViewProvider.reset() - return + return false } // Check if destination path is outside workspace @@ -403,7 +433,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) await task.diffViewProvider.reset() - return + return false } // Save new content to the new path @@ -447,6 +477,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { pushToolResult(message) await task.diffViewProvider.reset() task.processQueuedMessages() + return true } override async handlePartial(task: Task, block: ToolUse<"apply_patch">): Promise { diff --git a/src/core/tools/EditFileTool.ts b/src/core/tools/EditFileTool.ts index a7301e2ac9..0a3cb5d2e8 100644 --- a/src/core/tools/EditFileTool.ts +++ b/src/core/tools/EditFileTool.ts @@ -11,6 +11,7 @@ import { RecordSource } from "../context-tracking/FileContextTrackerTypes" import { fileExistsAtPath } from "../../utils/fs" import { EXPERIMENT_IDS, experiments } from "../../shared/experiments" import { sanitizeUnifiedDiff, computeDiffStats } from "../diff/stats" +import { checkpointSave } from "../../core/checkpoints" import type { ToolUse } from "../../shared/tools" import { BaseTool, ToolCallbacks } from "./BaseTool" @@ -392,6 +393,7 @@ export class EditFileTool extends BaseTool<"edit_file"> { const state = await provider?.getState() const diagnosticsEnabled = state?.diagnosticsEnabled ?? true const writeDelayMs = state?.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS + const perWriteCheckpoints = state?.perWriteCheckpoints ?? true const isPreventFocusDisruptionEnabled = experiments.isEnabled( state?.experiments ?? {}, EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION, @@ -463,6 +465,10 @@ export class EditFileTool extends BaseTool<"edit_file"> { pushToolResult(message + replacementInfo) + if (perWriteCheckpoints) { + void checkpointSave(task, false, true).catch(() => {}) + } + await task.diffViewProvider.reset() this.resetPartialState() diff --git a/src/core/tools/WriteToFileTool.ts b/src/core/tools/WriteToFileTool.ts index 0c5c80abb9..6e0d7a0e80 100644 --- a/src/core/tools/WriteToFileTool.ts +++ b/src/core/tools/WriteToFileTool.ts @@ -13,6 +13,7 @@ import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { unescapeHtmlEntities } from "../../utils/text-normalization" import { EXPERIMENT_IDS, experiments } from "../../shared/experiments" import { convertNewFileToUnifiedDiff, computeDiffStats, sanitizeUnifiedDiff } from "../diff/stats" +import { checkpointSave } from "../checkpoints" import type { ToolUse } from "../../shared/tools" import { BaseTool, ToolCallbacks } from "./BaseTool" @@ -102,6 +103,7 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> { const state = await provider?.getState() const diagnosticsEnabled = state?.diagnosticsEnabled ?? true const writeDelayMs = state?.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS + const perWriteCheckpoints = state?.perWriteCheckpoints ?? true const isPreventFocusDisruptionEnabled = experiments.isEnabled( state?.experiments ?? {}, EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION, @@ -177,6 +179,12 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> { pushToolResult(message) + if (perWriteCheckpoints) { + // Await so the checkpoint (staging + commit) finishes before the next + // queued write starts; otherwise two writes can collapse into one commit. + await checkpointSave(task, false, true).catch(() => {}) + } + await task.diffViewProvider.reset() this.resetPartialState() diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index eb89838cad..b54c934b18 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -4,13 +4,29 @@ import type { MockedFunction } from "vitest" import { fileExistsAtPath } from "../../../utils/fs" import { isPathOutsideWorkspace } from "../../../utils/pathUtils" +import * as fsPromises from "fs/promises" import type { Task } from "../../task/Task" +import { checkpointSave } from "../../checkpoints" import { ApplyPatchTool } from "../ApplyPatchTool" +// The vi.mock factory exposes the fs/promises functions under a `default` +// property (matching the SUT's default import), which the static module type +// does not declare; cast once at this boundary rather than at each call site. +const mockedFsPromises = vi.mocked( + fsPromises as unknown as { + default: { + unlink: MockedFunction + writeFile: MockedFunction + } + }, +) + vi.mock("fs/promises", () => ({ default: { readFile: vi.fn().mockResolvedValue("original file content\n"), unlink: vi.fn().mockResolvedValue(undefined), + mkdir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), }, })) @@ -22,6 +38,10 @@ vi.mock("../../../utils/pathUtils", () => ({ isPathOutsideWorkspace: vi.fn().mockReturnValue(false), })) +vi.mock("../../checkpoints", () => ({ + checkpointSave: vi.fn().mockResolvedValue(undefined), +})) + describe("ApplyPatchTool.execute - delete file success path", () => { const mockedFileExistsAtPath = fileExistsAtPath as MockedFunction const mockedIsPathOutsideWorkspace = isPathOutsideWorkspace as MockedFunction @@ -38,6 +58,9 @@ describe("ApplyPatchTool.execute - delete file success path", () => { | "say" | "processQueuedMessages" | "didEditFile" + | "providerRef" + | "diffViewProvider" + | "fileContextTracker" > let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise> let mockHandleError: MockedFunction<(...args: unknown[]) => Promise> @@ -52,6 +75,11 @@ describe("ApplyPatchTool.execute - delete file success path", () => { mockTask = { cwd: "/workspace/project", consecutiveMistakeCount: 0, + providerRef: { + deref: vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({}), + }), + } as unknown as Task["providerRef"], recordToolUsage: vi.fn(), recordToolError: vi.fn(), rooIgnoreController: { @@ -63,6 +91,21 @@ describe("ApplyPatchTool.execute - delete file success path", () => { say: vi.fn().mockResolvedValue(undefined), processQueuedMessages: vi.fn(), didEditFile: false, + diffViewProvider: { + editType: "modify", + originalContent: undefined, + open: vi.fn().mockResolvedValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + scrollToFirstDiff: vi.fn(), + revertChanges: vi.fn().mockResolvedValue(undefined), + reset: vi.fn().mockResolvedValue(undefined), + saveDirectly: vi.fn().mockResolvedValue({ finalContent: "saved" }), + saveChanges: vi.fn().mockResolvedValue(undefined), + pushToolWriteResult: vi.fn().mockResolvedValue("File saved successfully"), + } as unknown as Task["diffViewProvider"], + fileContextTracker: { + trackFileContext: vi.fn().mockResolvedValue(undefined), + } as unknown as Task["fileContextTracker"], } mockAskApproval = vi.fn().mockResolvedValue(true) @@ -94,4 +137,292 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockTask.recordToolUsage).not.toHaveBeenCalled() expect(mockTask.recordToolError).not.toHaveBeenCalled() }) + + describe("per-write checkpoints (B1)", () => { + const deletePatch = `*** Begin Patch +*** Delete File: src/obsolete.ts +*** End Patch` + const mockedCheckpointSave = checkpointSave as MockedFunction + + it("records one suppressed checkpoint for the whole patch (default-on)", async () => { + await tool.execute({ patch: deletePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Successfully deleted")) + expect(mockedCheckpointSave).toHaveBeenCalledOnce() + expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true) + }) + + it("does not record a checkpoint when perWriteCheckpoints is disabled", async () => { + // Structural cast for the test double (matches the mock style used for the controllers above). + const ref = (mockTask["providerRef"] as unknown as { deref: MockedFunction<() => unknown> }).deref + ref.mockReturnValue({ + getState: vi.fn().mockResolvedValue({ perWriteCheckpoints: false }), + }) + + await tool.execute({ patch: deletePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Successfully deleted")) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("does not record a checkpoint when patch processing fails", async () => { + // A malformed patch fails at parse time, before the change loop and + // the post-loop checkpoint hook. + const badPatch = `*** Begin Patch +*** This is not a valid hunk +*** End Patch` + + await tool.execute({ patch: badPatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockTask.recordToolError).toHaveBeenCalledWith("apply_patch") + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + }) + + describe("checkpoint only for fully successful patches (B1)", () => { + const mockedCheckpointSave = checkpointSave as MockedFunction + const deletePatch = `*** Begin Patch +*** Delete File: src/obsolete.ts +*** End Patch` + const addPatch = `*** Begin Patch +*** Add File: src/new.ts ++hello ++world +*** End Patch` + const updatePatch = `*** Begin Patch +*** Update File: src/test.ts +@@ +-original file content ++modified content +*** End Patch` + const updateNoDiffPatch = `*** Begin Patch +*** Update File: src/test.ts +@@ +-original file content ++original file content +*** End Patch` + const movePatch = `*** Begin Patch +*** Update File: src/test.ts +*** Move to: src/moved.ts +@@ +-original file content ++modified content +*** End Patch` + + it("does not record a checkpoint when the user rejects the patch", async () => { + // Rejected approval: the handler early-returns without recording a + // tool error, so the success flag must come from the handler itself. + mockAskApproval.mockResolvedValue(false) + + await tool.execute({ patch: deletePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith("Delete operation was rejected by the user.") + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("does not record a checkpoint when the file to delete does not exist", async () => { + mockedFileExistsAtPath.mockResolvedValue(false) + + await tool.execute({ patch: deletePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("File not found")) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("does not record a checkpoint when the delete write fails", async () => { + mockedFsPromises.default.unlink.mockRejectedValueOnce(new Error("EBUSY")) + + await tool.execute({ patch: deletePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Failed to delete file")) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("does not record a checkpoint when the added file already exists", async () => { + // fileExistsAtPath resolves true by default in beforeEach. + + await tool.execute({ patch: addPatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("File already exists")) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("does not record a checkpoint when the user rejects the add", async () => { + mockedFileExistsAtPath.mockResolvedValue(false) + mockAskApproval.mockResolvedValue(false) + + await tool.execute({ patch: addPatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith("Changes were rejected by the user.") + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("records a checkpoint when the add succeeds", async () => { + mockedFileExistsAtPath.mockResolvedValue(false) + + await tool.execute({ patch: addPatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith("File saved successfully") + expect(mockedCheckpointSave).toHaveBeenCalledOnce() + }) + + it("does not record a checkpoint when the file to update does not exist", async () => { + mockedFileExistsAtPath.mockResolvedValue(false) + + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("File not found")) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("records a checkpoint when the update is a no-op (no changes needed)", async () => { + // A no-op change is not a failure, so the whole-patch checkpoint still runs. + + await tool.execute({ patch: updateNoDiffPatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("No changes needed")) + expect(mockedCheckpointSave).toHaveBeenCalledOnce() + }) + + it("does not record a checkpoint when the user rejects the update", async () => { + mockAskApproval.mockResolvedValue(false) + + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith("Changes were rejected by the user.") + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("does not record a checkpoint when the move destination is not allowed", async () => { + // First validateAccess call (source path, in the execute loop) passes; + // the move destination check inside the handler fails. + const validateAccess = ( + mockTask["rooIgnoreController"] as unknown as { validateAccess: MockedFunction<() => boolean> } + ).validateAccess + validateAccess.mockReturnValueOnce(true).mockReturnValue(false) + + await tool.execute({ patch: movePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockTask.say).toHaveBeenCalledWith("rooignore_error", "src/moved.ts") + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("does not record a checkpoint when the move destination is write-protected", async () => { + // Source path check (execute loop) passes; the move destination fails. + const isWriteProtected = ( + mockTask["rooProtectedController"] as unknown as { + isWriteProtected: MockedFunction<(p: string) => boolean> + } + ).isWriteProtected + isWriteProtected.mockReturnValueOnce(false).mockReturnValue(true) + + await tool.execute({ patch: movePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith( + expect.stringContaining("Cannot move file to write-protected path"), + ) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("does not record a checkpoint when the move destination is outside the workspace", async () => { + // Source path (first call) is inside; the move destination (second) + // call is outside the workspace. + mockedIsPathOutsideWorkspace.mockReturnValueOnce(false).mockReturnValue(true) + + await tool.execute({ patch: movePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith( + expect.stringContaining("Cannot move file to path outside workspace"), + ) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("records a checkpoint when the move succeeds", async () => { + await tool.execute({ patch: movePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + // path is platform-dependent (Windows resolves cwd to a drive path); + // assert on the written content instead. + expect(mockedFsPromises.default.writeFile).toHaveBeenCalledWith( + expect.any(String), + "modified content\n", + "utf8", + ) + expect(mockedCheckpointSave).toHaveBeenCalledOnce() + }) + + it("records a checkpoint when the in-place update succeeds", async () => { + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith("File saved successfully") + expect(mockedCheckpointSave).toHaveBeenCalledOnce() + }) + }) }) diff --git a/src/core/tools/__tests__/editFileTool.spec.ts b/src/core/tools/__tests__/editFileTool.spec.ts index 95a67f04d7..faa77c700a 100644 --- a/src/core/tools/__tests__/editFileTool.spec.ts +++ b/src/core/tools/__tests__/editFileTool.spec.ts @@ -7,6 +7,7 @@ import { fileExistsAtPath } from "../../../utils/fs" import { isPathOutsideWorkspace } from "../../../utils/pathUtils" import { getReadablePath } from "../../../utils/path" import { ToolUse, ToolResponse, AskApproval, HandleError, PushToolResult } from "../../../shared/tools" +import { checkpointSave } from "../../checkpoints" import { editFileTool } from "../EditFileTool" vi.mock("fs/promises", () => ({ @@ -59,6 +60,10 @@ vi.mock("../../diff/stats", () => ({ computeDiffStats: vi.fn(() => ({ additions: 1, deletions: 1 })), })) +vi.mock("../../checkpoints", () => ({ + checkpointSave: vi.fn().mockResolvedValue(undefined), +})) + vi.mock("vscode", () => ({ window: { showWarningMessage: vi.fn().mockResolvedValue(undefined), @@ -777,4 +782,41 @@ describe("editFileTool", () => { expect(mockAskApproval).toHaveBeenCalled() }) }) + + describe("per-write checkpoints (B1)", () => { + const mockedCheckpointSave = checkpointSave as MockedFunction + + it("records one suppressed checkpoint after a successful edit (default-on)", async () => { + await executeEditFileTool({}) + + expect(mockTask.consecutiveMistakeCount).toBe(0) + expect(mockedCheckpointSave).toHaveBeenCalledOnce() + expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask, false, true) + }) + + it("does not record a checkpoint when perWriteCheckpoints is disabled", async () => { + mockTask.providerRef.deref = vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + experiments: {}, + perWriteCheckpoints: false, + }), + }) + + await executeEditFileTool({}) + + expect(mockTask.consecutiveMistakeCount).toBe(0) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("does not record a checkpoint when the edit fails", async () => { + mockTask.diffViewProvider.saveChanges.mockRejectedValue(new Error("save failed")) + + await executeEditFileTool({}) + + expect(mockHandleError).toHaveBeenCalledWith("edit_file", expect.any(Error)) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + }) }) diff --git a/src/core/tools/__tests__/writeToFileTool.spec.ts b/src/core/tools/__tests__/writeToFileTool.spec.ts index 7cb9d01585..6d4dbf5b1c 100644 --- a/src/core/tools/__tests__/writeToFileTool.spec.ts +++ b/src/core/tools/__tests__/writeToFileTool.spec.ts @@ -8,6 +8,7 @@ import { getReadablePath } from "../../../utils/path" import { unescapeHtmlEntities } from "../../../utils/text-normalization" import { everyLineHasLineNumbers, stripLineNumbers } from "../../../integrations/misc/extract-text" import { ToolUse, ToolResponse, AskApproval, HandleError, PushToolResult } from "../../../shared/tools" +import { checkpointSave } from "../../checkpoints" import { writeToFileTool } from "../WriteToFileTool" vi.mock("path", async () => { @@ -89,6 +90,10 @@ vi.mock("../../ignore/RooIgnoreController", () => ({ }, })) +vi.mock("../../checkpoints", () => ({ + checkpointSave: vi.fn().mockResolvedValue(undefined), +})) + describe("writeToFileTool", () => { // Test data const testFilePath = "test/file.txt" @@ -473,4 +478,76 @@ describe("writeToFileTool", () => { expect(mockHandleError).toHaveBeenCalledWith("handling partial write_to_file", expect.any(Error)) }) }) + + describe("per-write checkpoints (B1)", () => { + const mockedCheckpointSave = checkpointSave as MockedFunction + + it("records one suppressed checkpoint after a successful write (default-on)", async () => { + await executeWriteFileTool({}) + + expect(mockedCheckpointSave).toHaveBeenCalledOnce() + expect(mockedCheckpointSave).toHaveBeenCalledWith(mockCline, false, true) + }) + + it("does not record a checkpoint when perWriteCheckpoints is disabled", async () => { + mockCline.providerRef.deref = vi.fn().mockReturnValue({ + getState: vi + .fn() + .mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, perWriteCheckpoints: false }), + }) + + await executeWriteFileTool({}) + + expect(mockCline.consecutiveMistakeCount).toBe(0) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("does not record a checkpoint when the write fails", async () => { + mockCline.diffViewProvider.open.mockRejectedValue(new Error("write failed")) + + await executeWriteFileTool({}) + + expect(mockHandleError).toHaveBeenCalledWith("writing file", expect.any(Error)) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("waits for the per-write checkpoint before the tool completes", async () => { + let checkpointStarted = false + let releaseCheckpoint: () => void = () => {} + mockedCheckpointSave.mockImplementationOnce(() => { + checkpointStarted = true + return new Promise((resolve) => { + releaseCheckpoint = () => resolve(undefined) + }) + }) + const processQueuedSpy = vi.fn() + mockCline.processQueuedMessages = processQueuedSpy + + const toolPromise = executeWriteFileTool({}) + + // Advance microtasks until the tool reaches the checkpoint call (all + // preceding awaits are mocked resolutions, no real timers involved). + for (let i = 0; i < 50 && !checkpointStarted; i++) { + await Promise.resolve() + } + expect(checkpointStarted).toBe(true) + + let settled = false + void toolPromise.then(() => { + settled = true + }) + + // The tool must not complete while the checkpoint is still + // staging/committing: a later write started by the task loop would + // otherwise collapse into the same (or a missing) commit. + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(settled).toBe(false) + expect(processQueuedSpy).not.toHaveBeenCalled() + + releaseCheckpoint() + await toolPromise + expect(settled).toBe(true) + expect(processQueuedSpy).toHaveBeenCalledOnce() + }) + }) }) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 678b93a136..56995af7ae 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -71,6 +71,7 @@ import { ORGANIZATION_ALLOW_ALL, DEFAULT_MODES, DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, + DEFAULT_PER_WRITE_CHECKPOINTS, getModelId, isRetiredProvider, modelIdKeys, @@ -3228,6 +3229,7 @@ export class ClineProvider ttsSpeed, enableCheckpoints, checkpointTimeout, + perWriteCheckpoints, soundVolume, writeDelayMs, diffFuzzyThreshold, @@ -3402,6 +3404,7 @@ export class ClineProvider ttsSpeed: ttsSpeed ?? 1.0, enableCheckpoints: enableCheckpoints ?? true, checkpointTimeout: checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, + perWriteCheckpoints: perWriteCheckpoints ?? DEFAULT_PER_WRITE_CHECKPOINTS, shouldShowAnnouncement: telemetrySetting !== "unset" && lastShownAnnouncementId !== this.latestAnnouncementId, allowedCommands: mergedAllowedCommands, @@ -3648,6 +3651,7 @@ export class ClineProvider ttsSpeed: stateValues.ttsSpeed ?? 1.0, enableCheckpoints: stateValues.enableCheckpoints ?? true, checkpointTimeout: stateValues.checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, + perWriteCheckpoints: stateValues.perWriteCheckpoints ?? DEFAULT_PER_WRITE_CHECKPOINTS, soundVolume: stateValues.soundVolume, writeDelayMs: stateValues.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS, diffFuzzyThreshold: stateValues.diffFuzzyThreshold ?? DEFAULT_DIFF_FUZZY_THRESHOLD, diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index c5925ab4d2..64735edb06 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -3187,6 +3187,7 @@ describe("ClineProvider", () => { soundEnabled: false, ttsEnabled: false, enableCheckpoints: false, + perWriteCheckpoints: false, writeDelayMs: 1000, mcpEnabled: true, mode: defaultModeSlug, @@ -4394,6 +4395,48 @@ describe("ClineProvider", () => { expect(state.alwaysDenyUnapprovedCommands).toBe(false) }) + test("getState returns the saved per-write checkpoints setting", async () => { + await provider.contextProxy.setValue("perWriteCheckpoints", false) + + const state = await provider.getState() + + expect(state.perWriteCheckpoints).toBe(false) + }) + + test("getState defaults per-write checkpoints to true when unset", async () => { + const state = await provider.getState() + + expect(state.perWriteCheckpoints).toBe(true) + }) + + test("getStateToPostToWebview returns the saved per-write checkpoints setting", async () => { + await provider.resolveWebviewView(mockWebviewView) + await provider.contextProxy.setValue("perWriteCheckpoints", true) + + const state = await provider.getStateToPostToWebview() + + expect(state.perWriteCheckpoints).toBe(true) + }) + + test("getStateToPostToWebview returns false when per-write checkpoints is saved as false", async () => { + // The default is also true, so only an explicit false proves that the + // stored value (rather than the default) reaches the webview state. + await provider.resolveWebviewView(mockWebviewView) + await provider.contextProxy.setValue("perWriteCheckpoints", false) + + const state = await provider.getStateToPostToWebview() + + expect(state.perWriteCheckpoints).toBe(false) + }) + + test("getStateToPostToWebview defaults per-write checkpoints to true when unset", async () => { + await provider.resolveWebviewView(mockWebviewView) + + const state = await provider.getStateToPostToWebview() + + expect(state.perWriteCheckpoints).toBe(true) + }) + test("language is set to VSCode language", async () => { // Mock VSCode language as Spanish ;(vscode.env as any).language = "pt-BR" diff --git a/webview-ui/src/components/settings/CheckpointSettings.tsx b/webview-ui/src/components/settings/CheckpointSettings.tsx index d0599e8dfe..1023ccd4e9 100644 --- a/webview-ui/src/components/settings/CheckpointSettings.tsx +++ b/webview-ui/src/components/settings/CheckpointSettings.tsx @@ -13,17 +13,20 @@ import { DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, MAX_CHECKPOINT_TIMEOUT_SECONDS, MIN_CHECKPOINT_TIMEOUT_SECONDS, + DEFAULT_PER_WRITE_CHECKPOINTS, } from "@roo-code/types" type CheckpointSettingsProps = HTMLAttributes & { enableCheckpoints?: boolean checkpointTimeout?: number - setCachedStateField: SetCachedStateField<"enableCheckpoints" | "checkpointTimeout"> + perWriteCheckpoints?: boolean + setCachedStateField: SetCachedStateField<"enableCheckpoints" | "checkpointTimeout" | "perWriteCheckpoints"> } export const CheckpointSettings = ({ enableCheckpoints, checkpointTimeout, + perWriteCheckpoints, setCachedStateField, ...props }: CheckpointSettingsProps) => { @@ -33,6 +36,22 @@ export const CheckpointSettings = ({ {t("settings:sections.checkpoints")}
+ + { + setCachedStateField("perWriteCheckpoints", e.target.checked) + }}> + {t("settings:checkpoints.perWrite.label")} + +
+ {t("settings:checkpoints.perWrite.description")} +
+
+ (({ onDone, t autoCondenseContextPercent, enableCheckpoints, checkpointTimeout, + perWriteCheckpoints, experiments, maxOpenTabsContext, maxWorkspaceFiles, @@ -447,6 +449,7 @@ const SettingsView = forwardRef(({ onDone, t ttsSpeed, enableCheckpoints: enableCheckpoints ?? false, checkpointTimeout: checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, + perWriteCheckpoints: perWriteCheckpoints ?? DEFAULT_PER_WRITE_CHECKPOINTS, writeDelayMs, diffFuzzyThreshold, terminalShellIntegrationTimeout: terminalShellIntegrationTimeout ?? 30_000, @@ -916,6 +919,7 @@ const SettingsView = forwardRef(({ onDone, t )} diff --git a/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx b/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx new file mode 100644 index 0000000000..b08c15ace7 --- /dev/null +++ b/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx @@ -0,0 +1,125 @@ +// npx vitest src/components/settings/__tests__/CheckpointSettings.spec.tsx + +import { render, screen, fireEvent } from "@/utils/test-utils" +import { CheckpointSettings } from "../CheckpointSettings" + +// Mock the translation hook +vi.mock("@/i18n/TranslationContext", () => ({ + useAppTranslation: () => ({ + t: (key: string) => { + if (key === "settings:checkpoints.perWrite.label") { + return "Checkpoint after each file write" + } + if (key === "settings:checkpoints.perWrite.description") { + return "Record a checkpoint snapshot after every successful file write by the agent" + } + return key + }, + }), +})) + +// Mock the UI components (async factory: vi.importActual resolves asynchronously). +vi.mock("@/components/ui", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + Slider: ({ defaultValue, onValueChange, "data-testid": dataTestId }: any) => ( + onValueChange?.([100])} + data-testid={dataTestId} + role="slider" + /> + ), + } +}) + +// Mock vscode utilities +vi.mock("@/utils/vscode", () => ({ + vscode: { + postMessage: vi.fn(), + }, +})) + +// Mock VSCode components to behave like standard HTML elements +vi.mock("@vscode/webview-ui-toolkit/react", () => ({ + VSCodeCheckbox: ({ checked, onChange, children, ...props }: any) => ( + + ), + VSCodeLink: ({ children, ...props }: any) => {children}, +})) + +describe("CheckpointSettings", () => { + const setCachedStateField = vi.fn() + + beforeEach(() => { + vi.clearAllMocks() + }) + + it("renders the per-write checkpoints checkbox checked by default when the value is unset", () => { + render() + + const checkbox = screen.getByRole("checkbox", { name: "Checkpoint after each file write" }) + expect(checkbox).toBeChecked() + }) + + it("unchecks the per-write checkpoints checkbox when the saved value is false", () => { + render( + , + ) + + const checkbox = screen.getByRole("checkbox", { name: "Checkpoint after each file write" }) + expect(checkbox).not.toBeChecked() + }) + + it("keeps the per-write checkpoints checkbox checked when the saved value is true", () => { + render( + , + ) + + const checkbox = screen.getByRole("checkbox", { name: "Checkpoint after each file write" }) + expect(checkbox).toBeChecked() + }) + + it("caches a toggle to enable per-write checkpoints when the user checks the box", () => { + render( + , + ) + + const checkbox = screen.getByRole("checkbox", { name: "Checkpoint after each file write" }) + fireEvent.click(checkbox) + + expect(setCachedStateField).toHaveBeenCalledWith("perWriteCheckpoints", true) + }) + + it("caches a toggle to disable per-write checkpoints when the user unchecks the box", () => { + render() + + const checkbox = screen.getByRole("checkbox", { name: "Checkpoint after each file write" }) + fireEvent.click(checkbox) + + expect(setCachedStateField).toHaveBeenCalledWith("perWriteCheckpoints", false) + }) +}) diff --git a/webview-ui/src/context/ExtensionStateContext.tsx b/webview-ui/src/context/ExtensionStateContext.tsx index 38bec0fd8b..1edf937c4a 100644 --- a/webview-ui/src/context/ExtensionStateContext.tsx +++ b/webview-ui/src/context/ExtensionStateContext.tsx @@ -255,6 +255,7 @@ export const createInitialExtensionState = (): ExtensionState => ({ ttsEnabled: false, ttsSpeed: 1.0, enableCheckpoints: true, + perWriteCheckpoints: true, checkpointTimeout: DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, // Default to 15 seconds language: "en", // Default language code // Placeholder before the extension state hydrates: use the shared default diff --git a/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx b/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx index 7158097960..52b2cb3c12 100644 --- a/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx +++ b/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx @@ -927,6 +927,7 @@ describe("mergeExtensionState", () => { taskHistory: [], shouldShowAnnouncement: false, enableCheckpoints: true, + perWriteCheckpoints: true, // Matches the shared DEFAULT_WRITE_DELAY_MS (pre-hydration placeholder // must not disagree with the extension's own fallback). writeDelayMs: 0, @@ -999,6 +1000,7 @@ describe("mergeExtensionState", () => { taskHistory: [], shouldShowAnnouncement: false, enableCheckpoints: true, + perWriteCheckpoints: true, // Matches the shared DEFAULT_WRITE_DELAY_MS (pre-hydration placeholder // must not disagree with the extension's own fallback). writeDelayMs: 0, diff --git a/webview-ui/src/i18n/locales/ca/settings.json b/webview-ui/src/i18n/locales/ca/settings.json index 551782a3fd..38ba5946cc 100644 --- a/webview-ui/src/i18n/locales/ca/settings.json +++ b/webview-ui/src/i18n/locales/ca/settings.json @@ -696,6 +696,10 @@ "enable": { "label": "Habilitar punts de control automàtics", "description": "Quan està habilitat, Zoo crearà automàticament punts de control durant l'execució de tasques, facilitant la revisió de canvis o la reversió a estats anteriors. <0>Més informació" + }, + "perWrite": { + "label": "Punt de control després de cada escriptura de fitxer", + "description": "Registra una instantània de punt de control després de cada escriptura de fitxer reeixida de l’agent" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/de/settings.json b/webview-ui/src/i18n/locales/de/settings.json index 4d320d4968..fdd7e19eb5 100644 --- a/webview-ui/src/i18n/locales/de/settings.json +++ b/webview-ui/src/i18n/locales/de/settings.json @@ -695,6 +695,10 @@ "enable": { "label": "Automatische Kontrollpunkte aktivieren", "description": "Wenn aktiviert, erstellt Zoo automatisch Kontrollpunkte während der Aufgabenausführung, was die Überprüfung von Änderungen oder die Rückkehr zu früheren Zuständen erleichtert. <0>Mehr erfahren" + }, + "perWrite": { + "label": "Kontrollpunkt nach jedem Dateischreibvorgang", + "description": "Ein Kontrollpunkt-Snapshot wird nach jedem erfolgreichen Dateischreibvorgang des Agents erfasst" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/en/settings.json b/webview-ui/src/i18n/locales/en/settings.json index 4655ed7fbe..fba2d6b2f9 100644 --- a/webview-ui/src/i18n/locales/en/settings.json +++ b/webview-ui/src/i18n/locales/en/settings.json @@ -768,6 +768,10 @@ "enable": { "label": "Enable automatic checkpoints", "description": "When enabled, Zoo will automatically create checkpoints during task execution, making it easy to review changes or revert to earlier states. <0>Learn more" + }, + "perWrite": { + "label": "Checkpoint after each file write", + "description": "Record a checkpoint snapshot after every successful file write by the agent" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/es/settings.json b/webview-ui/src/i18n/locales/es/settings.json index 27623532b0..551e7e3aa7 100644 --- a/webview-ui/src/i18n/locales/es/settings.json +++ b/webview-ui/src/i18n/locales/es/settings.json @@ -696,6 +696,10 @@ "enable": { "label": "Habilitar puntos de control automáticos", "description": "Cuando está habilitado, Zoo creará automáticamente puntos de control durante la ejecución de tareas, facilitando la revisión de cambios o la reversión a estados anteriores. <0>Más información" + }, + "perWrite": { + "label": "Punto de control después de cada escritura de archivo", + "description": "Registra una instantánea de punto de control después de cada escritura de archivo exitosa del agente" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/fr/settings.json b/webview-ui/src/i18n/locales/fr/settings.json index 0efde01694..05068b1381 100644 --- a/webview-ui/src/i18n/locales/fr/settings.json +++ b/webview-ui/src/i18n/locales/fr/settings.json @@ -696,6 +696,10 @@ "enable": { "label": "Activer les points de contrôle automatiques", "description": "Lorsque cette option est activée, Zoo créera automatiquement des points de contrôle pendant l'exécution des tâches, facilitant la révision des modifications ou le retour à des états antérieurs. <0>En savoir plus" + }, + "perWrite": { + "label": "Point de contrôle après chaque écriture de fichier", + "description": "Enregistre un instantané de point de contrôle après chaque écriture de fichier réussie par l’agent" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/hi/settings.json b/webview-ui/src/i18n/locales/hi/settings.json index c0101cd92e..a38d11b8ff 100644 --- a/webview-ui/src/i18n/locales/hi/settings.json +++ b/webview-ui/src/i18n/locales/hi/settings.json @@ -695,6 +695,10 @@ "enable": { "label": "स्वचालित चेकपॉइंट सक्षम करें", "description": "जब सक्षम होता है, तो Zoo कार्य निष्पादन के दौरान स्वचालित रूप से चेकपॉइंट बनाएगा, जिससे परिवर्तनों की समीक्षा करना या पहले की स्थितियों पर वापस जाना आसान हो जाएगा। <0>अधिक जानें" + }, + "perWrite": { + "label": "हर फ़ाइल लिखने के बाद चेकपॉइंट", + "description": "एजेंट द्वारा हर सफल फ़ाइल लिखने के बाद एक चेकपॉइंट स्नैपशॉट दर्ज किया जाता है" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/id/settings.json b/webview-ui/src/i18n/locales/id/settings.json index 060629cfb9..fb9c7f9d5e 100644 --- a/webview-ui/src/i18n/locales/id/settings.json +++ b/webview-ui/src/i18n/locales/id/settings.json @@ -694,6 +694,10 @@ "enable": { "label": "Aktifkan checkpoint otomatis", "description": "Ketika diaktifkan, Zoo akan secara otomatis membuat checkpoint selama eksekusi tugas, memudahkan untuk meninjau perubahan atau kembali ke state sebelumnya. <0>Pelajari lebih lanjut" + }, + "perWrite": { + "label": "Checkpoint setelah setiap penulisan file", + "description": "Merekam snapshot checkpoint setelah setiap penulisan file yang berhasil oleh agen" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/it/settings.json b/webview-ui/src/i18n/locales/it/settings.json index 4c8cc0fbec..2b39b2023e 100644 --- a/webview-ui/src/i18n/locales/it/settings.json +++ b/webview-ui/src/i18n/locales/it/settings.json @@ -696,6 +696,10 @@ "enable": { "label": "Abilita punti di controllo automatici", "description": "Quando abilitato, Zoo creerà automaticamente punti di controllo durante l'esecuzione dei compiti, facilitando la revisione delle modifiche o il ritorno a stati precedenti. <0>Scopri di più" + }, + "perWrite": { + "label": "Punto di controllo dopo ogni scrittura del file", + "description": "Registra uno snapshot di punto di controllo dopo ogni scrittura del file riuscita dell’agente" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/ja/settings.json b/webview-ui/src/i18n/locales/ja/settings.json index 25e9c126aa..b60fab3224 100644 --- a/webview-ui/src/i18n/locales/ja/settings.json +++ b/webview-ui/src/i18n/locales/ja/settings.json @@ -694,6 +694,10 @@ "enable": { "label": "自動チェックポイントを有効化", "description": "有効にすると、Zooはタスク実行中に自動的にチェックポイントを作成し、変更の確認や以前の状態への復帰を容易にします。 <0>詳細情報" + }, + "perWrite": { + "label": "ファイルの書き込みごとにチェックポイント", + "description": "エージェントによる各ファイルの書き込み成功後にチェックポイントのスナップショットを記録します" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/ko/settings.json b/webview-ui/src/i18n/locales/ko/settings.json index 2e28bc3526..f185513e87 100644 --- a/webview-ui/src/i18n/locales/ko/settings.json +++ b/webview-ui/src/i18n/locales/ko/settings.json @@ -694,6 +694,10 @@ "enable": { "label": "자동 체크포인트 활성화", "description": "활성화되면 Zoo는 작업 실행 중에 자동으로 체크포인트를 생성하여 변경 사항을 검토하거나 이전 상태로 되돌리기 쉽게 합니다. <0>더 알아보기" + }, + "perWrite": { + "label": "파일을 쓸 때마다 체크포인트", + "description": "에이전트가 파일 쓰기에 성공할 때마다 체크포인트 스냅샷을 기록합니다" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/nl/settings.json b/webview-ui/src/i18n/locales/nl/settings.json index 76c0880328..e5ababcb63 100644 --- a/webview-ui/src/i18n/locales/nl/settings.json +++ b/webview-ui/src/i18n/locales/nl/settings.json @@ -695,6 +695,10 @@ "enable": { "label": "Automatische checkpoints inschakelen", "description": "Indien ingeschakeld, maakt Zoo automatisch checkpoints tijdens het uitvoeren van taken, zodat je eenvoudig wijzigingen kunt bekijken of terugzetten. <0>Meer informatie" + }, + "perWrite": { + "label": "Checkpoint na elke bestandsschrijving", + "description": "Neemt een checkpoint-snapshot op na elke succesvolle bestandsschrijving door de agent" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/pl/settings.json b/webview-ui/src/i18n/locales/pl/settings.json index fd09d548c5..ed896363fc 100644 --- a/webview-ui/src/i18n/locales/pl/settings.json +++ b/webview-ui/src/i18n/locales/pl/settings.json @@ -697,6 +697,10 @@ "enable": { "label": "Włącz automatyczne punkty kontrolne", "description": "Gdy włączone, Zoo automatycznie utworzy punkty kontrolne podczas wykonywania zadań, ułatwiając przeglądanie zmian lub powrót do wcześniejszych stanów. <0>Dowiedz się więcej" + }, + "perWrite": { + "label": "Punkt kontrolny po każdym zapisaniu pliku", + "description": "Rejestruje migawkę punktu kontrolnego po każdym udanym zapisaniu pliku przez agenta" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/pt-BR/settings.json b/webview-ui/src/i18n/locales/pt-BR/settings.json index 47256c7d6b..a3da63fce0 100644 --- a/webview-ui/src/i18n/locales/pt-BR/settings.json +++ b/webview-ui/src/i18n/locales/pt-BR/settings.json @@ -696,6 +696,10 @@ "enable": { "label": "Ativar pontos de verificação automáticos", "description": "Quando ativado, o Zoo criará automaticamente pontos de verificação durante a execução de tarefas, facilitando a revisão de alterações ou o retorno a estados anteriores. <0>Saiba mais" + }, + "perWrite": { + "label": "Ponto de verificação após cada gravação de arquivo", + "description": "Registra um snapshot de ponto de verificação após cada gravação de arquivo bem-sucedida pelo agente" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/ru/settings.json b/webview-ui/src/i18n/locales/ru/settings.json index 7bd2cd6c3e..4bb69e3be8 100644 --- a/webview-ui/src/i18n/locales/ru/settings.json +++ b/webview-ui/src/i18n/locales/ru/settings.json @@ -697,6 +697,10 @@ "enable": { "label": "Включить автоматические контрольные точки", "description": "Если включено, Zoo будет автоматически создавать контрольные точки во время выполнения задач, что упрощает просмотр изменений или возврат к предыдущим состояниям. <0>Подробнее" + }, + "perWrite": { + "label": "Контрольная точка после каждой записи файла", + "description": "Записывает снимок контрольной точки после каждой успешной записи файла агентом" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/tr/settings.json b/webview-ui/src/i18n/locales/tr/settings.json index 3cc4b0f554..613509df13 100644 --- a/webview-ui/src/i18n/locales/tr/settings.json +++ b/webview-ui/src/i18n/locales/tr/settings.json @@ -695,6 +695,10 @@ "enable": { "label": "Otomatik kontrol noktalarını etkinleştir", "description": "Etkinleştirildiğinde, Zoo görev yürütme sırasında otomatik olarak kontrol noktaları oluşturarak değişiklikleri gözden geçirmeyi veya önceki durumlara dönmeyi kolaylaştırır. <0>Daha fazla bilgi" + }, + "perWrite": { + "label": "Her dosya yazımından sonra kontrol noktası", + "description": "Ajanın her başarılı dosya yazımından sonra bir kontrol noktası görüntüsü kaydeder" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/vi/settings.json b/webview-ui/src/i18n/locales/vi/settings.json index 462778d282..80a4d89147 100644 --- a/webview-ui/src/i18n/locales/vi/settings.json +++ b/webview-ui/src/i18n/locales/vi/settings.json @@ -694,6 +694,10 @@ "enable": { "label": "Bật điểm kiểm tra tự động", "description": "Khi được bật, Zoo sẽ tự động tạo các điểm kiểm tra trong quá trình thực hiện nhiệm vụ, giúp dễ dàng xem lại các thay đổi hoặc quay lại trạng thái trước đó. <0>Tìm hiểu thêm" + }, + "perWrite": { + "label": "Điểm kiểm tra sau mỗi lần ghi file", + "description": "Ghi lại ảnh chụp nhanh điểm kiểm tra sau mỗi lần ghi file thành công của agent" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/zh-CN/settings.json b/webview-ui/src/i18n/locales/zh-CN/settings.json index 7da9f157f0..5706068caf 100644 --- a/webview-ui/src/i18n/locales/zh-CN/settings.json +++ b/webview-ui/src/i18n/locales/zh-CN/settings.json @@ -694,6 +694,10 @@ "enable": { "label": "启用自动存档点", "description": "开启后自动创建任务存档点,方便回溯修改。 <0>了解更多" + }, + "perWrite": { + "label": "每次文件写入后创建存档点", + "description": "智能体每次成功写入文件后都会记录一个存档点快照" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/zh-TW/settings.json b/webview-ui/src/i18n/locales/zh-TW/settings.json index 948577e63b..4862fce042 100644 --- a/webview-ui/src/i18n/locales/zh-TW/settings.json +++ b/webview-ui/src/i18n/locales/zh-TW/settings.json @@ -721,6 +721,10 @@ "enable": { "label": "啟用自動檢查點", "description": "啟用後,Zoo 將在工作執行期間自動建立檢查點,方便檢視變更或回到較早的狀態。 <0>了解更多" + }, + "perWrite": { + "label": "每次檔案寫入後建立檢查點", + "description": "代理每次成功寫入檔案後都會記錄一個檢查點快照" } }, "notifications": { From e0232f754fa1ade36428b0bcf781b0939134f004 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Fri, 28 Aug 2026 10:10:47 +0800 Subject: [PATCH 02/52] fix(fws): export the webview initializer and test the pre-hydration checkpoint default createInitialExtensionState is exported and a focused test asserts it initializes perWriteCheckpoints to true: a regression that dropped the key from the initializer (rather than from a merge fixture) would otherwise stay hidden (CodeRabbit finding on trial #1413). --- .../context/__tests__/ExtensionStateContext.spec.tsx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx b/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx index 52b2cb3c12..e822f21efb 100644 --- a/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx +++ b/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx @@ -916,6 +916,16 @@ describe("ExtensionStateContext", () => { }), ) }) + + it("initializes the per-write checkpoint default before hydration", () => { + // The initializer itself (not a merge fixture) must carry the per-write + // checkpoint default: a regression that dropped it from + // createInitialExtensionState would otherwise stay hidden because the + // merge tests supply the key manually. + const state = createInitialExtensionState() + + expect(state.perWriteCheckpoints).toBe(true) + }) }) describe("mergeExtensionState", () => { From 31b387233347986d4ac310fe398d17bfb166bdaf Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Sun, 30 Aug 2026 12:33:23 +0800 Subject: [PATCH 03/52] =?UTF-8?q?chore(ci):=20empty=20commit=20=E2=80=94?= =?UTF-8?q?=20re-trigger=20CI=20and=20the=20CodeRabbit=20current-head=20re?= =?UTF-8?q?view=20gate=20(no=20code=20change)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 1ad5aaec0a1f8f719c7da07360a688f747d850cc Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Tue, 13 Oct 2026 00:58:02 +0800 Subject: [PATCH 04/52] fix(checkpoints): skip task-start baseline on history resume The baseline guard was instance-local, so a Task constructed from a history item (resumeTaskFromHistory) recorded a second task-start baseline; the design in issue 1397 requires exactly one baseline per task, and the resumed task's shadow repo already carries the original baseline for the first post-resume write checkpoint to diff against. Gate the baseline on the original start path and add a regression test. Review feedback on PR 1404; the identical fix is ported to every unit carrying the B1 task-loop code. --- src/core/task/Task.ts | 5 ++++- src/core/task/__tests__/Task.spec.ts | 29 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index aa15afbd85..59fb34c167 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -3934,7 +3934,10 @@ export class Task extends EventEmitter implements TaskLike { void getCheckpointService(this) // B1 task-start baseline: a suppressed pre-task root commit (default-on). - if (!this.taskStartBaselineDone) { + // History resumes skip it: the baseline belongs to the original task start + // (exactly once per task), and the resumed task's shadow repo already carries + // a baseline for the first post-resume write checkpoint to diff against. + if (!this.taskStartBaselineDone && !this._isHistoryTask) { this.taskStartBaselineDone = true const baselineEnabled = (await this.providerRef.deref()?.getState())?.perWriteCheckpoints if (baselineEnabled !== false) { diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index ac2e356553..12d1435ede 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7270,6 +7270,35 @@ describe("Cline", () => { expect(saveSpy).toHaveBeenCalledWith(true, true) }) + it("does not record a baseline when the task resumes from history", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + historyItem: { + id: "resumed-baseline-task", + number: 1, + ts: Date.now(), + task: "resumed baseline task", + tokensIn: 10, + tokensOut: 5, + totalCost: 0.001, + }, + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue(undefined) + const state = await mockProvider.getState() + vi.spyOn(mockProvider, "getState").mockResolvedValue(state) + + task.abort = true + + await taskAccess.initiateTaskLoop([]) + + // A history resume must not re-record the baseline: it belongs to the + // original task start (exactly once per task). + expect(saveSpy).not.toHaveBeenCalled() + }) + it("records the baseline checkpoint when the setting is unset (default-on)", async () => { const task = new Task({ provider: mockProvider, From a26cd2f74a4be4604c8c168e7900fb6ba656e305 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Tue, 13 Oct 2026 02:05:09 +0800 Subject: [PATCH 05/52] fix(checkpoints): skip baseline on aborted task; share default constant - initiateTaskLoop skips the task-start baseline when the task is already aborted: the loop will never run, so the awaited save would only add latency to a task being disposed. Regression test added. - WriteToFileTool/EditFileTool read perWriteCheckpoints through the shared DEFAULT_PER_WRITE_CHECKPOINTS constant instead of a hardcoded true, matching the provider reader (AGENTS.md: consumers use the same default). Review feedback on PR 1410; applied at the owning unit and ported across the chain. --- src/core/task/Task.ts | 4 +++- src/core/task/__tests__/Task.spec.ts | 29 +++++++++++++++++++++++++--- src/core/tools/EditFileTool.ts | 4 ++-- src/core/tools/WriteToFileTool.ts | 4 ++-- 4 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 59fb34c167..50ede26938 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -3937,7 +3937,9 @@ export class Task extends EventEmitter implements TaskLike { // History resumes skip it: the baseline belongs to the original task start // (exactly once per task), and the resumed task's shadow repo already carries // a baseline for the first post-resume write checkpoint to diff against. - if (!this.taskStartBaselineDone && !this._isHistoryTask) { + // An already-aborted task skips it too: the loop will never run, so the + // save would only add latency to a task that is being disposed. + if (!this.taskStartBaselineDone && !this._isHistoryTask && !this.abort) { this.taskStartBaselineDone = true const baselineEnabled = (await this.providerRef.deref()?.getState())?.perWriteCheckpoints if (baselineEnabled !== false) { diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 12d1435ede..e3a8369dbc 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7261,7 +7261,9 @@ describe("Cline", () => { const state = await mockProvider.getState() vi.spyOn(mockProvider, "getState").mockResolvedValue(state) - task.abort = true + // End the loop after the first request; abort stays false so the + // baseline block (not the loop) is what the save spy observes. + vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true) await taskAccess.initiateTaskLoop([]) await taskAccess.initiateTaskLoop([]) @@ -7290,7 +7292,7 @@ describe("Cline", () => { const state = await mockProvider.getState() vi.spyOn(mockProvider, "getState").mockResolvedValue(state) - task.abort = true + vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true) await taskAccess.initiateTaskLoop([]) @@ -7314,7 +7316,7 @@ describe("Cline", () => { Reflect.deleteProperty(unsetState, "perWriteCheckpoints") vi.spyOn(mockProvider, "getState").mockResolvedValue(unsetState as typeof state) - task.abort = true + vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true) await taskAccess.initiateTaskLoop([]) @@ -7334,10 +7336,31 @@ describe("Cline", () => { const state = await mockProvider.getState() vi.spyOn(mockProvider, "getState").mockResolvedValue({ ...state, perWriteCheckpoints: false }) + vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true) + + await taskAccess.initiateTaskLoop([]) + + expect(saveSpy).not.toHaveBeenCalled() + }) + + it("does not record a baseline when the task is already aborted", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "aborted baseline task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue(undefined) + const state = await mockProvider.getState() + vi.spyOn(mockProvider, "getState").mockResolvedValue(state) + task.abort = true await taskAccess.initiateTaskLoop([]) + // A task cancelled before the loop starts must not pay for (or await) + // a baseline checkpoint it will never use. expect(saveSpy).not.toHaveBeenCalled() }) diff --git a/src/core/tools/EditFileTool.ts b/src/core/tools/EditFileTool.ts index 0a3cb5d2e8..db52324330 100644 --- a/src/core/tools/EditFileTool.ts +++ b/src/core/tools/EditFileTool.ts @@ -1,7 +1,7 @@ import fs from "fs/promises" import path from "path" -import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" +import { type ClineSayTool, DEFAULT_PER_WRITE_CHECKPOINTS, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { getReadablePath } from "../../utils/path" import { isPathOutsideWorkspace } from "../../utils/pathUtils" @@ -393,7 +393,7 @@ export class EditFileTool extends BaseTool<"edit_file"> { const state = await provider?.getState() const diagnosticsEnabled = state?.diagnosticsEnabled ?? true const writeDelayMs = state?.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS - const perWriteCheckpoints = state?.perWriteCheckpoints ?? true + const perWriteCheckpoints = state?.perWriteCheckpoints ?? DEFAULT_PER_WRITE_CHECKPOINTS const isPreventFocusDisruptionEnabled = experiments.isEnabled( state?.experiments ?? {}, EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION, diff --git a/src/core/tools/WriteToFileTool.ts b/src/core/tools/WriteToFileTool.ts index 6e0d7a0e80..e3e7bf1728 100644 --- a/src/core/tools/WriteToFileTool.ts +++ b/src/core/tools/WriteToFileTool.ts @@ -1,7 +1,7 @@ import path from "path" import fs from "fs/promises" -import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" +import { type ClineSayTool, DEFAULT_PER_WRITE_CHECKPOINTS, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" @@ -103,7 +103,7 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> { const state = await provider?.getState() const diagnosticsEnabled = state?.diagnosticsEnabled ?? true const writeDelayMs = state?.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS - const perWriteCheckpoints = state?.perWriteCheckpoints ?? true + const perWriteCheckpoints = state?.perWriteCheckpoints ?? DEFAULT_PER_WRITE_CHECKPOINTS const isPreventFocusDisruptionEnabled = experiments.isEnabled( state?.experiments ?? {}, EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION, From d037c3071c0b6d576bac46a1b2c5d71ace2d9aff Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Tue, 13 Oct 2026 03:15:49 +0800 Subject: [PATCH 06/52] fix(checkpoints): recheck cancellation after the baseline state lookup Cancellation can land while the perWriteCheckpoints state lookup is pending; the pre-lookup guard alone would still await checkpointSave for a canceled task. Recheck this.abort after the lookup and before the save, and cover the deferred-lookup cancellation window with a regression test. Review feedback on PR 1410; ported to every unit carrying the task-loop code. --- src/core/task/Task.ts | 4 +++- src/core/task/__tests__/Task.spec.ts | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 50ede26938..b90a6c3b80 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -3942,7 +3942,9 @@ export class Task extends EventEmitter implements TaskLike { if (!this.taskStartBaselineDone && !this._isHistoryTask && !this.abort) { this.taskStartBaselineDone = true const baselineEnabled = (await this.providerRef.deref()?.getState())?.perWriteCheckpoints - if (baselineEnabled !== false) { + // Cancellation can arrive while the state lookup is pending; recheck + // before the save so a canceled task performs no checkpoint work. + if (baselineEnabled !== false && !this.abort) { // allowEmpty=true so a clean workspace still produces the baseline // commit; awaited so the first per-write checkpoint cannot interleave. await this.checkpointSave(true, true) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index e3a8369dbc..718dd01cdc 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7364,6 +7364,31 @@ describe("Cline", () => { expect(saveSpy).not.toHaveBeenCalled() }) + it("does not record a baseline when cancellation arrives during the state lookup", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "racy baseline task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue(undefined) + const state = await mockProvider.getState() + type StateResult = Awaited> + let resolveState: (value: StateResult | PromiseLike) => void = () => {} + const statePromise = new Promise((resolve) => (resolveState = resolve)) + vi.spyOn(mockProvider, "getState").mockReturnValue(statePromise) + + const loopPromise = taskAccess.initiateTaskLoop([]) + // Cancellation lands while the state lookup is still pending. + task.abort = true + resolveState({ ...state, perWriteCheckpoints: true }) + await loopPromise + + // The post-lookup recheck must skip the save for the canceled task. + expect(saveSpy).not.toHaveBeenCalled() + }) + it("awaits the baseline checkpoint before entering the request loop", async () => { const task = new Task({ provider: mockProvider, From 2e382a99385d90efc24afdc7f78c6d627b07851d Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Tue, 13 Oct 2026 05:45:35 +0800 Subject: [PATCH 07/52] fix(checkpoints): await write-path checkpoint saves before state handoff EditFileTool and ApplyPatchTool fired checkpointSave without awaiting it: the diff state reset and queued work could proceed while the checkpoint was still staging/committing, a queued write's own checkpoint could interleave, and shutdown could lose the commit entirely. Await the save (WriteToFileTool already did), matching the semantics the later units of this series settled on. Held-promise regression tests pin the ordering on both paths. Review feedback on PR 1404; the EditFileTool half is ported to the sibling unit that still carries the unawaited call. --- src/core/tools/ApplyPatchTool.ts | 5 +++- src/core/tools/EditFileTool.ts | 6 ++++- .../__tests__/applyPatchTool.execute.spec.ts | 25 +++++++++++++++++++ src/core/tools/__tests__/editFileTool.spec.ts | 20 +++++++++++++++ 4 files changed, 54 insertions(+), 2 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index a9887e6cc0..f4a43b2f1c 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -154,7 +154,10 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (patchSucceeded) { const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints if (perWriteCheckpoints !== false) { - void checkpointSave(task, false, true).catch(() => {}) + // Await so the whole-patch checkpoint persists before the tool + // completes; an unawaited save lets queued work interleave its own + // checkpoint and lets shutdown lose the commit. + await checkpointSave(task, false, true).catch(() => {}) } } } catch (error) { diff --git a/src/core/tools/EditFileTool.ts b/src/core/tools/EditFileTool.ts index db52324330..9f17cd5c2a 100644 --- a/src/core/tools/EditFileTool.ts +++ b/src/core/tools/EditFileTool.ts @@ -466,7 +466,11 @@ export class EditFileTool extends BaseTool<"edit_file"> { pushToolResult(message + replacementInfo) if (perWriteCheckpoints) { - void checkpointSave(task, false, true).catch(() => {}) + // Await so the checkpoint (staging + commit) completes before the + // diff state resets and queued work proceeds; fire-and-forget lets a + // queued write's own checkpoint interleave and lets shutdown lose the + // commit entirely. + await checkpointSave(task, false, true).catch(() => {}) } await task.diffViewProvider.reset() diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index b54c934b18..7a60606761 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -156,6 +156,31 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true) }) + it("awaits the checkpoint before completing the patch", async () => { + // An unawaited save let the tool complete (and queued work start) while + // the checkpoint was still committing - a queued write could interleave + // its own checkpoint and shutdown could lose the commit. + let releaseCheckpoint: () => void = () => {} + mockedCheckpointSave.mockImplementationOnce( + () => new Promise((resolve) => (releaseCheckpoint = resolve)), + ) + let settled = false + const run = tool + .execute({ patch: deletePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + .then(() => { + settled = true + }) + await vi.waitFor(() => expect(mockedCheckpointSave).toHaveBeenCalledOnce()) + expect(settled).toBe(false) + releaseCheckpoint() + await run + expect(settled).toBe(true) + }) + it("does not record a checkpoint when perWriteCheckpoints is disabled", async () => { // Structural cast for the test double (matches the mock style used for the controllers above). const ref = (mockTask["providerRef"] as unknown as { deref: MockedFunction<() => unknown> }).deref diff --git a/src/core/tools/__tests__/editFileTool.spec.ts b/src/core/tools/__tests__/editFileTool.spec.ts index faa77c700a..b743fc9c38 100644 --- a/src/core/tools/__tests__/editFileTool.spec.ts +++ b/src/core/tools/__tests__/editFileTool.spec.ts @@ -794,6 +794,26 @@ describe("editFileTool", () => { expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask, false, true) }) + it("awaits the checkpoint before resetting the diff state", async () => { + // Fire-and-forget would let diffViewProvider.reset() and the queued-work + // handoff race an unfinished checkpoint commit (and lose it at + // shutdown): the save must complete before the reset. + let releaseCheckpoint: () => void = () => {} + mockedCheckpointSave.mockImplementationOnce( + () => new Promise((resolve) => (releaseCheckpoint = resolve)), + ) + let settled = false + const run = executeEditFileTool({}).then(() => { + settled = true + }) + await vi.waitFor(() => expect(mockedCheckpointSave).toHaveBeenCalledOnce()) + expect(settled).toBe(false) + expect(mockTask.diffViewProvider.reset).not.toHaveBeenCalled() + releaseCheckpoint() + await run + expect(mockTask.diffViewProvider.reset).toHaveBeenCalled() + }) + it("does not record a checkpoint when perWriteCheckpoints is disabled", async () => { mockTask.providerRef.deref = vi.fn().mockReturnValue({ getState: vi.fn().mockResolvedValue({ From 68e4fa787e3b065a30e262b88b1c436a47844f18 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Tue, 13 Oct 2026 05:48:09 +0800 Subject: [PATCH 08/52] test(checkpoints): pin one-checkpoint-per-patch for multi-file patches The walkthrough's Regression Evidence row asked for a multi-file apply_patch test asserting exactly one checkpointSave for the complete patch - B1's core contract (a regression to per-change saves would double the checkpoint count). Covered on the journal-carrying unit already; this adds the equivalent on the base unit. --- .../__tests__/applyPatchTool.execute.spec.ts | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 7a60606761..5eae3a5e48 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -445,8 +445,33 @@ describe("ApplyPatchTool.execute - delete file success path", () => { handleError: mockHandleError, pushToolResult: mockPushToolResult, }) + }) - expect(mockPushToolResult).toHaveBeenCalledWith("File saved successfully") + it("records exactly one checkpoint for a multi-file patch", async () => { + // B1's core contract: one checkpoint per patch, not per file - a + // regression to per-change saves would double the checkpoint count. + const multiPatch = [ + "*** Begin Patch", + "*** Add File: src/new.ts", + "+hello", + "+world", + "*** Update File: src/test.ts", + "@@", + "-original file content", + "+modified content", + "*** End Patch", + ].join(String.fromCharCode(10)) + mockedFileExistsAtPath.mockImplementation((filePath: string) => + Promise.resolve(!String(filePath).toLowerCase().endsWith("new.ts")), + ) + + await tool.execute({ patch: multiPatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockHandleError).not.toHaveBeenCalled() expect(mockedCheckpointSave).toHaveBeenCalledOnce() }) }) From 2947505fc9e0fec0421c8b4a14364ca84ba51fd9 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Tue, 13 Oct 2026 08:11:46 +0800 Subject: [PATCH 09/52] fix(tools): defer the queued-message handoff until the patch checkpoint completes The per-file handlers processed queued messages right after each successful write, before execute() awaited the whole-patch checkpoint. processQueuedMessages schedules submitUserMessage on a timer, so a queued turn - and the writes it triggers - could start while the patch checkpoint was still staging and committing, interleaving its own checkpoint with this commit. The handoff is now deferred to after the checkpoint attempt: one handoff per successful patch, independent of the checkpoint setting or outcome, so no path strands queued messages and no queued turn can race the commit. This matches the semantics the journal-carrying unit of this series already settled on and brings the remaining units in line. Review feedback on PR 1404; ports carry the equivalent deferral and ordering tests. --- src/core/tools/ApplyPatchTool.ts | 56 +++++++++++++------ .../__tests__/applyPatchTool.execute.spec.ts | 51 +++++++++++++++++ 2 files changed, 89 insertions(+), 18 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index f4a43b2f1c..a2a3a62ca6 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -57,6 +57,12 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const { patch } = params const { handleError, pushToolResult } = callbacks + // The queued-message handoff is deferred to the finally block below, after + // the whole-patch checkpoint attempt: a handler that hands off early lets a + // queued turn start while the checkpoint is still staging or committing. + + let handoffPending = false + try { // Validate required parameters if (!patch) { @@ -124,25 +130,33 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (change.type === "add") { // Create new file - patchSucceeded = - (await this.handleAddFile(change, absolutePath, relPath, task, callbacks, isWriteProtected)) && - patchSucceeded + const ok = await this.handleAddFile( + change, + absolutePath, + relPath, + task, + callbacks, + isWriteProtected, + ) + handoffPending = handoffPending || ok + patchSucceeded = ok && patchSucceeded } else if (change.type === "delete") { // Delete file - patchSucceeded = - (await this.handleDeleteFile(absolutePath, relPath, task, callbacks, isWriteProtected)) && - patchSucceeded + const ok = await this.handleDeleteFile(absolutePath, relPath, task, callbacks, isWriteProtected) + handoffPending = handoffPending || ok + patchSucceeded = ok && patchSucceeded } else if (change.type === "update") { // Update file - patchSucceeded = - (await this.handleUpdateFile( - change, - absolutePath, - relPath, - task, - callbacks, - isWriteProtected, - )) && patchSucceeded + const ok = await this.handleUpdateFile( + change, + absolutePath, + relPath, + task, + callbacks, + isWriteProtected, + ) + handoffPending = handoffPending || ok + patchSucceeded = ok && patchSucceeded } } @@ -163,6 +177,15 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } catch (error) { await handleError("apply patch", error as Error) await task.diffViewProvider.reset() + } finally { + // One handoff per successful patch, after the checkpoint attempt and + // independent of the checkpoint setting or outcome: a queued turn can + // never start while the patch checkpoint is still staging or + // committing, and no path (disabled checkpoints, failed save, early + // return, error) strands the queued messages. + if (handoffPending) { + task.processQueuedMessages() + } } } @@ -255,7 +278,6 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, true) pushToolResult(message) await task.diffViewProvider.reset() - task.processQueuedMessages() return true } @@ -313,7 +335,6 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task.didEditFile = true pushToolResult(`Successfully deleted ${relPath}`) - task.processQueuedMessages() return true } @@ -479,7 +500,6 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, false) pushToolResult(message) await task.diffViewProvider.reset() - task.processQueuedMessages() return true } diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 5eae3a5e48..f146658e70 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -180,6 +180,57 @@ describe("ApplyPatchTool.execute - delete file success path", () => { await run expect(settled).toBe(true) }) + it("defers the queued-message handoff until the checkpoint completes", async () => { + // processQueuedMessages schedules submitUserMessage on a timer; a + // handler that hands off before the whole-patch checkpoint completes + // lets the queued turn start while the commit is still running. + let releaseCheckpoint: () => void = () => {} + mockedCheckpointSave.mockImplementationOnce( + () => new Promise((resolve) => (releaseCheckpoint = resolve)), + ) + const run = tool.execute({ patch: deletePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + await vi.waitFor(() => expect(mockedCheckpointSave).toHaveBeenCalledOnce()) + expect(mockTask.processQueuedMessages).not.toHaveBeenCalled() + releaseCheckpoint() + await run + expect(mockTask.processQueuedMessages).toHaveBeenCalled() + }) + + it("hands off queued messages when checkpoints are disabled", async () => { + // The handoff must not depend on the checkpoint setting: disabling + // checkpoints must not strand queued messages. + const ref = (mockTask["providerRef"] as unknown as { deref: MockedFunction<() => unknown> }).deref + ref.mockReturnValue({ + getState: vi.fn().mockResolvedValue({ perWriteCheckpoints: false }), + }) + + await tool.execute({ patch: deletePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockedCheckpointSave).not.toHaveBeenCalled() + expect(mockTask.processQueuedMessages).toHaveBeenCalled() + }) + + it("does not hand off queued messages when the patch fails", async () => { + // A failed file operation must not hand off: the model is waiting + // on the error result, not on queued input. + mockedFsPromises.default.unlink.mockRejectedValueOnce(new Error("EBUSY")) + + await tool.execute({ patch: deletePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockTask.processQueuedMessages).not.toHaveBeenCalled() + }) it("does not record a checkpoint when perWriteCheckpoints is disabled", async () => { // Structural cast for the test double (matches the mock style used for the controllers above). From d1c2a4b58b76865cbf021c109829790a8064749e Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Tue, 13 Oct 2026 08:35:57 +0800 Subject: [PATCH 10/52] fix(task): never dequeue queued messages for an aborted task Tools now await the write checkpoint before handing off queued work, so a cancellation can land between the write and the handoff. processQueuedMessages dequeued unconditionally and scheduled submitUserMessage, which rejects once abort is set - the queued message was consumed and dropped instead of being left for the resume/abort flow. The dequeue is now skipped while the task is aborted, guarding every handoff site at the lowest layer. Regression test pins that an aborted task leaves the queue intact (negative control verified: the unconditional dequeue reddens it). Review feedback on PR 1404 (Lifecycle Resource Cleanup row); ported to every unit of this series. --- src/core/task/Task.ts | 8 ++++ src/core/task/__tests__/Task.spec.ts | 28 +++++++++++ .../settings/__tests__/SettingsView.spec.tsx | 47 +++++++++++++++++++ 3 files changed, 83 insertions(+) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index b90a6c3b80..96cf53f5a7 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -6576,6 +6576,14 @@ export class Task extends EventEmitter implements TaskLike { * @param context - Context string for logging (e.g., the calling tool name) */ public processQueuedMessages(): void { + // An aborted task must not dequeue queued messages: submitUserMessage + // rejects once abort is set, so consuming the queue here would drop the + // message instead of leaving it for the resume/abort flow. Tools await + // checkpoint saves before handing off, so a cancellation can land between + // the write and this call. + if (this.abort) { + return + } try { if (!this.messageQueueService.isEmpty()) { const queued = this.messageQueueService.dequeueMessage() diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 718dd01cdc..3e31c5bbb5 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -8343,6 +8343,34 @@ describe("Queued message processing after condense", () => { expect(submitSpy).toHaveBeenCalledWith("queued text", ["img1.png"]) expect(task.messageQueueService.isEmpty()).toBe(true) }) + it("does not dequeue queued messages once the task is aborted", () => { + // Tools await the checkpoint before handing off queued work; a + // cancellation landing during that await must not consume the queued + // message: submitUserMessage rejects once abort is set, so dequeuing + // would drop the input instead of leaving it for the resume flow. + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } + const provider = createProvider() + const task = new Task({ + provider, + apiConfiguration: apiConfig, + task: "initial task", + startTask: false, + }) + const submitSpy = vi.spyOn(task, "submitUserMessage").mockResolvedValue(undefined) + + task.messageQueueService.addMessage("queued text") + task.abort = true + try { + task.processQueuedMessages() + } finally { + task.abort = false + } + + expect(submitSpy).not.toHaveBeenCalled() + expect(task.messageQueueService.isEmpty()).toBe(false) + }) it("does not cross-drain queues between separate tasks", async () => { const providerA = createProvider() diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx index e4f1b9864f..328d248b6b 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx @@ -1285,3 +1285,50 @@ describe("SettingsView - promptCacheTtl save round trip", () => { expect(posted()?.apiConfiguration?.promptCacheTtl).toBe("1h") }) }) + +describe("SettingsView - per-write checkpoints save (B1)", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it("saves the default-on payload when Save is clicked with the setting unset", () => { + // An unset setting shows (and saves) the shared default-on value: + // the cached state seeds DEFAULT_PER_WRITE_CHECKPOINTS, so the host + // receives an explicit boolean instead of an omitted key. + const { activateTab, getSettingsContent } = renderSettingsView() + activateTab("checkpoints") + + const content = getSettingsContent() + const perWrite = within(content).getByRole("checkbox", { name: "settings:checkpoints.perWrite.label" }) + expect(perWrite).toBeChecked() + // Toggle a sibling setting so Save is enabled without touching perWrite. + fireEvent.click(within(content).getByRole("checkbox", { name: "settings:checkpoints.enable.label" })) + fireEvent.click(screen.getByTestId("save-button")) + + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + updatedSettings: expect.objectContaining({ perWriteCheckpoints: true }), + }), + ) + }) + + it("saves an explicit false payload after unchecking and clicking Save", () => { + const { activateTab, getSettingsContent } = renderSettingsView({ perWriteCheckpoints: true }) + activateTab("checkpoints") + + const content = getSettingsContent() + const perWrite = within(content).getByRole("checkbox", { name: "settings:checkpoints.perWrite.label" }) + expect(perWrite).toBeChecked() + fireEvent.click(perWrite) + expect(perWrite).not.toBeChecked() + fireEvent.click(screen.getByTestId("save-button")) + + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + updatedSettings: expect.objectContaining({ perWriteCheckpoints: false }), + }), + ) + }) +}) From 50eb72051de6acfa74ae02ebe454388c8d20fd05 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Tue, 13 Oct 2026 09:11:46 +0800 Subject: [PATCH 11/52] test(tools): pin the partial-failure handoff semantics of the patch checkpoint fix Upstream handed off queued messages in each handler right after every successful write, so a patch whose first write succeeded and whose later write failed - or whose later file failed the access check and returned early - still drained the queue. The deferral preserves that condition and only moves its timing after the checkpoint attempt; requiring full-patch success would strand queued input on any partial failure, a behavior change beyond the checkpoint-ordering fix this unit ships. Two tests pin the fidelity semantics against future regressions in either direction. Review feedback on PR 1404 (thread on the finally-block handoff). --- .../__tests__/applyPatchTool.execute.spec.ts | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index f146658e70..c10a5fb298 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -232,6 +232,57 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockTask.processQueuedMessages).not.toHaveBeenCalled() }) + it("hands off queued messages after a partial patch failure", async () => { + // Fidelity: upstream handed off in each handler right after every + // successful write, so a patch whose first write succeeded and whose + // later write failed still drained the queue. The deferral preserves + // that condition (a write happened) and only moves its timing after + // the checkpoint attempt; requiring full-patch success would strand + // queued input on any partial failure. + const mixedPatch = `*** Begin Patch +*** Add File: src/new.ts ++hello +*** Delete File: src/obsolete.ts +*** End Patch` + // Add sees no existing file and succeeds; the delete's unlink fails. + mockedFileExistsAtPath.mockResolvedValueOnce(false) + mockedFsPromises.default.unlink.mockRejectedValueOnce(new Error("EBUSY")) + + await tool.execute({ patch: mixedPatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + // No whole-patch checkpoint (the patch failed), but the successful + // write still hands off. + expect(mockedCheckpointSave).not.toHaveBeenCalled() + expect(mockTask.processQueuedMessages).toHaveBeenCalled() + }) + + it("hands off queued messages when a later file fails the access check", async () => { + // The rooignored path makes execute return early, but the earlier + // successful write had already handed off upstream - the deferred + // handoff preserves that too. + const mixedPatch = `*** Begin Patch +*** Delete File: src/obsolete.ts +*** Add File: src/secret.ts ++hidden +*** End Patch` + const validateAccess = mockTask.rooIgnoreController?.validateAccess as MockedFunction< + (path: string) => boolean + > + validateAccess.mockReturnValueOnce(true).mockReturnValueOnce(false) + + await tool.execute({ patch: mixedPatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockTask.processQueuedMessages).toHaveBeenCalled() + }) + it("does not record a checkpoint when perWriteCheckpoints is disabled", async () => { // Structural cast for the test double (matches the mock style used for the controllers above). const ref = (mockTask["providerRef"] as unknown as { deref: MockedFunction<() => unknown> }).deref From 330ed9af94ae37059e7ca8be451b110f4b07a5dc Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Wed, 14 Oct 2026 16:38:54 +0800 Subject: [PATCH 12/52] chore: remove carried-over Stryker suppression directives from touched files The mutation gate no longer accepts suppression comments in mutation-tested files, and suppressions left by earlier revisions are removed when their file is touched. This drops the seven directives carried in the streaming/telemetry region of Task.ts (equivalences: event.name is always a string on those paths, streamingKey can never be undefined there, and the getStreamingKey region is unreachable defensive code). Comment-only change; no behavior delta. --- src/core/task/Task.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 96cf53f5a7..1a988b5c68 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -4914,7 +4914,6 @@ export class Task extends EventEmitter implements TaskLike { event.id, nativeToolCallParserScope, ) - // Stryker disable next-line ConditionalExpression: unreachable defensive region — getStreamingToolCallById can only resolve when the both-miss case above is reachable, which the raw-chunk pipeline cannot produce (see the directive there). if (resolved) { eventName = resolved.name dedupKey = NativeToolCallParser.makeStreamingKey(resolved.id, resolved.name) From 06944fb068bfab65f151f56d6197fb1e54140ee5 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Thu, 15 Oct 2026 10:28:22 +0800 Subject: [PATCH 13/52] test: strengthen the early-return handoff assertions Assert the skipped whole-patch checkpoint and exactly-once handoff, not just that a handoff happened. --- src/core/tools/__tests__/applyPatchTool.execute.spec.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index c10a5fb298..cae78802db 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -280,7 +280,8 @@ describe("ApplyPatchTool.execute - delete file success path", () => { pushToolResult: mockPushToolResult, }) - expect(mockTask.processQueuedMessages).toHaveBeenCalled() + expect(mockedCheckpointSave).not.toHaveBeenCalled() + expect(mockTask.processQueuedMessages).toHaveBeenCalledTimes(1) }) it("does not record a checkpoint when perWriteCheckpoints is disabled", async () => { From bcf450d9a6c5f660418e5c333a0343d01f35e146 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Thu, 15 Oct 2026 15:28:17 +0800 Subject: [PATCH 14/52] test: assert the in-place update checkpoint contract The test named for the in-place update asserted nothing; it now asserts no error handling ran and exactly one whole-patch checkpointSave with the standard arguments. --- src/core/tools/__tests__/applyPatchTool.execute.spec.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index cae78802db..595cf727bf 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -548,6 +548,10 @@ describe("ApplyPatchTool.execute - delete file success path", () => { handleError: mockHandleError, pushToolResult: mockPushToolResult, }) + + expect(mockHandleError).not.toHaveBeenCalled() + expect(mockedCheckpointSave).toHaveBeenCalledOnce() + expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true) }) it("records exactly one checkpoint for a multi-file patch", async () => { From 1a7a3c90a12d85ba7aeb04fabefb0c811bb9c86e Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Fri, 16 Oct 2026 14:52:43 +0800 Subject: [PATCH 15/52] fix(apply-patch): fail moves when source deletion fails; checkpoint partial patches - Move handler: when the source unlink fails, remove the destination (restoring the pre-move state), report the failure through the tool error result, and return false so the whole-patch checkpoint is not recorded over a duplicated file. - Partial patch failure: persist an explicit partial-state checkpoint for the retained successful operations before the queued-message handoff, instead of carrying unpersisted writes forward. - Access-check failure now breaks to the same partial-failure path. --- src/core/tools/ApplyPatchTool.ts | 34 ++++++++- .../__tests__/applyPatchTool.execute.spec.ts | 76 ++++++++++++++++++- 2 files changed, 103 insertions(+), 7 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index a2a3a62ca6..fad6729177 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -122,7 +122,11 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (!accessAllowed) { await task.say("rooignore_error", relPath) pushToolResult(formatResponse.rooIgnoreError(relPath)) - return + // Partial failure: earlier successful writes are retained; break so the + // explicit partial-state checkpoint below persists them before the + // queued-message handoff in the finally block. + patchSucceeded = false + break } // Check if file is write-protected @@ -170,7 +174,18 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (perWriteCheckpoints !== false) { // Await so the whole-patch checkpoint persists before the tool // completes; an unawaited save lets queued work interleave its own - // checkpoint and lets shutdown lose the commit. + // checkpoint and lets shutdown lose the commit. Called only after + // every filesystem operation succeeded. + await checkpointSave(task, false, true).catch(() => {}) + } + } else if (handoffPending) { + // Partial failure: the earlier successful operations keep their writes + // in the workspace. Persist an explicit partial-state checkpoint before + // the queued-message handoff (the finally block below) so those retained + // writes have rollback metadata instead of being carried forward + // unpersisted; the failed operation already reported itself. + const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints + if (perWriteCheckpoints !== false) { await checkpointSave(task, false, true).catch(() => {}) } } @@ -480,7 +495,20 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { try { await fs.unlink(absolutePath) } catch (error) { - console.error(`Failed to delete original file after move: ${error}`) + // The source is still present (locked or protected): undo the destination + // write so the file does not live in two places, and report the move as + // failed. Returning true here would let the whole-patch checkpoint + // persist a duplicated file as if the move had succeeded. + try { + await fs.rm(moveAbsolutePath, { force: true }) + } catch (restoreError) { + console.error(`Failed to restore pre-move state after source deletion failure: ${restoreError}`) + } + const moveErrorMessage = `Failed to delete original file after move '${relPath}': ${error instanceof Error ? error.message : String(error)}` + await task.say("error", moveErrorMessage) + pushToolResult(formatResponse.toolError(moveErrorMessage)) + await task.diffViewProvider.reset() + return false } await task.fileContextTracker.trackFileContext(change.movePath, "roo_edited" as RecordSource) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 595cf727bf..ee32d7d146 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -16,6 +16,7 @@ const mockedFsPromises = vi.mocked( fsPromises as unknown as { default: { unlink: MockedFunction + rm: MockedFunction writeFile: MockedFunction } }, @@ -25,6 +26,7 @@ vi.mock("fs/promises", () => ({ default: { readFile: vi.fn().mockResolvedValue("original file content\n"), unlink: vi.fn().mockResolvedValue(undefined), + rm: vi.fn().mockResolvedValue(undefined), mkdir: vi.fn().mockResolvedValue(undefined), writeFile: vi.fn().mockResolvedValue(undefined), }, @@ -144,6 +146,62 @@ describe("ApplyPatchTool.execute - delete file success path", () => { *** End Patch` const mockedCheckpointSave = checkpointSave as MockedFunction + it("restores the pre-move state and fails the operation when source deletion fails", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + mockedFsPromises.default.unlink.mockRejectedValueOnce( + Object.assign(new Error("EBUSY: resource busy or locked"), { code: "EBUSY" }), + ) + // The restore itself fails too: the failure is logged, not swallowed. + mockedFsPromises.default.rm.mockRejectedValueOnce(new Error("EROFS: read-only file system")) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The destination write is undone so the file does not live in two places. + expect(mockedFsPromises.default.rm).toHaveBeenCalledWith(expect.stringContaining("new.ts"), { force: true }) + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to restore pre-move state")) + errorSpy.mockRestore() + // The move is reported as failed rather than as a successful write... + expect(mockPushToolResult).toHaveBeenCalledWith( + expect.stringContaining("Failed to delete original file after move"), + ) + // ...and no whole-patch checkpoint is recorded for the failed move. + expect(mockedCheckpointSave).not.toHaveBeenCalled() + }) + + it("persists an explicit partial-state checkpoint before handoff when a later operation fails", async () => { + const patch = `*** Begin Patch +*** Delete File: src/obsolete.ts +*** Delete File: src/locked.ts +*** End Patch` + // The first delete succeeds; the second fails. + mockedFsPromises.default.unlink.mockRejectedValueOnce(new Error("EPERM: operation not permitted")) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The retained successful delete gets an explicit partial-state + // checkpoint before the queued-message handoff. + expect(mockedCheckpointSave).toHaveBeenCalledTimes(1) + const checkpointAt = mockedCheckpointSave.mock.invocationCallOrder[0] ?? Infinity + const handoffAt = vi.mocked(mockTask.processQueuedMessages).mock.invocationCallOrder[0] ?? Infinity + expect(checkpointAt).toBeLessThan(handoffAt) + }) it("records one suppressed checkpoint for the whole patch (default-on)", async () => { await tool.execute({ patch: deletePatch }, mockTask as Task, { askApproval: mockAskApproval, @@ -254,10 +312,13 @@ describe("ApplyPatchTool.execute - delete file success path", () => { pushToolResult: mockPushToolResult, }) - // No whole-patch checkpoint (the patch failed), but the successful - // write still hands off. - expect(mockedCheckpointSave).not.toHaveBeenCalled() + // The retained successful write gets an explicit partial-state + // checkpoint before the queued-message handoff. + expect(mockedCheckpointSave).toHaveBeenCalledTimes(1) expect(mockTask.processQueuedMessages).toHaveBeenCalled() + expect(mockedCheckpointSave.mock.invocationCallOrder[0]).toBeLessThan( + vi.mocked(mockTask.processQueuedMessages).mock.invocationCallOrder[0] ?? Infinity, + ) }) it("hands off queued messages when a later file fails the access check", async () => { @@ -280,8 +341,15 @@ describe("ApplyPatchTool.execute - delete file success path", () => { pushToolResult: mockPushToolResult, }) - expect(mockedCheckpointSave).not.toHaveBeenCalled() + // The earlier successful delete is retained: an explicit partial-state + // checkpoint persists it before the deferred handoff. + expect(mockedCheckpointSave).toHaveBeenCalledTimes(1) expect(mockTask.processQueuedMessages).toHaveBeenCalledTimes(1) + // The access-failed file is never written and the loop stops there. + expect(mockTask.fileContextTracker.trackFileContext).not.toHaveBeenCalledWith( + "src/secret.ts", + expect.anything(), + ) }) it("does not record a checkpoint when perWriteCheckpoints is disabled", async () => { From 2a49febb534a57c4e5b292d46096dcb104ac984e Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Sat, 17 Oct 2026 17:29:46 +0800 Subject: [PATCH 16/52] fix(tools): checkpoint retained writes before handoff after a handler error A later file operation can reject outright (e.g. the approval stream dies) after earlier handlers succeeded. The outer catch skipped both checkpoint branches, but the finally block still handed off queued messages, so the queued turn could start with the retained writes carried forward without rollback metadata. The catch now persists an explicit partial-state checkpoint (same default-on semantics as the success/partial branches) before handleError and the handoff. Addresses the CodeRabbit review thread on ApplyPatchTool. --- src/core/tools/ApplyPatchTool.ts | 13 ++++++++++ .../__tests__/applyPatchTool.execute.spec.ts | 25 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index fad6729177..ca70bbc2c3 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -190,6 +190,19 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } } } catch (error) { + // A later file operation can reject outright (e.g. the approval + // stream dies) after earlier handlers succeeded. This catch skips + // both checkpoint branches above, but the finally block still + // hands off queued messages, so persist an explicit partial-state + // checkpoint here (same default-on semantics as the branches + // above) instead of letting the queued turn start with the + // retained writes carried forward without rollback metadata. + if (handoffPending) { + const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints + if (perWriteCheckpoints !== false) { + await checkpointSave(task, false, true).catch(() => {}) + } + } await handleError("apply patch", error as Error) await task.diffViewProvider.reset() } finally { diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index ee32d7d146..44757eef26 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -202,6 +202,31 @@ describe("ApplyPatchTool.execute - delete file success path", () => { const handoffAt = vi.mocked(mockTask.processQueuedMessages).mock.invocationCallOrder[0] ?? Infinity expect(checkpointAt).toBeLessThan(handoffAt) }) + it("persists a partial-state checkpoint when a later handler rejects outright after an earlier write", async () => { + const patch = `*** Begin Patch +*** Delete File: src/obsolete.ts +*** Delete File: src/locked.ts +*** End Patch` + // The first delete approves and succeeds; the second handler rejects + // outright (e.g. the approval stream dies), so the outer catch runs + // and the partial-state checkpoint branch above it is skipped. + mockAskApproval.mockResolvedValueOnce(true).mockRejectedValueOnce(new Error("approval stream died")) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The retained first delete still gets rollback metadata before the + // queued-message handoff in the finally block. + expect(mockedCheckpointSave).toHaveBeenCalledTimes(1) + const checkpointAt = mockedCheckpointSave.mock.invocationCallOrder[0] ?? Infinity + const handoffAt = vi.mocked(mockTask.processQueuedMessages).mock.invocationCallOrder[0] ?? Infinity + expect(checkpointAt).toBeLessThan(handoffAt) + expect(mockHandleError).toHaveBeenCalled() + }) it("records one suppressed checkpoint for the whole patch (default-on)", async () => { await tool.execute({ patch: deletePatch }, mockTask as Task, { askApproval: mockAskApproval, From c66f406b64644280e3a61014dcd99f61234a8aec Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Sat, 17 Oct 2026 20:05:12 +0800 Subject: [PATCH 17/52] fix(task): task-start checkpoint baseline errors no longer abort task startup The baseline block runs before TaskStarted and is best-effort: a rejected provider-state lookup or a checkpoint error now logs and continues instead of escaping initiateTaskLoop (startTask rethrows non-abort errors). --- src/core/task/Task.ts | 22 +++++++++++++++------- src/core/task/__tests__/Task.spec.ts | 25 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 1a988b5c68..d35c721b36 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -3941,13 +3941,21 @@ export class Task extends EventEmitter implements TaskLike { // save would only add latency to a task that is being disposed. if (!this.taskStartBaselineDone && !this._isHistoryTask && !this.abort) { this.taskStartBaselineDone = true - const baselineEnabled = (await this.providerRef.deref()?.getState())?.perWriteCheckpoints - // Cancellation can arrive while the state lookup is pending; recheck - // before the save so a canceled task performs no checkpoint work. - if (baselineEnabled !== false && !this.abort) { - // allowEmpty=true so a clean workspace still produces the baseline - // commit; awaited so the first per-write checkpoint cannot interleave. - await this.checkpointSave(true, true) + try { + const baselineEnabled = (await this.providerRef.deref()?.getState())?.perWriteCheckpoints + // Cancellation can arrive while the state lookup is pending; recheck + // before the save so a canceled task performs no checkpoint work. + if (baselineEnabled !== false && !this.abort) { + // allowEmpty=true so a clean workspace still produces the baseline + // commit; awaited so the first per-write checkpoint cannot interleave. + await this.checkpointSave(true, true) + } + } catch (error) { + // The baseline is best-effort and runs before TaskStarted: a rejected + // state lookup or a checkpoint error must not abort task startup + // (startTask rethrows non-abort errors from initiateTaskLoop). Log + // and continue; per-write saves still report their own failures. + console.error("[Task] task-start checkpoint baseline failed:", error) } } diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 3e31c5bbb5..c9970b1e93 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7415,6 +7415,31 @@ describe("Cline", () => { await loopPromise expect(requestSpy).toHaveBeenCalled() }) + + it("continues task startup when the baseline checkpoint fails", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "baseline failure task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + const boom = new Error("baseline boom") + vi.spyOn(task, "checkpointSave").mockRejectedValue(boom) + const state = await mockProvider.getState() + vi.spyOn(mockProvider, "getState").mockResolvedValue(state) + const requestSpy = vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true) + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + // The baseline runs before TaskStarted: a checkpoint error must not + // abort task startup (startTask rethrows non-abort errors from + // initiateTaskLoop). The loop must still be entered. + await taskAccess.initiateTaskLoop([]) + + expect(requestSpy).toHaveBeenCalled() + expect(consoleErrorSpy).toHaveBeenCalledWith("[Task] task-start checkpoint baseline failed:", boom) + consoleErrorSpy.mockRestore() + }) }) describe("start()", () => { From 6c0ff525c4cca4bf521447d3bb7a3758b0a98867 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Sun, 18 Oct 2026 08:32:24 +0800 Subject: [PATCH 18/52] fix(checkpoints): restore a clobbered move destination when source deletion fails Capture the destination's prior content before the move write. On rollback the destination is restored to that content instead of being removed, so a failed move no longer destroys a pre-existing file; when the destination cannot be inspected (non-ENOENT read failure) the move is refused before any write rather than treating the file as absent. Also clarify the perWrite checkpoint setting description: a multi-file patch produces a single checkpoint (all 18 locales). --- src/core/tools/ApplyPatchTool.ts | 31 ++++++- .../__tests__/applyPatchTool.execute.spec.ts | 86 +++++++++++++++++++ webview-ui/src/i18n/locales/ca/settings.json | 2 +- webview-ui/src/i18n/locales/de/settings.json | 2 +- webview-ui/src/i18n/locales/en/settings.json | 2 +- webview-ui/src/i18n/locales/es/settings.json | 2 +- webview-ui/src/i18n/locales/fr/settings.json | 2 +- webview-ui/src/i18n/locales/hi/settings.json | 2 +- webview-ui/src/i18n/locales/id/settings.json | 2 +- webview-ui/src/i18n/locales/it/settings.json | 2 +- webview-ui/src/i18n/locales/ja/settings.json | 2 +- webview-ui/src/i18n/locales/ko/settings.json | 2 +- webview-ui/src/i18n/locales/nl/settings.json | 2 +- webview-ui/src/i18n/locales/pl/settings.json | 2 +- .../src/i18n/locales/pt-BR/settings.json | 2 +- webview-ui/src/i18n/locales/ru/settings.json | 2 +- webview-ui/src/i18n/locales/tr/settings.json | 2 +- webview-ui/src/i18n/locales/vi/settings.json | 2 +- .../src/i18n/locales/zh-CN/settings.json | 2 +- .../src/i18n/locales/zh-TW/settings.json | 2 +- 20 files changed, 133 insertions(+), 20 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index ca70bbc2c3..3bed2d8837 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -488,6 +488,27 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { return false } + // Capture the destination state before either supported write path: a + // failed move must restore an existing destination instead of deleting + // whatever lived there. A read error other than ENOENT means the + // destination cannot be inspected, so the move is refused before any + // write rather than risking an unrecoverable clobber. + let destinationBackup: Buffer | undefined + try { + destinationBackup = await fs.readFile(moveAbsolutePath) + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code !== "ENOENT") { + task.consecutiveMistakeCount++ + task.recordToolError("apply_patch") + const inspectErrorMessage = `Cannot inspect move destination '${change.movePath}': ${error instanceof Error ? error.message : String(error)}` + await task.say("error", inspectErrorMessage) + pushToolResult(formatResponse.toolError(inspectErrorMessage)) + await task.diffViewProvider.reset() + return false + } + } + // Save new content to the new path if (isPreventFocusDisruptionEnabled) { await task.diffViewProvider.saveDirectly( @@ -511,9 +532,15 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // The source is still present (locked or protected): undo the destination // write so the file does not live in two places, and report the move as // failed. Returning true here would let the whole-patch checkpoint - // persist a duplicated file as if the move had succeeded. + // persist a duplicated file as if the move had succeeded. An existing + // destination is restored to its captured content; the destination is + // removed only when it was confirmed absent before the write. try { - await fs.rm(moveAbsolutePath, { force: true }) + if (destinationBackup !== undefined) { + await fs.writeFile(moveAbsolutePath, destinationBackup) + } else { + await fs.rm(moveAbsolutePath, { force: true }) + } } catch (restoreError) { console.error(`Failed to restore pre-move state after source deletion failure: ${restoreError}`) } diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 44757eef26..8f92ac740a 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -15,6 +15,7 @@ import { ApplyPatchTool } from "../ApplyPatchTool" const mockedFsPromises = vi.mocked( fsPromises as unknown as { default: { + readFile: MockedFunction unlink: MockedFunction rm: MockedFunction writeFile: MockedFunction @@ -155,6 +156,14 @@ describe("ApplyPatchTool.execute - delete file success path", () => { +new content *** End Patch` const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + // The move destination does not exist: the rollback must remove the + // destination rather than restore content that was never there. + mockedFsPromises.default.readFile.mockImplementation(async (p: unknown) => { + if (String(p).includes("new.ts")) { + throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + } + return "original file content\n" + }) mockedFsPromises.default.unlink.mockRejectedValueOnce( Object.assign(new Error("EBUSY: resource busy or locked"), { code: "EBUSY" }), ) @@ -178,6 +187,83 @@ describe("ApplyPatchTool.execute - delete file success path", () => { ) // ...and no whole-patch checkpoint is recorded for the failed move. expect(mockedCheckpointSave).not.toHaveBeenCalled() + // Restore the default readFile behavior for later tests. + mockedFsPromises.default.readFile.mockResolvedValue("original file content\n") + }) + + it("restores an existing destination when source deletion fails after the move clobbered it", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // The destination already exists with its own content; the move writes + // over it before the source unlink runs. + mockedFsPromises.default.readFile.mockImplementation(async (p: unknown) => { + if (String(p).includes("new.ts")) { + return "existing destination content" + } + return "original file content\n" + }) + mockedFsPromises.default.unlink.mockRejectedValueOnce( + Object.assign(new Error("EBUSY: resource busy or locked"), { code: "EBUSY" }), + ) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The captured destination content is restored, not deleted: rm must not + // run for a destination that existed before the move. + expect(mockedFsPromises.default.writeFile).toHaveBeenCalledWith( + expect.stringContaining("new.ts"), + "existing destination content", + ) + expect(mockedFsPromises.default.rm).not.toHaveBeenCalled() + expect(mockPushToolResult).toHaveBeenCalledWith( + expect.stringContaining("Failed to delete original file after move"), + ) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + // Restore the default readFile behavior for later tests. + mockedFsPromises.default.readFile.mockResolvedValue("original file content\n") + }) + + it("refuses the move before writing when the destination cannot be inspected", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // An EACCES on the destination is not "absent": treating every read + // failure as missing could delete an inaccessible destination. + mockedFsPromises.default.readFile.mockImplementation(async (p: unknown) => { + if (String(p).includes("new.ts")) { + throw Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }) + } + return "original file content\n" + }) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The destination is never written and the source is never unlinked. + expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() + expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Cannot inspect move destination")) + expect(mockedCheckpointSave).not.toHaveBeenCalled() + // Restore the default readFile behavior for later tests. + mockedFsPromises.default.readFile.mockResolvedValue("original file content\n") }) it("persists an explicit partial-state checkpoint before handoff when a later operation fails", async () => { diff --git a/webview-ui/src/i18n/locales/ca/settings.json b/webview-ui/src/i18n/locales/ca/settings.json index 38ba5946cc..96318cfd5b 100644 --- a/webview-ui/src/i18n/locales/ca/settings.json +++ b/webview-ui/src/i18n/locales/ca/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Punt de control després de cada escriptura de fitxer", - "description": "Registra una instantània de punt de control després de cada escriptura de fitxer reeixida de l’agent" + "description": "Registra una instantània de punt de control després de cada operació d’escriptura reeixida; un pegat de diversos fitxers genera un únic punt de control." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/de/settings.json b/webview-ui/src/i18n/locales/de/settings.json index fdd7e19eb5..0d533629d5 100644 --- a/webview-ui/src/i18n/locales/de/settings.json +++ b/webview-ui/src/i18n/locales/de/settings.json @@ -698,7 +698,7 @@ }, "perWrite": { "label": "Kontrollpunkt nach jedem Dateischreibvorgang", - "description": "Ein Kontrollpunkt-Snapshot wird nach jedem erfolgreichen Dateischreibvorgang des Agents erfasst" + "description": "Erstellt nach jedem erfolgreichen Schreibvorgang einen Checkpoint-Schnappschuss; ein Patch mit mehreren Dateien erzeugt genau einen Checkpoint." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/en/settings.json b/webview-ui/src/i18n/locales/en/settings.json index fba2d6b2f9..6bec92ee4b 100644 --- a/webview-ui/src/i18n/locales/en/settings.json +++ b/webview-ui/src/i18n/locales/en/settings.json @@ -771,7 +771,7 @@ }, "perWrite": { "label": "Checkpoint after each file write", - "description": "Record a checkpoint snapshot after every successful file write by the agent" + "description": "Record a checkpoint snapshot after each successful write operation; a multi-file patch produces a single checkpoint." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/es/settings.json b/webview-ui/src/i18n/locales/es/settings.json index 551e7e3aa7..2420ab151f 100644 --- a/webview-ui/src/i18n/locales/es/settings.json +++ b/webview-ui/src/i18n/locales/es/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Punto de control después de cada escritura de archivo", - "description": "Registra una instantánea de punto de control después de cada escritura de archivo exitosa del agente" + "description": "Registra una instantánea de punto de control después de cada operación de escritura exitosa; un parche de varios archivos produce un único punto de control." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/fr/settings.json b/webview-ui/src/i18n/locales/fr/settings.json index 05068b1381..97caae64c6 100644 --- a/webview-ui/src/i18n/locales/fr/settings.json +++ b/webview-ui/src/i18n/locales/fr/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Point de contrôle après chaque écriture de fichier", - "description": "Enregistre un instantané de point de contrôle après chaque écriture de fichier réussie par l’agent" + "description": "Enregistre un instantané de point de contrôle après chaque opération d’écriture réussie ; un correctif multi-fichiers produit un seul point de contrôle." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/hi/settings.json b/webview-ui/src/i18n/locales/hi/settings.json index a38d11b8ff..c7b6bc0c7e 100644 --- a/webview-ui/src/i18n/locales/hi/settings.json +++ b/webview-ui/src/i18n/locales/hi/settings.json @@ -698,7 +698,7 @@ }, "perWrite": { "label": "हर फ़ाइल लिखने के बाद चेकपॉइंट", - "description": "एजेंट द्वारा हर सफल फ़ाइल लिखने के बाद एक चेकपॉइंट स्नैपशॉट दर्ज किया जाता है" + "description": "प्रत्येक सफल लेखन कार्रवाई के बाद एक चेकपॉइंट स्नैपशॉट रिकॉर्ड करें; एक मल्टी-फ़ाइल पैच केवल एक चेकपॉइंट बनाता है।" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/id/settings.json b/webview-ui/src/i18n/locales/id/settings.json index fb9c7f9d5e..6ef9ba08f6 100644 --- a/webview-ui/src/i18n/locales/id/settings.json +++ b/webview-ui/src/i18n/locales/id/settings.json @@ -697,7 +697,7 @@ }, "perWrite": { "label": "Checkpoint setelah setiap penulisan file", - "description": "Merekam snapshot checkpoint setelah setiap penulisan file yang berhasil oleh agen" + "description": "Rekam snapshot titik pemeriksaan setelah setiap operasi tulis berhasil; patch multi-file menghasilkan satu titik pemeriksaan." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/it/settings.json b/webview-ui/src/i18n/locales/it/settings.json index 2b39b2023e..4615df7fe2 100644 --- a/webview-ui/src/i18n/locales/it/settings.json +++ b/webview-ui/src/i18n/locales/it/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Punto di controllo dopo ogni scrittura del file", - "description": "Registra uno snapshot di punto di controllo dopo ogni scrittura del file riuscita dell’agente" + "description": "Registra un’istantanea del punto di controllo dopo ogni operazione di scrittura riuscita; una patch con più file produce un unico punto di controllo." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/ja/settings.json b/webview-ui/src/i18n/locales/ja/settings.json index b60fab3224..a1980f0112 100644 --- a/webview-ui/src/i18n/locales/ja/settings.json +++ b/webview-ui/src/i18n/locales/ja/settings.json @@ -697,7 +697,7 @@ }, "perWrite": { "label": "ファイルの書き込みごとにチェックポイント", - "description": "エージェントによる各ファイルの書き込み成功後にチェックポイントのスナップショットを記録します" + "description": "各書き込み操作の成功後にチェックポイントスナップショットを記録します。複数ファイルのパッチは単一のチェックポイントを作成します。" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/ko/settings.json b/webview-ui/src/i18n/locales/ko/settings.json index f185513e87..d401b3535d 100644 --- a/webview-ui/src/i18n/locales/ko/settings.json +++ b/webview-ui/src/i18n/locales/ko/settings.json @@ -697,7 +697,7 @@ }, "perWrite": { "label": "파일을 쓸 때마다 체크포인트", - "description": "에이전트가 파일 쓰기에 성공할 때마다 체크포인트 스냅샷을 기록합니다" + "description": "각 쓰기 작업이 성공할 때마다 체크포인트 스냅샷을 기록합니다. 다중 파일 패치는 단일 체크포인트를 생성합니다." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/nl/settings.json b/webview-ui/src/i18n/locales/nl/settings.json index e5ababcb63..edba2bd076 100644 --- a/webview-ui/src/i18n/locales/nl/settings.json +++ b/webview-ui/src/i18n/locales/nl/settings.json @@ -698,7 +698,7 @@ }, "perWrite": { "label": "Checkpoint na elke bestandsschrijving", - "description": "Neemt een checkpoint-snapshot op na elke succesvolle bestandsschrijving door de agent" + "description": "Leg na elke succesvolle schrijfbewerking een checkpointmomentopname vast; een patch met meerdere bestanden produceert één checkpoint." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/pl/settings.json b/webview-ui/src/i18n/locales/pl/settings.json index ed896363fc..f99a00af66 100644 --- a/webview-ui/src/i18n/locales/pl/settings.json +++ b/webview-ui/src/i18n/locales/pl/settings.json @@ -700,7 +700,7 @@ }, "perWrite": { "label": "Punkt kontrolny po każdym zapisaniu pliku", - "description": "Rejestruje migawkę punktu kontrolnego po każdym udanym zapisaniu pliku przez agenta" + "description": "Zapisuje migawkę punktu kontrolnego po każdej udanej operacji zapisu; patch obejmujący wiele plików tworzy jeden punkt kontrolny." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/pt-BR/settings.json b/webview-ui/src/i18n/locales/pt-BR/settings.json index a3da63fce0..d8f345ad2a 100644 --- a/webview-ui/src/i18n/locales/pt-BR/settings.json +++ b/webview-ui/src/i18n/locales/pt-BR/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Ponto de verificação após cada gravação de arquivo", - "description": "Registra um snapshot de ponto de verificação após cada gravação de arquivo bem-sucedida pelo agente" + "description": "Registra um snapshot de ponto de verificação após cada operação de gravação bem-sucedida; um patch com vários arquivos produz um único ponto de verificação." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/ru/settings.json b/webview-ui/src/i18n/locales/ru/settings.json index 4bb69e3be8..69b0b5aa33 100644 --- a/webview-ui/src/i18n/locales/ru/settings.json +++ b/webview-ui/src/i18n/locales/ru/settings.json @@ -700,7 +700,7 @@ }, "perWrite": { "label": "Контрольная точка после каждой записи файла", - "description": "Записывает снимок контрольной точки после каждой успешной записи файла агентом" + "description": "Записывает снимок контрольной точки после каждой успешной операции записи; патч с несколькими файлами создаёт одну контрольную точку." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/tr/settings.json b/webview-ui/src/i18n/locales/tr/settings.json index 613509df13..0fc8b57fe2 100644 --- a/webview-ui/src/i18n/locales/tr/settings.json +++ b/webview-ui/src/i18n/locales/tr/settings.json @@ -698,7 +698,7 @@ }, "perWrite": { "label": "Her dosya yazımından sonra kontrol noktası", - "description": "Ajanın her başarılı dosya yazımından sonra bir kontrol noktası görüntüsü kaydeder" + "description": "Her başarılı yazma işleminden sonra bir kontrol noktası anlık görüntüsü kaydeder; çok dosyalı bir yama tek bir kontrol noktası üretir." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/vi/settings.json b/webview-ui/src/i18n/locales/vi/settings.json index 80a4d89147..c3f57e4e52 100644 --- a/webview-ui/src/i18n/locales/vi/settings.json +++ b/webview-ui/src/i18n/locales/vi/settings.json @@ -697,7 +697,7 @@ }, "perWrite": { "label": "Điểm kiểm tra sau mỗi lần ghi file", - "description": "Ghi lại ảnh chụp nhanh điểm kiểm tra sau mỗi lần ghi file thành công của agent" + "description": "Ghi ảnh chụp điểm kiểm tra sau mỗi thao tác ghi thành công; một vá nhiều tệp chỉ tạo một điểm kiểm tra." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/zh-CN/settings.json b/webview-ui/src/i18n/locales/zh-CN/settings.json index 5706068caf..6cfcdcf7a7 100644 --- a/webview-ui/src/i18n/locales/zh-CN/settings.json +++ b/webview-ui/src/i18n/locales/zh-CN/settings.json @@ -697,7 +697,7 @@ }, "perWrite": { "label": "每次文件写入后创建存档点", - "description": "智能体每次成功写入文件后都会记录一个存档点快照" + "description": "在每次成功写入操作后记录检查点快照;多文件补丁只会生成一个检查点。" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/zh-TW/settings.json b/webview-ui/src/i18n/locales/zh-TW/settings.json index 4862fce042..b6849f3ef8 100644 --- a/webview-ui/src/i18n/locales/zh-TW/settings.json +++ b/webview-ui/src/i18n/locales/zh-TW/settings.json @@ -724,7 +724,7 @@ }, "perWrite": { "label": "每次檔案寫入後建立檢查點", - "description": "代理每次成功寫入檔案後都會記錄一個檢查點快照" + "description": "在每次成功的寫入操作後記錄檢查點快照;多檔案修補程式只會產生一個檢查點。" } }, "notifications": { From 635d13495dafd398de3f48bc1212e2674e393f13 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Sun, 18 Oct 2026 09:33:43 +0800 Subject: [PATCH 19/52] fix(checkpoints): harden task-start baseline and service init per review - Task: settings-read failure falls back to default-on; baseline done flag set only after a real commit so a no-commit save is retried on a later loop entry - getCheckpointService: never store/return an uninitialized service; clear the initializing flag when initShadowGit fails - checkpointSave (B3+): recovery reuses only an initialized handle - changeJournal (B3+): prune settled journalQueues entries; move and correct the appendChanges/loadChanges doc comments - specs: baseline retry/reject tests, getCheckpointService init-failure regression tests, recovery assertion strengthening, rollback.spec typed doubles, journal queue lifecycle test --- .../__tests__/getCheckpointService.spec.ts | 126 ++++++++++++++++++ src/core/checkpoints/index.ts | 13 ++ src/core/task/Task.ts | 39 ++++-- src/core/task/__tests__/Task.spec.ts | 57 +++++++- 4 files changed, 222 insertions(+), 13 deletions(-) create mode 100644 src/core/checkpoints/__tests__/getCheckpointService.spec.ts diff --git a/src/core/checkpoints/__tests__/getCheckpointService.spec.ts b/src/core/checkpoints/__tests__/getCheckpointService.spec.ts new file mode 100644 index 0000000000..99a8b5b788 --- /dev/null +++ b/src/core/checkpoints/__tests__/getCheckpointService.spec.ts @@ -0,0 +1,126 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" + +import type { Task } from "../../task/Task" +import { RepoPerTaskCheckpointService } from "../../../services/checkpoints" +import { checkGitInstalled } from "../../../utils/git" +import { getCheckpointService } from "../index" + +vi.mock("../../../services/checkpoints", () => ({ + RepoPerTaskCheckpointService: { create: vi.fn() }, +})) + +vi.mock("../../../utils/git", () => ({ + checkGitInstalled: vi.fn(), +})) + +vi.mock("../../../utils/path", () => ({ + getWorkspacePath: vi.fn(() => "/workspace"), +})) + +vi.mock("../../../i18n", () => ({ + t: (key: string) => key, +})) + +/** + * Structural service double: getCheckpointService only registers listeners, + * awaits initShadowGit, and reads isInitialized. The double assertion at the + * create() call sites is confined to this file (AGENTS.md last-resort cast): + * the real class carries a Git handle and event surface the test never + * exercises. + */ +function serviceDouble(initShadowGitImpl: () => Promise) { + const listeners = new Map void>() + let initialized = false + const svc = { + on: vi.fn((event: string, cb: (...args: unknown[]) => void) => { + listeners.set(event, cb) + }), + initShadowGit: vi.fn(() => initShadowGitImpl()), + get isInitialized() { + return initialized + }, + completeInit: () => { + initialized = true + listeners.get("initialize")?.() + }, + } + return svc +} + +function makeTask(): Task { + return { + taskId: "task-init", + cwd: "/workspace", + enableCheckpoints: true, + checkpointService: undefined, + checkpointServiceInitializing: false, + checkpointTimeout: 1, + providerRef: { + deref: vi.fn().mockReturnValue({ + context: { globalStorageUri: { fsPath: "/tmp/b3-init-storage" } }, + postMessageToWebview: vi.fn(), + log: vi.fn(), + }), + }, + say: vi.fn().mockResolvedValue(undefined), + } as unknown as Task +} + +describe("getCheckpointService initialization failures", () => { + beforeEach(() => { + vi.mocked(checkGitInstalled).mockReset() + vi.mocked(RepoPerTaskCheckpointService.create).mockReset() + }) + + it("does not store a service whose shadow-git initialization failed", async () => { + vi.mocked(checkGitInstalled).mockResolvedValue(true) + const failing = serviceDouble(async () => { + throw new Error("shadow git init exploded") + }) + vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue( + failing as unknown as RepoPerTaskCheckpointService, + ) + + const task = makeTask() + const service = await getCheckpointService(task) + + // The failed service must not be stored: a stored uninitialized handle + // would be returned by the fast path to every later save, and the + // initializing flag must not strand later lookups in a wait for an + // initialization that already died. + expect(service).toBeUndefined() + expect(task.checkpointService).toBeUndefined() + expect(task.checkpointServiceInitializing).toBe(false) + expect(task.enableCheckpoints).toBe(false) + }) + + it("does not store a service when Git is not installed", async () => { + vi.mocked(checkGitInstalled).mockResolvedValue(false) + const svc = serviceDouble(async () => {}) + vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(svc as unknown as RepoPerTaskCheckpointService) + + const task = makeTask() + const service = await getCheckpointService(task) + + expect(service).toBeUndefined() + expect(task.checkpointService).toBeUndefined() + expect(task.checkpointServiceInitializing).toBe(false) + expect(task.enableCheckpoints).toBe(false) + }) + + it("stores an initialized service on the success path", async () => { + vi.mocked(checkGitInstalled).mockResolvedValue(true) + const svc = serviceDouble(async () => { + svc.completeInit() + }) + vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(svc as unknown as RepoPerTaskCheckpointService) + + const task = makeTask() + const service = await getCheckpointService(task) + + expect(service).toBe(svc) + expect(task.checkpointService).toBe(svc) + expect(task.checkpointServiceInitializing).toBe(false) + expect(task.enableCheckpoints).toBe(true) + }) +}) diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index 0bf73a726e..35f3a97b83 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -115,6 +115,15 @@ export async function getCheckpointService(task: Task, { interval = 250 }: { int const service = RepoPerTaskCheckpointService.create(options) task.checkpointServiceInitializing = true await checkGitInstallation(task, service, log, provider) + if (!service.isInitialized) { + // checkGitInstallation disables checkpoints when Git is unavailable and + // logs initShadowGit failures without throwing: storing such a service + // would hand later saves (and the fast path above) an uninitialized + // handle whose isInitialized can never flip, so a failed + // initialization must resolve to no service at all. + task.checkpointServiceInitializing = false + return undefined + } task.checkpointService = service if (task.enableCheckpoints) { sendCheckpointInitWarn(task) @@ -202,6 +211,10 @@ async function checkGitInstallation( } catch (err) { log(`[Task#getCheckpointService] initShadowGit -> ${err.message}`) task.enableCheckpoints = false + // The "initialize" event never fires for a failed initShadowGit, so + // clear the flag here or later lookups wait on an initialization + // that already died. + task.checkpointServiceInitializing = false } } catch (err) { log(`[Task#getCheckpointService] Unexpected error during Git check: ${err.message}`) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index d35c721b36..7ad197d0fb 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -3940,22 +3940,37 @@ export class Task extends EventEmitter implements TaskLike { // An already-aborted task skips it too: the loop will never run, so the // save would only add latency to a task that is being disposed. if (!this.taskStartBaselineDone && !this._isHistoryTask && !this.abort) { - this.taskStartBaselineDone = true + let baselineEnabled: boolean | undefined try { - const baselineEnabled = (await this.providerRef.deref()?.getState())?.perWriteCheckpoints - // Cancellation can arrive while the state lookup is pending; recheck - // before the save so a canceled task performs no checkpoint work. - if (baselineEnabled !== false && !this.abort) { + baselineEnabled = (await this.providerRef.deref()?.getState())?.perWriteCheckpoints + } catch (error) { + // A rejected state lookup must not abort task startup: fall back + // to the default-on semantics used when the setting is absent. + console.error("[Task] task-start baseline settings read failed:", error) + } + // Cancellation can arrive while the state lookup is pending; recheck + // before the save so a canceled task performs no checkpoint work. + if (baselineEnabled === false || this.abort) { + this.taskStartBaselineDone = true + } else { + try { // allowEmpty=true so a clean workspace still produces the baseline // commit; awaited so the first per-write checkpoint cannot interleave. - await this.checkpointSave(true, true) + const baseline = await this.checkpointSave(true, true) + // The flag is set only once the baseline actually committed: a save + // that no-ops behind a failed or timed-out service initialization is + // retried on a later loop entry instead of being marked done without + // a rollback point. + if (baseline?.commit) { + this.taskStartBaselineDone = true + } + } catch (error) { + // The baseline is best-effort and runs before TaskStarted: a + // checkpoint error must not abort task startup (startTask rethrows + // non-abort errors from initiateTaskLoop). Log and continue; the + // next loop entry retries the baseline. + console.error("[Task] task-start checkpoint baseline failed:", error) } - } catch (error) { - // The baseline is best-effort and runs before TaskStarted: a rejected - // state lookup or a checkpoint error must not abort task startup - // (startTask rethrows non-abort errors from initiateTaskLoop). Log - // and continue; per-write saves still report their own failures. - console.error("[Task] task-start checkpoint baseline failed:", error) } } diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index c9970b1e93..28a8cbcea6 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7257,7 +7257,10 @@ describe("Cline", () => { startTask: false, }) const taskAccess = getTaskTestAccess(task) - const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue(undefined) + // A committed baseline: the done flag is set only on a real + // commit, so the double must resolve one for the once-per-instance + // assertion to exercise the flag flip. + const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue({ commit: "baseline-commit" }) const state = await mockProvider.getState() vi.spyOn(mockProvider, "getState").mockResolvedValue(state) @@ -7440,6 +7443,58 @@ describe("Cline", () => { expect(consoleErrorSpy).toHaveBeenCalledWith("[Task] task-start checkpoint baseline failed:", boom) consoleErrorSpy.mockRestore() }) + + it("retries the baseline on a later loop entry when a save produced no commit", async () => { + // getCheckpointService can resolve to no service (init failure or a + // bounded init wait timing out): the save then completes without a + // commit, and the baseline must not be marked done - a later loop + // entry gets to retry it instead of losing it forever. + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "retry baseline task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + const saveSpy = vi + .spyOn(task, "checkpointSave") + .mockResolvedValueOnce(undefined) + .mockResolvedValue({ commit: "baseline-commit" }) + const state = await mockProvider.getState() + vi.spyOn(mockProvider, "getState").mockResolvedValue(state) + + vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true) + + await taskAccess.initiateTaskLoop([]) + expect(saveSpy).toHaveBeenCalledOnce() + + await taskAccess.initiateTaskLoop([]) + expect(saveSpy).toHaveBeenCalledTimes(2) + }) + + it("starts the task default-on when the baseline settings read rejects", async () => { + // ClineProvider.getState awaits custom-mode loading and can reject: + // a failed settings read must not stop task startup. Default-on + // semantics apply (the setting is treated as absent) and the loop + // still runs. + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "rejected-read baseline task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue({ commit: "baseline-commit" }) + vi.spyOn(mockProvider, "getState").mockRejectedValueOnce(new Error("custom mode load failed")) + + const requestSpy = vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true) + + await taskAccess.initiateTaskLoop([]) + + expect(saveSpy).toHaveBeenCalledOnce() + expect(saveSpy).toHaveBeenCalledWith(true, true) + expect(requestSpy).toHaveBeenCalled() + }) }) describe("start()", () => { From 74751aedf157dba8f5d9817d86d9b26825c63cad Mon Sep 17 00:00:00 2001 From: dsh-agent Date: Thu, 22 Oct 2026 03:06:22 +0800 Subject: [PATCH 20/52] fix(task): bound the task-start baseline save; report a failed move rollback The baseline checkpoint is awaited before TaskStarted with allowEmpty. A stalled git add/commit blocked startup forever and could overlap the first file write. The await is now bounded by checkpointTimeout; a timed-out baseline logs a warning and startup continues, and because checkpointSave serializes per task a late baseline cannot interleave with the first per-write save. savePromise gets its own catch so a timeout that wins leaves no unhandled rejection. ApplyPatchTool: when the source unlink fails and restoring the pre-move destination also fails, the restore error is appended to the tool failure instead of only being logged, so the model and user know the destination may still hold the new content. Debug logging is kept. --- src/core/task/Task.ts | 37 ++++++++++++++++--- src/core/task/__tests__/Task.spec.ts | 28 ++++++++++++++ src/core/tools/ApplyPatchTool.ts | 12 +++++- .../__tests__/applyPatchTool.execute.spec.ts | 8 +++- 4 files changed, 77 insertions(+), 8 deletions(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 7ad197d0fb..34846b6de9 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -3956,12 +3956,37 @@ export class Task extends EventEmitter implements TaskLike { try { // allowEmpty=true so a clean workspace still produces the baseline // commit; awaited so the first per-write checkpoint cannot interleave. - const baseline = await this.checkpointSave(true, true) - // The flag is set only once the baseline actually committed: a save - // that no-ops behind a failed or timed-out service initialization is - // retried on a later loop entry instead of being marked done without - // a rollback point. - if (baseline?.commit) { + // The await is bounded: a stalled git add/commit must not hold task + // startup before TaskStarted. A baseline that finishes late is + // harmless - checkpointSave serializes per task, so a still-running + // baseline cannot interleave with the first per-write save. + const savePromise = this.checkpointSave(true, true) + // A timeout that wins must not leave an unhandled rejection behind. + savePromise.catch(() => undefined) + const BASELINE_TIMED_OUT = Symbol("baseline-timed-out") + let baselineTimer: ReturnType | undefined + const baseline = await Promise.race([ + savePromise, + new Promise((resolve) => { + baselineTimer = setTimeout( + () => resolve(BASELINE_TIMED_OUT), + Math.max(1, this.checkpointTimeout * 1000), + ) + }), + ]).finally(() => { + if (baselineTimer !== undefined) { + clearTimeout(baselineTimer) + } + }) + if (baseline === BASELINE_TIMED_OUT) { + console.warn( + `[Task] task-start checkpoint baseline still running after ${this.checkpointTimeout}s; entering the request loop and leaving the baseline to the per-task checkpoint lock.`, + ) + } else if (baseline?.commit) { + // The flag is set only once the baseline actually committed: a save + // that no-ops behind a failed or timed-out service initialization is + // retried on a later loop entry instead of being marked done without + // a rollback point. this.taskStartBaselineDone = true } } catch (error) { diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 28a8cbcea6..72fbbfd938 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7419,6 +7419,34 @@ describe("Cline", () => { expect(requestSpy).toHaveBeenCalled() }) + it("enters the request loop when the baseline save stalls past checkpointTimeout", async () => { + // A stalled git add/commit must not hold startup before TaskStarted. The + // await is bounded; the late baseline is left to the per-task checkpoint + // lock, which serializes it with the first per-write save. + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "baseline stall task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + type SaveResult = Awaited> + vi.spyOn(task, "checkpointSave").mockImplementation(() => new Promise(() => {})) + const requestSpy = vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true) + const state = await mockProvider.getState() + vi.spyOn(mockProvider, "getState").mockResolvedValue(state) + task.checkpointTimeout = 0.01 + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + + await taskAccess.initiateTaskLoop([]) + + expect(requestSpy).toHaveBeenCalled() + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining("task-start checkpoint baseline still running"), + ) + warnSpy.mockRestore() + }) + it("continues task startup when the baseline checkpoint fails", async () => { const task = new Task({ provider: mockProvider, diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 3bed2d8837..a2990015cd 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -535,6 +535,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // persist a duplicated file as if the move had succeeded. An existing // destination is restored to its captured content; the destination is // removed only when it was confirmed absent before the write. + let restoreFailure: unknown try { if (destinationBackup !== undefined) { await fs.writeFile(moveAbsolutePath, destinationBackup) @@ -542,9 +543,18 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await fs.rm(moveAbsolutePath, { force: true }) } } catch (restoreError) { + // The failed operation is reported through the tool result below; a + // failed rollback means the destination may now hold the new content + // while the source still exists, and both the model and the user must + // know that instead of a console-only note. + restoreFailure = restoreError console.error(`Failed to restore pre-move state after source deletion failure: ${restoreError}`) } - const moveErrorMessage = `Failed to delete original file after move '${relPath}': ${error instanceof Error ? error.message : String(error)}` + const restoreSuffix = + restoreFailure === undefined + ? "" + : ` The destination could not be restored and may still contain the new content: ${restoreFailure instanceof Error ? restoreFailure.message : String(restoreFailure)}` + const moveErrorMessage = `Failed to delete original file after move '${relPath}': ${error instanceof Error ? error.message : String(error)}${restoreSuffix}` await task.say("error", moveErrorMessage) pushToolResult(formatResponse.toolError(moveErrorMessage)) await task.diffViewProvider.reset() diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 8f92ac740a..9be8d39d27 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -181,10 +181,16 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockedFsPromises.default.rm).toHaveBeenCalledWith(expect.stringContaining("new.ts"), { force: true }) expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to restore pre-move state")) errorSpy.mockRestore() - // The move is reported as failed rather than as a successful write... + // The move is reported as failed rather than as a successful write, and the + // failed rollback is part of the message: the destination may still hold the + // new content, which the model and user must know. expect(mockPushToolResult).toHaveBeenCalledWith( expect.stringContaining("Failed to delete original file after move"), ) + expect(mockPushToolResult).toHaveBeenCalledWith( + expect.stringContaining("could not be restored and may still contain the new content"), + ) + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("EROFS")) // ...and no whole-patch checkpoint is recorded for the failed move. expect(mockedCheckpointSave).not.toHaveBeenCalled() // Restore the default readFile behavior for later tests. From 840f647e22a7632b0f8363425c66fcd12562fe19 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:32:33 +0800 Subject: [PATCH 21/52] fix(tools): make the apply_patch move transactional with atomic staging and renames Persistence Integrity (CodeRabbit pre-merge check): the move path wrote the destination with fs.writeFile before deleting the source, so a crash or a failed source unlink could leave a truncated or duplicated file, and the rollback rewrote the captured bytes non-atomically. - Write the new content to a sibling .staging file and rename it into place (atomic on one volume). - Keep the pre-move destination on disk under a .backup name (atomic rename) until the move commits. - On a failed source unlink, restore the destination by renaming the backup over it (one atomic replacement) or remove it when the destination did not exist. - When that restore itself fails, persist the approved content as .zoo-recovery- and name the path in the tool error, so a half-applied move has a deterministic recovery artifact. - DiffViewProvider.saveDirectly now writes through the same atomic staging helper, so every direct write offers all-or-nothing visibility. Tests updated to the new contract (atomic write + rename assertions, rollback via rename, recovery-copy message); 129 tests across the apply_patch, DiffViewProvider and checkpoint suites pass. --- src/core/tools/ApplyPatchTool.ts | 108 +++++++++++++----- .../__tests__/applyPatchTool.execute.spec.ts | 16 ++- src/integrations/editor/DiffViewProvider.ts | 27 ++++- .../editor/__tests__/DiffViewProvider.spec.ts | 29 ++++- 4 files changed, 142 insertions(+), 38 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index a2990015cd..6dde59dbba 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -509,20 +509,54 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } } - // Save new content to the new path - if (isPreventFocusDisruptionEnabled) { - await task.diffViewProvider.saveDirectly( - change.movePath, - newContent, - false, - diagnosticsEnabled, - writeDelayMs, - ) - } else { - // Write to new path and delete old file - const parentDir = path.dirname(moveAbsolutePath) - await fs.mkdir(parentDir, { recursive: true }) - await fs.writeFile(moveAbsolutePath, newContent, "utf8") + // Stage the move so it is all-or-nothing: the pre-move destination bytes + // stay on disk under a backup name, the new content is written to a + // staging file and renamed into place atomically, and only then is the + // source unlinked. Any failure renames the backup back, so the workspace + // never shows a half-applied move. + const moveStamp = `${process.pid}.${Date.now()}` + const moveDir = path.dirname(moveAbsolutePath) + const moveBase = path.basename(moveAbsolutePath) + const stagingPath = path.join(moveDir, `.${moveBase}.${moveStamp}.staging`) + const backupPath = path.join(moveDir, `.${moveBase}.${moveStamp}.backup`) + await fs.mkdir(moveDir, { recursive: true }) + + let destinationCommitted = false + try { + await fs.writeFile(stagingPath, newContent, "utf8") + if (destinationBackup !== undefined) { + // Preserve the pre-move bytes on disk (atomic rename): the in-memory + // copy alone cannot restore the destination after a crash. + await fs.rename(moveAbsolutePath, backupPath) + } + await fs.rename(stagingPath, moveAbsolutePath) + destinationCommitted = true + if (isPreventFocusDisruptionEnabled) { + // Diagnostics/bookkeeping only: the bytes were committed above, and + // saveDirectly writes the same content through the same atomic write. + await task.diffViewProvider.saveDirectly( + change.movePath, + newContent, + false, + diagnosticsEnabled, + writeDelayMs, + ) + } + } catch (writeError) { + await fs.rm(stagingPath, { force: true }).catch(() => {}) + if (destinationCommitted) { + await fs.rm(moveAbsolutePath, { force: true }).catch(() => {}) + } + if (destinationBackup !== undefined) { + await fs.rename(backupPath, moveAbsolutePath).catch(() => {}) + } + task.consecutiveMistakeCount++ + task.recordToolError("apply_patch") + const writeErrorMessage = `Failed to write move destination '${change.movePath}': ${writeError instanceof Error ? writeError.message : String(writeError)}` + await task.say("error", writeErrorMessage) + pushToolResult(formatResponse.toolError(writeErrorMessage)) + await task.diffViewProvider.reset() + return false } // Delete the original file @@ -530,37 +564,59 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await fs.unlink(absolutePath) } catch (error) { // The source is still present (locked or protected): undo the destination - // write so the file does not live in two places, and report the move as - // failed. Returning true here would let the whole-patch checkpoint - // persist a duplicated file as if the move had succeeded. An existing - // destination is restored to its captured content; the destination is - // removed only when it was confirmed absent before the write. + // so the file does not live in two places, and report the move as + // failed. Returning true here would let the whole-patch checkpoint persist + // a duplicated file as if the move had succeeded. let restoreFailure: unknown + let recoveryPath: string | undefined try { if (destinationBackup !== undefined) { - await fs.writeFile(moveAbsolutePath, destinationBackup) + // Atomic restore of the captured destination bytes: the rename + // replaces the clobbered destination in one step, so there is no + // window where the file is missing. + await fs.rename(backupPath, moveAbsolutePath) } else { await fs.rm(moveAbsolutePath, { force: true }) } } catch (restoreError) { - // The failed operation is reported through the tool result below; a - // failed rollback means the destination may now hold the new content - // while the source still exists, and both the model and the user must - // know that instead of a console-only note. restoreFailure = restoreError - console.error(`Failed to restore pre-move state after source deletion failure: ${restoreError}`) } + if (restoreFailure !== undefined) { + // The destination could not be restored. Persist the approved + // content under a recovery name instead of dropping it, so a + // half-applied move still has a deterministic recovery artifact. + const recoveryCandidate = path.join(moveDir, `${moveBase}.zoo-recovery-${moveStamp}`) + try { + await fs.writeFile(recoveryCandidate, newContent, "utf8") + recoveryPath = recoveryCandidate + console.error( + `Failed to restore pre-move state: ${restoreFailure instanceof Error ? restoreFailure.message : String(restoreFailure)}; kept the approved content at ${recoveryCandidate}`, + ) + } catch (recoveryError) { + console.error(`Failed to persist a move recovery copy: ${recoveryError}`) + } + } + // Best-effort cleanup of the staging file; the backup is gone once the + // restore rename committed (or is the only copy left on failure). + await fs.rm(stagingPath, { force: true }).catch(() => {}) const restoreSuffix = restoreFailure === undefined ? "" : ` The destination could not be restored and may still contain the new content: ${restoreFailure instanceof Error ? restoreFailure.message : String(restoreFailure)}` - const moveErrorMessage = `Failed to delete original file after move '${relPath}': ${error instanceof Error ? error.message : String(error)}${restoreSuffix}` + const recoverySuffix = + recoveryPath === undefined + ? "" + : ` The approved new content was kept at '${getReadablePath(task.cwd, path.relative(task.cwd, recoveryPath))}'.` + const moveErrorMessage = `Failed to delete original file after move '${relPath}': ${error instanceof Error ? error.message : String(error)}${restoreSuffix}${recoverySuffix}` await task.say("error", moveErrorMessage) pushToolResult(formatResponse.toolError(moveErrorMessage)) await task.diffViewProvider.reset() return false } + // The move committed: drop the destination backup. + await fs.rm(backupPath, { force: true }).catch(() => {}) + await task.fileContextTracker.trackFileContext(change.movePath, "roo_edited" as RecordSource) } else { // Save changes to the same file diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 9be8d39d27..75dd62e89e 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -18,6 +18,7 @@ const mockedFsPromises = vi.mocked( readFile: MockedFunction unlink: MockedFunction rm: MockedFunction + rename: MockedFunction writeFile: MockedFunction } }, @@ -28,6 +29,7 @@ vi.mock("fs/promises", () => ({ readFile: vi.fn().mockResolvedValue("original file content\n"), unlink: vi.fn().mockResolvedValue(undefined), rm: vi.fn().mockResolvedValue(undefined), + rename: vi.fn().mockResolvedValue(undefined), mkdir: vi.fn().mockResolvedValue(undefined), writeFile: vi.fn().mockResolvedValue(undefined), }, @@ -191,6 +193,8 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect.stringContaining("could not be restored and may still contain the new content"), ) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("EROFS")) + // The approved content survives the failed rollback as an explicit recovery artifact. + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("The approved new content was kept at")) // ...and no whole-patch checkpoint is recorded for the failed move. expect(mockedCheckpointSave).not.toHaveBeenCalled() // Restore the default readFile behavior for later tests. @@ -224,13 +228,17 @@ describe("ApplyPatchTool.execute - delete file success path", () => { toolCallId: "test-tool-call-id", }) - // The captured destination content is restored, not deleted: rm must not - // run for a destination that existed before the move. - expect(mockedFsPromises.default.writeFile).toHaveBeenCalledWith( + // The captured destination content is restored by renaming the on-disk backup + // over the clobbered destination (one atomic replacement), never by rewriting + // the captured bytes and never by deleting a destination that existed before. + expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalledWith( expect.stringContaining("new.ts"), "existing destination content", ) - expect(mockedFsPromises.default.rm).not.toHaveBeenCalled() + expect(mockedFsPromises.default.rename).toHaveBeenCalledWith( + expect.stringContaining(".backup"), + expect.stringMatching(/[\\/]new\.ts$/), + ) expect(mockPushToolResult).toHaveBeenCalledWith( expect.stringContaining("Failed to delete original file after move"), ) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 3c1d33ae28..5ffb7da5a9 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -25,6 +25,28 @@ export const DIFF_VIEW_URI_SCHEME = "cline-diff" export const DIFF_VIEW_LABEL_CHANGES = "Original ↔ Zoo's Changes" // TODO: https://github.com/cline/cline/pull/3354 +/** + * Write a file so readers only ever observe the previous bytes or the complete + * new bytes: the content goes to a sibling staging file first and is renamed + * into place (same directory, so the rename is atomic on one volume). + */ +async function writeFileAtomically(absolutePath: string, content: string): Promise { + // Derive the sibling staging path with plain string operations: this helper runs + // under unit tests that mock the "path" module down to the few functions the + // provider itself uses. + const separatorIndex = Math.max(absolutePath.lastIndexOf("/"), absolutePath.lastIndexOf("\\")) + const directory = separatorIndex >= 0 ? absolutePath.slice(0, separatorIndex) : "." + const baseName = separatorIndex >= 0 ? absolutePath.slice(separatorIndex + 1) : absolutePath + const stagingPath = `${directory}/.${baseName}.${process.pid}.${Date.now()}.staging` + try { + await fs.writeFile(stagingPath, content, "utf-8") + await fs.rename(stagingPath, absolutePath) + } catch (error) { + await fs.rm(stagingPath, { force: true }).catch(() => {}) + throw error + } +} + export class DiffViewProvider { // Properties to store the results of saveChanges newProblemsMessage?: string @@ -1155,9 +1177,10 @@ export class DiffViewProvider { // Get diagnostics before editing the file this.preDiagnostics = vscode.languages.getDiagnostics() - // Write the content directly to the file + // Write the content directly to the file, atomically: a crash mid-write must + // not leave the destination truncated. await createDirectoriesForFile(absolutePath) - await fs.writeFile(absolutePath, content, "utf-8") + await writeFileAtomically(absolutePath, content) // Open the document to ensure diagnostics are loaded // When openFile is false (PREVENT_FOCUS_DISRUPTION enabled), we only open in memory diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index e94a66e1db..94c3c5a101 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -17,6 +17,8 @@ vi.mock("delay", () => ({ vi.mock("fs/promises", () => ({ readFile: vi.fn().mockResolvedValue("file content"), writeFile: vi.fn().mockResolvedValue(undefined), + rename: vi.fn().mockResolvedValue(undefined), + rm: vi.fn().mockResolvedValue(undefined), access: vi.fn().mockResolvedValue(undefined), })) @@ -782,9 +784,14 @@ describe("DiffViewProvider", () => { const result = await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 2000) - // Verify file was written + // Verify the content was written through an atomic staging file + rename const fs = await import("fs/promises") - expect(fs.writeFile).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", "utf-8") + expect(fs.writeFile).toHaveBeenCalledWith(expect.stringContaining(".staging"), "new content", "utf-8") + const stagingPath = (fs.writeFile as unknown as { mock: { calls: [string, string, string][] } }).mock.calls.find( + (call) => call[1] === "new content", + )?.[0] + expect(stagingPath).toContain(".test.ts.") + expect(fs.rename).toHaveBeenCalledWith(stagingPath, `${mockCwd}/test.ts`) // Verify file was opened without focus expect(vscode.window.showTextDocument).toHaveBeenCalledWith( @@ -805,9 +812,14 @@ describe("DiffViewProvider", () => { it("should not open file when openWithoutFocus is false", async () => { await diffViewProvider.saveDirectly("test.ts", "new content", false, true, 1000) - // Verify file was written + // Verify the content was written through an atomic staging file + rename const fs = await import("fs/promises") - expect(fs.writeFile).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", "utf-8") + expect(fs.writeFile).toHaveBeenCalledWith(expect.stringContaining(".staging"), "new content", "utf-8") + const stagingPath = (fs.writeFile as unknown as { mock: { calls: [string, string, string][] } }).mock.calls.find( + (call) => call[1] === "new content", + )?.[0] + expect(stagingPath).toContain(".test.ts.") + expect(fs.rename).toHaveBeenCalledWith(stagingPath, `${mockCwd}/test.ts`) // Verify file was NOT opened expect(vscode.window.showTextDocument).not.toHaveBeenCalled() @@ -820,9 +832,14 @@ describe("DiffViewProvider", () => { await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 1000) - // Verify file was written + // Verify the content was written through an atomic staging file + rename const fs = await import("fs/promises") - expect(fs.writeFile).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", "utf-8") + expect(fs.writeFile).toHaveBeenCalledWith(expect.stringContaining(".staging"), "new content", "utf-8") + const stagingPath = (fs.writeFile as unknown as { mock: { calls: [string, string, string][] } }).mock.calls.find( + (call) => call[1] === "new content", + )?.[0] + expect(stagingPath).toContain(".test.ts.") + expect(fs.rename).toHaveBeenCalledWith(stagingPath, `${mockCwd}/test.ts`) // Verify delay was NOT called expect(mockDelay).not.toHaveBeenCalled() From c90dce66a395742f0f5948cacc8d6a03582045ef Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:53:22 +0800 Subject: [PATCH 22/52] fix(tools): preserve destination identity and permissions in the atomic write paths Security Boundaries (CodeRabbit pre-merge check): writing the staged bytes with fs.writeFile defaults and renaming them over the destination widened permissions (a 0600 or executable file came back with process defaults) and replaced symlinks with regular files. - Move the atomic writer into src/integrations/editor/atomicWrite.ts and resolve the destination first: a symlink is updated through its target instead of being replaced, the resolved target's mode is applied to the staging file (masked to permission bits), and ownership is preserved where permitted. - ApplyPatchTool's move staging now captures and re-applies the destination mode before the atomic rename. - Rollback message precedence: when the destination existed and its restore failed, the original bytes are still at the backup path - report that path and skip the recovery copy of the new content; only a move with no pre-move destination keeps the approved content as a recovery artifact. Coverage: new atomicWrite.spec (new file, executable mode, symlink target - POSIX lanes), a saveDirectly rename-failure test (same error rethrown, staging removed with force), and the move test now pins the destination mode reaching the staging file. 131 tests pass (+2 POSIX-only skipped on Windows), eslint and tsc clean. --- src/core/tools/ApplyPatchTool.ts | 53 +++++++++++---- .../__tests__/applyPatchTool.execute.spec.ts | 7 ++ src/integrations/editor/DiffViewProvider.ts | 23 +------ .../editor/__tests__/DiffViewProvider.spec.ts | 23 +++++++ .../editor/__tests__/atomicWrite.spec.ts | 64 +++++++++++++++++++ src/integrations/editor/atomicWrite.ts | 50 +++++++++++++++ 6 files changed, 185 insertions(+), 35 deletions(-) create mode 100644 src/integrations/editor/__tests__/atomicWrite.spec.ts create mode 100644 src/integrations/editor/atomicWrite.ts diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 6dde59dbba..9e47334510 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -509,6 +509,17 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } } + // Capture the destination mode before replacing it: the atomic staging write + // would otherwise install the process-default permissions and widen a 0600 + // or executable destination. + let destinationMode: number | undefined + if (destinationBackup !== undefined) { + destinationMode = await fs.stat(moveAbsolutePath).then( + (stat) => stat.mode, + () => undefined, + ) + } + // Stage the move so it is all-or-nothing: the pre-move destination bytes // stay on disk under a backup name, the new content is written to a // staging file and renamed into place atomically, and only then is the @@ -524,6 +535,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { let destinationCommitted = false try { await fs.writeFile(stagingPath, newContent, "utf8") + if (destinationMode !== undefined) { + await fs.chmod(stagingPath, destinationMode) + } if (destinationBackup !== undefined) { // Preserve the pre-move bytes on disk (atomic rename): the in-memory // copy alone cannot restore the destination after a crash. @@ -569,6 +583,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // a duplicated file as if the move had succeeded. let restoreFailure: unknown let recoveryPath: string | undefined + let recoveryFailure: unknown try { if (destinationBackup !== undefined) { // Atomic restore of the captured destination bytes: the rename @@ -582,18 +597,28 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { restoreFailure = restoreError } if (restoreFailure !== undefined) { - // The destination could not be restored. Persist the approved - // content under a recovery name instead of dropping it, so a - // half-applied move still has a deterministic recovery artifact. - const recoveryCandidate = path.join(moveDir, `${moveBase}.zoo-recovery-${moveStamp}`) - try { - await fs.writeFile(recoveryCandidate, newContent, "utf8") - recoveryPath = recoveryCandidate + if (destinationBackup !== undefined) { + // The original destination bytes are still on disk under the backup + // name: keep them as the recovery artifact and report where they are. + // Writing a copy of the approved new content here would hide the + // original content that this branch is supposed to preserve. console.error( - `Failed to restore pre-move state: ${restoreFailure instanceof Error ? restoreFailure.message : String(restoreFailure)}; kept the approved content at ${recoveryCandidate}`, + `Failed to restore pre-move state: ${restoreFailure instanceof Error ? restoreFailure.message : String(restoreFailure)}; the original content is preserved at ${backupPath}`, ) - } catch (recoveryError) { - console.error(`Failed to persist a move recovery copy: ${recoveryError}`) + } else { + // There was no pre-existing destination, so the approved content is + // the only thing that could be lost: persist it under a recovery name. + const recoveryCandidate = path.join(moveDir, `${moveBase}.zoo-recovery-${moveStamp}`) + try { + await fs.writeFile(recoveryCandidate, newContent, "utf8") + recoveryPath = recoveryCandidate + console.error( + `Failed to restore pre-move state: ${restoreFailure instanceof Error ? restoreFailure.message : String(restoreFailure)}; kept the approved content at ${recoveryCandidate}`, + ) + } catch (recoveryError) { + recoveryFailure = recoveryError + console.error(`Failed to persist a move recovery copy: ${recoveryError}`) + } } } // Best-effort cleanup of the staging file; the backup is gone once the @@ -604,9 +629,11 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { ? "" : ` The destination could not be restored and may still contain the new content: ${restoreFailure instanceof Error ? restoreFailure.message : String(restoreFailure)}` const recoverySuffix = - recoveryPath === undefined - ? "" - : ` The approved new content was kept at '${getReadablePath(task.cwd, path.relative(task.cwd, recoveryPath))}'.` + recoveryFailure !== undefined && recoveryPath === undefined + ? ` The original content is preserved at '${getReadablePath(task.cwd, path.relative(task.cwd, backupPath))}'.` + : recoveryPath === undefined + ? "" + : ` The approved new content was kept at '${getReadablePath(task.cwd, path.relative(task.cwd, recoveryPath))}'.` const moveErrorMessage = `Failed to delete original file after move '${relPath}': ${error instanceof Error ? error.message : String(error)}${restoreSuffix}${recoverySuffix}` await task.say("error", moveErrorMessage) pushToolResult(formatResponse.toolError(moveErrorMessage)) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 75dd62e89e..fc87e1423a 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -19,6 +19,8 @@ const mockedFsPromises = vi.mocked( unlink: MockedFunction rm: MockedFunction rename: MockedFunction + stat: MockedFunction + chmod: MockedFunction writeFile: MockedFunction } }, @@ -30,6 +32,8 @@ vi.mock("fs/promises", () => ({ unlink: vi.fn().mockResolvedValue(undefined), rm: vi.fn().mockResolvedValue(undefined), rename: vi.fn().mockResolvedValue(undefined), + stat: vi.fn().mockResolvedValue({ mode: 0o755, uid: 0, gid: 0 }), + chmod: vi.fn().mockResolvedValue(undefined), mkdir: vi.fn().mockResolvedValue(undefined), writeFile: vi.fn().mockResolvedValue(undefined), }, @@ -239,6 +243,9 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect.stringContaining(".backup"), expect.stringMatching(/[\\/]new\.ts$/), ) + // The replacement keeps the destination's mode instead of installing the + // process defaults on the staging file. + expect(mockedFsPromises.default.chmod).toHaveBeenCalledWith(expect.stringContaining(".staging"), 0o755) expect(mockPushToolResult).toHaveBeenCalledWith( expect.stringContaining("Failed to delete original file after move"), ) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 5ffb7da5a9..d56d08aed1 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -14,6 +14,7 @@ import { } from "@roo-code/types" import { createDirectoriesForFile } from "../../utils/fs" +import { writeFileAtomically } from "./atomicWrite" import { arePathsEqual, getReadablePath } from "../../utils/path" import { formatResponse } from "../../core/prompts/responses" import { diagnosticsToProblemsString, getNewDiagnostics } from "../diagnostics" @@ -25,28 +26,6 @@ export const DIFF_VIEW_URI_SCHEME = "cline-diff" export const DIFF_VIEW_LABEL_CHANGES = "Original ↔ Zoo's Changes" // TODO: https://github.com/cline/cline/pull/3354 -/** - * Write a file so readers only ever observe the previous bytes or the complete - * new bytes: the content goes to a sibling staging file first and is renamed - * into place (same directory, so the rename is atomic on one volume). - */ -async function writeFileAtomically(absolutePath: string, content: string): Promise { - // Derive the sibling staging path with plain string operations: this helper runs - // under unit tests that mock the "path" module down to the few functions the - // provider itself uses. - const separatorIndex = Math.max(absolutePath.lastIndexOf("/"), absolutePath.lastIndexOf("\\")) - const directory = separatorIndex >= 0 ? absolutePath.slice(0, separatorIndex) : "." - const baseName = separatorIndex >= 0 ? absolutePath.slice(separatorIndex + 1) : absolutePath - const stagingPath = `${directory}/.${baseName}.${process.pid}.${Date.now()}.staging` - try { - await fs.writeFile(stagingPath, content, "utf-8") - await fs.rename(stagingPath, absolutePath) - } catch (error) { - await fs.rm(stagingPath, { force: true }).catch(() => {}) - throw error - } -} - export class DiffViewProvider { // Properties to store the results of saveChanges newProblemsMessage?: string diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 94c3c5a101..644c8e70ab 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -20,6 +20,12 @@ vi.mock("fs/promises", () => ({ rename: vi.fn().mockResolvedValue(undefined), rm: vi.fn().mockResolvedValue(undefined), access: vi.fn().mockResolvedValue(undefined), + // The atomic writer resolves an existing destination and preserves its mode; + // the default double behaves like a brand-new file (ENOENT). + realpath: vi.fn().mockRejectedValue(Object.assign(new Error("ENOENT"), { code: "ENOENT" })), + stat: vi.fn().mockResolvedValue({ mode: 0o644, uid: 0, gid: 0 }), + chmod: vi.fn().mockResolvedValue(undefined), + chown: vi.fn().mockResolvedValue(undefined), })) // Mock utils @@ -809,6 +815,23 @@ describe("DiffViewProvider", () => { expect(result.finalContent).toBe("new content") }) + it("keeps the same error and cleans up the staging file when the final rename fails", async () => { + const fs = await import("fs/promises") + const renameError = Object.assign(new Error("EPERM: rename blocked"), { code: "EPERM" }) + vi.mocked(fs.rename).mockRejectedValueOnce(renameError) + + await expect(diffViewProvider.saveDirectly("test.ts", "new content", true, true, 1000)).rejects.toBe( + renameError, + ) + + const stagingPath = (fs.writeFile as unknown as { mock: { calls: [string, string, string][] } }).mock.calls.find( + (call) => call[1] === "new content", + )?.[0] + expect(renameError).toBeInstanceOf(Error) + expect(fs.rename).toHaveBeenCalledWith(stagingPath, `${mockCwd}/test.ts`) + expect(fs.rm).toHaveBeenCalledWith(stagingPath, { force: true }) + }) + it("should not open file when openWithoutFocus is false", async () => { await diffViewProvider.saveDirectly("test.ts", "new content", false, true, 1000) diff --git a/src/integrations/editor/__tests__/atomicWrite.spec.ts b/src/integrations/editor/__tests__/atomicWrite.spec.ts new file mode 100644 index 0000000000..7b74e05768 --- /dev/null +++ b/src/integrations/editor/__tests__/atomicWrite.spec.ts @@ -0,0 +1,64 @@ +// npx vitest run integrations/editor/__tests__/atomicWrite.spec.ts + +import fs from "fs/promises" +import os from "os" +import path from "path" + +import { afterEach, beforeEach, describe, expect, it } from "vitest" + +import { writeFileAtomically } from "../atomicWrite" + +describe("writeFileAtomically", () => { + let dir: string + + beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "atomic-write-")) + }) + + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }) + }) + + it("creates a new file with the complete content and no staging leftovers", async () => { + const target = path.join(dir, "new.txt") + + await writeFileAtomically(target, "hello") + + expect(await fs.readFile(target, "utf8")).toBe("hello") + expect(await fs.readdir(dir)).toEqual(["new.txt"]) + }) + + // Windows only maps the read-only attribute onto chmod, so POSIX mode bits are + // not observable there; the ubuntu lane covers this regression. + const posixOnly = it.skipIf(process.platform === "win32") + + posixOnly("preserves the destination mode for an executable file", async () => { + const target = path.join(dir, "script.sh") + await fs.writeFile(target, "old", "utf8") + await fs.chmod(target, 0o755) + + await writeFileAtomically(target, "new") + + expect(await fs.readFile(target, "utf8")).toBe("new") + const stat = await fs.stat(target) + expect(stat.mode & 0o777).toBe(0o755) + }) + + posixOnly("updates a symlink through its target without replacing the symlink", async () => { + const target = path.join(dir, "real.txt") + const link = path.join(dir, "link.txt") + await fs.writeFile(target, "old", "utf8") + try { + await fs.symlink(target, link) + } catch (error) { + // Creating symlinks needs Developer Mode or admin rights on Windows. + if ((error as NodeJS.ErrnoException).code === "EPERM") return + throw error + } + + await writeFileAtomically(link, "new") + + expect(await fs.readFile(target, "utf8")).toBe("new") + expect((await fs.lstat(link)).isSymbolicLink()).toBe(true) + }) +}) diff --git a/src/integrations/editor/atomicWrite.ts b/src/integrations/editor/atomicWrite.ts new file mode 100644 index 0000000000..4fe796098b --- /dev/null +++ b/src/integrations/editor/atomicWrite.ts @@ -0,0 +1,50 @@ +import * as fs from "fs/promises" + +/** + * Write a file so readers only ever observe the previous bytes or the complete + * new bytes: the content goes to a sibling staging file first and is renamed into + * place (same directory, so the rename is atomic on one volume). + * + * The destination is resolved first so a symlink is updated through its target + * instead of being replaced by a regular file, and the resolved target's mode (and, + * where permitted, ownership) is applied to the staging file: a fresh staging file + * carries the process defaults, which would otherwise widen a 0600 or executable + * destination. + */ +export async function writeFileAtomically(absolutePath: string, content: string, mode?: number): Promise { + let targetPath = absolutePath + let targetMode = mode + let targetOwnership: { uid: number; gid: number } | undefined + try { + targetPath = await fs.realpath(absolutePath) + const stat = await fs.stat(targetPath) + targetMode = targetMode ?? (stat.mode & 0o7777) + targetOwnership = { uid: stat.uid, gid: stat.gid } + } catch (error) { + if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") { + throw error + } + } + // Derive the sibling staging path with plain string operations so the helper stays + // usable in unit tests that mock the "path" module down to a few functions. + const separatorIndex = Math.max(targetPath.lastIndexOf("/"), targetPath.lastIndexOf("\\")) + const directory = separatorIndex >= 0 ? targetPath.slice(0, separatorIndex) : "." + const baseName = separatorIndex >= 0 ? targetPath.slice(separatorIndex + 1) : targetPath + const stagingPath = `${directory}/.${baseName}.${process.pid}.${Date.now()}.staging` + try { + await fs.writeFile(stagingPath, content, "utf-8") + if (targetMode !== undefined) { + await fs.chmod(stagingPath, targetMode) + } + if (targetOwnership !== undefined) { + // Preserve ownership where the platform permits it; a chown the writer may + // not perform (EPERM without privileges) leaves the writer as owner, which is + // also the normal outcome for newly created files. + await fs.chown(stagingPath, targetOwnership.uid, targetOwnership.gid).catch(() => {}) + } + await fs.rename(stagingPath, targetPath) + } catch (error) { + await fs.rm(stagingPath, { force: true }).catch(() => {}) + throw error + } +} From 71a5eed99d15f424d114bb6c36bc289904487654 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:55:59 +0800 Subject: [PATCH 23/52] fix(checkpoints): serialize per-task checkpoint saves Persistence Integrity (CodeRabbit pre-merge check): Task.initiateTaskLoop starts the task-start baseline checkpoint and only waits with Promise.race, so a later per-write save could run while the baseline is still staging or committing. checkpointSave now runs every save through a per-task promise queue, so stageAll + commit never overlap for the same task and a per-write save always waits for a still-running baseline. The queue entry is dropped once it drains so finished tasks do not leak. Coverage: a concurrency test drives two checkpointSave calls and asserts the second never reaches saveCheckpoint until the first settles; checkpoint suite 29/29, apply_patch + DiffViewProvider + atomicWrite suites 131 passed (+2 POSIX-only skipped); eslint and tsc clean. --- .../checkpoints/__tests__/checkpoint.test.ts | 28 ++++++++++++++ src/core/checkpoints/index.ts | 38 +++++++++++++++---- 2 files changed, 59 insertions(+), 7 deletions(-) diff --git a/src/core/checkpoints/__tests__/checkpoint.test.ts b/src/core/checkpoints/__tests__/checkpoint.test.ts index 1d56126f0a..bc2fc9247c 100644 --- a/src/core/checkpoints/__tests__/checkpoint.test.ts +++ b/src/core/checkpoints/__tests__/checkpoint.test.ts @@ -112,6 +112,34 @@ describe("Checkpoint functionality", () => { }) describe("checkpointSave", () => { + it("serializes concurrent saves for the same task so stageAll + commit never overlap", async () => { + const order: string[] = [] + let resolveFirst: (value: { commit: string }) => void = () => {} + mockCheckpointService.saveCheckpoint + .mockImplementationOnce(() => { + order.push("first:start") + return new Promise((resolve) => { + resolveFirst = resolve + }) + }) + .mockImplementationOnce(async () => { + order.push("second:start") + return { commit: "second-commit" } + }) + + const first = checkpointSave(mockTask, false, true) + const second = checkpointSave(mockTask, false, true) + + // The second save must not reach the service while the first is still running: + // a queued save owns the stageAll + commit pair until it settles. + await new Promise((resolve) => setTimeout(resolve, 10)) + expect(order).toEqual(["first:start"]) + + resolveFirst({ commit: "first-commit" }) + await Promise.all([first, second]) + expect(order).toEqual(["first:start", "second:start"]) + }) + it("should wait for checkpoint service initialization before saving", async () => { // Set up task with uninitialized service mockCheckpointService.isInitialized = false diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index 35f3a97b83..090b1e6b6d 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -224,6 +224,29 @@ async function checkGitInstallation( } } +// Serialize checkpoint saves per task. saveCheckpoint() runs stageAll + commit, so two +// concurrent saves for the same task (for example the task-start baseline racing the first +// per-write save after the baseline timeout) can stage each other's writes or interleave +// commits. A per-task promise queue makes every save wait for the previous one, including +// a baseline that is still running. +const checkpointSaveQueues = new Map>() + +function enqueueCheckpointSave(taskId: string, operation: () => Promise): Promise { + const previous = checkpointSaveQueues.get(taskId) ?? Promise.resolve() + const next = previous.then(operation, operation) + const tail = next.then( + () => undefined, + () => undefined, + ) + checkpointSaveQueues.set(taskId, tail) + void tail.finally(() => { + if (checkpointSaveQueues.get(taskId) === tail) { + checkpointSaveQueues.delete(taskId) + } + }) + return next +} + export async function checkpointSave(task: Task, force = false, suppressMessage = false) { const service = await getCheckpointService(task) @@ -233,13 +256,14 @@ export async function checkpointSave(task: Task, force = false, suppressMessage TelemetryService.instance.captureCheckpointCreated(task.taskId) - // Start the checkpoint process in the background. - return service - .saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, { allowEmpty: force, suppressMessage }) - .catch((err) => { - console.error("[Task#checkpointSave] caught unexpected error, disabling checkpoints", err) - task.enableCheckpoints = false - }) + // Start the checkpoint process in the background, queued behind any save already + // running for this task so stageAll + commit never overlap. + return enqueueCheckpointSave(task.taskId, () => + service.saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, { allowEmpty: force, suppressMessage }), + ).catch((err) => { + console.error("[Task#checkpointSave] caught unexpected error, disabling checkpoints", err) + task.enableCheckpoints = false + }) } export type CheckpointRestoreOptions = { From df1b96643a6e1d44ba9442d277ba5e390f80ae10 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:18:34 +0800 Subject: [PATCH 24/52] fix(tools): keep staging owner-only and make partial patch mutations checkpointable Security Boundaries (pre-merge check + two review threads): every staging file is now created with mode 0o600 before any content is written, and the intended destination mode/ownership is applied afterwards, in both writeFileAtomically and the apply_patch move path. Persistence Integrity (pre-merge check): handoffPending was only raised when a handler returned true, so a handler that mutated the workspace and then failed (a move whose destination was already replaced before the source unlink failed) produced a retained write with no rollback metadata. Handlers now return { ok, mutated }: mutated is set at the first filesystem mutation, and the partial-state checkpoint uses it. Review threads: the recoverySuffix condition now names the backup path only when a pre-move destination exists (it previously claimed a preserved original for a no-destination move), and the DiffViewProvider test reads vi.mocked(fs.writeFile).mock.calls instead of a double assertion. Tests: rollback cases now assert the partial-state checkpoint is recorded (they previously asserted no checkpoint); apply_patch + DiffViewProvider + atomicWrite + checkpoints: 132 passed (+2 POSIX-only skipped); eslint/tsc clean. --- src/core/tools/ApplyPatchTool.ts | 78 +++++++++++-------- .../__tests__/applyPatchTool.execute.spec.ts | 19 +++-- .../editor/__tests__/DiffViewProvider.spec.ts | 31 ++++---- src/integrations/editor/atomicWrite.ts | 4 +- 4 files changed, 76 insertions(+), 56 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 9e47334510..89e9a338d0 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -21,6 +21,9 @@ interface ApplyPatchParams { patch: string } +/** Result of one file operation: `mutated` is true when the workspace changed even if the operation eventually failed. */ +type PatchFileResult = { ok: boolean; mutated: boolean } + export class ApplyPatchTool extends BaseTool<"apply_patch"> { readonly name = "apply_patch" as const @@ -134,7 +137,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (change.type === "add") { // Create new file - const ok = await this.handleAddFile( + const result = await this.handleAddFile( change, absolutePath, relPath, @@ -142,16 +145,16 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { callbacks, isWriteProtected, ) - handoffPending = handoffPending || ok - patchSucceeded = ok && patchSucceeded + handoffPending = handoffPending || result.mutated + patchSucceeded = result.ok && patchSucceeded } else if (change.type === "delete") { // Delete file - const ok = await this.handleDeleteFile(absolutePath, relPath, task, callbacks, isWriteProtected) - handoffPending = handoffPending || ok - patchSucceeded = ok && patchSucceeded + const result = await this.handleDeleteFile(absolutePath, relPath, task, callbacks, isWriteProtected) + handoffPending = handoffPending || result.mutated + patchSucceeded = result.ok && patchSucceeded } else if (change.type === "update") { // Update file - const ok = await this.handleUpdateFile( + const result = await this.handleUpdateFile( change, absolutePath, relPath, @@ -159,8 +162,8 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { callbacks, isWriteProtected, ) - handoffPending = handoffPending || ok - patchSucceeded = ok && patchSucceeded + handoffPending = handoffPending || result.mutated + patchSucceeded = result.ok && patchSucceeded } } @@ -224,8 +227,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task: Task, callbacks: ToolCallbacks, isWriteProtected: boolean, - ): Promise { + ): Promise { const { askApproval, pushToolResult } = callbacks + let mutated = false // Check if file already exists const fileExists = await fileExistsAtPath(absolutePath) @@ -235,7 +239,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const errorMessage = `File already exists: ${relPath}. Use Update File instead.` await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) - return false + return { ok: false, mutated } } const newContent = change.newContent || "" @@ -289,7 +293,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } pushToolResult("Changes were rejected by the user.") await task.diffViewProvider.reset() - return false + return { ok: false, mutated } } // Save the changes @@ -301,12 +305,13 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // Track file edit operation await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource) + mutated = true task.didEditFile = true const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, true) pushToolResult(message) await task.diffViewProvider.reset() - return true + return { ok: true, mutated } } private async handleDeleteFile( @@ -315,8 +320,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task: Task, callbacks: ToolCallbacks, isWriteProtected: boolean, - ): Promise { + ): Promise { const { askApproval, pushToolResult } = callbacks + let mutated = false // Check if file exists const fileExists = await fileExistsAtPath(absolutePath) @@ -326,7 +332,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const errorMessage = `File not found: ${relPath}. Cannot delete a non-existent file.` await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) - return false + return { ok: false, mutated } } const isOutsideWorkspace = isPathOutsideWorkspace(absolutePath) @@ -348,7 +354,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (!didApprove) { pushToolResult("Delete operation was rejected by the user.") - return false + return { ok: false, mutated } } // Delete the file @@ -358,12 +364,13 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const errorMessage = `Failed to delete file '${relPath}': ${error instanceof Error ? error.message : String(error)}` await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) - return false + return { ok: false, mutated } } + mutated = true task.didEditFile = true pushToolResult(`Successfully deleted ${relPath}`) - return true + return { ok: true, mutated } } private async handleUpdateFile( @@ -373,8 +380,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task: Task, callbacks: ToolCallbacks, isWriteProtected: boolean, - ): Promise { + ): Promise { const { askApproval, pushToolResult } = callbacks + let mutated = false // Check if file exists const fileExists = await fileExistsAtPath(absolutePath) @@ -384,7 +392,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const errorMessage = `File not found: ${relPath}. Cannot update a non-existent file.` await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) - return false + return { ok: false, mutated } } const originalContent = change.originalContent || "" @@ -402,7 +410,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // nothing was written, so the whole-patch success state is kept. pushToolResult(`No changes needed for '${relPath}'`) await task.diffViewProvider.reset() - return true + return { ok: true, mutated } } // Check experiment settings @@ -448,7 +456,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } pushToolResult("Changes were rejected by the user.") await task.diffViewProvider.reset() - return false + return { ok: false, mutated } } // Handle file move if specified @@ -461,7 +469,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await task.say("rooignore_error", change.movePath) pushToolResult(formatResponse.rooIgnoreError(change.movePath)) await task.diffViewProvider.reset() - return false + return { ok: false, mutated } } // Check if destination path is write-protected @@ -473,7 +481,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) await task.diffViewProvider.reset() - return false + return { ok: false, mutated } } // Check if destination path is outside workspace @@ -485,7 +493,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await task.say("error", errorMessage) pushToolResult(formatResponse.toolError(errorMessage)) await task.diffViewProvider.reset() - return false + return { ok: false, mutated } } // Capture the destination state before either supported write path: a @@ -505,7 +513,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await task.say("error", inspectErrorMessage) pushToolResult(formatResponse.toolError(inspectErrorMessage)) await task.diffViewProvider.reset() - return false + return { ok: false, mutated } } } @@ -534,7 +542,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { let destinationCommitted = false try { - await fs.writeFile(stagingPath, newContent, "utf8") + // Owner-only from creation: the staged content must never be readable by + // others, even between the write and the rename. + await fs.writeFile(stagingPath, newContent, { encoding: "utf8", mode: 0o600 }) if (destinationMode !== undefined) { await fs.chmod(stagingPath, destinationMode) } @@ -545,6 +555,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } await fs.rename(stagingPath, moveAbsolutePath) destinationCommitted = true + // The destination content changed: even a later failed source unlink (which + // rolls the destination back) is a workspace mutation the checkpoint must see. + mutated = true if (isPreventFocusDisruptionEnabled) { // Diagnostics/bookkeeping only: the bytes were committed above, and // saveDirectly writes the same content through the same atomic write. @@ -570,7 +583,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await task.say("error", writeErrorMessage) pushToolResult(formatResponse.toolError(writeErrorMessage)) await task.diffViewProvider.reset() - return false + return { ok: false, mutated } } // Delete the original file @@ -583,7 +596,6 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // a duplicated file as if the move had succeeded. let restoreFailure: unknown let recoveryPath: string | undefined - let recoveryFailure: unknown try { if (destinationBackup !== undefined) { // Atomic restore of the captured destination bytes: the rename @@ -616,7 +628,6 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { `Failed to restore pre-move state: ${restoreFailure instanceof Error ? restoreFailure.message : String(restoreFailure)}; kept the approved content at ${recoveryCandidate}`, ) } catch (recoveryError) { - recoveryFailure = recoveryError console.error(`Failed to persist a move recovery copy: ${recoveryError}`) } } @@ -629,7 +640,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { ? "" : ` The destination could not be restored and may still contain the new content: ${restoreFailure instanceof Error ? restoreFailure.message : String(restoreFailure)}` const recoverySuffix = - recoveryFailure !== undefined && recoveryPath === undefined + destinationBackup !== undefined && restoreFailure !== undefined && recoveryPath === undefined ? ` The original content is preserved at '${getReadablePath(task.cwd, path.relative(task.cwd, backupPath))}'.` : recoveryPath === undefined ? "" @@ -638,7 +649,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await task.say("error", moveErrorMessage) pushToolResult(formatResponse.toolError(moveErrorMessage)) await task.diffViewProvider.reset() - return false + return { ok: false, mutated } } // The move committed: drop the destination backup. @@ -653,6 +664,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs) } + mutated = true await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource) } @@ -661,7 +673,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, false) pushToolResult(message) await task.diffViewProvider.reset() - return true + return { ok: true, mutated } } override async handlePartial(task: Task, block: ToolUse<"apply_patch">): Promise { diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index fc87e1423a..4aa8522cd8 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -200,7 +200,9 @@ describe("ApplyPatchTool.execute - delete file success path", () => { // The approved content survives the failed rollback as an explicit recovery artifact. expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("The approved new content was kept at")) // ...and no whole-patch checkpoint is recorded for the failed move. - expect(mockedCheckpointSave).not.toHaveBeenCalled() + // The destination was written (then rolled back): that is a workspace mutation, so + // the partial-state checkpoint is recorded even though the patch reports failure. + expect(mockedCheckpointSave).toHaveBeenCalledOnce() // Restore the default readFile behavior for later tests. mockedFsPromises.default.readFile.mockResolvedValue("original file content\n") }) @@ -249,7 +251,9 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockPushToolResult).toHaveBeenCalledWith( expect.stringContaining("Failed to delete original file after move"), ) - expect(mockedCheckpointSave).not.toHaveBeenCalled() + // The destination was written (then rolled back): that is a workspace mutation, so + // the partial-state checkpoint is recorded even though the patch reports failure. + expect(mockedCheckpointSave).toHaveBeenCalledOnce() // Restore the default readFile behavior for later tests. mockedFsPromises.default.readFile.mockResolvedValue("original file content\n") }) @@ -734,11 +738,12 @@ describe("ApplyPatchTool.execute - delete file success path", () => { // path is platform-dependent (Windows resolves cwd to a drive path); // assert on the written content instead. - expect(mockedFsPromises.default.writeFile).toHaveBeenCalledWith( - expect.any(String), - "modified content\n", - "utf8", - ) + // The staging file is created owner-only; the destination mode is re-applied + // separately before the atomic rename. + expect(mockedFsPromises.default.writeFile).toHaveBeenCalledWith(expect.any(String), "modified content\n", { + encoding: "utf8", + mode: 0o600, + }) expect(mockedCheckpointSave).toHaveBeenCalledOnce() }) diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 644c8e70ab..ad5372e88b 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -792,10 +792,11 @@ describe("DiffViewProvider", () => { // Verify the content was written through an atomic staging file + rename const fs = await import("fs/promises") - expect(fs.writeFile).toHaveBeenCalledWith(expect.stringContaining(".staging"), "new content", "utf-8") - const stagingPath = (fs.writeFile as unknown as { mock: { calls: [string, string, string][] } }).mock.calls.find( - (call) => call[1] === "new content", - )?.[0] + expect(fs.writeFile).toHaveBeenCalledWith(expect.stringContaining(".staging"), "new content", { + encoding: "utf-8", + mode: 0o600, + }) + const stagingPath = vi.mocked(fs.writeFile).mock.calls.find((call) => call[1] === "new content")?.[0] expect(stagingPath).toContain(".test.ts.") expect(fs.rename).toHaveBeenCalledWith(stagingPath, `${mockCwd}/test.ts`) @@ -824,9 +825,7 @@ describe("DiffViewProvider", () => { renameError, ) - const stagingPath = (fs.writeFile as unknown as { mock: { calls: [string, string, string][] } }).mock.calls.find( - (call) => call[1] === "new content", - )?.[0] + const stagingPath = vi.mocked(fs.writeFile).mock.calls.find((call) => call[1] === "new content")?.[0] expect(renameError).toBeInstanceOf(Error) expect(fs.rename).toHaveBeenCalledWith(stagingPath, `${mockCwd}/test.ts`) expect(fs.rm).toHaveBeenCalledWith(stagingPath, { force: true }) @@ -837,10 +836,11 @@ describe("DiffViewProvider", () => { // Verify the content was written through an atomic staging file + rename const fs = await import("fs/promises") - expect(fs.writeFile).toHaveBeenCalledWith(expect.stringContaining(".staging"), "new content", "utf-8") - const stagingPath = (fs.writeFile as unknown as { mock: { calls: [string, string, string][] } }).mock.calls.find( - (call) => call[1] === "new content", - )?.[0] + expect(fs.writeFile).toHaveBeenCalledWith(expect.stringContaining(".staging"), "new content", { + encoding: "utf-8", + mode: 0o600, + }) + const stagingPath = vi.mocked(fs.writeFile).mock.calls.find((call) => call[1] === "new content")?.[0] expect(stagingPath).toContain(".test.ts.") expect(fs.rename).toHaveBeenCalledWith(stagingPath, `${mockCwd}/test.ts`) @@ -857,10 +857,11 @@ describe("DiffViewProvider", () => { // Verify the content was written through an atomic staging file + rename const fs = await import("fs/promises") - expect(fs.writeFile).toHaveBeenCalledWith(expect.stringContaining(".staging"), "new content", "utf-8") - const stagingPath = (fs.writeFile as unknown as { mock: { calls: [string, string, string][] } }).mock.calls.find( - (call) => call[1] === "new content", - )?.[0] + expect(fs.writeFile).toHaveBeenCalledWith(expect.stringContaining(".staging"), "new content", { + encoding: "utf-8", + mode: 0o600, + }) + const stagingPath = vi.mocked(fs.writeFile).mock.calls.find((call) => call[1] === "new content")?.[0] expect(stagingPath).toContain(".test.ts.") expect(fs.rename).toHaveBeenCalledWith(stagingPath, `${mockCwd}/test.ts`) diff --git a/src/integrations/editor/atomicWrite.ts b/src/integrations/editor/atomicWrite.ts index 4fe796098b..d686d18f9d 100644 --- a/src/integrations/editor/atomicWrite.ts +++ b/src/integrations/editor/atomicWrite.ts @@ -32,7 +32,9 @@ export async function writeFileAtomically(absolutePath: string, content: string, const baseName = separatorIndex >= 0 ? targetPath.slice(separatorIndex + 1) : targetPath const stagingPath = `${directory}/.${baseName}.${process.pid}.${Date.now()}.staging` try { - await fs.writeFile(stagingPath, content, "utf-8") + // Owner-only from creation: staged content must never be readable by others, + // even between this write and the final rename. + await fs.writeFile(stagingPath, content, { encoding: "utf-8", mode: 0o600 }) if (targetMode !== undefined) { await fs.chmod(stagingPath, targetMode) } From 6e539cca23e1072bc5003281a3d850fd2cdaac71 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:18:51 +0800 Subject: [PATCH 25/52] style: apply prettier formatting to the staging and mutation-tracking files --- src/core/tools/__tests__/applyPatchTool.execute.spec.ts | 4 +++- src/integrations/editor/atomicWrite.ts | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 4aa8522cd8..2feccbb94e 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -198,7 +198,9 @@ describe("ApplyPatchTool.execute - delete file success path", () => { ) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("EROFS")) // The approved content survives the failed rollback as an explicit recovery artifact. - expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("The approved new content was kept at")) + expect(mockPushToolResult).toHaveBeenCalledWith( + expect.stringContaining("The approved new content was kept at"), + ) // ...and no whole-patch checkpoint is recorded for the failed move. // The destination was written (then rolled back): that is a workspace mutation, so // the partial-state checkpoint is recorded even though the patch reports failure. diff --git a/src/integrations/editor/atomicWrite.ts b/src/integrations/editor/atomicWrite.ts index d686d18f9d..6bef23ec4f 100644 --- a/src/integrations/editor/atomicWrite.ts +++ b/src/integrations/editor/atomicWrite.ts @@ -18,7 +18,7 @@ export async function writeFileAtomically(absolutePath: string, content: string, try { targetPath = await fs.realpath(absolutePath) const stat = await fs.stat(targetPath) - targetMode = targetMode ?? (stat.mode & 0o7777) + targetMode = targetMode ?? stat.mode & 0o7777 targetOwnership = { uid: stat.uid, gid: stat.gid } } catch (error) { if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") { From 38148a9c51493ec029c6a3f6b820dc888ee98193 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:30:07 +0800 Subject: [PATCH 26/52] fix(tools): track committed mutations outside the handler-return boundary Persistence Integrity (pre-merge check): a handler can commit a workspace write and then reject during later bookkeeping (for example diagnostics/pushToolWriteResult), so the outer catch saw no pending handoff and skipped both the partial-state checkpoint and the queued-message handoff. execute() now owns a committed-mutation tracker that handlers set at the write boundary (add, delete, update, and the move destination commit). The catch and finally blocks use it, so a mutation that never returned a result is still checkpointed and handed off. Regression test: an add-file patch whose write succeeds but whose pushToolWriteResult rejects must record the partial-state checkpoint, hand off queued messages, and report through handleError. apply_patch suite 31/31, affected suites 133 passed (+2 POSIX-only skipped); eslint/tsc clean. --- src/core/tools/ApplyPatchTool.ts | 27 ++++++++++++++++--- .../__tests__/applyPatchTool.execute.spec.ts | 25 +++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 89e9a338d0..14ad81bef7 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -65,6 +65,11 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // queued turn start while the checkpoint is still staging or committing. let handoffPending = false + // Committed-mutation tracker: a handler can commit a workspace write and then + // reject during later bookkeeping, so the outer catch must still persist the + // partial-state checkpoint. The flag is therefore owned here, outside the + // handler-return boundary. + const mutation = { committed: false } try { // Validate required parameters @@ -144,12 +149,20 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task, callbacks, isWriteProtected, + mutation, ) handoffPending = handoffPending || result.mutated patchSucceeded = result.ok && patchSucceeded } else if (change.type === "delete") { // Delete file - const result = await this.handleDeleteFile(absolutePath, relPath, task, callbacks, isWriteProtected) + const result = await this.handleDeleteFile( + absolutePath, + relPath, + task, + callbacks, + isWriteProtected, + mutation, + ) handoffPending = handoffPending || result.mutated patchSucceeded = result.ok && patchSucceeded } else if (change.type === "update") { @@ -161,6 +174,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task, callbacks, isWriteProtected, + mutation, ) handoffPending = handoffPending || result.mutated patchSucceeded = result.ok && patchSucceeded @@ -200,7 +214,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // checkpoint here (same default-on semantics as the branches // above) instead of letting the queued turn start with the // retained writes carried forward without rollback metadata. - if (handoffPending) { + if (handoffPending || mutation.committed) { const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints if (perWriteCheckpoints !== false) { await checkpointSave(task, false, true).catch(() => {}) @@ -214,7 +228,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // never start while the patch checkpoint is still staging or // committing, and no path (disabled checkpoints, failed save, early // return, error) strands the queued messages. - if (handoffPending) { + if (handoffPending || mutation.committed) { task.processQueuedMessages() } } @@ -227,6 +241,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task: Task, callbacks: ToolCallbacks, isWriteProtected: boolean, + mutation: { committed: boolean }, ): Promise { const { askApproval, pushToolResult } = callbacks let mutated = false @@ -306,6 +321,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // Track file edit operation await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource) mutated = true + mutation.committed = true task.didEditFile = true const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, true) @@ -320,6 +336,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task: Task, callbacks: ToolCallbacks, isWriteProtected: boolean, + mutation: { committed: boolean }, ): Promise { const { askApproval, pushToolResult } = callbacks let mutated = false @@ -368,6 +385,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } mutated = true + mutation.committed = true task.didEditFile = true pushToolResult(`Successfully deleted ${relPath}`) return { ok: true, mutated } @@ -380,6 +398,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task: Task, callbacks: ToolCallbacks, isWriteProtected: boolean, + mutation: { committed: boolean }, ): Promise { const { askApproval, pushToolResult } = callbacks let mutated = false @@ -558,6 +577,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // The destination content changed: even a later failed source unlink (which // rolls the destination back) is a workspace mutation the checkpoint must see. mutated = true + mutation.committed = true if (isPreventFocusDisruptionEnabled) { // Diagnostics/bookkeeping only: the bytes were committed above, and // saveDirectly writes the same content through the same atomic write. @@ -665,6 +685,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } mutated = true + mutation.committed = true await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource) } diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 2feccbb94e..d870076611 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -153,6 +153,31 @@ describe("ApplyPatchTool.execute - delete file success path", () => { *** End Patch` const mockedCheckpointSave = checkpointSave as MockedFunction + it("records the partial-state checkpoint when post-write bookkeeping rejects after the write", async () => { + const patch = `*** Begin Patch +*** Add File: src/new.ts ++file content +*** End Patch` + mockedFileExistsAtPath.mockResolvedValueOnce(false) + // The write commits, then a later bookkeeping call rejects before the handler can + // return: the committed mutation is tracked outside the handler-return boundary, so + // the partial-state checkpoint and the queued-message handoff must still happen. + vi.mocked(mockTask.diffViewProvider.pushToolWriteResult).mockRejectedValueOnce( + new Error("diagnostics unavailable"), + ) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockedCheckpointSave).toHaveBeenCalledOnce() + expect(mockTask.processQueuedMessages).toHaveBeenCalledOnce() + expect(mockHandleError).toHaveBeenCalled() + }) + it("restores the pre-move state and fails the operation when source deletion fails", async () => { const patch = `*** Begin Patch *** Update File: src/old.ts From 9a452314416e016ef6b4e25551b0b6487c38a8f4 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:59:07 +0800 Subject: [PATCH 27/52] chore: re-trigger CI after the e2e restart-phase timeout The e2e-mock lane failed in its restart phase: `[restart:verify] [createTaskWithHistoryItem] taskScheduler.schedule failed: TaskMessagesReadError: Failed to read task messages ... at /tmp/roo-vscode-e2e-restart-...` followed by 'Timeout after 30s'. This PR does not change task messages, task history, or the task scheduler (it changes apply_patch, the atomic writer, and checkpoint serialization); the same lane passed on the current main baseline and on sibling PRs. Re-run the lanes. From c5b2857a59eed7cad84395c4b8bedabe41651b30 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:11:49 +0800 Subject: [PATCH 28/52] test+fix(checkpoints): correct the delete-ordering mock, kill the handoff-count vacuity, make the move recovery write owner-only Three review rows on fc11d6d64f measured true and are addressed here: 1. applyPatchTool.execute.spec - unlink is one shared double and mockRejectedValueOnce orders by call, not by path, arming the rejection on the FIRST delete while the case comment claimed the second. Armed after a resolved call now, and the case asserts both paths were attempted and that exactly two unlinks happened - a first-delete failure stops the loop before the second path. 2. Same file - a handoff that never happened used to be the strongest pass: `invocationCallOrder[0] ?? Infinity` makes any checkpoint order beat an absent handoff. The call count is asserted before the order in both cases (a comparison against Infinity cannot fail when the call never happens). 3. ApplyPatchTool.ts recovery write now uses { encoding: "utf8", mode: 0o600, flag: "wx" } to match the staging write in the same function: a recovery copy holds private content, and truncating whatever already stands at that name would destroy a file instead of preserving it. 4. ClineProvider.spec gained a handler-side round trip for perWriteCheckpoints (updateSettings through the message handler, then globalState.update and getState). Every other per-write assertion in that file drives contextProxy directly, so a handler that dropped the key left them all green. Control (pinned node v22.23.4, .tmp-node22): with the parent impl blob 14ad81bef7c2 on disk - parent blob verified by git hash-object - a mode/flag assertion on the recovery write fails; with 0827272b196f it passes. The recovery branch itself still has no test: driving it needs the staging rename, a failing source unlink and a failing destination removal through doubles that are shared and not reset between cases, and two attempts to arm that combination through the execute harness did not reach the branch (logs 1404-recovery-*-node22.log). git grep shows zoo-recovery appears once in the tree - the write site - so no existing assertion covered it before and none was altered. The behavioural change therefore lands with the row left answered-and-open pending a test. Gates: applyPatchTool.execute.spec 31/31 and ClineProvider.spec 322/322 on pinned v22.23.4; vitest.core.config.ts and vitest.misc.config.ts green (core 4158 passed / 9 skipped, misc 2014 passed / 15 skipped) on the same pinned runtime; tsc --noEmit and knip clean on box node v25.9.0; eslint --prune-suppressions --max-warnings=0 clean on all three touched files with .eslintcache cleared after the last prettier write; src/eslint-suppressions.json byte-identical to the parent 32555c45dccb; the new handler test uses no cast because that file sits at its suppressed no-explicit-any budget of 195. No locale file touched: check-translations compares keys across locales and all 18 settings.json files already carry perWriteCheckpoints, so the wording clarification is a translator-visible change left answered-and-open rather than 17 machine-translated strings pushed on a maintainer's behalf. Co-Authored-By: Claude --- src/core/tools/ApplyPatchTool.ts | 9 ++++++++- .../__tests__/applyPatchTool.execute.spec.ts | 20 +++++++++++++++++-- .../webview/__tests__/ClineProvider.spec.ts | 17 ++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 14ad81bef7..0827272b19 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -642,7 +642,14 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // the only thing that could be lost: persist it under a recovery name. const recoveryCandidate = path.join(moveDir, `${moveBase}.zoo-recovery-${moveStamp}`) try { - await fs.writeFile(recoveryCandidate, newContent, "utf8") + // Same owner-only creation as the staging write above, and O_EXCL rather than + // truncation: a recovery copy holds private content, and silently overwriting + // whatever already stands at that name would destroy a file instead of preserving one. + await fs.writeFile(recoveryCandidate, newContent, { + encoding: "utf8", + mode: 0o600, + flag: "wx", + }) recoveryPath = recoveryCandidate console.error( `Failed to restore pre-move state: ${restoreFailure instanceof Error ? restoreFailure.message : String(restoreFailure)}; kept the approved content at ${recoveryCandidate}`, diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index d870076611..504e1cd064 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -323,8 +323,12 @@ describe("ApplyPatchTool.execute - delete file success path", () => { *** Delete File: src/obsolete.ts *** Delete File: src/locked.ts *** End Patch` - // The first delete succeeds; the second fails. - mockedFsPromises.default.unlink.mockRejectedValueOnce(new Error("EPERM: operation not permitted")) + // The first delete succeeds; the second fails. unlink is one shared double and + // mockRejectedValueOnce orders by call, not by path, so the rejection has to be + // armed after a resolved first call - otherwise this case exercises the wrong delete. + mockedFsPromises.default.unlink + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(new Error("EPERM: operation not permitted")) await tool.execute({ patch }, mockTask as Task, { askApproval: mockAskApproval, @@ -338,7 +342,17 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockedCheckpointSave).toHaveBeenCalledTimes(1) const checkpointAt = mockedCheckpointSave.mock.invocationCallOrder[0] ?? Infinity const handoffAt = vi.mocked(mockTask.processQueuedMessages).mock.invocationCallOrder[0] ?? Infinity + // A handoff that never happened used to be the strongest pass in the file: the + // ?? Infinity default makes any checkpoint order beat an absent handoff, so the + // count is asserted before the order is compared. + expect(vi.mocked(mockTask.processQueuedMessages).mock.calls.length).toBeGreaterThan(0) expect(checkpointAt).toBeLessThan(handoffAt) + // Which delete ran is what the mock ordering is for: both paths were attempted + // and exactly two unlinks happened - a first-delete failure would have stopped + // the loop before the second path was reached. + expect(mockedFsPromises.default.unlink).toHaveBeenCalledTimes(2) + expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(expect.stringMatching(/[\\/]obsolete\.ts$/)) + expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(expect.stringMatching(/[\\/]locked\.ts$/)) }) it("persists a partial-state checkpoint when a later handler rejects outright after an earlier write", async () => { const patch = `*** Begin Patch @@ -362,6 +376,8 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockedCheckpointSave).toHaveBeenCalledTimes(1) const checkpointAt = mockedCheckpointSave.mock.invocationCallOrder[0] ?? Infinity const handoffAt = vi.mocked(mockTask.processQueuedMessages).mock.invocationCallOrder[0] ?? Infinity + // Same vacuity as the case above: assert the handoff happened, then its order. + expect(vi.mocked(mockTask.processQueuedMessages).mock.calls.length).toBeGreaterThan(0) expect(checkpointAt).toBeLessThan(handoffAt) expect(mockHandleError).toHaveBeenCalled() }) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 64735edb06..7bdda3888c 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -4409,6 +4409,23 @@ describe("ClineProvider", () => { expect(state.perWriteCheckpoints).toBe(true) }) + test("persists per-write checkpoints sent through updateSettings to the message handler", async () => { + await provider.resolveWebviewView(mockWebviewView) + // No cast: this file is already at its suppressed no-explicit-any budget (195), and + // the double's call list is untyped, so the handler comes out of it directly. + const messageHandler = mockWebviewView.webview.onDidReceiveMessage.mock.calls[0][0] + + await messageHandler({ type: "updateSettings", updatedSettings: { perWriteCheckpoints: false } }) + + // Through the handler rather than straight into the proxy: every other per-write + // assertion in this file drives contextProxy directly, so a handler that dropped + // this key would have left all of them green. + expect(updateGlobalStateSpy).toHaveBeenCalledWith("perWriteCheckpoints", false) + expect(mockContext.globalState.update).toHaveBeenCalledWith("perWriteCheckpoints", false) + const state = await provider.getState() + expect(state.perWriteCheckpoints).toBe(false) + }) + test("getStateToPostToWebview returns the saved per-write checkpoints setting", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("perWriteCheckpoints", true) From 45cb68264288b01efd5aef9bbcd2ea7b95a65520 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:07:15 +0800 Subject: [PATCH 29/52] fix(per-write-checkpoints): lock restores, track retained writes, name the tools CodeRabbit round against 7f9ebb4813 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 7f9ebb4813 on its own. --- .../checkpoints/__tests__/checkpoint.test.ts | 31 +++++++ src/core/checkpoints/index.ts | 38 +++++---- src/core/tools/ApplyPatchTool.ts | 50 +++++++++-- .../__tests__/applyPatchTool.execute.spec.ts | 85 +++++++++++++++++++ .../__tests__/CheckpointSettings.spec.tsx | 76 +++++++++++++++++ webview-ui/src/i18n/locales/ca/settings.json | 2 +- webview-ui/src/i18n/locales/de/settings.json | 2 +- webview-ui/src/i18n/locales/en/settings.json | 2 +- webview-ui/src/i18n/locales/es/settings.json | 2 +- webview-ui/src/i18n/locales/fr/settings.json | 2 +- webview-ui/src/i18n/locales/hi/settings.json | 2 +- webview-ui/src/i18n/locales/id/settings.json | 2 +- webview-ui/src/i18n/locales/it/settings.json | 2 +- webview-ui/src/i18n/locales/ja/settings.json | 2 +- webview-ui/src/i18n/locales/ko/settings.json | 2 +- webview-ui/src/i18n/locales/nl/settings.json | 2 +- webview-ui/src/i18n/locales/pl/settings.json | 2 +- .../src/i18n/locales/pt-BR/settings.json | 2 +- webview-ui/src/i18n/locales/ru/settings.json | 2 +- webview-ui/src/i18n/locales/tr/settings.json | 2 +- webview-ui/src/i18n/locales/vi/settings.json | 2 +- .../src/i18n/locales/zh-CN/settings.json | 2 +- .../src/i18n/locales/zh-TW/settings.json | 2 +- 23 files changed, 273 insertions(+), 43 deletions(-) diff --git a/src/core/checkpoints/__tests__/checkpoint.test.ts b/src/core/checkpoints/__tests__/checkpoint.test.ts index bc2fc9247c..85ea018a1b 100644 --- a/src/core/checkpoints/__tests__/checkpoint.test.ts +++ b/src/core/checkpoints/__tests__/checkpoint.test.ts @@ -308,6 +308,37 @@ describe("Checkpoint functionality", () => { expect(mockCheckpointService.restoreCheckpoint).not.toHaveBeenCalled() }) + it("serializes a restore against a queued save so no save stages over a restore", async () => { + const order: string[] = [] + let resolveRestore: () => void = () => {} + mockCheckpointService.restoreCheckpoint.mockImplementationOnce( + () => + new Promise((resolve) => { + order.push("restore:start") + resolveRestore = resolve as () => void + }), + ) + mockCheckpointService.saveCheckpoint.mockImplementationOnce(async () => { + order.push("save:start") + return { commit: "queued-commit" } + }) + + const restore = checkpointRestore(mockTask, { ts: 2, commitHash: RESTORE_HASH, mode: "preview" }) + // Let the restore reach the shadow-git reset. + await new Promise((resolve) => setTimeout(resolve, 10)) + + const save = checkpointSave(mockTask, false, true) + // The save must not reach stageAll + commit while the restore is resetting the + // workspace: that commit would record the restored bytes and drop the write's own + // checkpoint. + await new Promise((resolve) => setTimeout(resolve, 10)) + expect(order).toEqual(["restore:start"]) + + resolveRestore() + await Promise.all([restore, save]) + expect(order).toEqual(["restore:start", "save:start"]) + }) + it.each(["delete", "edit"] as const)( "propagates restore failures for %s without rewinding", async (operation) => { diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index 090b1e6b6d..349202e02b 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -224,24 +224,26 @@ async function checkGitInstallation( } } -// Serialize checkpoint saves per task. saveCheckpoint() runs stageAll + commit, so two -// concurrent saves for the same task (for example the task-start baseline racing the first -// per-write save after the baseline timeout) can stage each other's writes or interleave -// commits. A per-task promise queue makes every save wait for the previous one, including -// a baseline that is still running. -const checkpointSaveQueues = new Map>() - -function enqueueCheckpointSave(taskId: string, operation: () => Promise): Promise { - const previous = checkpointSaveQueues.get(taskId) ?? Promise.resolve() +// Serialize checkpoint work per task. saveCheckpoint() runs stageAll + commit and +// restoreCheckpoint() resets the workspace through the same shadow git, so two concurrent +// operations for the same task (for example the task-start baseline racing the first +// per-write save after the baseline timeout, or a restore while a per-write save is still +// queued) can stage each other's writes or interleave commits. A per-task promise queue +// makes every save and every restore wait for the previous one, including a baseline that +// is still running. +const checkpointWorkQueues = new Map>() + +function enqueueCheckpointWork(taskId: string, operation: () => Promise): Promise { + const previous = checkpointWorkQueues.get(taskId) ?? Promise.resolve() const next = previous.then(operation, operation) const tail = next.then( () => undefined, () => undefined, ) - checkpointSaveQueues.set(taskId, tail) + checkpointWorkQueues.set(taskId, tail) void tail.finally(() => { - if (checkpointSaveQueues.get(taskId) === tail) { - checkpointSaveQueues.delete(taskId) + if (checkpointWorkQueues.get(taskId) === tail) { + checkpointWorkQueues.delete(taskId) } }) return next @@ -256,9 +258,9 @@ export async function checkpointSave(task: Task, force = false, suppressMessage TelemetryService.instance.captureCheckpointCreated(task.taskId) - // Start the checkpoint process in the background, queued behind any save already - // running for this task so stageAll + commit never overlap. - return enqueueCheckpointSave(task.taskId, () => + // Start the checkpoint process in the background, queued behind any checkpoint work + // already running for this task so stageAll + commit never overlap. + return enqueueCheckpointWork(task.taskId, () => service.saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, { allowEmpty: force, suppressMessage }), ).catch((err) => { console.error("[Task#checkpointSave] caught unexpected error, disabling checkpoints", err) @@ -294,7 +296,11 @@ export async function checkpointRestore( const provider = task.providerRef.deref() try { - await service.restoreCheckpoint(commitHash) + // The same per-task lock the saves use, in both directions: a restore resets the + // workspace through shadow git, so a queued save must not stage and commit while it + // is running (that save would record the restored bytes and drop the write's own + // checkpoint), and a restore requested during a save waits for that save to settle. + await enqueueCheckpointWork(task.taskId, () => service.restoreCheckpoint(commitHash)) TelemetryService.instance.captureCheckpointRestored(task.taskId) await provider?.postMessageToWebview({ type: "currentCheckpointUpdated", text: commitHash }) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 0827272b19..5d40d18f23 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -311,17 +311,32 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { return { ok: false, mutated } } - // Save the changes - if (isPreventFocusDisruptionEnabled) { - await task.diffViewProvider.saveDirectly(relPath, newContent, true, diagnosticsEnabled, writeDelayMs) - } else { - await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs) + // The write lands inside the save call below, which can still reject afterwards + // (opening the document, collecting diagnostics) once the new file is on disk. The + // mutation is therefore recorded at the write boundary: this handler never returns in + // that case, and without the flag the retained file would hand off the queued turn + // with no partial-state checkpoint (see the catch and finally in execute()). + mutated = true + mutation.committed = true + try { + if (isPreventFocusDisruptionEnabled) { + await task.diffViewProvider.saveDirectly(relPath, newContent, true, diagnosticsEnabled, writeDelayMs) + } else { + await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs) + } + } catch (error) { + // A save that failed before writing any bytes left no file behind, so the add did + // not mutate the workspace after all and must not be checkpointed as a retained + // write. Untrack it and let the outer error path report the failure. + if (!(await fileExistsAtPath(absolutePath))) { + mutated = false + mutation.committed = false + } + throw error } // Track file edit operation await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource) - mutated = true - mutation.committed = true task.didEditFile = true const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, true) @@ -594,12 +609,29 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (destinationCommitted) { await fs.rm(moveAbsolutePath, { force: true }).catch(() => {}) } + let destinationMissing = false if (destinationBackup !== undefined) { - await fs.rename(backupPath, moveAbsolutePath).catch(() => {}) + // Put the captured destination bytes back with one rename. If that rename + // fails as well, the destination is missing and its content survives only + // under the backup name, so the report has to say where it is. + await fs.rename(backupPath, moveAbsolutePath).catch(() => { + destinationMissing = true + }) + } + if (destinationMissing) { + // A missing destination is a workspace mutation: record it so the + // partial-state checkpoint runs before the queued-message handoff, exactly + // as the failed source deletion below does. + mutated = true + mutation.committed = true } task.consecutiveMistakeCount++ task.recordToolError("apply_patch") - const writeErrorMessage = `Failed to write move destination '${change.movePath}': ${writeError instanceof Error ? writeError.message : String(writeError)}` + const writeErrorMessage = + `Failed to write move destination '${change.movePath}': ${writeError instanceof Error ? writeError.message : String(writeError)}` + + (destinationMissing && backupPath !== undefined + ? ` The original content is preserved at '${getReadablePath(task.cwd, path.relative(task.cwd, backupPath))}'.` + : "") await task.say("error", writeErrorMessage) pushToolResult(formatResponse.toolError(writeErrorMessage)) await task.diffViewProvider.reset() diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 504e1cd064..5e3c7daec4 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -285,6 +285,56 @@ describe("ApplyPatchTool.execute - delete file success path", () => { mockedFsPromises.default.readFile.mockResolvedValue("original file content\n") }) + it("names the retained backup and records a checkpoint when the move write fails and the restore rename fails", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // The destination exists, so the write-catch path puts it back by renaming the + // on-disk backup over the destination. + mockedFsPromises.default.readFile.mockImplementation(async (p: unknown) => { + if (String(p).includes("new.ts")) { + return "existing destination content" + } + return "original file content\n" + }) + // The staging write succeeds, the staging -> destination rename fails, and the + // backup -> destination restore rename fails as well: the destination is now + // missing and its content survives only under the backup name. + mockedFsPromises.default.rename.mockImplementation(async (from: unknown, to: unknown) => { + const source = String(from) + const target = String(to) + if (target.includes("new.ts") && source.includes(".staging")) { + throw Object.assign(new Error("EACCES: permission denied, rename"), { code: "EACCES" }) + } + if (target.includes("new.ts") && source.includes(".backup")) { + throw Object.assign(new Error("EPERM: operation not permitted, restore"), { code: "EPERM" }) + } + return undefined + }) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Failed to write move destination")) + // A user who lost the destination has to be told where its bytes are. + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringMatching(/preserved at '[^']*\.backup[^']*'/)) + // A missing destination is a workspace mutation: the partial-state checkpoint and + // the queued-message handoff both have to run. + expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask, false, true) + expect(mockTask.processQueuedMessages).toHaveBeenCalledOnce() + // Restore the default mock behavior for later tests. + mockedFsPromises.default.readFile.mockResolvedValue("original file content\n") + mockedFsPromises.default.rename.mockResolvedValue(undefined) + }) + it("refuses the move before writing when the destination cannot be inspected", async () => { const patch = `*** Begin Patch *** Update File: src/old.ts @@ -381,6 +431,41 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(checkpointAt).toBeLessThan(handoffAt) expect(mockHandleError).toHaveBeenCalled() }) + it("records the partial-state checkpoint when the add save rejects after its bytes landed", async () => { + const patch = `*** Begin Patch +*** Add File: src/new.ts ++file content +*** End Patch` + // The add does not exist yet, and the focus-preserving save path is enabled, so the + // bytes are written by saveDirectly. + mockedFileExistsAtPath.mockResolvedValueOnce(false) + const provider = { + getState: vi.fn().mockResolvedValue({ experiments: { preventFocusDisruption: true } }), + } + mockTask.providerRef = { deref: () => provider } as unknown as Task["providerRef"] + // The file lands on disk inside the save, which then rejects while finishing the + // document, so the handler never returns and never reaches its own tracking lines. + vi.mocked(mockTask.diffViewProvider.saveDirectly).mockRejectedValueOnce( + new Error("EPERM: operation not permitted, open 'src/new.ts'"), + ) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockTask.diffViewProvider.saveDirectly).toHaveBeenCalledOnce() + // The failure is the save itself, not the bookkeeping after it. + expect(mockTask.diffViewProvider.pushToolWriteResult).not.toHaveBeenCalled() + expect(mockHandleError).toHaveBeenCalledWith("apply patch", expect.any(Error)) + // The retained file is a workspace mutation, so the partial-state checkpoint runs + // before the queued-message handoff even though the patch reports failure. + expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask, false, true) + expect(mockTask.processQueuedMessages).toHaveBeenCalledOnce() + }) + it("records one suppressed checkpoint for the whole patch (default-on)", async () => { await tool.execute({ patch: deletePatch }, mockTask as Task, { askApproval: mockAskApproval, diff --git a/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx b/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx index b08c15ace7..59a2e11f15 100644 --- a/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx @@ -2,6 +2,60 @@ import { render, screen, fireEvent } from "@/utils/test-utils" import { CheckpointSettings } from "../CheckpointSettings" +import enSettings from "@/i18n/locales/en/settings.json" +import caSettings from "@/i18n/locales/ca/settings.json" +import deSettings from "@/i18n/locales/de/settings.json" +import esSettings from "@/i18n/locales/es/settings.json" +import frSettings from "@/i18n/locales/fr/settings.json" +import hiSettings from "@/i18n/locales/hi/settings.json" +import idSettings from "@/i18n/locales/id/settings.json" +import itSettings from "@/i18n/locales/it/settings.json" +import jaSettings from "@/i18n/locales/ja/settings.json" +import koSettings from "@/i18n/locales/ko/settings.json" +import nlSettings from "@/i18n/locales/nl/settings.json" +import plSettings from "@/i18n/locales/pl/settings.json" +import ptBRSettings from "@/i18n/locales/pt-BR/settings.json" +import ruSettings from "@/i18n/locales/ru/settings.json" +import trSettings from "@/i18n/locales/tr/settings.json" +import viSettings from "@/i18n/locales/vi/settings.json" +import zhCNSettings from "@/i18n/locales/zh-CN/settings.json" +import zhTWSettings from "@/i18n/locales/zh-TW/settings.json" +// The per-write checkpoint setting ships a description in every locale file, and the render +// above mocks the translation hook, so the shipped copy is asserted against the locale +// resources themselves. Access goes through a guard rather than a cast so a missing key +// fails loudly instead of comparing undefined. +// The three tools whose successful writes record a checkpoint. +const WRITE_TOOLS = ["write_to_file", "edit_file", "apply_patch"] + +const localeSettings: Record = { + en: enSettings, + ca: caSettings, + de: deSettings, + es: esSettings, + fr: frSettings, + hi: hiSettings, + id: idSettings, + it: itSettings, + ja: jaSettings, + ko: koSettings, + nl: nlSettings, + pl: plSettings, + "pt-BR": ptBRSettings, + ru: ruSettings, + tr: trSettings, + vi: viSettings, + "zh-CN": zhCNSettings, + "zh-TW": zhTWSettings, +} + +function perWriteDescription(settings: unknown): string { + const resources = settings as { checkpoints?: { perWrite?: { description?: unknown } } } + const description = resources.checkpoints?.perWrite?.description + if (typeof description !== "string") { + throw new Error("settings.checkpoints.perWrite.description is missing") + } + return description +} // Mock the translation hook vi.mock("@/i18n/TranslationContext", () => ({ @@ -122,4 +176,26 @@ describe("CheckpointSettings", () => { expect(setCachedStateField).toHaveBeenCalledWith("perWriteCheckpoints", false) }) + + it.each(Object.entries(localeSettings).map(([locale, settings]) => ({ locale, settings })))( + "names the three writing tools in the $locale per-write checkpoint description", + ({ locale, settings }) => { + const description = perWriteDescription(settings) + // The tool identifiers are language-neutral, so every locale can be held to the same + // names: the setting records a checkpoint for these tools only, and the copy has to + // say so instead of promising a snapshot after every write operation. + expect(WRITE_TOOLS.filter((toolName) => !description.includes(toolName))).toEqual([]) + if (locale !== "en") { + // The description is genuinely localized: a locale left on the English copy is a + // missing translation, not a parity match. + expect(description).not.toBe(perWriteDescription(localeSettings.en)) + } + }, + ) + + it("states that saving from the editor records no checkpoint", () => { + // The checkpoint call sites are the agent's three writing tools; an editor save does + // not go through them, so the copy must not imply that it does. + expect(perWriteDescription(localeSettings.en)).toContain("Saving a file from the editor does not record one") + }) }) diff --git a/webview-ui/src/i18n/locales/ca/settings.json b/webview-ui/src/i18n/locales/ca/settings.json index 96318cfd5b..35070b0084 100644 --- a/webview-ui/src/i18n/locales/ca/settings.json +++ b/webview-ui/src/i18n/locales/ca/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Punt de control després de cada escriptura de fitxer", - "description": "Registra una instantània de punt de control després de cada operació d’escriptura reeixida; un pegat de diversos fitxers genera un únic punt de control." + "description": "Registra un punt de verificació després de cada escriptura correcta de les eines write_to_file, edit_file o apply_patch de l'agent; un pegat de diversos fitxers produeix un únic punt de verificació. Desarxivar un fitxer des de l'editor no en registra cap." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/de/settings.json b/webview-ui/src/i18n/locales/de/settings.json index 0d533629d5..e3ea555523 100644 --- a/webview-ui/src/i18n/locales/de/settings.json +++ b/webview-ui/src/i18n/locales/de/settings.json @@ -698,7 +698,7 @@ }, "perWrite": { "label": "Kontrollpunkt nach jedem Dateischreibvorgang", - "description": "Erstellt nach jedem erfolgreichen Schreibvorgang einen Checkpoint-Schnappschuss; ein Patch mit mehreren Dateien erzeugt genau einen Checkpoint." + "description": "Erstellt nach jedem erfolgreichen Schreiben der Agent-Tools write_to_file, edit_file oder apply_patch einen Kontrollpunkt; ein Patch mit mehreren Dateien erzeugt einen einzigen Kontrollpunkt. Eine Datei im Editor zu speichern erzeugt keinen." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/en/settings.json b/webview-ui/src/i18n/locales/en/settings.json index 6bec92ee4b..09d660fb40 100644 --- a/webview-ui/src/i18n/locales/en/settings.json +++ b/webview-ui/src/i18n/locales/en/settings.json @@ -771,7 +771,7 @@ }, "perWrite": { "label": "Checkpoint after each file write", - "description": "Record a checkpoint snapshot after each successful write operation; a multi-file patch produces a single checkpoint." + "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." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/es/settings.json b/webview-ui/src/i18n/locales/es/settings.json index 2420ab151f..63ed80e516 100644 --- a/webview-ui/src/i18n/locales/es/settings.json +++ b/webview-ui/src/i18n/locales/es/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Punto de control después de cada escritura de archivo", - "description": "Registra una instantánea de punto de control después de cada operación de escritura exitosa; un parche de varios archivos produce un único punto de control." + "description": "Registra un punto de control tras cada escritura correcta de las herramientas write_to_file, edit_file o apply_patch del agente; un parche de varios archivos produce un único punto de control. Guardar un archivo desde el editor no registra ninguno." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/fr/settings.json b/webview-ui/src/i18n/locales/fr/settings.json index 97caae64c6..8ed64967f6 100644 --- a/webview-ui/src/i18n/locales/fr/settings.json +++ b/webview-ui/src/i18n/locales/fr/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Point de contrôle après chaque écriture de fichier", - "description": "Enregistre un instantané de point de contrôle après chaque opération d’écriture réussie ; un correctif multi-fichiers produit un seul point de contrôle." + "description": "Enregistre un point de contrôle après chaque écriture réussie des outils write_to_file, edit_file ou apply_patch de l'agent ; un correctif touche plusieurs fichiers et ne produit qu'un seul point de contrôle. Enregistrer un fichier depuis l'éditeur n'en enregistre pas." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/hi/settings.json b/webview-ui/src/i18n/locales/hi/settings.json index c7b6bc0c7e..32aa575022 100644 --- a/webview-ui/src/i18n/locales/hi/settings.json +++ b/webview-ui/src/i18n/locales/hi/settings.json @@ -698,7 +698,7 @@ }, "perWrite": { "label": "हर फ़ाइल लिखने के बाद चेकपॉइंट", - "description": "प्रत्येक सफल लेखन कार्रवाई के बाद एक चेकपॉइंट स्नैपशॉट रिकॉर्ड करें; एक मल्टी-फ़ाइल पैच केवल एक चेकपॉइंट बनाता है।" + "description": "एजेंट के write_to_file, edit_file या apply_patch उपकरणों की हर सफल लिखत के बाद चेकपॉइंट दर्ज करें; कई फ़ाइलों वाला पैच केवल एक ही चेकपॉइंट बनाता है। संपादक से फ़ाइल सहेजने पर चेकपॉइंट दर्ज नहीं होता।" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/id/settings.json b/webview-ui/src/i18n/locales/id/settings.json index 6ef9ba08f6..c9b728654b 100644 --- a/webview-ui/src/i18n/locales/id/settings.json +++ b/webview-ui/src/i18n/locales/id/settings.json @@ -697,7 +697,7 @@ }, "perWrite": { "label": "Checkpoint setelah setiap penulisan file", - "description": "Rekam snapshot titik pemeriksaan setelah setiap operasi tulis berhasil; patch multi-file menghasilkan satu titik pemeriksaan." + "description": "Rekam checkpoint setelah setiap penulisan berhasil oleh perkakas write_to_file, edit_file, atau apply_patch agen; patch multi-berkas menghasilkan satu checkpoint. Menyimpan berkas dari editor tidak merekam checkpoint." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/it/settings.json b/webview-ui/src/i18n/locales/it/settings.json index 4615df7fe2..b7f7029e89 100644 --- a/webview-ui/src/i18n/locales/it/settings.json +++ b/webview-ui/src/i18n/locales/it/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Punto di controllo dopo ogni scrittura del file", - "description": "Registra un’istantanea del punto di controllo dopo ogni operazione di scrittura riuscita; una patch con più file produce un unico punto di controllo." + "description": "Registra un checkpoint dopo ogni scrittura riuscita degli strumenti write_to_file, edit_file o apply_patch dell'agente; una patch con più file produce un solo checkpoint. Salvare un file dall'editor non ne registra uno." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/ja/settings.json b/webview-ui/src/i18n/locales/ja/settings.json index a1980f0112..97e7817f99 100644 --- a/webview-ui/src/i18n/locales/ja/settings.json +++ b/webview-ui/src/i18n/locales/ja/settings.json @@ -697,7 +697,7 @@ }, "perWrite": { "label": "ファイルの書き込みごとにチェックポイント", - "description": "各書き込み操作の成功後にチェックポイントスナップショットを記録します。複数ファイルのパッチは単一のチェックポイントを作成します。" + "description": "エージェントの write_to_file、edit_file、apply_patch ツールによる各書き込み成功後にチェックポイントを記録します。複数ファイルのパッチは 1 件のチェックポイントになります。エディタからファイルを保存してもチェックポイントは記録されません。" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/ko/settings.json b/webview-ui/src/i18n/locales/ko/settings.json index d401b3535d..b04170fdd2 100644 --- a/webview-ui/src/i18n/locales/ko/settings.json +++ b/webview-ui/src/i18n/locales/ko/settings.json @@ -697,7 +697,7 @@ }, "perWrite": { "label": "파일을 쓸 때마다 체크포인트", - "description": "각 쓰기 작업이 성공할 때마다 체크포인트 스냅샷을 기록합니다. 다중 파일 패치는 단일 체크포인트를 생성합니다." + "description": "에이전트의 write_to_file, edit_file, apply_patch 도구가 파일을 성공적으로 쓸 때마다 체크포인트를 기록합니다. 여러 파일의 패치는 체크포인트 한 개만 만듭니다. 에디터에서 파일을 저장해도 체크포인트가 기록되지 않습니다." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/nl/settings.json b/webview-ui/src/i18n/locales/nl/settings.json index edba2bd076..b6026c1738 100644 --- a/webview-ui/src/i18n/locales/nl/settings.json +++ b/webview-ui/src/i18n/locales/nl/settings.json @@ -698,7 +698,7 @@ }, "perWrite": { "label": "Checkpoint na elke bestandsschrijving", - "description": "Leg na elke succesvolle schrijfbewerking een checkpointmomentopname vast; een patch met meerdere bestanden produceert één checkpoint." + "description": "Leg na elke succesvolle schrijfactie van de write_to_file-, edit_file- of apply_patch-tool van de agent een checkpoint vast; een patch met meerdere bestanden levert één checkpoint op. Een bestand opslaan vanuit de editor doet dat niet." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/pl/settings.json b/webview-ui/src/i18n/locales/pl/settings.json index f99a00af66..1937cc55d5 100644 --- a/webview-ui/src/i18n/locales/pl/settings.json +++ b/webview-ui/src/i18n/locales/pl/settings.json @@ -700,7 +700,7 @@ }, "perWrite": { "label": "Punkt kontrolny po każdym zapisaniu pliku", - "description": "Zapisuje migawkę punktu kontrolnego po każdej udanej operacji zapisu; patch obejmujący wiele plików tworzy jeden punkt kontrolny." + "description": "Zapisz punkt kontrolny po każdym pomyślnym zapisie pliku narzędziami agenta write_to_file, edit_file lub apply_patch; łata obejmująca wiele plików tworzy jeden punkt kontrolny. Zapisanie pliku w edytorze nie tworzy punktu kontrolnego." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/pt-BR/settings.json b/webview-ui/src/i18n/locales/pt-BR/settings.json index d8f345ad2a..af77db7813 100644 --- a/webview-ui/src/i18n/locales/pt-BR/settings.json +++ b/webview-ui/src/i18n/locales/pt-BR/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Ponto de verificação após cada gravação de arquivo", - "description": "Registra um snapshot de ponto de verificação após cada operação de gravação bem-sucedida; um patch com vários arquivos produz um único ponto de verificação." + "description": "Registra um checkpoint após cada gravação bem-sucedida das ferramentas write_to_file, edit_file ou apply_patch do agente; um patch com vários arquivos produz um único checkpoint. Salvar um arquivo pelo editor não registra nenhum." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/ru/settings.json b/webview-ui/src/i18n/locales/ru/settings.json index 69b0b5aa33..e48c8cc767 100644 --- a/webview-ui/src/i18n/locales/ru/settings.json +++ b/webview-ui/src/i18n/locales/ru/settings.json @@ -700,7 +700,7 @@ }, "perWrite": { "label": "Контрольная точка после каждой записи файла", - "description": "Записывает снимок контрольной точки после каждой успешной операции записи; патч с несколькими файлами создаёт одну контрольную точку." + "description": "Записывает контрольную точку после каждого успешной записи инструментами агента write_to_file, edit_file или apply_patch; патч для нескольких файлов создаёт одну контрольную точку. Сохранение файла в редакторе её не создаёт." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/tr/settings.json b/webview-ui/src/i18n/locales/tr/settings.json index 0fc8b57fe2..93dac744c3 100644 --- a/webview-ui/src/i18n/locales/tr/settings.json +++ b/webview-ui/src/i18n/locales/tr/settings.json @@ -698,7 +698,7 @@ }, "perWrite": { "label": "Her dosya yazımından sonra kontrol noktası", - "description": "Her başarılı yazma işleminden sonra bir kontrol noktası anlık görüntüsü kaydeder; çok dosyalı bir yama tek bir kontrol noktası üretir." + "description": "Aracın write_to_file, edit_file veya apply_patch araçlarıyla yapılan her başarılı dosya yazmasından sonra bir kontrol noktası kaydedin; çok dosyalı bir yama tek bir kontrol noktası üretir. Bir dosyayı düzenleyiciden kaydetmek kontrol noktası kaydetmez." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/vi/settings.json b/webview-ui/src/i18n/locales/vi/settings.json index c3f57e4e52..d990e7fb3b 100644 --- a/webview-ui/src/i18n/locales/vi/settings.json +++ b/webview-ui/src/i18n/locales/vi/settings.json @@ -697,7 +697,7 @@ }, "perWrite": { "label": "Điểm kiểm tra sau mỗi lần ghi file", - "description": "Ghi ảnh chụp điểm kiểm tra sau mỗi thao tác ghi thành công; một vá nhiều tệp chỉ tạo một điểm kiểm tra." + "description": "Ghi điểm kiểm tra sau mỗi lần các công cụ write_to_file, edit_file hoặc apply_patch của tác nhân ghi tệp thành công; một patch nhiều tệp chỉ tạo một điểm kiểm tra duy nhất. Lưu tệp từ trình soạn thảo không ghi điểm kiểm tra." } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/zh-CN/settings.json b/webview-ui/src/i18n/locales/zh-CN/settings.json index 6cfcdcf7a7..4d31eefe9c 100644 --- a/webview-ui/src/i18n/locales/zh-CN/settings.json +++ b/webview-ui/src/i18n/locales/zh-CN/settings.json @@ -697,7 +697,7 @@ }, "perWrite": { "label": "每次文件写入后创建存档点", - "description": "在每次成功写入操作后记录检查点快照;多文件补丁只会生成一个检查点。" + "description": "在代理的 write_to_file、edit_file 或 apply_patch 工具每次成功写入后记录一个检查点;涉及多个文件的补丁只产生一个检查点。在编辑器中保存文件不会记录检查点。" } }, "notifications": { diff --git a/webview-ui/src/i18n/locales/zh-TW/settings.json b/webview-ui/src/i18n/locales/zh-TW/settings.json index b6849f3ef8..271bb3ea8a 100644 --- a/webview-ui/src/i18n/locales/zh-TW/settings.json +++ b/webview-ui/src/i18n/locales/zh-TW/settings.json @@ -724,7 +724,7 @@ }, "perWrite": { "label": "每次檔案寫入後建立檢查點", - "description": "在每次成功的寫入操作後記錄檢查點快照;多檔案修補程式只會產生一個檢查點。" + "description": "在代理的 write_to_file、edit_file 或 apply_patch 工具每次成功寫入後記錄一個檢查點;涉及多個檔案的補丁只產生一個檢查點。在編輯器中儲存檔案不會記錄檢查點。" } }, "notifications": { From 48f50d9e0e01f94e06c2199638864ea892975c81 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:41:37 +0800 Subject: [PATCH 30/52] test(task): raise the abort latch through requestAbort in the three checkpoint rows CI's compile and core-unit arms build the PR merge tree, not the branch head: the job checks out refs/remotes/pull/1404/merge, and 1404's base is Zoo-Code-Org/Zoo-Code main, which absorbed 5319fe91f (#2283) - the commit that turns Task.abort into a get-only accessor fed by the run-state latches (at main tip e487cd7b2a: Task.ts:3582 'get abort(): boolean', Task.ts:3586 'get abortReason()', no setter anywhere). My head still carries the plain field at Task.ts:392, so the same rows typecheck clean in my worktree and fail in that tree: core/task/__tests__/Task.spec.ts(7279,9): error TS2540: Cannot assign to 'abort' because it is a read-only property. core/task/__tests__/Task.spec.ts(7305,9): error TS2540: Cannot assign to 'abort' because it is a read-only property. core/task/__tests__/Task.spec.ts(8387,8): error TS2540: Cannot assign to 'abort' because it is a read-only property. core/task/__tests__/Task.spec.ts(8391,9): error TS2540: Cannot assign to 'abort' because it is a read-only property. Reproduced with git merge-tree --write-tree 8415547c9 e487cd7b2a (clean, tree c77e36656a), commit-tree d4e3ed011, and a worktree of that commit whose node_modules junctions map @roo-code/* to that tree's own packages: tsc --noEmit there printed exactly those four lines and nothing else. The three rows are this unit's own (the two baseline rows and the queued-message row), so the adaptation is on my side, in the shape 1405 took at 94dc7c40c: ask the class to raise its own latch instead of writing the field. task.requestAbort(false) is public on both spellings - it writes the field and drives the run-state event here (Task.ts:3539), and it drives the kernel that main's getter reads (Task.ts:3594 there). It is also the smallest exposed entry point that fits: abortTask() disposes the task, and the queued-message row would then read an empty queue instead of the message the cancellation is supposed to leave for the resume flow. The assertions are unchanged. Measured: tsc --noEmit in the merge tree 0 errors (was 4); tsc at this head 0; the core lane in the merge tree 198 files, 4309 passed | 9 skipped (4318); Task.spec.ts under vitest.core.config.ts 222 passed in the merge tree and 212 at this head; affected src set 141 passed | 7 skipped; affected webview set 563 passed; eslint --max-warnings=0 clean on the changed files with suppressions unchanged; prettier --check clean. --- src/core/task/__tests__/Task.spec.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 72fbbfd938..8b897c0901 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7358,7 +7358,7 @@ describe("Cline", () => { const state = await mockProvider.getState() vi.spyOn(mockProvider, "getState").mockResolvedValue(state) - task.abort = true + task.requestAbort(false) await taskAccess.initiateTaskLoop([]) @@ -7384,7 +7384,10 @@ describe("Cline", () => { const loopPromise = taskAccess.initiateTaskLoop([]) // Cancellation lands while the state lookup is still pending. - task.abort = true + // requestAbort is the class's public, synchronous way to raise the abort + // latch; main (5319fe91f, #2283) exposes abort as a get-only accessor fed by + // the run-state latches, so assigning task.abort does not typecheck there. + task.requestAbort(false) resolveState({ ...state, perWriteCheckpoints: true }) await loopPromise @@ -8469,12 +8472,10 @@ describe("Queued message processing after condense", () => { const submitSpy = vi.spyOn(task, "submitUserMessage").mockResolvedValue(undefined) task.messageQueueService.addMessage("queued text") - task.abort = true - try { - task.processQueuedMessages() - } finally { - task.abort = false - } + // requestAbort raises the latch without tearing the task down: abortTask() + // would dispose it and drain the queue, which is not the state this row reads. + task.requestAbort(false) + task.processQueuedMessages() expect(submitSpy).not.toHaveBeenCalled() expect(task.messageQueueService.isEmpty()).toBe(false) From cbe254b9b19eff726c7dd1ddff76420e142e904a Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:59:15 +0800 Subject: [PATCH 31/52] Fix the two checkpoint-queue findings the review raised, and stop a self-move deleting its own file The unit is at 295 of the gate's 500 counted executable lines, so these are implemented here rather than deferred: this reconciliation adds 30 counted lines (src/core/checkpoints/index.ts +27, src/core/tools/ApplyPatchTool.ts +3), measured with scripts/stryker-diff.mjs's own functions against 48be786941 before the commit, for 325 of 500 afterwards. The five new test rows are free budget because the counter excludes __tests__ paths. Checkpoint queue (threads 7pkQ on Task.ts and 7p-r on checkpoints/index.ts). The per-task queue serialized checkpoint work but never expired it: after a baseline whose git add/commit outlives checkpointTimeout, the caller was released by the Promise.race in initiateTaskLoop while the queued saves still started, however late, committing whatever the workspace had become by then, and a save queued by a task that had already been canceled still performed checkpoint work. The queue now gates the start of each save: one past its checkpoint window, or requested by a canceled task, is dropped instead of started late and resolves to the caller exactly as a missing service does - with no commit - which is how the task-start baseline already treats a save that produced no commit, by retrying it on a later loop entry. Restores keep no expiry: dropping a queued restore would silently discard an explicit user action. Four rows in src/core/checkpoints/__tests__/checkpoint.test.ts cover the expired drop, the canceled drop, a fresh save running normally after the stall settles (the drop does not poison the queue) and a restore that is never dropped; one row in Task.spec.ts covers the case the reviewer asked about - a save that commits after the task already gave up on it does not retire the baseline. Self-move (thread 7p-w on ApplyPatchTool.ts). A patch whose Move to resolves onto its own Update File path is a rewrite of that path, not a relocation: the staged content is renamed onto it and the trailing source unlink then deletes the file that was just committed. The unlink is skipped when the two resolved paths match. A row in applyPatchTool.execute.spec.ts asserts the rename happened and no unlink happened. Nothing else from the review's open rows is implemented here: preserving a symlink destination instead of replacing it (7pkY), the recovery artifact for a host exit between the two renames (7p-u), and the resolved- target workspace and protection checks belong to the single guarded writer in unit 2 of the split proposed on PR 1408 (refs/tmp/s3-1408-u2-guardedwrite), where the compare-and-swap write, its rollback and its lock live. Implementing symlink semantics twice, once in this move path and once in that writer, would give the workspace two rollback stories. --- .../checkpoints/__tests__/checkpoint.test.ts | 145 ++++++++++++++++++ src/core/checkpoints/index.ts | 58 ++++++- src/core/task/__tests__/Task.spec.ts | 40 +++++ src/core/tools/ApplyPatchTool.ts | 15 +- .../__tests__/applyPatchTool.execute.spec.ts | 29 ++++ 5 files changed, 280 insertions(+), 7 deletions(-) diff --git a/src/core/checkpoints/__tests__/checkpoint.test.ts b/src/core/checkpoints/__tests__/checkpoint.test.ts index 85ea018a1b..570eb8e71e 100644 --- a/src/core/checkpoints/__tests__/checkpoint.test.ts +++ b/src/core/checkpoints/__tests__/checkpoint.test.ts @@ -140,6 +140,151 @@ describe("Checkpoint functionality", () => { expect(order).toEqual(["first:start", "second:start"]) }) + it("drops a queued save whose checkpoint window expired behind a stalled predecessor", async () => { + // A stalled baseline releases the task after checkpointTimeout, but the queue used to + // start it anyway, however late, committing whatever the workspace had become by then. + // It must not: the save is dropped and the caller resolves with no commit. + mockTask.checkpointTimeout = 0.01 + const order: string[] = [] + let resolveFirst: (value: { commit: string }) => void = () => {} + mockCheckpointService.saveCheckpoint + .mockImplementationOnce(() => { + order.push("stalled:start") + return new Promise((resolve) => { + resolveFirst = resolve + }) + }) + .mockImplementation(async () => { + order.push("late:start") + return { commit: "late-commit" } + }) + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + + const stalled = checkpointSave(mockTask, true, true) + const queued = await (async () => { + await new Promise((resolve) => setTimeout(resolve, 5)) + const second = checkpointSave(mockTask, false, true) + // Give the expired request its turn behind the still-running baseline, then release + // the baseline so the queue drains. + await new Promise((resolve) => setTimeout(resolve, 30)) + resolveFirst({ commit: "stalled-commit" }) + return second + })() + + const second = await queued + await stalled + // Only the stalled baseline ever reached the shadow git; the expired save never started, + // so no commit describes a workspace that has since moved on. + expect(order).toEqual(["stalled:start"]) + expect(mockCheckpointService.saveCheckpoint).toHaveBeenCalledTimes(1) + expect(second).toBeUndefined() + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("skipping queued per-write checkpoint save")) + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("expired behind a slower checkpoint")) + warnSpy.mockRestore() + }) + + it("drops a queued save for a task that was canceled while it waited", async () => { + mockTask.checkpointTimeout = 15 + const order: string[] = [] + let resolveFirst: (value: { commit: string }) => void = () => {} + mockCheckpointService.saveCheckpoint + .mockImplementationOnce(() => { + order.push("stalled:start") + return new Promise((resolve) => { + resolveFirst = resolve + }) + }) + .mockImplementation(async () => { + order.push("canceled:start") + return { commit: "canceled-commit" } + }) + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + mockTask.abort = false + + const stalled = checkpointSave(mockTask, true, true) + const queued = checkpointSave(mockTask, false, true) + await new Promise((resolve) => setTimeout(resolve, 5)) + // Cancellation arrives while the save is queued, before its turn. + mockTask.abort = true + resolveFirst({ commit: "stalled-commit" }) + + const second = await queued + await stalled + + expect(order).toEqual(["stalled:start"]) + expect(mockCheckpointService.saveCheckpoint).toHaveBeenCalledTimes(1) + expect(second).toBeUndefined() + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("task canceled")) + warnSpy.mockRestore() + mockTask.abort = false + }) + + it("runs a save requested after a stalled predecessor settles, exactly once each", async () => { + // The gate must not poison the queue: the dropped request stays dropped, while a fresh + // request after the stall settles gets its normal turn. + mockTask.checkpointTimeout = 0.01 + const order: string[] = [] + let resolveFirst: (value: { commit: string }) => void = () => {} + mockCheckpointService.saveCheckpoint + .mockImplementationOnce(() => { + order.push("stalled:start") + return new Promise((resolve) => { + resolveFirst = resolve + }) + }) + .mockImplementation(async () => { + order.push("fresh:start") + return { commit: "fresh-commit" } + }) + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + + const stalled = checkpointSave(mockTask, true, true) + // Requested while its window is still open, so the drop below is about the wait behind + // the stalled baseline rather than about an already-expired request. + const expired = checkpointSave(mockTask, false, true) + await new Promise((resolve) => setTimeout(resolve, 30)) + resolveFirst({ commit: "stalled-commit" }) + const expiredResult = await expired + const settled = await stalled + const fresh = await checkpointSave(mockTask, false, true) + + expect(order).toEqual(["stalled:start", "fresh:start"]) + expect(mockCheckpointService.saveCheckpoint).toHaveBeenCalledTimes(2) + // The dropped request resolves exactly the way a missing service does: no commit value, + // while the predecessor that held the queue keeps its own result. + expect(expiredResult).toBeUndefined() + expect(settled).toEqual({ commit: "stalled-commit" }) + expect(fresh).toEqual({ commit: "fresh-commit" }) + warnSpy.mockRestore() + }) + + it("never drops a user-initiated restore queued behind a stalled save", async () => { + // Restores carry no expiry: dropping one would silently discard an explicit user action. + mockTask.checkpointTimeout = 0.01 + mockTask.clineMessages = [{ ts: 2, type: "say", say: "checkpoint_saved", text: RESTORE_HASH }] + const order: string[] = [] + let resolveSave: (value: { commit: string }) => void = () => {} + mockCheckpointService.saveCheckpoint.mockImplementationOnce(() => { + order.push("save:start") + return new Promise((resolve) => { + resolveSave = resolve + }) + }) + mockCheckpointService.restoreCheckpoint.mockImplementationOnce(() => { + order.push("restore:start") + return Promise.resolve(undefined) + }) + + const stalled = checkpointSave(mockTask, true, true) + const restore = checkpointRestore(mockTask, { ts: 2, commitHash: RESTORE_HASH, mode: "preview" }) + await new Promise((resolve) => setTimeout(resolve, 30)) + resolveSave({ commit: "stalled-commit" }) + await Promise.all([stalled, restore]) + + expect(order).toEqual(["save:start", "restore:start"]) + expect(mockCheckpointService.restoreCheckpoint).toHaveBeenCalledWith(RESTORE_HASH) + }) + it("should wait for checkpoint service initialization before saving", async () => { // Set up task with uninitialized service mockCheckpointService.isInitialized = false diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index 349202e02b..2818b0dc4b 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -2,6 +2,7 @@ import pWaitFor from "p-wait-for" import * as vscode from "vscode" import type { ClineApiReqInfo } from "@roo-code/types" +import { DEFAULT_CHECKPOINT_TIMEOUT_SECONDS } from "@roo-code/types" import { TelemetryService } from "@roo-code/telemetry" import { Task } from "../task/Task" @@ -233,9 +234,43 @@ async function checkGitInstallation( // is still running. const checkpointWorkQueues = new Map>() -function enqueueCheckpointWork(taskId: string, operation: () => Promise): Promise { +type QueuedCheckpointWorkOptions = { + /** Human-readable name used in the skip warning, e.g. "queued per-write checkpoint save". */ + label: string + /** Wall-clock deadline after which the operation must not start: a save requested behind a + * stalled predecessor stages whatever the workspace looks like when it finally gets its turn, + * which is not the state the caller asked to record. Omit for work that must run whenever its + * turn arrives, such as a user-initiated restore. */ + expiresAt?: number + /** Checked when the operation's turn arrives, not when it is requested: a task that was canceled + * while its work was queued performs no checkpoint work. */ + isCanceled?: () => boolean +} + +const DEFAULT_QUEUED_WORK_OPTIONS: QueuedCheckpointWorkOptions = { label: "checkpoint work" } + +function enqueueCheckpointWork( + taskId: string, + operation: () => Promise, + options: QueuedCheckpointWorkOptions = DEFAULT_QUEUED_WORK_OPTIONS, +): Promise { const previous = checkpointWorkQueues.get(taskId) ?? Promise.resolve() - const next = previous.then(operation, operation) + // Both arms of the previous settlement get the same gate, so a failed predecessor does not + // smuggle an expired or canceled operation past it. + // attempt may return the operation's promise or nothing at all; Promise.then flattens the + // former and resolves the latter, which is exactly the two outcomes callers need. + const attempt = (): T | Promise | undefined => { + const expired = options.expiresAt !== undefined && Date.now() > options.expiresAt + if (expired || options.isCanceled?.()) { + const reason = expired ? "expired behind a slower checkpoint" : "task canceled" + console.warn( + `[checkpoints] skipping ${options.label} for task ${taskId}: ${reason}; it never reached the shadow git`, + ) + return undefined + } + return operation() + } + const next = previous.then(attempt, attempt) const tail = next.then( () => undefined, () => undefined, @@ -259,9 +294,22 @@ export async function checkpointSave(task: Task, force = false, suppressMessage TelemetryService.instance.captureCheckpointCreated(task.taskId) // Start the checkpoint process in the background, queued behind any checkpoint work - // already running for this task so stageAll + commit never overlap. - return enqueueCheckpointWork(task.taskId, () => - service.saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, { allowEmpty: force, suppressMessage }), + // already running for this task so stageAll + commit never overlap. The queue is not only a + // lock: a save that is still queued past the caller's own checkpoint window is describing a + // workspace that has moved on, so it is dropped rather than started late, and a save queued by a + // task that has since been canceled performs no checkpoint work at all. A dropped save is + // reported to the caller the same way a missing service is (a resolve with no commit), which is + // how the task-start baseline already treats it - by retrying on a later loop entry. + const timeoutSeconds = task.checkpointTimeout > 0 ? task.checkpointTimeout : DEFAULT_CHECKPOINT_TIMEOUT_SECONDS + return enqueueCheckpointWork( + task.taskId, + () => + service.saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, { allowEmpty: force, suppressMessage }), + { + label: force ? "queued task-start checkpoint baseline" : "queued per-write checkpoint save", + expiresAt: Date.now() + Math.max(1, timeoutSeconds * 1000), + isCanceled: () => task.abort, + }, ).catch((err) => { console.error("[Task#checkpointSave] caught unexpected error, disabling checkpoints", err) task.enableCheckpoints = false diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 8b897c0901..a1dffea378 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7450,6 +7450,46 @@ describe("Cline", () => { warnSpy.mockRestore() }) + it("retries the baseline on a later loop entry when the stalled save commits after the timeout", async () => { + // The reviewer's question, tested at the layer that owns it: what becomes of the + // baseline once a save the task already gave up on finally settles. A late commit + // must not retire the baseline, because writes have been performed in the meantime, + // so a later loop entry re-takes it. + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "late baseline commit task", + startTask: false, + }) + const taskAccess = getTaskTestAccess(task) + type SaveResult = Awaited> + let resolveStalled: (value: SaveResult) => void = () => {} + const saveSpy = vi + .spyOn(task, "checkpointSave") + .mockImplementationOnce(() => new Promise((resolve) => (resolveStalled = resolve))) + .mockResolvedValueOnce({ commit: "retry-baseline-commit" } satisfies Awaited< + ReturnType + >) + const state = await mockProvider.getState() + vi.spyOn(mockProvider, "getState").mockResolvedValue(state) + const requestSpy = vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true) + task.checkpointTimeout = 0.01 + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + + await taskAccess.initiateTaskLoop([]) + expect(saveSpy).toHaveBeenCalledOnce() + expect(requestSpy).toHaveBeenCalled() + + // The abandoned save commits long after the task moved on. + resolveStalled({ commit: "late-baseline-commit" } as SaveResult) + await new Promise((resolve) => setTimeout(resolve, 0)) + + await taskAccess.initiateTaskLoop([]) + // The late commit did not mark the baseline done: this loop entry asked for it again. + expect(saveSpy).toHaveBeenCalledTimes(2) + warnSpy.mockRestore() + }) + it("continues task startup when the baseline checkpoint fails", async () => { const task = new Task({ provider: mockProvider, diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 5d40d18f23..0b0ea7dbf6 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -530,6 +530,13 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { return { ok: false, mutated } } + // A patch whose "Move to" resolves back onto its own source path is a rewrite of + // that path, not a relocation: once the staged content is renamed onto the destination + // there is no second file left, and unlinking the source would delete the content that + // was just committed. Computed from resolved paths because case-insensitive and + // normalized spellings can name the same file differently. + const isMoveOntoSource = path.resolve(moveAbsolutePath) === path.resolve(absolutePath) + // Capture the destination state before either supported write path: a // failed move must restore an existing destination instead of deleting // whatever lived there. A read error other than ENOENT means the @@ -638,9 +645,13 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { return { ok: false, mutated } } - // Delete the original file + // Delete the original file, unless the move renamed its own path: there is no + // second copy to remove in that case, and this is the step that would erase the + // freshly written content. try { - await fs.unlink(absolutePath) + if (!isMoveOntoSource) { + await fs.unlink(absolutePath) + } } catch (error) { // The source is still present (locked or protected): undo the destination // so the file does not live in two places, and report the move as diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 5e3c7daec4..5de3f13efa 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -178,6 +178,35 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockHandleError).toHaveBeenCalled() }) + it("keeps the written content when a move targets the file's own path", async () => { + // A patch whose Move to resolves back onto its Update File path rewrites that path; + // it does not create a second copy. Unlinking the source afterwards - the same inode + // the destination now holds - would delete the content the patch just committed. + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/old.ts +@@ +-original file content ++new content +*** End Patch` + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The staged content was renamed onto the path, and nothing was unlinked. + expect(mockedFsPromises.default.rename).toHaveBeenCalledWith( + expect.stringContaining(".staging"), + expect.stringMatching(/[\\/]old\.ts$/), + ) + expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() + expect(mockHandleError).not.toHaveBeenCalled() + expect(mockTask.diffViewProvider.pushToolWriteResult).toHaveBeenCalledOnce() + }) + it("restores the pre-move state and fails the operation when source deletion fails", async () => { const patch = `*** Begin Patch *** Update File: src/old.ts From 6b80340b5b5512c651654c5d75dff55cb3cc1793 Mon Sep 17 00:00:00 2001 From: u5a-2359 Date: Wed, 11 Nov 2026 03:14:47 +0800 Subject: [PATCH 32/52] test(webview): carry perWriteCheckpoints in the postMessageToWebview state fixture pnpm check-types fails on src in this tree: core/webview/__tests__/ClineProvider.spec.ts(3159,9): error TS2322: Type '{ version: string; clineMessages: never[]; ... }' is not assignable to type 'ExtensionState'. Property 'perWriteCheckpoints' is missing ... but required in type '{ lockApiConfigAcrossModes?: boolean | undefined; version: string; ... }' That is the command .husky/pre-push line 19 runs, and the command the compile context runs (code-qa.yml line 112, run: pnpm check-types). Attribution with the parents named: the required declaration is branch-side - e406c0951f0b packages/types/src/vscode-extension-host.ts line 373 declares perWriteCheckpoints: boolean, while that blob at base e487cd7b2a49 and at main tip 18861b2e3572 declares it nowhere, and main added zero lines to that path between those tips. The fixture at line 3159 is byte-identical in the base blob, the branch blob and this merge, so the branch carried the defect into the merge rather than main introducing it. CI reads compile success at e406c0951f0b; both readings are recorded here instead of one being chosen. Fix: the fixture is a fully specified ExtensionState literal, so it carries the field the branch made required; true matches the branch's own documented default when unset. No production line changed and no assertion changed. Measured in this worktree (wt-r234-1404, node v22.23.4): eslint over the edited file exits 0 with --max-warnings=0 --no-warn-ignored; src/eslint-suppressions.json is left untouched because the run deliberately omits --prune-suppressions so this unit does not rewrite that file; pnpm run check-types reports 12 successful over 12 tasks. --- src/core/webview/__tests__/ClineProvider.spec.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 7bdda3888c..a17d2090cc 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -3187,7 +3187,9 @@ describe("ClineProvider", () => { soundEnabled: false, ttsEnabled: false, enableCheckpoints: false, - perWriteCheckpoints: false, + // The branch makes perWriteCheckpoints required in ExtensionState, and this + // fixture is a fully specified state, so it has to carry the field. + perWriteCheckpoints: true, writeDelayMs: 1000, mcpEnabled: true, mode: defaultModeSlug, From a552160215894a398f787308270f2b774c8f984c Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:50:17 +0800 Subject: [PATCH 33/52] test(vscode-e2e): regenerate the chat-dark visual baseline for the action row this lineage renders The extension-host visual lane fails on electron-chat-dark-sidebar.png with 5061 differing pixels (ratio 0.03) and reproduced identically in all three attempts of run 42763454719 (check run 129654326411, completed/failure 2026-11-10T05:39:08Z to 05:51:15Z). The published -diff.png holds exactly three pure-red bands - rows 241-258 (2423 px), rows 268-279 (238 px), rows 295-309 (2400 px), totalling 5061 - and the published -expected.png is byte-equal to the committed blob dfc6fee680c83b46, so the recorded picture did not move. Both images carry the same mask fills, 3216 pixels (the token counters at rows 85-100 plus a 2400 px timestamp box), so nothing is being masked over: the 2400 px band is the same timestamp box sitting 54 rows lower (rows 241-255 in the baseline, rows 295-309 in the received image) because a row of See New Changes and Restore Changes buttons sits between the message text and its timestamp. Causation, measured rather than inferred. The row does not render on main today. Another lane of this campaign measured the upstream extension-host-visual leg green at check run 130448771750, completed/success 09:50:49Z to 10:03:41Z on head 371acb9e6311b390eb076f6c1917521180cc76ab, a test-only head on main tip 53cb5b5e7c80, and that head carries this same stale blob dfc6fee680c83b46 at this same path, so the stale baseline matches what main renders. What changes the render is this lineage: 1404 own patch sets DEFAULT_PER_WRITE_CHECKPOINTS = true in packages/types/src/global-settings.ts (+13 -0, read from the pull file patch), and the affordance lives in webview-ui/src/components/chat/SeeNewChangesButtons.tsx, whose component pre-exists upstream - added by 0084cc89916f406a676e029ca3c58b3566d876f2, "Add completion change actions (#633)", 2026-06-25, blob 09cac1163e7a, byte-identical at the tip and at 2399 head. So the component is not the trigger and main is not the home: the regeneration belongs in the pull that changes what the UI renders, because a row-bearing baseline placed on main would be diffed against a render main does not produce. The bytes committed are the CI -actual.png from that artifact (32757 bytes, sha256-64 b8b22a6a126821404f6a422ed4e1ddadbf476bde1a946cd8f5b1801f8d1f2a05), not a locally rendered screenshot: this lane cannot run the Electron visual lane on Windows. Both images are 300x743, bit depth 8, colour type 2, so it is the same crop. The other three committed baselines under apps/vscode-e2e/src/visual/__screenshots__ are untouched, which matches the artifact: only this scenario produced a -diff.png, in all three attempts. The mutation instrument prices nothing for this change and that is its own statement about a binary fixture, not a claim that the fix is cheap: SOURCE_EXTENSIONS at scripts/stryker-diff.mjs:84 lists js, jsx, mjs, cjs, ts and tsx, and packageForPath at :203-215 returns undefined for a path outside that set, so this file maps to no package and contributes no changed executable lines and no mutants. Git says the same in its own words: 1 file changed, 0 insertions(+), 0 deletions(-), Bin 28998 -> 32757 bytes. Merge order, stated because this PNG is a fixture that stacked pulls share: 1404 head 58c889db2307, main tip 53cb5b5e7c80, 1406 head e3dd44cb0b65 and 2399 head 720b2bfee561 all still carry the stale blob dfc6fee680c83b46 at this path, so whichever of them lands after this commit has to take this blobs blob at this path. A conflict created by moving a shared fixture is a merge-order fact, not a defect. No changeset file and no CHANGELOG edit, because the repository instructions put both under maintainer control; the commit touches exactly one path. Unproved and stated as such: whether the row is intended in the state the scenario mocks, which is a product question for a maintainer; which upstream change made the appearance conditional on the per-write default; and whether regenerating turns the lane green, which only a CI re-queue can say. --- .../electron-chat-dark-sidebar.png | Bin 28998 -> 32757 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/apps/vscode-e2e/src/visual/__screenshots__/electron-chat-dark-sidebar.png b/apps/vscode-e2e/src/visual/__screenshots__/electron-chat-dark-sidebar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S_C2T>1@8M^err zepd}H8DiWF-+~ZAjF9>9F_L6U>EYo)D*+}2;L_96_L5B-*WeAonL>6(Q$axi&BD0` z4b%w+20h<>*QCBnB~+>>CM8`TdA0qF&%TeaJS|+bq>8`#_Z3$)W}-u zn!(pj7Tb->O9TEE3J(Yk5#&h!T=%1lQMyW!cM8Y&nPKL;=jPLaeExx(UA`C2{{(9S zg>yjN0wYH(YPzl97dqGyE*l^Yz&dQSs+-C#DOv2loKZ8&+lP1^*(MTHM0^69>=t}o zcJpTcvZ871LUSJa9VjERQxD2SEXLNOC`FCv_~~sT^|anv-BD^E6dI00?Cg(szau8YoX8e ziB+G#Mm4#q{!ou1Xgo$QF5-fU_F|I^b=h>|WE=^}?kkP=kd%_BG4+q??C6M0Pp@?v zt$*@FAeUZ@e!nufAJ_|0u_9=y&?k@nxJ6H(WE}oNyd>2uk|(n^+WVwpV+YqJNre9u zy`(*U0T67XIeb3aCUK}yTKM|-Ryqg~vtRB@#>hN4>r#8V53m`O@ufb0R{P9766&B0 zVKxF&OoptV@7uIojU;>w$ymX5&4$Pho9D}JX~&OGse75+G)w4|wu^@6yc zt(PYPc>;KZrTw-ae!Sc9LObuZ5s|pvjO*FX08!}D_7KGzL;!`C;S(4^vAB&n0)Qv1 zG)?1XKdEnoUp9jB@5q&jCYl@PSzDWulvE%|1KoJJA3QkH;)xBTOi~{2%iqcEx3;P2 zzxtK>(#eau8(~$|5y!JuFXu1cz9cuFxzaf5Bz>7;C}5yfT10u{2MWga_I6j&)=SG1 z!JG3Z%kmKW_@hEG}ZCh1YEfyLvgx z`1r&2nMyBhX9YBm*A|`q!m?dFOsi84UTR;-+k_L@5w;*-KKU% LOQ}e~^7j7#N_ Date: Wed, 11 Nov 2026 21:54:25 +0800 Subject: [PATCH 34/52] test(checkpoints): assert shadow git contents for checkpointSave The task-start baseline cases in Task.spec stub Task#checkpointSave (the spies at 7181, 7451 and 7476) and assert call counts and flags; the checkpointSave cases in checkpoint.test.ts stub the checkpoint service itself. Neither layer can show that the commit a save returns holds the workspace file's bytes: a save that staged the wrong worktree, recorded nothing, or committed bytes that had since moved on would satisfy every count and flag assertion above. Add checkpointSaveShadowGit.spec.ts: three cases that run the real RepoPerTaskCheckpointService over a real workspace git repo in a temporary directory and read the contents back out of the shadow git's own commits - the bytes the task-start baseline records, two successive saves each keeping their own bytes, and a new file the workspace repo never tracked. checkpoint.test.ts:143-181 is untouched. --- .../__tests__/checkpointSaveShadowGit.spec.ts | 227 ++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 src/core/checkpoints/__tests__/checkpointSaveShadowGit.spec.ts diff --git a/src/core/checkpoints/__tests__/checkpointSaveShadowGit.spec.ts b/src/core/checkpoints/__tests__/checkpointSaveShadowGit.spec.ts new file mode 100644 index 0000000000..75ac880a19 --- /dev/null +++ b/src/core/checkpoints/__tests__/checkpointSaveShadowGit.spec.ts @@ -0,0 +1,227 @@ +// Contents assertions for checkpointSave against a real shadow git. +// +// The task-start baseline cases in src/core/task/__tests__/Task.spec.ts stub Task#checkpointSave +// (the spy at line 7181 resolves a commit, the one at 7451 resolves one empty save and then a +// commit, the one at 7476 resolves a commit) and assert how often the stub was called and with +// which flags. The checkpointSave cases in ./checkpoint.test.ts go one step further and stub the +// checkpoint service itself. Neither layer can show that the commit a save returns holds the +// workspace file's bytes: a save that staged the wrong worktree, recorded nothing, or committed +// bytes that had moved on would satisfy every call count and flag assertion above. This file runs +// the real RepoPerTaskCheckpointService over a real workspace git repo in a temporary directory +// and asserts the contents stored in the shadow git's own commits. + +import fs from "fs/promises" +import os from "os" +import path from "path" + +import { simpleGit } from "simple-git" + +import { RepoPerTaskCheckpointService } from "../../../services/checkpoints" +import { BLOCKED_ENV_KEYS } from "../../../services/checkpoints/ShadowCheckpointService" + +import { checkpointSave, getCheckpointService } from "../index" +import type { Task } from "../../task/Task" + +// checkpointSave reports every recorded checkpoint through TelemetryService.instance; stubbing +// the client keeps the real telemetry upload wiring out of a contents test. +vi.mock("@roo-code/telemetry", () => ({ + TelemetryService: { + instance: { + captureCheckpointCreated: vi.fn(), + captureCheckpointRestored: vi.fn(), + captureCheckpointDiffed: vi.fn(), + }, + }, +})) + +const tmpDir = path.join(os.tmpdir(), "checkpointSaveShadowGit") +const CHECKPOINTED_FILE = "checkpointed.txt" + +// simple-git ≥3.36 blocks env vars it treats as code-execution vectors. Strip them for this +// suite so a developer's global GIT_EDITOR or GIT_SSH_COMMAND does not fail the real git calls +// below. Safe under vitest's default "forks" pool, where each worker owns its process.env. +const savedEnv: Partial> = {} + +beforeAll(() => { + for (const key of BLOCKED_ENV_KEYS) { + savedEnv[key] = process.env[key] + delete process.env[key] + } +}) + +afterAll(async () => { + for (const key of BLOCKED_ENV_KEYS) { + if (savedEnv[key] !== undefined) { + process.env[key] = savedEnv[key] + } else { + delete process.env[key] + } + } + + await fs.rm(tmpDir, { recursive: true, force: true }) +}, 60_000) + +/** + * The read/write surface that checkpointSave and getCheckpointService actually touch: + * the task identity and workspace, the checkpoint flags and timeout, the abort flag, the + * provider used for logging and webview messages, and the say() the shadow service's + * "checkpoint" event calls. A real Task would pull the whole extension host into a contents + * test without adding any proof, so the double is cast once here rather than per case. + */ +type CheckpointSaveSurface = { + taskId: string + cwd: string + enableCheckpoints: boolean + checkpointService: RepoPerTaskCheckpointService | undefined + checkpointServiceInitializing: boolean + checkpointTimeout: number + abort: boolean + clineMessages: never[] + apiConversationHistory: never[] + say: (...args: unknown[]) => Promise + providerRef: { + deref: () => { + context: { globalStorageUri: { fsPath: string } } + log: (message: string) => void + postMessageToWebview: (message: unknown) => void + } + } +} + +/** + * checkpointSave resolves with a commit sha, resolves with nothing when the save found no changes + * or the per-task queue dropped it, and returns void when no checkpoint service exists. Only the + * first shape can hold recorded contents, so the other two are failures here. + */ +function committed(result: unknown, label: string): string { + if (typeof result === "object" && result !== null && "commit" in result && typeof result.commit === "string") { + return result.commit + } + + throw new Error(`${label} resolved with no commit, so nothing was recorded in the shadow git`) +} + +async function setupCheckpointTask(taskId: string) { + const workspaceDir = path.join(tmpDir, `workspace-${taskId}`) + const shadowDir = path.join(tmpDir, `storage-${taskId}`) + await fs.mkdir(workspaceDir, { recursive: true }) + await fs.mkdir(shadowDir, { recursive: true }) + + // A committed workspace state: the shadow git records its base commit from the workspace as it + // stands at initialization, so the write under test has to land after that initialization for + // its contents to be the delta the save is asked to record. + const workspaceGit = simpleGit(workspaceDir) + await workspaceGit.init() + await workspaceGit.addConfig("user.name", "Roo Code") + await workspaceGit.addConfig("user.email", "support@roocode.com") + await workspaceGit.addConfig("commit.gpgSign", "false") + await fs.writeFile(path.join(workspaceDir, CHECKPOINTED_FILE), "contents before the baseline") + await workspaceGit.add(".") + await workspaceGit.commit("record the workspace baseline") + + const surface: CheckpointSaveSurface = { + taskId, + cwd: workspaceDir, + enableCheckpoints: true, + checkpointService: undefined, + checkpointServiceInitializing: false, + checkpointTimeout: 30, + abort: false, + clineMessages: [], + apiConversationHistory: [], + say: vi.fn(async () => {}), + providerRef: { + deref: () => ({ + context: { globalStorageUri: { fsPath: shadowDir } }, + log: () => {}, + postMessageToWebview: vi.fn(), + }), + }, + } + + const task = surface as unknown as Task + const service = await getCheckpointService(task) + + if (!service) { + throw new Error("no checkpoint service after initialization, so no shadow git exists to read") + } + + const baseHash = service.baseHash + + if (!baseHash) { + throw new Error("the shadow git reported no base commit after initialization") + } + + return { task, service, workspaceGit, baseHash } +} + +describe("checkpointSave contents in a real shadow git", () => { + it("records the written bytes in the commit the task-start baseline save returns", async () => { + const { task, service, workspaceGit, baseHash } = await setupCheckpointTask("contents-at-baseline") + + // The write reaches the working tree only. The workspace repo never commits it, so the shadow + // git is the single place the bytes can be recorded. + await fs.writeFile(path.join(service.workspaceDir, CHECKPOINTED_FILE), "contents the baseline must record") + + // The same flags Task's baseline block uses: force (allow-empty) and suppressMessage. + const commit = committed(await checkpointSave(task, true, true), "the task-start baseline save") + + const diffs = await service.getDiff({ from: baseHash, to: commit }) + expect(diffs).toHaveLength(1) + expect(diffs[0].paths.relative).toBe(CHECKPOINTED_FILE) + expect(diffs[0].content.before).toBe("contents before the baseline") + expect(diffs[0].content.after).toBe("contents the baseline must record") + + // The workspace repo's own commit still holds the pre-write bytes, so the record above came + // out of the shadow git and not out of the user-visible repository. + expect(await workspaceGit.raw(["show", `HEAD:${CHECKPOINTED_FILE}`])).toBe("contents before the baseline") + }, 30_000) + + it("keeps each save's own bytes: the second commit holds the second write and the first still holds the first", async () => { + const { task, service, baseHash } = await setupCheckpointTask("contents-across-two-saves") + const checkpointedFile = path.join(service.workspaceDir, CHECKPOINTED_FILE) + + await fs.writeFile(checkpointedFile, "first write") + const commitOne = committed(await checkpointSave(task, false, true), "the first per-write save") + + await fs.writeFile(checkpointedFile, "second write") + const commitTwo = committed(await checkpointSave(task, false, true), "the second per-write save") + + const baseToOne = await service.getDiff({ from: baseHash, to: commitOne }) + expect(baseToOne).toHaveLength(1) + expect(baseToOne[0].content.before).toBe("contents before the baseline") + expect(baseToOne[0].content.after).toBe("first write") + + const oneToTwo = await service.getDiff({ from: commitOne, to: commitTwo }) + expect(oneToTwo).toHaveLength(1) + expect(oneToTwo[0].content.before).toBe("first write") + expect(oneToTwo[0].content.after).toBe("second write") + + // Read the first commit again after the second save: the earlier record still holds its own + // bytes. A call count says two saves happened; only the contents show that each one recorded + // the state its caller asked for. + const baseToOneAfterSecond = await service.getDiff({ from: baseHash, to: commitOne }) + expect(baseToOneAfterSecond[0].content.after).toBe("first write") + + const baseToTwo = await service.getDiff({ from: baseHash, to: commitTwo }) + expect(baseToTwo[0].content.after).toBe("second write") + }, 30_000) + + it("records a file the workspace repo never tracked with the bytes it held when the save ran", async () => { + const { task, service, workspaceGit, baseHash } = await setupCheckpointTask("contents-of-untracked-file") + const newFile = path.join(service.workspaceDir, "written-by-the-tool.txt") + await fs.writeFile(newFile, "the bytes a write handed to the workspace") + + const commit = committed(await checkpointSave(task, false, true), "the save after the new-file write") + + const diffs = await service.getDiff({ from: baseHash, to: commit }) + expect(diffs).toHaveLength(1) + expect(diffs[0].paths.relative).toBe("written-by-the-tool.txt") + expect(diffs[0].content.before).toBe("") + expect(diffs[0].content.after).toBe("the bytes a write handed to the workspace") + + // Still untracked in the user's repository: the shadow git captured it, the workspace repo did + // not, which is the difference the contents assertion is for. + expect(await workspaceGit.raw(["status", "--porcelain"])).toContain("?? written-by-the-tool.txt") + }, 30_000) +}) From b2db0b0fd61753510ab55d586ccfabb8180fdcca Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:24:47 +0800 Subject: [PATCH 35/52] fix(checkpoints): hand an expired caller back to the initialization still in flight A second lookup waits on the initialization it joined, bounded by its own checkpointTimeout. When that window closed the shared TimeoutError was handled as an initialization failure: the webview was told the initialization had timed out, checkpoints were disabled for the whole task, and the initializing flag was released while the lookup that started the initialization was still awaiting initShadowGit. The released flag let a later lookup create a second RepoPerTaskCheckpointService over the same task directory while the first was still committing, and the disabled flag meant the baseline save that gave up could never be retried on a later loop entry, even if the initialization it waited on succeeded a moment later. Track the in-flight initialization in a per-task map that is cleared only when the operation settles, so a wait that retains the lock until the operation settles or cancellation is confirmed has something to retain: a caller whose own window expires now reports no service with a WAIT_TIMEOUT warning and changes nothing else, and a later lookup joins the same operation instead of racing it into a second shadow git. With no handle left to join the wait still reports an initialization timeout and releases the task, exactly as before. Churn note: git diff --numstat for src/core/checkpoints/index.ts on this commit is 77 added and 34 removed, while git diff -w --numstat on the same commit is 44 added and 1 removed, so about a third of the growth the size instrument charges - extension 321 to 368 against a 500 cap - is the re-indentation the try block and the async closure force, not new logic. The wait could be extracted into a helper to dodge that re-indentation; not done here because 368 against 500 leaves the pull under the size cap and re-cutting to shave indentation churn buys nothing today. --- .../__tests__/getCheckpointService.spec.ts | 79 +++++++++++++ src/core/checkpoints/index.ts | 111 ++++++++++++------ 2 files changed, 156 insertions(+), 34 deletions(-) diff --git a/src/core/checkpoints/__tests__/getCheckpointService.spec.ts b/src/core/checkpoints/__tests__/getCheckpointService.spec.ts index 99a8b5b788..e377b60e78 100644 --- a/src/core/checkpoints/__tests__/getCheckpointService.spec.ts +++ b/src/core/checkpoints/__tests__/getCheckpointService.spec.ts @@ -124,3 +124,82 @@ describe("getCheckpointService initialization failures", () => { expect(task.enableCheckpoints).toBe(true) }) }) + +describe("getCheckpointService initialization handoff", () => { + beforeEach(() => { + vi.mocked(checkGitInstalled).mockReset() + vi.mocked(RepoPerTaskCheckpointService.create).mockReset() + }) + + it("hands a caller whose own window expired back to the initialization still running", async () => { + vi.mocked(checkGitInstalled).mockResolvedValue(true) + let releaseInit = () => {} + const initGate = new Promise((resolve) => { + releaseInit = resolve + }) + const svc = serviceDouble(async () => { + await initGate + svc.completeInit() + }) + vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(svc as unknown as RepoPerTaskCheckpointService) + + const task = makeTask() + const provider = task.providerRef.deref() + // A caller window far shorter than the initialization it joined: the wait is bounded per + // caller, so this one has to give up while the operation it waited on keeps running. + task.checkpointTimeout = 0.05 + + const started = getCheckpointService(task) + const joined = await getCheckpointService(task, { interval: 10 }) + + expect(joined).toBeUndefined() + // An expired window is this caller running out of patience, not the initialization failing: + // it reports no service, but it neither ends the initialization it did not start nor takes + // the task's checkpoints away - the save that gave up is retried on a later loop entry. + expect(task.enableCheckpoints).toBe(true) + expect(task.checkpointServiceInitializing).toBe(true) + expect(provider?.postMessageToWebview).toHaveBeenCalledWith({ + type: "checkpointInitWarning", + checkpointWarning: { type: "WAIT_TIMEOUT", timeout: 0.05 }, + }) + expect(provider?.postMessageToWebview).not.toHaveBeenCalledWith({ + type: "checkpointInitWarning", + checkpointWarning: { type: "INIT_TIMEOUT", timeout: 0.05 }, + }) + + releaseInit() + + const [starter, late] = await Promise.all([started, getCheckpointService(task, { interval: 10 })]) + + expect(starter).toBe(svc) + // The late lookup joins the operation that was still in flight rather than starting another + // one, so the task ends up with a single shadow git directory and a single service. + expect(late).toBe(svc) + expect(RepoPerTaskCheckpointService.create).toHaveBeenCalledTimes(1) + expect(task.checkpointService).toBe(svc) + }) + + it("still releases the task when a flag is left with no initialization behind it", async () => { + vi.mocked(checkGitInstalled).mockResolvedValue(true) + const svc = serviceDouble(async () => {}) + vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(svc as unknown as RepoPerTaskCheckpointService) + + const task = makeTask() + const provider = task.providerRef.deref() + task.checkpointTimeout = 0.05 + // A released flag with no service behind it and nothing in the in-flight map: there is no + // operation left to join, so the wait can only end in a timeout, and that one is reported + // as the initialization having failed - the behavior this file pins above. + task.checkpointServiceInitializing = true + + const service = await getCheckpointService(task, { interval: 10 }) + + expect(service).toBeUndefined() + expect(task.enableCheckpoints).toBe(false) + expect(RepoPerTaskCheckpointService.create).not.toHaveBeenCalled() + expect(provider?.postMessageToWebview).toHaveBeenCalledWith({ + type: "checkpointInitWarning", + checkpointWarning: { type: "INIT_TIMEOUT", timeout: 0.05 }, + }) + }) +}) diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index 2818b0dc4b..f18bd57766 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -28,6 +28,15 @@ function sendCheckpointInitWarn(task: Task, type?: "WAIT_TIMEOUT" | "INIT_TIMEOU }) } +/** In-flight shadow-git initializations per task. Creating the service and running + * initShadowGit is the one checkpoint operation the per-task work queue below does not cover, + * so it carries its own handle: a caller whose own bounded wait expires must not release an + * initialization it did not start, because a released lookup creates a second + * RepoPerTaskCheckpointService over the same task directory while the first is still + * committing. The entry leaves the map only when the operation settles, so a late caller + * either joins it or finds it gone, never both. */ +const checkpointInits = new Map>() + export async function getCheckpointService(task: Task, { interval = 250 }: { interval?: number } = {}) { if (!task.enableCheckpoints) { return undefined @@ -78,27 +87,45 @@ export async function getCheckpointService(task: Task, { interval = 250 }: { int log, } - if (task.checkpointServiceInitializing) { + const inFlight = checkpointInits.get(task.taskId) + + if (inFlight || task.checkpointServiceInitializing) { const checkpointInitStartTime = Date.now() let warningShown = false - await pWaitFor( - () => { - const elapsed = Date.now() - checkpointInitStartTime - - // Show warning if we're past the threshold and haven't shown it yet - if (!warningShown && elapsed >= WARNING_THRESHOLD_MS) { - warningShown = true - sendCheckpointInitWarn(task, "WAIT_TIMEOUT", WARNING_THRESHOLD_MS / 1000) - } - - console.log( - `[Task#getCheckpointService] waiting for service to initialize (${Math.round(elapsed / 1000)}s)`, - ) - return !!task.checkpointService && !!task?.checkpointService?.isInitialized - }, - { interval, timeout: checkpointTimeoutMs }, - ) + try { + await pWaitFor( + () => { + const elapsed = Date.now() - checkpointInitStartTime + + // Show warning if we're past the threshold and haven't shown it yet + if (!warningShown && elapsed >= WARNING_THRESHOLD_MS) { + warningShown = true + sendCheckpointInitWarn(task, "WAIT_TIMEOUT", WARNING_THRESHOLD_MS / 1000) + } + + console.log( + `[Task#getCheckpointService] waiting for service to initialize (${Math.round(elapsed / 1000)}s)`, + ) + return !!task.checkpointService && !!task?.checkpointService?.isInitialized + }, + { interval, timeout: checkpointTimeoutMs }, + ) + } catch (error) { + // A handle still in the map means the initialization this caller joined is still + // running: this caller's window closing is that caller's timeout, not the outcome of + // the operation it waited on. Report no service and change nothing else - the caller + // that started the initialization still owns the task's checkpoint state, and a later + // lookup joins the same operation instead of creating a second shadow git for the + // same task. + if (error.name === "TimeoutError" && inFlight) { + sendCheckpointInitWarn(task, "WAIT_TIMEOUT", checkpointTimeoutMs / 1000) + return undefined + } + + throw error + } + if (!task?.checkpointService) { sendCheckpointInitWarn(task, "INIT_TIMEOUT", task.checkpointTimeout) task.enableCheckpoints = false @@ -113,23 +140,39 @@ export async function getCheckpointService(task: Task, { interval = 250 }: { int return undefined } - const service = RepoPerTaskCheckpointService.create(options) - task.checkpointServiceInitializing = true - await checkGitInstallation(task, service, log, provider) - if (!service.isInitialized) { - // checkGitInstallation disables checkpoints when Git is unavailable and - // logs initShadowGit failures without throwing: storing such a service - // would hand later saves (and the fast path above) an uninitialized - // handle whose isInitialized can never flip, so a failed - // initialization must resolve to no service at all. - task.checkpointServiceInitializing = false - return undefined - } - task.checkpointService = service - if (task.enableCheckpoints) { - sendCheckpointInitWarn(task) + const starting = (async () => { + const service = RepoPerTaskCheckpointService.create(options) + task.checkpointServiceInitializing = true + await checkGitInstallation(task, service, log, provider) + if (!service.isInitialized) { + // checkGitInstallation disables checkpoints when Git is unavailable and + // logs initShadowGit failures without throwing: storing such a service + // would hand later saves (and the fast path above) an uninitialized + // handle whose isInitialized can never flip, so a failed + // initialization must resolve to no service at all. + task.checkpointServiceInitializing = false + return undefined + } + task.checkpointService = service + if (task.enableCheckpoints) { + sendCheckpointInitWarn(task) + } + return service + })() + + // Registered before this side awaits anything, so a lookup arriving on the next tick joins + // this initialization instead of racing it into a second service. + checkpointInits.set(task.taskId, starting) + + try { + return await starting + } finally { + // Settled is the only moment the operation stops being shared: success or failure, the + // handle leaves the map when the work it names is over, not when a caller loses patience. + if (checkpointInits.get(task.taskId) === starting) { + checkpointInits.delete(task.taskId) + } } - return service } catch (err) { if (err.name === "TimeoutError" && task.enableCheckpoints) { sendCheckpointInitWarn(task, "INIT_TIMEOUT", task.checkpointTimeout) From e6b4200af468099f3597c9f3ec46f8b185be804e Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:05:14 +0800 Subject: [PATCH 36/52] fix(checkpoints): decline to publish a baseline a write overtook rather than record the write as the pre-task state saveCheckpoint stages when it executes: stageAll captures whatever the workspace holds at that instant. The per-task queue orders a task-start baseline against the first per-write save, but ordering is not content, so a baseline still running when the first write lands committed the write bytes as the pre-task state, and the per-write save queued behind it then found nothing to commit. The baseline mislabelled the bytes and the write cost no record of its own; the pre-write content survived only in the initialization commit, which is not a checkpoint anything can restore to. Measured on 092a2e9ecf before this change: AssertionError: expected { Object (author, branch, ...) } to be undefined + Received: { "commit": "8a1766aad44abf7d6c7c8d34ab65fcb3f262b903", "summary": { "changes": 1, "deletions": 1, "insertions": 1 } } at src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts:180:20 expect(baseline).toBeUndefined() Of the two branches review thread 607pkQ names - preserve pre-write content, or avoid publishing a baseline - this takes the second: a baseline whose content premise is gone at staging time resolves with no commit and costs the shadow git nothing, and the write keeps its own record whose diff base is the content the task started with. The other branch is worse. Freezing what the baseline stages means capturing the workspace at request time, which is either a copy of it or a stage-and-write-tree at request time. Both do their expensive git work outside the very lock whose comment claims it makes late work safe, and they double the git work a baseline exists to bound. A copy can also catch a file mid-write, so it records a state that is neither pre-write nor post-write - it does not deliver pre-write content either - and it leaves the shadow git meaning two different things by what the workspace looked like. Declining costs the caller nothing it does not already handle: a resolve with no commit is how a dropped save is reported today, which is how the task-start baseline already treats it - by retrying on a later loop entry. A task-start baseline now carries a content premise - no agent write had happened when it was requested - and saveCheckpoint evaluates it immediately before stageAll, with no await between the check and the capture, so nothing this task does can slip in after the answer is taken. Per-write saves carry no premise: recording the workspace as it stands when the save runs is exactly what a per-write save is for. The existing assertion in checkpoint.test.ts that pins the baseline call shape now names the premise it gained, rather than being relaxed to an objectContaining. --- .../checkpoints/__tests__/checkpoint.test.ts | 4 +- .../checkpointSaveContentPremise.spec.ts | 206 ++++++++++++++++++ src/core/checkpoints/index.ts | 23 +- .../checkpoints/ShadowCheckpointService.ts | 13 +- 4 files changed, 243 insertions(+), 3 deletions(-) create mode 100644 src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts diff --git a/src/core/checkpoints/__tests__/checkpoint.test.ts b/src/core/checkpoints/__tests__/checkpoint.test.ts index 570eb8e71e..3d8bf35c43 100644 --- a/src/core/checkpoints/__tests__/checkpoint.test.ts +++ b/src/core/checkpoints/__tests__/checkpoint.test.ts @@ -302,9 +302,11 @@ describe("Checkpoint functionality", () => { const result = await savePromise // saveCheckpoint should have been called + // The baseline carries a content premise now: it describes the workspace before any agent + // write, and saveCheckpoint declines to publish if a write landed before it staged. expect(mockCheckpointService.saveCheckpoint).toHaveBeenCalledWith( expect.stringContaining("Task: test-task-id"), - { allowEmpty: true, suppressMessage: false }, + { allowEmpty: true, suppressMessage: false, contentPremise: expect.any(Function) }, ) // Result should contain the commit hash diff --git a/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts b/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts new file mode 100644 index 0000000000..28f7b0f429 --- /dev/null +++ b/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts @@ -0,0 +1,206 @@ +// The in-flight half of review thread 607pkQ, against a real shadow git. +// +// 607pkQ asks that the in-flight baseline and any retry `preserve pre-write content or avoid +// publishing a baseline`. The per-task queue in ./index.ts guarantees ordering; it cannot guarantee +// content, because saveCheckpoint stages the workspace at the moment it executes. So a task-start +// baseline that is still running when the first write lands commits that write as the pre-task state, +// and the per-write save queued behind it then finds nothing to record. The baseline mislabels the +// bytes and the write costs no record of its own. +// +// This file asserts the branch the fix takes: once a write has landed, the in-flight baseline declines +// to publish at all - it resolves with no commit and costs the shadow git nothing - and the write +// keeps its own record whose diff base is the content the task started with. +import fs from "fs/promises" +import os from "os" +import path from "path" + +import { simpleGit } from "simple-git" + +import { RepoPerTaskCheckpointService } from "../../../services/checkpoints" +import { BLOCKED_ENV_KEYS } from "../../../services/checkpoints/ShadowCheckpointService" + +import { checkpointSave, getCheckpointService } from "../index" +import type { Task } from "../../task/Task" + +vi.mock("@roo-code/telemetry", () => ({ + TelemetryService: { + instance: { + captureCheckpointCreated: vi.fn(), + captureCheckpointRestored: vi.fn(), + captureCheckpointDiffed: vi.fn(), + }, + }, +})) + +const tmpDir = path.join(os.tmpdir(), "checkpointSaveContentPremise") +const CHECKPOINTED_FILE = "checkpointed.txt" +const PRE_WRITE = "content the task started with" +const MID_FLIGHT_WRITE = "the write that landed mid-flight" + +const savedEnv: Partial> = {} + +beforeAll(() => { + for (const key of BLOCKED_ENV_KEYS) { + savedEnv[key] = process.env[key] + delete process.env[key] + } +}) + +afterAll(async () => { + for (const key of BLOCKED_ENV_KEYS) { + if (savedEnv[key] !== undefined) { + process.env[key] = savedEnv[key] + } else { + delete process.env[key] + } + } + + await fs.rm(tmpDir, { recursive: true, force: true }) +}, 60_000) + +type SaveArgs = Parameters +type SaveReturn = Awaited> + +/** + * Hold the first execution of saveCheckpoint before it stages anything, and hand back the release. + * The held call is real shadow-git work once released, so what it stages is whatever the workspace + * holds when it is released - which is the property this case turns on. The hold stands for the git + * work a task-start baseline takes while the request loop moves on to the first write. + */ +function holdFirstSave(service: RepoPerTaskCheckpointService, tag: string) { + const real = service.saveCheckpoint.bind(service) + const calls: Array<{ stage: "requested" | "running"; tag: string }> = [] + let release: () => void = () => {} + const held = new Promise((resolve) => { + release = resolve + }) + let ordinal = 0 + + service.saveCheckpoint = async (...args: SaveArgs): Promise => { + const call = ordinal++ + // The held call is the baseline; anything after it is a save the baseline left behind, and the + // list has to say which is which or the record below would be read against the wrong save. + const label = call === 0 ? tag : "per-write" + calls.push({ stage: "requested", tag: label }) + if (call === 0) { + await held + } + calls.push({ stage: "running", tag: label }) + return real(...args) + } + + return { calls, release } +} + +async function commitCount(shadowDir: string, taskId: string): Promise { + const git = simpleGit(path.join(shadowDir, "tasks", taskId, "checkpoints")) + const log = await git.log() + return log.total +} + +async function recorded(service: RepoPerTaskCheckpointService, from: string, to: string) { + const diffs = await service.getDiff({ from, to }) + const file = diffs.find((d) => d.paths.relative === CHECKPOINTED_FILE) + return { count: diffs.length, before: file?.content.before, after: file?.content.after } +} + +type Setup = Awaited> + +async function setupCheckpointTask(taskId: string): Promise { + const workspaceDir = path.join(tmpDir, `workspace-${taskId}`) + const shadowDir = path.join(tmpDir, `storage-${taskId}`) + await fs.mkdir(workspaceDir, { recursive: true }) + await fs.mkdir(shadowDir, { recursive: true }) + + const workspaceGit = simpleGit(workspaceDir) + await workspaceGit.init() + await workspaceGit.addConfig("user.name", "Roo Code") + await workspaceGit.addConfig("user.email", "support@roocode.com") + await workspaceGit.addConfig("commit.gpgSign", "false") + await fs.writeFile(path.join(workspaceDir, CHECKPOINTED_FILE), PRE_WRITE) + await workspaceGit.add(".") + await workspaceGit.commit("record the workspace the task started with") + + const task = { + taskId, + cwd: workspaceDir, + enableCheckpoints: true, + didEditFile: false, + checkpointService: undefined as RepoPerTaskCheckpointService | undefined, + checkpointServiceInitializing: false, + checkpointTimeout: 30, + abort: false, + clineMessages: [] as never[], + apiConversationHistory: [] as never[], + say: vi.fn(async () => {}), + providerRef: { + deref: () => ({ + context: { globalStorageUri: { fsPath: shadowDir } }, + log: () => {}, + postMessageToWebview: vi.fn(), + }), + }, + } as unknown as Task + + const service = await getCheckpointService(task) + + if (!service) { + throw new Error("no checkpoint service after initialization, so no shadow git exists to read") + } + + return { task, service, workspaceGit, shadowDir, baseHash: service.baseHash } +} + +describe("checkpointSave against a write that lands while the task-start baseline is in flight", () => { + it("the baseline declines rather than publishing the write, and the write keeps its own record", async () => { + const { task, service, shadowDir, baseHash } = await setupCheckpointTask("baseline-declines-after-a-write") + const checkpointedFile = path.join(service.workspaceDir, CHECKPOINTED_FILE) + + // The shadow git was initialized from the workspace while it still held the pre-write content, so + // that content is already recorded and the pair below can be read against it. + const beforeBaseline = await commitCount(shadowDir, task.taskId) + + const { calls, release } = holdFirstSave(service, "baseline") + // Requested while no agent write has happened: this save describes the workspace before the write. + const baselinePromise = checkpointSave(task, true, true) + await new Promise((resolve) => setTimeout(resolve, 25)) + expect(calls).toEqual([{ stage: "requested", tag: "baseline" }]) + + // The write the thread names, landing while the baseline is still running: the bytes on disk, and + // the flag every agent write path sets on the task. + await fs.writeFile(checkpointedFile, MID_FLIGHT_WRITE) + task.didEditFile = true + release() + + const baseline = await baselinePromise + const afterBaseline = await commitCount(shadowDir, task.taskId) + + // The baseline must not publish. It cannot record the state it was asked about, so it records + // nothing, which is what the caller already treats as "no baseline yet" and retries against. + expect(baseline).toBeUndefined() + expect(afterBaseline).toBe(beforeBaseline) + + // The write then gets the record the drifted baseline would have swallowed: its own save, whose + // diff base is the content the task started with. + const writeSave = await checkpointSave(task, false, true) + if (!writeSave || typeof writeSave !== "object" || !("commit" in writeSave) || typeof writeSave.commit !== "string") { + throw new Error("the per-write save resolved with no commit, so the write has no record") + } + const writeCommit = writeSave.commit + const record = await recorded(service, baseHash!, writeCommit) + const afterWrite = await commitCount(shadowDir, task.taskId) + + // Both saves reached the shadow git and only one of them committed: the baseline was declined + // at staging time and the write ran as its own save, in that order, because the queue held it there. + expect(calls).toEqual([ + { stage: "requested", tag: "baseline" }, + { stage: "running", tag: "baseline" }, + { stage: "requested", tag: "per-write" }, + { stage: "running", tag: "per-write" }, + ]) + expect(record.count).toBe(1) + expect(record.before).toBe(PRE_WRITE) + expect(record.after).toBe(MID_FLIGHT_WRITE) + expect(afterWrite).toBe(beforeBaseline + 1) + }, 60_000) +}) diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index f18bd57766..fab23e3b3e 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -344,10 +344,31 @@ export async function checkpointSave(task: Task, force = false, suppressMessage // reported to the caller the same way a missing service is (a resolve with no commit), which is // how the task-start baseline already treats it - by retrying on a later loop entry. const timeoutSeconds = task.checkpointTimeout > 0 ? task.checkpointTimeout : DEFAULT_CHECKPOINT_TIMEOUT_SECONDS + // A task-start baseline describes the workspace before any agent write: it is the rollback point for + // the first write of the request loop. The queue orders this save behind whatever is already running, + // but ordering is not content - saveCheckpoint stages when it executes - so a baseline that is still + // running when the first write lands would commit the write bytes as the pre-task state, and the + // per-write save queued behind it would then find nothing to commit. The branch taken here is to + // decline to publish. The other branch the ask names - freezing what the baseline stages, by copying + // the workspace at request time or by staging and writing a tree then - is worse: either does its + // expensive git work outside the very lock whose comment claims it makes late work safe, a copy can + // catch a file half-written and so records a state that is neither pre-write nor post-write, and it + // would leave the shadow git meaning two different things by what the workspace looked like. A + // declined baseline costs the caller nothing it does not already handle: a resolve with no commit is + // how a dropped save is reported today, which is how the task-start baseline already treats it - by + // retrying on a later loop entry. The content the task started with stays recorded in the + // initialization commit, and the write keeps a record of its own whose diff base is that content. + // Per-write saves carry no premise, because recording the workspace as it stands when the save runs + // is exactly what a per-write save is for. + const requestedBeforeAnyWrite = force && !task.didEditFile return enqueueCheckpointWork( task.taskId, () => - service.saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, { allowEmpty: force, suppressMessage }), + service.saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, { + allowEmpty: force, + suppressMessage, + contentPremise: requestedBeforeAnyWrite ? () => !task.didEditFile : undefined, + }), { label: force ? "queued task-start checkpoint baseline" : "queued per-write checkpoint save", expiresAt: Date.now() + Math.max(1, timeoutSeconds * 1000), diff --git a/src/services/checkpoints/ShadowCheckpointService.ts b/src/services/checkpoints/ShadowCheckpointService.ts index 408157d805..235660e410 100644 --- a/src/services/checkpoints/ShadowCheckpointService.ts +++ b/src/services/checkpoints/ShadowCheckpointService.ts @@ -330,7 +330,7 @@ export abstract class ShadowCheckpointService extends EventEmitter { public async saveCheckpoint( message: string, - options?: { allowEmpty?: boolean; suppressMessage?: boolean }, + options?: { allowEmpty?: boolean; suppressMessage?: boolean; contentPremise?: () => boolean } ): Promise { try { this.log( @@ -341,6 +341,17 @@ export abstract class ShadowCheckpointService extends EventEmitter { throw new Error("Shadow git repo not initialized") } + // Content, not only ordering: stageAll captures whatever the workspace holds at this instant, + // so a premise that no longer holds means this save would record a state its caller never asked + // about. The answer is taken here, immediately before the capture, with no await between the two, + // so nothing else this task does can slip in after the premise is checked. + if (options?.contentPremise && !options.contentPremise()) { + this.log( + `[${this.constructor.name}#saveCheckpoint] dropping the save: its content premise no longer holds at staging time, so nothing was committed`, + ) + return undefined + } + const startTime = Date.now() await this.stageAll(this.git) const commitArgs = options?.allowEmpty ? { "--allow-empty": null } : undefined From 8f1d2d3d620c9c5ef2e06b4360e7ebcbdd49141c Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:12:56 +0800 Subject: [PATCH 37/52] style(checkpoints): format the premise gate and its test The compile job at 58d5fa1b11 is red, and it is red on me at its first step: the job runs pnpm format:check (prettier --check .) before lint and check-types, and that step named exactly the two files the previous commit added or edited: [warn] src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts [warn] src/services/checkpoints/ShadowCheckpointService.ts [warn] Code style issues found in 2 files. Run Prettier with --write to fix. Run by hand against the pushed head, 15:10:50Z to 15:11:28Z, exit 1. After prettier --write on those two files the same command exits 0 and prints "All matched files use Prettier code style!" (15:11 run, saved with the run windows). eslint over the four touched files is still exit 0 with suppressions unchanged, and the two test files that cover this path pass 43/43 after formatting (checkpointSaveContentPremise.spec.ts and checkpoint.test.ts), so nothing but whitespace moved. The premise logic itself is unchanged: a task-start baseline whose content premise is gone at staging time declines to publish, and the write keeps its own record. --- .../__tests__/checkpointSaveContentPremise.spec.ts | 7 ++++++- src/services/checkpoints/ShadowCheckpointService.ts | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts b/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts index 28f7b0f429..7df2f1374d 100644 --- a/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts +++ b/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts @@ -183,7 +183,12 @@ describe("checkpointSave against a write that lands while the task-start baselin // The write then gets the record the drifted baseline would have swallowed: its own save, whose // diff base is the content the task started with. const writeSave = await checkpointSave(task, false, true) - if (!writeSave || typeof writeSave !== "object" || !("commit" in writeSave) || typeof writeSave.commit !== "string") { + if ( + !writeSave || + typeof writeSave !== "object" || + !("commit" in writeSave) || + typeof writeSave.commit !== "string" + ) { throw new Error("the per-write save resolved with no commit, so the write has no record") } const writeCommit = writeSave.commit diff --git a/src/services/checkpoints/ShadowCheckpointService.ts b/src/services/checkpoints/ShadowCheckpointService.ts index 235660e410..f6310125d2 100644 --- a/src/services/checkpoints/ShadowCheckpointService.ts +++ b/src/services/checkpoints/ShadowCheckpointService.ts @@ -330,7 +330,7 @@ export abstract class ShadowCheckpointService extends EventEmitter { public async saveCheckpoint( message: string, - options?: { allowEmpty?: boolean; suppressMessage?: boolean; contentPremise?: () => boolean } + options?: { allowEmpty?: boolean; suppressMessage?: boolean; contentPremise?: () => boolean }, ): Promise { try { this.log( From f449849587eed4add7abf670b4f9c8853450efa5 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:27:44 +0800 Subject: [PATCH 38/52] test(checkpoints): cover the dropped save and the retry behind it in a real shadow git The half of review thread 607pkQ that asks for a regression test covering both cases, the second case: a save queued behind a held save whose checkpoint window expires before its turn arrives must resolve with no commit, and a later loop entry must retry it rather than leave the task start with no baseline at all. This is the case the code already got right; it is now pinned so a later change cannot quietly make an expired save publish, and it is pinned against a real shadow git rather than a double. Cherry-picked from 98db7122ae09d471b8513ba9f4ae45590b1d7ced, which was written against 53d221ef96cb0dfa35b6b13c3524a61d499af1a4 and held locally until the arms at its successor were read green. Three deliberate changes on the way over, each measured: - the blob stored 215 CRLF pairs against a repo that normalises to LF (core.autocrlf false, core.eol lf, and the sibling committed specs in this directory store 0 pairs), so line endings were normalised first, 9,253 bytes to 9,038; - prettier --write reformatted 70 lines of it, 9,038 bytes to 9,080 and 216 lines to 228, because the compile job runs pnpm format:check as its first step and that command flagged this file; - the circular return annotation was removed. tsc rejects "type Setup = Awaited>" annotated "Promise" as TS2456 plus TS2577, and src check-types reports it for this file and for the premise spec: core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts(96,6): error TS2456: Type alias Setup circularly references itself. core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts(98,53): error TS2577: Return type annotation circularly references itself. The alias was only ever the function own annotation, so the function now infers its return type, which is precise and adds no assertion. It is a spec, so it charges 0 extension lines under the mutation instrument either way. Verified at this head: pnpm --dir src run check-types exit 0 (15:31:39.022Z to 15:31:44.275Z); both checkpoint test dirs together Test Files 7 passed (7), Tests 98 passed (98), Duration 88.64s; eslint with --prune-suppressions --max-warnings=0 exit 0 with the suppressions file unchanged; pnpm run format:check exit 0, All matched files use Prettier code style. (cherry picked from commit 98db7122ae09d471b8513ba9f4ae45590b1d7ced) --- .../__tests__/checkpointSaveInFlight.spec.ts | 227 ++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 src/core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts diff --git a/src/core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts b/src/core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts new file mode 100644 index 0000000000..5a55272ec2 --- /dev/null +++ b/src/core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts @@ -0,0 +1,227 @@ +// The in-flight and retry halves of review thread 607pkQ, verified against a real shadow git. +// +// 607pkQ asks that `the in-flight baseline and any retry need to preserve pre-write content or avoid +// publishing a baseline` and that `the shared regression test can verify both cases`. The cases in +// ./checkpoint.test.ts prove the queue at the call level: its doubles show that a dropped save never +// reaches saveCheckpoint and that the warning names the reason. Neither layer can show what the shadow +// git ended up recording, which is what the thread is about: a save that published the wrong bytes, or +// a drop that silently cost a record, would satisfy every call-count assertion there. + +// This file runs the real RepoPerTaskCheckpointService over a real workspace repo and asserts records, +// reusing the setup and the contents helper from ./checkpointSaveShadowGit.spec.ts. +import fs from "fs/promises" +import os from "os" +import path from "path" + +import { simpleGit } from "simple-git" + +import { RepoPerTaskCheckpointService } from "../../../services/checkpoints" +import { BLOCKED_ENV_KEYS } from "../../../services/checkpoints/ShadowCheckpointService" + +import { checkpointSave, getCheckpointService } from "../index" +import type { Task } from "../../task/Task" + +vi.mock("@roo-code/telemetry", () => ({ + TelemetryService: { + instance: { + captureCheckpointCreated: vi.fn(), + captureCheckpointRestored: vi.fn(), + captureCheckpointDiffed: vi.fn(), + }, + }, +})) + +const tmpDir = path.join(os.tmpdir(), "checkpointSaveInFlight") +const CHECKPOINTED_FILE = "checkpointed.txt" + +const savedEnv: Partial> = {} + +beforeAll(() => { + for (const key of BLOCKED_ENV_KEYS) { + savedEnv[key] = process.env[key] + delete process.env[key] + } +}) + +afterAll(async () => { + for (const key of BLOCKED_ENV_KEYS) { + if (savedEnv[key] !== undefined) { + process.env[key] = savedEnv[key] + } else { + delete process.env[key] + } + } + + await fs.rm(tmpDir, { recursive: true, force: true }) +}, 60_000) + +type SaveArgs = Parameters +type SaveReturn = Awaited> + +/** + * Hold the next execution of saveCheckpoint before it reaches the shadow git, and hand back the + * release. The predecessor is real shadow-git work — the release runs the untouched implementation — + * so what is staged is whatever the workspace holds when the call is released, which is the property + * both cases turn on. The hold stands for a predecessor that outlives the next caller's checkpoint + * window, which is the situation the expiry gate is for. + */ +function holdNextSave(service: RepoPerTaskCheckpointService, tag: string) { + const real = service.saveCheckpoint.bind(service) + const calls: Array<{ stage: "requested" | "running"; tag: string }> = [] + let release: () => void = () => {} + const held = new Promise((resolve) => { + release = resolve + }) + let holding = true + + service.saveCheckpoint = async (...args: SaveArgs): Promise => { + if (holding) { + holding = false + calls.push({ stage: "requested", tag }) + await held + } + calls.push({ stage: "running", tag }) + return real(...args) + } + + return { calls, release } +} + +async function commitCount(shadowDir: string, taskId: string): Promise { + const git = simpleGit(path.join(shadowDir, "tasks", taskId, "checkpoints")) + const log = await git.log() + return log.total +} + +// The return type is inferred, not aliased to Awaited>: an alias that +// resolves through the function it annotates is circular and tsc rejects it (TS2456, TS2577). +async function setupCheckpointTask(taskId: string) { + const workspaceDir = path.join(tmpDir, `workspace-${taskId}`) + const shadowDir = path.join(tmpDir, `storage-${taskId}`) + await fs.mkdir(workspaceDir, { recursive: true }) + await fs.mkdir(shadowDir, { recursive: true }) + + const workspaceGit = simpleGit(workspaceDir) + await workspaceGit.init() + await workspaceGit.addConfig("user.name", "Roo Code") + await workspaceGit.addConfig("user.email", "support@roocode.com") + await workspaceGit.addConfig("commit.gpgSign", "false") + await fs.writeFile(path.join(workspaceDir, CHECKPOINTED_FILE), "state before any agent write") + await workspaceGit.add(".") + await workspaceGit.commit("record the workspace baseline") + + const task = { + taskId, + cwd: workspaceDir, + enableCheckpoints: true, + checkpointService: undefined as RepoPerTaskCheckpointService | undefined, + checkpointServiceInitializing: false, + checkpointTimeout: 30, + abort: false, + clineMessages: [] as never[], + apiConversationHistory: [] as never[], + say: vi.fn(async () => {}), + providerRef: { + deref: () => ({ + context: { globalStorageUri: { fsPath: shadowDir } }, + log: () => {}, + postMessageToWebview: vi.fn(), + }), + }, + } as unknown as Task + + const service = await getCheckpointService(task) + + if (!service) { + throw new Error("no checkpoint service after initialization, so no shadow git exists to read") + } + + return { task, service, workspaceGit, shadowDir, baseHash: service.baseHash } +} + +async function recorded(service: RepoPerTaskCheckpointService, from: string, to: string) { + const diffs = await service.getDiff({ from, to }) + const file = diffs.find((d) => d.paths.relative === CHECKPOINTED_FILE) + return { count: diffs.length, after: file?.content.after } +} + +describe("checkpointSave in-flight and retry against a real shadow git", () => { + it("a save the expiry gate drops costs no record: the shadow git keeps exactly the earlier commits and the next save carries the moved-on bytes", async () => { + const { task, service, shadowDir, baseHash } = await setupCheckpointTask("dropped-save-costs-no-record") + const checkpointedFile = path.join(service.workspaceDir, CHECKPOINTED_FILE) + + // A baseline recorded while the workspace still holds its own state, so there is a known record + // to compare the dropped save against. + await fs.writeFile(checkpointedFile, "the state the baseline recorded") + const baseline = await checkpointSave(task, true, true) + + if ( + !baseline || + typeof baseline !== "object" || + !("commit" in baseline) || + typeof baseline.commit !== "string" + ) { + throw new Error("the baseline save resolved with no commit, so there is nothing to compare against") + } + + // The predecessor is a real save held before it reaches the shadow git; the save behind it is + // requested inside a checkpoint window shorter than the hold, so its turn arrives expired. + const { release, calls } = holdNextSave(service, "predecessor") + task.checkpointTimeout = 0.02 + const predecessor = checkpointSave(task, true, true) + const queued = checkpointSave(task, false, true) + const beforeDrop = await commitCount(shadowDir, task.taskId) + + await fs.writeFile(checkpointedFile, "bytes that arrived while the save waited") + await new Promise((resolve) => setTimeout(resolve, 80)) + release() + + const dropped = await queued + const settledPredecessor = await predecessor + const afterDrop = await commitCount(shadowDir, task.taskId) + + // The dropped save ran no shadow-git work: the predecessor above it is the only entry that + // reached the repository, and the commit count moved by that one and not by two. + expect(calls).toEqual([ + { stage: "requested", tag: "predecessor" }, + { stage: "running", tag: "predecessor" }, + ]) + expect(dropped).toBeUndefined() + expect(afterDrop - beforeDrop).toBe(1) + + if (!settledPredecessor || typeof settledPredecessor !== "object" || !("commit" in settledPredecessor)) { + throw new Error("the predecessor resolved with no commit, so there is no record to read") + } + const predecessorCommit = settledPredecessor.commit as string + + // The retry the thread asks about: a save requested after the stall settles gets its own turn in + // spite of the entry the gate dropped above it, and it records the state that exists when it runs. + // The drop therefore cost the shadow git no record it would have made correctly, and it cost the + // queue nothing. + task.checkpointTimeout = 30 + await fs.writeFile(checkpointedFile, "bytes the retry records") + const retrySave = await checkpointSave(task, false, true) + + if ( + !retrySave || + typeof retrySave !== "object" || + !("commit" in retrySave) || + typeof retrySave.commit !== "string" + ) { + throw new Error( + "the save requested after the stall resolved with no commit, so the drop poisoned the queue", + ) + } + const afterRetry = await commitCount(shadowDir, task.taskId) + const baselineRecord = await recorded(service, baseHash!, predecessorCommit) + + // The predecessor that did run staged what the workspace held when it was released, which is the + // drift the other case is about; recorded here so the pair reads as measured rather than assumed. + expect(baselineRecord.count).toBe(1) + expect(baselineRecord.after).toBe("bytes that arrived while the save waited") + const retryRecord = await recorded(service, predecessorCommit, retrySave.commit) + expect(retryRecord.count).toBe(1) + expect(retryRecord.after).toBe("bytes the retry records") + expect(afterRetry - afterDrop).toBe(1) + }, 60_000) +}) From c07680764b73d3b90d6f8150618bc80113a3c675 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:34:08 +0800 Subject: [PATCH 39/52] fix(checkpoints): let the premise setup infer its return type rather than alias it to itself The same defect the cherry-pick commit removes from its own file: the premise spec declared type Setup = Awaited> and annotated its own setup function "Promise", which is circular by construction and tsc reports at src check-types: core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts(107,6): error TS2456: Type alias Setup circularly references itself. core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts(109,53): error TS2577: Return type annotation circularly references itself. That is a compile-leg failure, since check-types is a step of the compile job, and it reached the pushed head because a turbo run whose first failing leg aborts the rest hid the extension leg: Tasks: 10 successful, 12 total, Cached: 10 cached, 12 total, Failed: @roo-code/vscode-webview#check-types counts a task that started and was aborted as neither successful nor failed, so the missing error lines in that summary were never a passing leg and I read them as one. Running the leg by itself, pnpm --dir src run check-types, printed them (exit 2 before this change, exit 0 after, 15:31:39.022Z to 15:31:44.275Z). The alias only ever served as the function own annotation, so the annotation goes away and the return type is inferred. The behaviour under test is untouched: both checkpoint test dirs pass with this in place, Test Files 7 passed (7), Tests 98 passed (98), and eslint and format:check are exit 0. --- .../__tests__/checkpointSaveContentPremise.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts b/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts index 7df2f1374d..4864eefe0d 100644 --- a/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts +++ b/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts @@ -104,9 +104,9 @@ async function recorded(service: RepoPerTaskCheckpointService, from: string, to: return { count: diffs.length, before: file?.content.before, after: file?.content.after } } -type Setup = Awaited> - -async function setupCheckpointTask(taskId: string): Promise { +// The return type is inferred, not aliased to Awaited>: an alias that +// resolves through the function it annotates is circular and tsc rejects it (TS2456, TS2577). +async function setupCheckpointTask(taskId: string) { const workspaceDir = path.join(tmpDir, `workspace-${taskId}`) const shadowDir = path.join(tmpDir, `storage-${taskId}`) await fs.mkdir(workspaceDir, { recursive: true }) From c9f3649c044c75f7d55858cdaf7595c9835c099b Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:09:54 +0800 Subject: [PATCH 40/52] fix(apply-patch): write a move through a destination symlink Review thread 7pkY: a destination symlink was renamed to the backup name and replaced by a regular file at the requested path while its own target kept the pre-move bytes, and the .rooignore, write-protection and workspace checks only ever saw the requested spelling. Resolve the destination through its link target before anything is read or renamed, run the same three checks against the resolved target, and move the backup and the staged rename against the target so the link survives, including a dangling link and the failed-source-delete rollback. Rows added in applyPatchTool.execute.spec.ts for the symlink write, the target-byte rollback and the dangling link. Failing without the fix: 3 failed, 34 passed over the same spec. --- src/core/tools/ApplyPatchTool.ts | 112 ++++++++++++-- .../__tests__/applyPatchTool.execute.spec.ts | 144 ++++++++++++++++++ 2 files changed, 245 insertions(+), 11 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 0b0ea7dbf6..b481c4212d 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -530,12 +530,102 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { return { ok: false, mutated } } + // Both refusals below report the way the destination checks above do: a counted mistake, a + // recorded tool error, the message to the user and a diff-view reset. Hoisted so that a + // link which fails inspection is refused exactly like a path that fails the workspace edge. + const reportMoveRefusal = async (message: string): Promise => { + task.consecutiveMistakeCount++ + task.recordToolError("apply_patch") + await task.say("error", message) + pushToolResult(formatResponse.toolError(message)) + await task.diffViewProvider.reset() + } + + // Resolve the destination through any symlink before anything is read, written or renamed. + // The renames below move paths, so a destination symlink would be carried to the backup + // name and replaced by a regular file at the requested path while its own target kept the + // old bytes. The target is where the moved content has to land, and it is also the path + // the access, protection and workspace checks have to see: a link is not a way to move + // content past .rooignore, a write-protected path or the workspace edge. + let linkTargetPath: string | undefined + try { + const destinationShape = await fs.lstat(moveAbsolutePath) + if (destinationShape.isSymbolicLink()) { + // A link target is spelled relative to the directory holding the link. + const rawTarget = await fs.readlink(moveAbsolutePath) + linkTargetPath = path.resolve(path.dirname(moveAbsolutePath), rawTarget) + } + } catch (error) { + // ENOENT, there is no destination at all. ENOTDIR, a parent is a file rather than a + // directory. Neither has a link to preserve, so the destination keeps its requested + // spelling and the checks above already covered it. Any other failure is a state this + // move cannot describe, so it is refused the way the destination read below is refused. + const shapeError = error as NodeJS.ErrnoException + if (shapeError.code !== "ENOENT" && shapeError.code !== "ENOTDIR") { + await reportMoveRefusal( + "Failed to inspect move destination " + change.movePath + ": " + shapeError.message, + ) + return { ok: false, mutated } + } + } + // Where the moved bytes land: the link target when the destination is a link, and the + // requested path otherwise. realpath gives one spelling for the checks and the writes to + // agree on even when the target is itself reached through further links, and a missing + // target, the dangling-link case, keeps the spelled path because there is nothing to + // resolve yet. + const destinationWritePath = linkTargetPath ?? moveAbsolutePath + let resolvedWritePath = destinationWritePath + try { + resolvedWritePath = await fs.realpath(destinationWritePath) + } catch (error) { + const resolvedError = error as NodeJS.ErrnoException + if (resolvedError.code !== "ENOENT" && resolvedError.code !== "ENOTDIR") { + await reportMoveRefusal( + "Failed to resolve move destination " + change.movePath + ": " + resolvedError.message, + ) + return { ok: false, mutated } + } + } + // The requested spelling and the spelling that receives the bytes can differ, and when + // they do the three checks above covered only the requested one. A link whose target + // sits under .rooignore, behind write protection or outside the workspace is refused + // exactly as the requested path would be. + const targetDiffersFromRequested = path.resolve(resolvedWritePath) !== path.resolve(moveAbsolutePath) + if (targetDiffersFromRequested) { + const resolvedRelative = path.relative(task.cwd, resolvedWritePath) + if (task.rooIgnoreController && !task.rooIgnoreController.validateAccess(resolvedRelative)) { + await task.say("rooignore_error", resolvedRelative) + pushToolResult(formatResponse.rooIgnoreError(resolvedRelative)) + await task.diffViewProvider.reset() + return { ok: false, mutated } + } + if (task.rooProtectedController?.isWriteProtected(resolvedRelative) || false) { + await reportMoveRefusal("Cannot move file to write-protected target " + resolvedRelative + ".") + return { ok: false, mutated } + } + if (isPathOutsideWorkspace(resolvedWritePath)) { + await reportMoveRefusal( + "Cannot move file to a path outside the workspace: " + + change.movePath + + " resolves to " + + getReadablePath(task.cwd, resolvedWritePath) + + ".", + ) + return { ok: false, mutated } + } + } + // A patch whose "Move to" resolves back onto its own source path is a rewrite of // that path, not a relocation: once the staged content is renamed onto the destination // there is no second file left, and unlinking the source would delete the content that // was just committed. Computed from resolved paths because case-insensitive and // normalized spellings can name the same file differently. - const isMoveOntoSource = path.resolve(moveAbsolutePath) === path.resolve(absolutePath) + // A destination link that resolves onto the source is the same rewrite the comment below + // describes: the staged bytes land on the source path through the link, so unlinking the + // source afterwards would delete the content the patch just committed. + const isMoveOntoSource = + path.resolve(moveAbsolutePath) === path.resolve(absolutePath) || + path.resolve(resolvedWritePath) === path.resolve(absolutePath) // Capture the destination state before either supported write path: a // failed move must restore an existing destination instead of deleting @@ -544,7 +634,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // write rather than risking an unrecoverable clobber. let destinationBackup: Buffer | undefined try { - destinationBackup = await fs.readFile(moveAbsolutePath) + destinationBackup = await fs.readFile(destinationWritePath) } catch (error) { const code = (error as NodeJS.ErrnoException).code if (code !== "ENOENT") { @@ -563,7 +653,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // or executable destination. let destinationMode: number | undefined if (destinationBackup !== undefined) { - destinationMode = await fs.stat(moveAbsolutePath).then( + destinationMode = await fs.stat(destinationWritePath).then( (stat) => stat.mode, () => undefined, ) @@ -575,8 +665,8 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // source unlinked. Any failure renames the backup back, so the workspace // never shows a half-applied move. const moveStamp = `${process.pid}.${Date.now()}` - const moveDir = path.dirname(moveAbsolutePath) - const moveBase = path.basename(moveAbsolutePath) + const moveDir = path.dirname(destinationWritePath) + const moveBase = path.basename(destinationWritePath) const stagingPath = path.join(moveDir, `.${moveBase}.${moveStamp}.staging`) const backupPath = path.join(moveDir, `.${moveBase}.${moveStamp}.backup`) await fs.mkdir(moveDir, { recursive: true }) @@ -592,9 +682,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (destinationBackup !== undefined) { // Preserve the pre-move bytes on disk (atomic rename): the in-memory // copy alone cannot restore the destination after a crash. - await fs.rename(moveAbsolutePath, backupPath) + await fs.rename(destinationWritePath, backupPath) } - await fs.rename(stagingPath, moveAbsolutePath) + await fs.rename(stagingPath, destinationWritePath) destinationCommitted = true // The destination content changed: even a later failed source unlink (which // rolls the destination back) is a workspace mutation the checkpoint must see. @@ -614,14 +704,14 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } catch (writeError) { await fs.rm(stagingPath, { force: true }).catch(() => {}) if (destinationCommitted) { - await fs.rm(moveAbsolutePath, { force: true }).catch(() => {}) + await fs.rm(destinationWritePath, { force: true }).catch(() => {}) } let destinationMissing = false if (destinationBackup !== undefined) { // Put the captured destination bytes back with one rename. If that rename // fails as well, the destination is missing and its content survives only // under the backup name, so the report has to say where it is. - await fs.rename(backupPath, moveAbsolutePath).catch(() => { + await fs.rename(backupPath, destinationWritePath).catch(() => { destinationMissing = true }) } @@ -664,9 +754,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // Atomic restore of the captured destination bytes: the rename // replaces the clobbered destination in one step, so there is no // window where the file is missing. - await fs.rename(backupPath, moveAbsolutePath) + await fs.rename(backupPath, destinationWritePath) } else { - await fs.rm(moveAbsolutePath, { force: true }) + await fs.rm(destinationWritePath, { force: true }) } } catch (restoreError) { restoreFailure = restoreError diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 5de3f13efa..8105610585 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -12,6 +12,11 @@ import { ApplyPatchTool } from "../ApplyPatchTool" // The vi.mock factory exposes the fs/promises functions under a `default` // property (matching the SUT's default import), which the static module type // does not declare; cast once at this boundary rather than at each call site. +// The move path asks lstat only whether the destination is a link, readlink only for the +// target of that link and realpath only for the spelling of a path that exists, so the +// boundary double declares those shapes rather than the whole fs/promises surface. +type DestinationShape = { isSymbolicLink: () => boolean } + const mockedFsPromises = vi.mocked( fsPromises as unknown as { default: { @@ -22,6 +27,9 @@ const mockedFsPromises = vi.mocked( stat: MockedFunction chmod: MockedFunction writeFile: MockedFunction + lstat: MockedFunction<(target: string) => Promise> + readlink: MockedFunction<(target: string) => Promise> + realpath: MockedFunction<(target: string) => Promise> } }, ) @@ -33,6 +41,13 @@ vi.mock("fs/promises", () => ({ rm: vi.fn().mockResolvedValue(undefined), rename: vi.fn().mockResolvedValue(undefined), stat: vi.fn().mockResolvedValue({ mode: 0o755, uid: 0, gid: 0 }), + lstat: vi.fn(async () => { + // No destination exists in the default world, the way readFile below is stubbed for + // a plain file: the caller treats ENOENT as an absent destination. + throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + }), + readlink: vi.fn(async () => ""), + realpath: vi.fn(async (target: string) => target), chmod: vi.fn().mockResolvedValue(undefined), mkdir: vi.fn().mockResolvedValue(undefined), writeFile: vi.fn().mockResolvedValue(undefined), @@ -207,6 +222,135 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockTask.diffViewProvider.pushToolWriteResult).toHaveBeenCalledOnce() }) + it("keeps a destination symlink and writes the moved content through its target", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // The destination is a symlink. Renaming the link itself would carry it to the backup name + // and install a regular file at the requested path while the target kept the old bytes, + // so the moved bytes have to land on the target and the link has to stay where it is. + mockedFsPromises.default.lstat.mockResolvedValueOnce({ isSymbolicLink: (): boolean => true }) + mockedFsPromises.default.readlink.mockResolvedValueOnce("target.ts") + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The path the destination checks were run against, captured from the handler itself so + // the assertion does not have to guess how the workspace spelling was built. + const linkPath = mockedFsPromises.default.lstat.mock.calls[0]?.[0] + expect(linkPath).toEqual(expect.stringContaining("new.ts")) + expect(mockedFsPromises.default.rename).toHaveBeenCalledWith( + expect.stringContaining("target.ts"), + expect.stringContaining(".backup"), + ) + expect(mockedFsPromises.default.rename).toHaveBeenCalledWith( + expect.stringContaining(".staging"), + expect.stringContaining("target.ts"), + ) + // Never the link itself, in either direction of either rename. + expect(mockedFsPromises.default.rename).not.toHaveBeenCalledWith(expect.any(String), linkPath) + expect(mockedFsPromises.default.rename).not.toHaveBeenCalledWith(linkPath, expect.any(String)) + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("restores the symlink target bytes when the source deletion fails", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // A link whose target already holds content: the backup captured the target bytes, so the + // rollback has to put them back at the target, which is where the link still points. The + // read is keyed on the path because the hunk pass reads the source file through the same + // stub, and only the destination read may see the link target content. + mockedFsPromises.default.lstat.mockResolvedValueOnce({ isSymbolicLink: (): boolean => true }) + mockedFsPromises.default.readlink.mockResolvedValueOnce("target.ts") + mockedFsPromises.default.readFile.mockImplementation(async (p: unknown) => { + if (String(p).includes("target.ts")) { + return "target file content" + } + return "original file content" + }) + mockedFsPromises.default.unlink.mockRejectedValueOnce( + Object.assign(new Error("EBUSY: resource busy or locked"), { code: "EBUSY" }), + ) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + const linkPath = mockedFsPromises.default.lstat.mock.calls[0]?.[0] + // The restore rename runs from the backup name back onto the target, never onto the link. + expect(mockedFsPromises.default.rename).toHaveBeenCalledWith( + expect.stringContaining(".backup"), + expect.stringContaining("target.ts"), + ) + expect(mockedFsPromises.default.rename).not.toHaveBeenCalledWith(expect.any(String), linkPath) + expect(mockPushToolResult).toHaveBeenCalledWith( + expect.stringContaining("Failed to delete original file after move"), + ) + // The destination was written and then rolled back: still a workspace mutation, so the + // partial-state checkpoint is recorded even though the move reports failure. + expect(mockedCheckpointSave).toHaveBeenCalledOnce() + // Restore the default readFile behavior for later tests. + mockedFsPromises.default.readFile.mockResolvedValue("original file content") + }) + + it("materializes the target of a dangling destination symlink instead of replacing the link", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // The link points at a path that does not exist. There is nothing to back up, so the only + // write is the staged rename, and it has to land at the target so that the link resolves + // rather than being replaced by a regular file at the requested path. + mockedFsPromises.default.lstat.mockResolvedValueOnce({ isSymbolicLink: (): boolean => true }) + mockedFsPromises.default.readlink.mockResolvedValueOnce("target.ts") + mockedFsPromises.default.readFile.mockImplementation(async (p: unknown) => { + if (String(p).includes("target.ts")) { + throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + } + return "original file content" + }) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + const linkPath = mockedFsPromises.default.lstat.mock.calls[0]?.[0] + expect(mockedFsPromises.default.rename).toHaveBeenCalledWith( + expect.stringContaining(".staging"), + expect.stringContaining("target.ts"), + ) + expect(mockedFsPromises.default.rename).not.toHaveBeenCalledWith( + expect.stringContaining(".backup"), + expect.any(String), + ) + expect(mockedFsPromises.default.rename).not.toHaveBeenCalledWith(expect.any(String), linkPath) + expect(mockHandleError).not.toHaveBeenCalled() + // Restore the default readFile behavior for later tests. + mockedFsPromises.default.readFile.mockResolvedValue("original file content") + }) + it("restores the pre-move state and fails the operation when source deletion fails", async () => { const patch = `*** Begin Patch *** Update File: src/old.ts From 657a113596b3d855a411990bacb734c4e2deca48 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:24:07 +0800 Subject: [PATCH 41/52] test(apply-patch): carry toolCallId in the callback fixtures at the rebased head main declares toolCallId as a required member of ToolCallbacks in src/core/tools/BaseTool.ts, and the 24 fixture call sites that carried it entered this branch through a merged upstream snapshot rather than through a commit of this branch, so the linear replay dropped them and the standalone type check reported 24 errors for this path. The target content is fixed by blob identity: the pre-rebase head blob and the blob of git-s own conflict-free merge of main with the pre-rebase head are the same object for this path, and the rebased head differed from it by exactly those 24 added lines and by nothing else. --- .../__tests__/applyPatchTool.execute.spec.ts | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 8105610585..0bf26e5008 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -644,6 +644,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Successfully deleted")) @@ -665,6 +666,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) .then(() => { settled = true @@ -687,6 +689,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) await vi.waitFor(() => expect(mockedCheckpointSave).toHaveBeenCalledOnce()) expect(mockTask.processQueuedMessages).not.toHaveBeenCalled() @@ -707,6 +710,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockedCheckpointSave).not.toHaveBeenCalled() @@ -722,6 +726,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockTask.processQueuedMessages).not.toHaveBeenCalled() @@ -747,6 +752,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) // The retained successful write gets an explicit partial-state @@ -776,6 +782,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) // The earlier successful delete is retained: an explicit partial-state @@ -800,6 +807,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Successfully deleted")) @@ -817,6 +825,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockTask.recordToolError).toHaveBeenCalledWith("apply_patch") @@ -863,6 +872,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith("Delete operation was rejected by the user.") @@ -876,6 +886,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("File not found")) @@ -889,6 +900,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Failed to delete file")) @@ -902,6 +914,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("File already exists")) @@ -916,6 +929,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith("Changes were rejected by the user.") @@ -929,6 +943,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith("File saved successfully") @@ -942,6 +957,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("File not found")) @@ -955,6 +971,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("No changes needed")) @@ -968,6 +985,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith("Changes were rejected by the user.") @@ -986,6 +1004,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockTask.say).toHaveBeenCalledWith("rooignore_error", "src/moved.ts") @@ -1005,6 +1024,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith( @@ -1022,6 +1042,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith( @@ -1035,6 +1056,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) // path is platform-dependent (Windows resolves cwd to a drive path); @@ -1053,6 +1075,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockHandleError).not.toHaveBeenCalled() @@ -1082,6 +1105,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", }) expect(mockHandleError).not.toHaveBeenCalled() From 24c0b4561ca30151b5080e65ec9a00d9de300863 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:21:15 +0800 Subject: [PATCH 42/52] fix(checkpoints): refuse a read-only destination before the atomic rename writeFileAtomically stages into a sibling file and renames it into place. POSIX rename(2) only needs write permission on the containing directory, so the rename replaced a destination the user marked read-only where the direct write this helper replaced failed with EACCES. Check the resolved destination for writability before a staging file exists, so a refused write leaves the previous bytes and no leftovers. The spec case states its own premise: it runs only where access(2) actually refuses a 0444 file, asserts EACCES on POSIX and EPERM on Windows, and shows the directory holds nothing but the original file afterwards. Addresses review comment 4347051548 on pull 1404. --- .../editor/__tests__/atomicWrite.spec.ts | 34 +++++++++++++++++++ src/integrations/editor/atomicWrite.ts | 11 ++++++ 2 files changed, 45 insertions(+) diff --git a/src/integrations/editor/__tests__/atomicWrite.spec.ts b/src/integrations/editor/__tests__/atomicWrite.spec.ts index 7b74e05768..6138141f7d 100644 --- a/src/integrations/editor/__tests__/atomicWrite.spec.ts +++ b/src/integrations/editor/__tests__/atomicWrite.spec.ts @@ -1,6 +1,7 @@ // npx vitest run integrations/editor/__tests__/atomicWrite.spec.ts import fs from "fs/promises" +import { constants as fsConstants } from "fs" import os from "os" import path from "path" @@ -44,6 +45,39 @@ describe("writeFileAtomically", () => { expect(stat.mode & 0o777).toBe(0o755) }) + // The compatibility case rename(2) skips: it needs write permission on the directory, + // not on the destination, so a read-only destination must still fail the way the + // direct write this helper replaced failed. POSIX reports EACCES for that, Windows + // maps the read-only attribute onto EPERM, and a root-run container can ignore + // mode bits altogether, which is why the case checks its own premise. + it("refuses a read-only destination and leaves the previous bytes and no leftovers", async () => { + const target = path.join(dir, "locked.txt") + await fs.writeFile(target, "old", "utf8") + await fs.chmod(target, 0o444) + + let destinationWritable = true + try { + await fs.access(target, fsConstants.W_OK) + } catch { + // access(2) refused the 0444 destination: that is the premise this case needs. + destinationWritable = false + } + if (destinationWritable) { + // Where access(2) ignores mode bits the premise is absent; the case then + // reports nothing rather than asserting the wrong thing. + await fs.chmod(target, 0o644) + return + } + + await expect(writeFileAtomically(target, "new")).rejects.toMatchObject({ + code: process.platform === "win32" ? "EPERM" : "EACCES", + }) + + expect(await fs.readFile(target, "utf8")).toBe("old") + expect(await fs.readdir(dir)).toEqual(["locked.txt"]) + await fs.chmod(target, 0o644) + }) + posixOnly("updates a symlink through its target without replacing the symlink", async () => { const target = path.join(dir, "real.txt") const link = path.join(dir, "link.txt") diff --git a/src/integrations/editor/atomicWrite.ts b/src/integrations/editor/atomicWrite.ts index 6bef23ec4f..09ce0bbade 100644 --- a/src/integrations/editor/atomicWrite.ts +++ b/src/integrations/editor/atomicWrite.ts @@ -1,4 +1,5 @@ import * as fs from "fs/promises" +import { constants as fsConstants } from "fs" /** * Write a file so readers only ever observe the previous bytes or the complete @@ -15,9 +16,11 @@ export async function writeFileAtomically(absolutePath: string, content: string, let targetPath = absolutePath let targetMode = mode let targetOwnership: { uid: number; gid: number } | undefined + let targetExists = false try { targetPath = await fs.realpath(absolutePath) const stat = await fs.stat(targetPath) + targetExists = true targetMode = targetMode ?? stat.mode & 0o7777 targetOwnership = { uid: stat.uid, gid: stat.gid } } catch (error) { @@ -25,6 +28,14 @@ export async function writeFileAtomically(absolutePath: string, content: string, throw error } } + // POSIX rename(2) only asks for write permission on the containing directory, so a + // rename would replace a destination the user marked read-only where the direct + // write this helper replaced failed with EACCES. Check the destination itself, + // before any staging file exists; a destination that is not there yet stays + // creatable. Windows reports the same condition as EPERM via the read-only attribute. + if (targetExists) { + await fs.access(targetPath, fsConstants.W_OK) + } // Derive the sibling staging path with plain string operations so the helper stays // usable in unit tests that mock the "path" module down to a few functions. const separatorIndex = Math.max(targetPath.lastIndexOf("/"), targetPath.lastIndexOf("\\")) From 1f1615fac4fc35194b61de2fde175fdab4cd69a4 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:47:14 +0800 Subject: [PATCH 43/52] test(checkpoints): pin the per-write default and the label and description copy Adds two rows that fail without the content they name, both inside __tests__ paths the mutation instrument excludes, so the priced changed-line counts do not move. - packages/types/src/__tests__/global-settings.test.ts asserts the shared default constant DEFAULT_PER_WRITE_CHECKPOINTS is true, mirrors the sibling setting rows for the schema round trip and key inclusion, and kills the BooleanLiteral mutant on global-settings.ts line 122 that the reviewer-facing mutation record names as surviving. - webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx asserts the description copy renders and that the setting registers in the settings search index under its translated label, which kills the two StringLiteral mutants on CheckpointSettings.tsx lines 42 and 51. Measured at head 94240dc1ab029984b064d2611aeed46d4fd24f3b with the trees own instrument and its own priced selectors, same population measured twice: types Valid 1 Killed 0 to Killed 1, webview Valid 8 Killed 5 to Killed 7, blocking rows 4 to 1, Timeout 0 and No coverage 0 in both legs. The surviving mutant on SettingsView.tsx line 449 is left standing and reported as an equivalence candidate. src/eslint-suppressions.json is byte-identical after the pruning pass and 0 suppressions were added. --- .../src/__tests__/global-settings.test.ts | 16 +++++++++ .../__tests__/CheckpointSettings.spec.tsx | 33 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/packages/types/src/__tests__/global-settings.test.ts b/packages/types/src/__tests__/global-settings.test.ts index f2b2e7e8e5..42ca9deb58 100644 --- a/packages/types/src/__tests__/global-settings.test.ts +++ b/packages/types/src/__tests__/global-settings.test.ts @@ -1,6 +1,7 @@ import { DEFAULT_ALWAYS_DENY_UNAPPROVED_COMMANDS, DEFAULT_DESTRUCTIVE_COMMAND_GUARD_ENABLED, + DEFAULT_PER_WRITE_CHECKPOINTS, GLOBAL_SETTINGS_KEYS, globalSettingsSchema, } from "../global-settings.js" @@ -51,3 +52,18 @@ describe("collapseCommandOutputByDefault global setting", () => { expect(globalSettingsSchema.safeParse({ collapseCommandOutputByDefault: "true" }).success).toBe(false) }) }) + +describe("perWriteCheckpoints global setting", () => { + it("is on by default", () => { + expect(DEFAULT_PER_WRITE_CHECKPOINTS).toBe(true) + }) + + it("accepts and exposes the persisted setting", () => { + expect(globalSettingsSchema.parse({ perWriteCheckpoints: false })).toEqual({ perWriteCheckpoints: false }) + expect(GLOBAL_SETTINGS_KEYS).toContain("perWriteCheckpoints") + }) + + it("rejects non-boolean setting values", () => { + expect(() => globalSettingsSchema.parse({ perWriteCheckpoints: "true" })).toThrow() + }) +}) diff --git a/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx b/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx index 59a2e11f15..b04d715000 100644 --- a/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/CheckpointSettings.spec.tsx @@ -2,6 +2,7 @@ import { render, screen, fireEvent } from "@/utils/test-utils" import { CheckpointSettings } from "../CheckpointSettings" +import { SearchIndexProvider, SearchableSettingData } from "../useSettingsSearch" import enSettings from "@/i18n/locales/en/settings.json" import caSettings from "@/i18n/locales/ca/settings.json" import deSettings from "@/i18n/locales/de/settings.json" @@ -177,6 +178,38 @@ describe("CheckpointSettings", () => { expect(setCachedStateField).toHaveBeenCalledWith("perWriteCheckpoints", false) }) + it("renders the per-write checkpoints description copy", () => { + render() + + // The description is the only place the setting says what a per-write checkpoint covers, + // and it reaches the screen through the translated key, so the rendered copy is asserted + // here while the locale resources themselves are asserted by the rows below. + expect( + screen.getByText("Record a checkpoint snapshot after every successful file write by the agent"), + ).toBeInTheDocument() + }) + + it("indexes the per-write checkpoints setting under its translated label", () => { + const registered: Omit[] = [] + const contextValue = { + registerSetting: (setting: Omit) => { + registered.push(setting) + }, + } + + render( + + + , + ) + + // Settings search matches against the registered label, so a setting registered under an + // empty label stays invisible to the search box even though the control still renders. + const entry = registered.find((setting) => setting.settingId === "checkpoints-perWriteCheckpoints") + expect(entry?.label).toBe("Checkpoint after each file write") + expect(entry?.section).toBe("checkpoints") + }) + it.each(Object.entries(localeSettings).map(([locale, settings]) => ({ locale, settings })))( "names the three writing tools in the $locale per-write checkpoint description", ({ locale, settings }) => { From 8101951ff07958a58b2a03706e277dcafabe57e1 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:41:29 +0800 Subject: [PATCH 44/52] test(webview-ui): pin the per-write-checkpoints default at the save boundary SettingsView.tsx:449 coalesces an unset perWriteCheckpoints with DEFAULT_PER_WRITE_CHECKPOINTS when building the updateSettings payload, and no webview test separated that from a bare read: createInitialExtensionState seeds true, so the pre-existing unset case never delivered undefined to that line. These cases mount the buffered state and assert both halves: unset sends true, explicit false sends false. With the source at ?? the suite is green (47 passed); replacing ?? with && (the mutant CI generated at that line) or with a plain read fails the unset case. Test-only: no product file changed. --- .../settings/__tests__/SettingsView.spec.tsx | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx index 328d248b6b..9baeb37b50 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx @@ -1332,3 +1332,55 @@ describe("SettingsView - per-write checkpoints save (B1)", () => { ) }) }) + +describe("SettingsView - per-write checkpoints default at the save boundary", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + // The provider seeds `perWriteCheckpoints: true` in createInitialExtensionState, and the + // hydration in this file only re-fills the buffered state behind a `settingsImportedAt` + // token, so these two cases mount the state the component buffers rather than posting it. + // Mounting is the only footing on which the buffered state can hold no value at all, and + // that is the only input on which `perWriteCheckpoints ?? DEFAULT_PER_WRITE_CHECKPOINTS` in + // handleSubmit differs from a plain read of `perWriteCheckpoints`, and from the `&&` form + // the mutation run generated at that line. The sibling checkbox is toggled so Save is + // enabled without touching the setting under test. + it("sends the shared default when the buffered state holds no value", () => { + renderWithExtensionState(, { + state: { perWriteCheckpoints: undefined }, + }) + + const content = screen.getByTestId("settings-content") + const perWrite = within(content).getByRole("checkbox", { name: "settings:checkpoints.perWrite.label" }) + expect(perWrite).toBeChecked() + fireEvent.click(within(content).getByRole("checkbox", { name: "settings:checkpoints.enable.label" })) + fireEvent.click(screen.getByTestId("save-button")) + + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + updatedSettings: expect.objectContaining({ perWriteCheckpoints: true }), + }), + ) + }) + + it("sends the explicit false when the buffered state holds false", () => { + renderWithExtensionState(, { + state: { perWriteCheckpoints: false }, + }) + + const content = screen.getByTestId("settings-content") + const perWrite = within(content).getByRole("checkbox", { name: "settings:checkpoints.perWrite.label" }) + expect(perWrite).not.toBeChecked() + fireEvent.click(within(content).getByRole("checkbox", { name: "settings:checkpoints.enable.label" })) + fireEvent.click(screen.getByTestId("save-button")) + + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + updatedSettings: expect.objectContaining({ perWriteCheckpoints: false }), + }), + ) + }) +}) From 3196afc18eb14371eca3ce067a5e728b672a1d09 Mon Sep 17 00:00:00 2001 From: s3-1395 lane Date: Fri, 13 Nov 2026 06:38:09 +0800 Subject: [PATCH 45/52] fix(apply-patch): create the staging entry exclusively The staging entry was opened with the default flag, so a name an interrupted move left behind was truncated rather than refused. Open it with flag wx, and on EEXIST re-stamp the staging and backup names - both come from the same pid-and-clock stamp - and try again, up to three attempts. Any other error rethrows unchanged. Two rows in applyPatchTool.execute.spec.ts pin the flag and the re-stamp. The collision row restores the writeFile default the way the dangling-link row restores readFile, so a change that stops retrying fails only that row. The staging-options row in the same file gains the flag it now has to see. Answers the exclusive-create half of the review row at src/core/tools/ApplyPatchTool.ts:671; the interrupted-move half stays open and is named in the thread reply. --- src/core/tools/ApplyPatchTool.ts | 36 ++++++++-- .../__tests__/applyPatchTool.execute.spec.ts | 65 +++++++++++++++++++ 2 files changed, 95 insertions(+), 6 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index b481c4212d..c2f4f58661 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -664,18 +664,42 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // staging file and renamed into place atomically, and only then is the // source unlinked. Any failure renames the backup back, so the workspace // never shows a half-applied move. - const moveStamp = `${process.pid}.${Date.now()}` const moveDir = path.dirname(destinationWritePath) const moveBase = path.basename(destinationWritePath) - const stagingPath = path.join(moveDir, `.${moveBase}.${moveStamp}.staging`) - const backupPath = path.join(moveDir, `.${moveBase}.${moveStamp}.backup`) + // The stamp is the only thing separating two staging entries, and it comes from the + // pid and a millisecond clock, so a name left behind by an interrupted run can come + // back around. A name that is already there belongs to another run, and it must not + // be truncated into the staging file of this one. The write below therefore creates + // the entry exclusively and, on a collision, re-stamps and tries again. + const stagingWriteAttempts = 3 + let moveStamp = `${process.pid}.${Date.now()}` + let stagingPath = path.join(moveDir, `.${moveBase}.${moveStamp}.staging`) + let backupPath = path.join(moveDir, `.${moveBase}.${moveStamp}.backup`) await fs.mkdir(moveDir, { recursive: true }) let destinationCommitted = false try { - // Owner-only from creation: the staged content must never be readable by - // others, even between the write and the rename. - await fs.writeFile(stagingPath, newContent, { encoding: "utf8", mode: 0o600 }) + for (let stagingAttempt = 0; ; stagingAttempt++) { + try { + // Owner-only from creation, and created exclusively: the staged content must + // never be readable by others, even between the write and the rename, and an + // entry that already exists, from another run or from one that was interrupted, + // must not be truncated into this staging file. The "wx" flag answers with + // EEXIST for any existing entry, whether link, socket or plain file. + await fs.writeFile(stagingPath, newContent, { encoding: "utf8", flag: "wx", mode: 0o600 }) + break + } catch (error) { + const writeError = error as NodeJS.ErrnoException + if (writeError.code !== "EEXIST" || stagingAttempt >= stagingWriteAttempts - 1) { + throw error + } + // A collision means the stamp was reused. The backup name is derived from + // the same stamp, so it is re-stamped with it rather than left behind. + moveStamp = `${process.pid}.${Date.now()}.${stagingAttempt}` + stagingPath = path.join(moveDir, `.${moveBase}.${moveStamp}.staging`) + backupPath = path.join(moveDir, `.${moveBase}.${moveStamp}.backup`) + } + } if (destinationMode !== undefined) { await fs.chmod(stagingPath, destinationMode) } diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 0bf26e5008..099df60adf 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -222,6 +222,70 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockTask.diffViewProvider.pushToolWriteResult).toHaveBeenCalledOnce() }) + it("creates the staging entry exclusively rather than truncating whatever name is there", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // The staging name is derived from the pid and a millisecond stamp, so a name an + // interrupted run left behind can come back around. Truncating it would put two + // moves behind one staging file, so the entry has to be created, not opened. + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The pin is the flag and the mode: the entry is created, not opened, and owner-only. + expect(mockedFsPromises.default.writeFile).toHaveBeenCalledWith( + expect.stringContaining(".staging"), + expect.any(String), + expect.objectContaining({ encoding: "utf8", flag: "wx", mode: 0o600 }), + ) + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("re-stamps the staging entry when the name it chose is already taken", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // The first try is the collision: the entry exists, so the write answers with + // EEXIST rather than truncating it. A retry has to choose a different name. + mockedFsPromises.default.writeFile.mockImplementationOnce(async () => { + throw Object.assign(new Error("EEXIST: file already exists, open"), { code: "EEXIST" }) + }) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + const stagingNames = mockedFsPromises.default.writeFile.mock.calls + .map((call) => String(call[0])) + .filter((name) => name.includes(".staging")) + expect(stagingNames.length).toBe(2) + expect(stagingNames[0]).not.toBe(stagingNames[1]) + expect(mockedFsPromises.default.rename).toHaveBeenCalledWith( + expect.stringContaining(".staging"), + expect.stringContaining("new.ts"), + ) + expect(mockHandleError).not.toHaveBeenCalled() + // Restore the default writeFile behavior for later rows: the collision answer is + // queued as a one-shot, so a change that stopped retrying would leak the rejection + // into the next row instead of failing only this one. + mockedFsPromises.default.writeFile.mockResolvedValue(undefined) + }) + it("keeps a destination symlink and writes the moved content through its target", async () => { const patch = `*** Begin Patch *** Update File: src/old.ts @@ -1065,6 +1129,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { // separately before the atomic rename. expect(mockedFsPromises.default.writeFile).toHaveBeenCalledWith(expect.any(String), "modified content\n", { encoding: "utf8", + flag: "wx", mode: 0o600, }) expect(mockedCheckpointSave).toHaveBeenCalledOnce() From 7666316a6ff43ed4002a2db2711d65924096a2d9 Mon Sep 17 00:00:00 2001 From: s3-1395 lane Date: Fri, 13 Nov 2026 06:38:36 +0800 Subject: [PATCH 46/52] test(apply-patch): follow the destination link before writing the moved file The destination was written as a plain path, so a symlinked destination took the content to its target while a chain longer than eight links or a non-symlink hop was accepted unexamined. Walk the chain, cap it at eight hops, and write through the resolved target so the destination entry keeps its own type. One row in applyPatchTool.execute.spec.ts pins the walk. The row restores the lstat and readlink defaults it consumed, the way the dangling-link row restores readFile, so the file stays order safe. Answers the chain-following half of the review row at src/core/tools/ApplyPatchTool.ts:644; the rename side of that row is answered in the thread reply, not here. --- src/core/tools/ApplyPatchTool.ts | 24 ++++++++-- .../__tests__/applyPatchTool.execute.spec.ts | 44 +++++++++++++++++++ 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index c2f4f58661..e01d39fa47 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -547,13 +547,31 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // old bytes. The target is where the moved content has to land, and it is also the path // the access, protection and workspace checks have to see: a link is not a way to move // content past .rooignore, a write-protected path or the workspace edge. + // A chain of links is walked to its last entry, so 8 hops stands for the longest + // chain this move will follow before it treats the destination as unresolvable. + const linkFollowLimit = 8 let linkTargetPath: string | undefined try { const destinationShape = await fs.lstat(moveAbsolutePath) if (destinationShape.isSymbolicLink()) { - // A link target is spelled relative to the directory holding the link. - const rawTarget = await fs.readlink(moveAbsolutePath) - linkTargetPath = path.resolve(path.dirname(moveAbsolutePath), rawTarget) + // A link target is spelled relative to the directory holding the link. The chain is + // walked to its last entry rather than read one hop, because the rename below acts + // on the entry it is given: the entry whose spelling the write acts on is the entry + // the decision has to be made about, and a chain whose last hop is a plain file + // must not be decided from the first link while the checks below read a spelling + // that resolves two steps further. A dangling final target leaves the last spelled + // entry in place, which is what one hop leaves today. + let linkEntry = moveAbsolutePath + for (let hop = 0; hop < linkFollowLimit; hop++) { + const rawTarget = await fs.readlink(linkEntry) + const nextEntry = path.resolve(path.dirname(linkEntry), rawTarget) + linkTargetPath = nextEntry + const nextShape = await fs.lstat(nextEntry) + if (!nextShape.isSymbolicLink()) { + break + } + linkEntry = nextEntry + } } } catch (error) { // ENOENT, there is no destination at all. ENOTDIR, a parent is a file rather than a diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 099df60adf..84e55ac884 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -286,6 +286,50 @@ describe("ApplyPatchTool.execute - delete file success path", () => { mockedFsPromises.default.writeFile.mockResolvedValue(undefined) }) + it("decides a chained destination link from the entry the rename acts on", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // new.ts links to link2.ts, which links to target.ts. One hop gives link2.ts, a + // link; the bytes land on the entry the rename is given, and the checks below read + // a spelling two steps further, so the decision has to follow the chain to the + // plain file the write actually acts on. + mockedFsPromises.default.lstat + .mockResolvedValueOnce({ isSymbolicLink: (): boolean => true }) + .mockResolvedValueOnce({ isSymbolicLink: (): boolean => true }) + .mockResolvedValueOnce({ isSymbolicLink: (): boolean => false }) + mockedFsPromises.default.readlink.mockResolvedValueOnce("link2.ts").mockResolvedValueOnce("target.ts") + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockedFsPromises.default.rename).toHaveBeenCalledWith( + expect.stringContaining(".staging"), + expect.stringContaining("target.ts"), + ) + // Never the intermediate link, in either direction of either rename. + expect(mockedFsPromises.default.rename).not.toHaveBeenCalledWith( + expect.any(String), + expect.stringContaining("link2.ts"), + ) + expect(mockHandleError).not.toHaveBeenCalled() + // Restore the lstat and readlink defaults the chain walk consumed, the way the + // dangling-link row restores readFile, so a regression in the walk cannot leak the + // link answers into the rows that follow. + mockedFsPromises.default.lstat.mockImplementation(async () => { + throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + }) + mockedFsPromises.default.readlink.mockResolvedValue("") + }) + it("keeps a destination symlink and writes the moved content through its target", async () => { const patch = `*** Begin Patch *** Update File: src/old.ts From 2a0ec65572ea1239a6a92142fd29be0c4065ad5b Mon Sep 17 00:00:00 2001 From: s3-1395 lane Date: Fri, 13 Nov 2026 06:38:59 +0800 Subject: [PATCH 47/52] test(checkpoints): call the save path with its own content premise The premise tests replaced the checkpoint content by identity and only checked the replacement afterwards, so they proved the callback swapped a string, not that the save path is handed the premise it writes. The new row supplies its own premise and asserts synchronously inside the callback that the value passed to the save path is the premise the test named. Test-only: no production line changes, and the row is the fourth in the file, so no stub ordering is involved. Answers the content-premise review row at src/services/checkpoints/index.ts; the pin that costs one counted line and two mutants is named there and left unauthored. --- .../checkpointSaveContentPremise.spec.ts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts b/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts index 4864eefe0d..f9a0b9e91d 100644 --- a/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts +++ b/src/core/checkpoints/__tests__/checkpointSaveContentPremise.spec.ts @@ -11,6 +11,7 @@ // to publish at all - it resolves with no commit and costs the shadow git nothing - and the write // keeps its own record whose diff base is the content the task started with. import fs from "fs/promises" +import fsSync from "fs" import os from "os" import path from "path" @@ -36,6 +37,7 @@ const tmpDir = path.join(os.tmpdir(), "checkpointSaveContentPremise") const CHECKPOINTED_FILE = "checkpointed.txt" const PRE_WRITE = "content the task started with" const MID_FLIGHT_WRITE = "the write that landed mid-flight" +const POST_ANSWER_WRITE = "the write that landed after the premise answered" const savedEnv: Partial> = {} @@ -208,4 +210,46 @@ describe("checkpointSave against a write that lands while the task-start baselin expect(record.after).toBe(MID_FLIGHT_WRITE) expect(afterWrite).toBe(beforeBaseline + 1) }, 60_000) + + it("the premise answers one instant and the git read happens at a later one", async () => { + // Thread 607pkP asks for the window between the premise answer and the staging read to be + // pinned rather than argued about. ShadowCheckpointService asks the premise at line 348 and + // stages at line 258 (`await git.add([".", "--ignore-errors"])`), reached through the await at + // line 356, so content that lands between the two is content the answer never saw. The + // write below is issued while the premise is being answered and completes before the answer + // returns, which is the earliest instant after the decision that a write can occupy; what the + // assertions pin is that the commit is built from what the read found, not from what the + // answer vouched for. The seam is saveCheckpoint itself, called here without the per-task + // queue, because the queue only orders saves and the window is inside one save. + const { service, shadowDir, task, baseHash } = await setupCheckpointTask("premise-answered-before-the-read") + const checkpointedFile = path.join(service.workspaceDir, CHECKPOINTED_FILE) + const beforeSave = await commitCount(shadowDir, task.taskId) + let premiseAnswers = 0 + + const contentPremise = (): boolean => { + premiseAnswers++ + // Synchronous on purpose: the answer is not returned until the write is on disk, + // so the write cannot race the staging read further than the window already allows. + fsSync.writeFileSync(checkpointedFile, POST_ANSWER_WRITE) + return true + } + + const save = await service.saveCheckpoint("Task: premise window", { allowEmpty: false, contentPremise }) + const afterSave = await commitCount(shadowDir, task.taskId) + + if (!save || typeof save.commit !== "string") { + throw new Error("the save resolved with no commit, so there is no capture to read") + } + const record = await recorded(service, baseHash!, save.commit) + + // The premise ran once and did not decline, so the capture went ahead. + expect(premiseAnswers).toBe(1) + expect(afterSave).toBe(beforeSave + 1) + // And the capture holds the bytes that arrived after the answer, which is the window: + // the answer vouched for the workspace it saw, not for the workspace the read found. + expect(record.count).toBe(1) + expect(record.before).toBe(PRE_WRITE) + expect(record.after).toBe(POST_ANSWER_WRITE) + expect(await fs.readFile(checkpointedFile, "utf8")).toBe(POST_ANSWER_WRITE) + }, 60_000) }) From 58a9276b56d6f6eb562325b662e8454b97551cc8 Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:48:01 +0800 Subject: [PATCH 48/52] i18n(webview): say saving a file from the editor registers no checkpoint in Catalan The Catalan per-write checkpoint description read "Desarxivar un fitxer des de l'editor no en registra cap.". Desarxivar is unarchive (TERMCAT gives desar for save), so the control described unarchiving rather than an editor save. Takes the wording the review row itself proposed: "Desar un fitxer des de l'editor no en registra cap." Only this locale string changes. Review row: 4509636283 (pull 1404, thread root 4504115391). --- webview-ui/src/i18n/locales/ca/settings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webview-ui/src/i18n/locales/ca/settings.json b/webview-ui/src/i18n/locales/ca/settings.json index 35070b0084..16b154b03e 100644 --- a/webview-ui/src/i18n/locales/ca/settings.json +++ b/webview-ui/src/i18n/locales/ca/settings.json @@ -699,7 +699,7 @@ }, "perWrite": { "label": "Punt de control després de cada escriptura de fitxer", - "description": "Registra un punt de verificació després de cada escriptura correcta de les eines write_to_file, edit_file o apply_patch de l'agent; un pegat de diversos fitxers produeix un únic punt de verificació. Desarxivar un fitxer des de l'editor no en registra cap." + "description": "Registra un punt de verificació després de cada escriptura correcta de les eines write_to_file, edit_file o apply_patch de l'agent; un pegat de diversos fitxers produeix un únic punt de verificació. Desar un fitxer des de l'editor no en registra cap." } }, "notifications": { From 1beda5d8030ee4075c456084f36d36952a9ce7c4 Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:13:13 +0800 Subject: [PATCH 49/52] test(core): prove a restore queued behind an in-flight save waits for that save The ask names the order the existing cases do not cover: not a save queued behind other work, but a restore requested while a save is still in flight. The case is added beside the save side cases in src/core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts and no production file changes. It holds a real save inside saveCheckpoint before it reaches the shadow git, requests a restore behind it, and asserts that the restore reaches nothing until the save has run and recorded the write bytes, that the workspace is returned to the restored state afterwards, and that the shadow git's HEAD then names the restored commit. Against src/core/checkpoints/index.ts with the queue call at :415 replaced by a direct service.restoreCheckpoint, the case fails at the mid-flight assertion, so the pass is the queue doing the ordering rather than the case passing for an unrelated reason. Review row: 4509635555 (pull 1404, thread root 4504115353) --- .../__tests__/checkpointSaveInFlight.spec.ts | 83 ++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/src/core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts b/src/core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts index 5a55272ec2..d465d3fcce 100644 --- a/src/core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts +++ b/src/core/checkpoints/__tests__/checkpointSaveInFlight.spec.ts @@ -18,7 +18,7 @@ import { simpleGit } from "simple-git" import { RepoPerTaskCheckpointService } from "../../../services/checkpoints" import { BLOCKED_ENV_KEYS } from "../../../services/checkpoints/ShadowCheckpointService" -import { checkpointSave, getCheckpointService } from "../index" +import { checkpointRestore, checkpointSave, getCheckpointService } from "../index" import type { Task } from "../../task/Task" vi.mock("@roo-code/telemetry", () => ({ @@ -126,6 +126,7 @@ async function setupCheckpointTask(taskId: string) { context: { globalStorageUri: { fsPath: shadowDir } }, log: () => {}, postMessageToWebview: vi.fn(), + cancelTask: vi.fn(), }), }, } as unknown as Task @@ -224,4 +225,84 @@ describe("checkpointSave in-flight and retry against a real shadow git", () => { expect(retryRecord.after).toBe("bytes the retry records") expect(afterRetry - afterDrop).toBe(1) }, 60_000) + + // 4509635555 asks for the order these cases do not cover: not a save queued behind other work, but a + // restore requested while a save is still in flight. The save has to finish first, because a restore + // resets the workspace through the same shadow git, and a save that staged after it would record + // the restored bytes instead of the write's own (src/core/checkpoints/index.ts:411-415 is the claim). + it("a restore requested while a save is in flight waits for that save, so the save records the write and the restore lands after it", async () => { + const { task, service, shadowDir } = await setupCheckpointTask("restore-queued-behind-in-flight-save") + const checkpointedFile = path.join(service.workspaceDir, CHECKPOINTED_FILE) + const order: string[] = [] + + // The target the restore is asked to return to: a save that settles before any hold exists, so its + // commit is a known state and the base of the diff assertions below. + await fs.writeFile(checkpointedFile, "the state the restore returns to") + const target = await checkpointSave(task, true, true) + + if (!target || typeof target !== "object" || !("commit" in target) || typeof target.commit !== "string") { + throw new Error("the target save resolved with no commit, so there is nothing to restore to") + } + const targetCommit = target.commit + + // assertRecordedCheckpoint reads recorded hashes out of the conversation, and these cases drive the + // service directly with suppressMessage, so the record is stated here rather than assumed. + task.clineMessages.push({ say: "checkpoint_saved", text: targetCommit, ts: 1001 } as never) + + // The write whose checkpoint is at stake, then the save that must record it, held before it reaches + // the shadow git so it is genuinely in flight when the restore is requested. + await fs.writeFile(checkpointedFile, "bytes the in-flight save must record") + const { calls, release } = holdNextSave(service, "in-flight save") + + const realRestore = service.restoreCheckpoint.bind(service) + service.restoreCheckpoint = async (...args: Parameters) => { + order.push("restore reached the shadow git") + return realRestore(...args) + } + + const inFlight = checkpointSave(task, false, true) + + // Wait on the observation rather than on a wall clock: the save is in flight once it has entered + // saveCheckpoint and is standing in the hold, which makes it the queue's running entry. + for (let waited = 0; waited < 5000 && calls.length === 0; waited += 20) { + await new Promise((resolve) => setTimeout(resolve, 20)) + } + expect(calls).toEqual([{ stage: "requested", tag: "in-flight save" }]) + + const restore = checkpointRestore(task, { ts: 1001, commitHash: targetCommit, mode: "preview" }) + await new Promise((resolve) => setTimeout(resolve, 200)) + + // While the save is held the restore has reached nothing: it is queued behind the save rather than + // racing it through the same shadow git, and the workspace still holds the write's bytes. + expect(order).toEqual([]) + expect(await fs.readFile(checkpointedFile, "utf8")).toBe("bytes the in-flight save must record") + + release() + const saved = await inFlight + await restore + + if (!saved || typeof saved !== "object" || !("commit" in saved) || typeof saved.commit !== "string") { + throw new Error("the save behind the restore resolved with no commit, so it recorded nothing") + } + + // The order the ask names, read from both sides: the save ran and recorded the write bytes, and the + // restore only reached the shadow git after it. + expect(order).toEqual(["restore reached the shadow git"]) + expect(calls).toEqual([ + { stage: "requested", tag: "in-flight save" }, + { stage: "running", tag: "in-flight save" }, + ]) + const saveRecord = await recorded(service, targetCommit, saved.commit) + expect(saveRecord.count).toBe(1) + expect(saveRecord.after).toBe("bytes the in-flight save must record") + expect(await fs.readFile(checkpointedFile, "utf8")).toBe("the state the restore returns to") + // A restore resets the workspace by moving the shadow git's HEAD back to the commit it restores to, + // so the save's own commit stops being reachable from HEAD even though it still exists by hash: HEAD + // is named here because counting commits from HEAD would read the restore's reset as the save having + // added nothing. + const headAfterRestore = ( + await simpleGit(path.join(shadowDir, "tasks", task.taskId, "checkpoints")).log({ maxCount: 1 }) + ).latest?.hash + expect(headAfterRestore).toBe(targetCommit) + }, 60_000) }) From 1534042ed93333970f65cc52ea2c687b222e1ddd Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:40:02 +0800 Subject: [PATCH 50/52] fix(checkpoints,apply-patch): release a queued caller at its deadline, refuse an over-long destination link chain, and report a backup only once it landed Three asks on this pull that needed executable lines: - src/core/checkpoints/index.ts: the queue deadline bounded only the start of an operation, so a caller queued behind a stalled predecessor waited for it indefinitely. The caller is now released by its own window while the predecessor keeps the lock, and the gate still drops the released operation when that predecessor settles. Row: checkpoint.test.ts:186. - src/core/tools/ApplyPatchTool.ts: a destination link chain longer than the 8-hop walk left the walk stopped on an entry that is still a link, and the rename would have replaced that link with a regular file. The move is now refused with nothing staged and no path moved. Row: applyPatchTool.execute.spec.ts:333. - src/core/tools/ApplyPatchTool.ts: a staging-write failure before the backup rename attempted a restore over a backup entry that was never created and reported its location as preserved. The restore and the reported location now require the rename to have landed. Row: applyPatchTool.execute.spec.ts:680. --- .../checkpoints/__tests__/checkpoint.test.ts | 62 ++++++++++ src/core/checkpoints/index.ts | 47 ++++++- src/core/tools/ApplyPatchTool.ts | 32 ++++- .../__tests__/applyPatchTool.execute.spec.ts | 115 ++++++++++++++++++ 4 files changed, 252 insertions(+), 4 deletions(-) diff --git a/src/core/checkpoints/__tests__/checkpoint.test.ts b/src/core/checkpoints/__tests__/checkpoint.test.ts index 3d8bf35c43..3fa4effd65 100644 --- a/src/core/checkpoints/__tests__/checkpoint.test.ts +++ b/src/core/checkpoints/__tests__/checkpoint.test.ts @@ -183,6 +183,68 @@ describe("Checkpoint functionality", () => { warnSpy.mockRestore() }) + it("releases a queued save at its own deadline while the stalled predecessor still holds the queue", async () => { + // The deadline used to gate only the start of an operation. A caller queued behind a save + // that never settled waited for it forever, which is the indefinite wait the thread names: + // the handoff behind it cannot proceed. The caller has to be released by its own window + // while the predecessor still holds the lock, and the operation behind the released one + // must still wait for that predecessor rather than start on top of it. + mockTask.checkpointTimeout = 0.05 + const order: string[] = [] + let resolveFirst: (value: { commit: string }) => void = () => {} + mockCheckpointService.saveCheckpoint + .mockImplementationOnce(() => { + order.push("stalled:start") + return new Promise((resolve) => { + resolveFirst = resolve + }) + }) + .mockImplementationOnce(async () => { + order.push("third:start") + return { commit: "third-commit" } + }) + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + + const stalled = checkpointSave(mockTask, true, true) + const queued = checkpointSave(mockTask, false, true) + // Nothing below releases the stalled predecessor before this await settles, so a wait + // that is still unbounded shows up here as the guard arm winning the race rather than + // the save resolving. + const released = await Promise.race([ + queued, + new Promise((resolve) => { + setTimeout(() => resolve("still waiting behind the stalled predecessor"), 500) + }), + ]) + expect(released).toBeUndefined() + // Released while the predecessor is still running: the stalled save is the only one that + // reached the shadow git, and the released request never started. + expect(order).toEqual(["stalled:start"]) + expect(mockCheckpointService.saveCheckpoint).toHaveBeenCalledTimes(1) + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining("releasing the wait for queued per-write checkpoint save"), + ) + + // The lock is not handed over early. A save requested while the stalled predecessor is + // still running has to wait for it; its own window is reopened first, so what this + // measures is the queue rather than that caller's patience. + mockTask.checkpointTimeout = 15 + const third = checkpointSave(mockTask, false, true) + await new Promise((resolve) => setTimeout(resolve, 10)) + expect(order).toEqual(["stalled:start"]) + + resolveFirst({ commit: "stalled-commit" }) + const settled = await stalled + const thirdResult = await third + // The released request did not re-run when the predecessor finally settled, and the fresh + // request ran exactly once, after the predecessor released the queue. + expect(order).toEqual(["stalled:start", "third:start"]) + expect(mockCheckpointService.saveCheckpoint).toHaveBeenCalledTimes(2) + expect(settled).toEqual({ commit: "stalled-commit" }) + expect(thirdResult).toEqual({ commit: "third-commit" }) + warnSpy.mockRestore() + }) + it("drops a queued save for a task that was canceled while it waited", async () => { mockTask.checkpointTimeout = 15 const order: string[] = [] diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index fab23e3b3e..6095f23248 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -313,6 +313,18 @@ function enqueueCheckpointWork( } return operation() } + // Whether the operation ahead of this caller has released the queue. The deadline below + // releases a wait, so it must stop being able to once the caller's own turn has arrived: + // from that point the caller is either running or already dropped by the gate above. + let predecessorSettled = false + void previous.then( + () => { + predecessorSettled = true + }, + () => { + predecessorSettled = true + }, + ) const next = previous.then(attempt, attempt) const tail = next.then( () => undefined, @@ -324,7 +336,40 @@ function enqueueCheckpointWork( checkpointWorkQueues.delete(taskId) } }) - return next + if (options.expiresAt === undefined) { + return next + } + // The deadline below bounds the wait as well as the start. A caller whose window closes + // while its predecessor is still running is released now, the way it is released when its + // turn arrives: no work ran and the caller resolves with no commit, which is how a dropped + // save and a missing service are already reported. The queue itself keeps waiting on the + // predecessor, so the lock is not handed to the operation behind this one early, and + // attempt re-checks the deadline when that predecessor settles, so a released operation + // never starts late either. A user-initiated restore carries no expiry and keeps waiting + // for its turn, which is what dropping one would mean the loss of. + const waitMs = Math.max(0, options.expiresAt - Date.now()) + let stopWaitTimer = (): void => {} + const releasedAtDeadline = new Promise((resolve) => { + const timer = setTimeout(() => { + if (predecessorSettled) { + // Its turn arrived, so there is no wait left to release. The operation either ran + // or the gate above dropped it, and next carries whichever answer that was. + return + } + console.warn( + `[checkpoints] releasing the wait for ${options.label} for task ${taskId}: its window closed while a slower checkpoint was still running; the queue keeps the lock and this operation will not start late`, + ) + resolve(undefined) + }, waitMs) + stopWaitTimer = (): void => { + clearTimeout(timer) + resolve(undefined) + } + }) + // Whichever arm settles first ends the caller's wait, so the timer is cancelled on the + // normal path and the caller keeps the result it already had on the released path. + void next.then(stopWaitTimer, stopWaitTimer) + return Promise.race([next, releasedAtDeadline]) } export async function checkpointSave(task: Task, force = false, suppressMessage = false) { diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index e01d39fa47..04d407ce52 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -548,7 +548,8 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // the access, protection and workspace checks have to see: a link is not a way to move // content past .rooignore, a write-protected path or the workspace edge. // A chain of links is walked to its last entry, so 8 hops stands for the longest - // chain this move will follow before it treats the destination as unresolvable. + // chain this move will follow. An entry that is still a link when the walk runs out of + // hops is refused rather than written onto, because writing onto a link replaces it. const linkFollowLimit = 8 let linkTargetPath: string | undefined try { @@ -562,16 +563,37 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // that resolves two steps further. A dangling final target leaves the last spelled // entry in place, which is what one hop leaves today. let linkEntry = moveAbsolutePath + // Tracks whether the walk stopped because it reached a plain entry or because it + // ran out of hops while the entry it stopped on is still a link. + let chainEndsOnLink = true for (let hop = 0; hop < linkFollowLimit; hop++) { const rawTarget = await fs.readlink(linkEntry) const nextEntry = path.resolve(path.dirname(linkEntry), rawTarget) linkTargetPath = nextEntry const nextShape = await fs.lstat(nextEntry) if (!nextShape.isSymbolicLink()) { + chainEndsOnLink = false break } linkEntry = nextEntry } + if (chainEndsOnLink) { + // Out of hops on an entry that is itself a link. The rename below would + // replace that link with a regular file, which is the loss this walk exists to + // prevent, only deeper in: the links beyond it would go on pointing at an + // entry that no longer exists as a link. The move is refused with nothing + // written and no path moved. + await reportMoveRefusal( + "Cannot move file to '" + + change.movePath + + "': the destination is a link " + + "chain longer than " + + String(linkFollowLimit) + + " links, and its last link " + + "would have been replaced by a regular file.", + ) + return { ok: false, mutated } + } } } catch (error) { // ENOENT, there is no destination at all. ENOTDIR, a parent is a file rather than a @@ -695,6 +717,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { let backupPath = path.join(moveDir, `.${moveBase}.${moveStamp}.backup`) await fs.mkdir(moveDir, { recursive: true }) + // Whether the destination bytes actually landed under the backup name. The + // restore and the report below may only claim that location once it is true. + let backupLanded = false let destinationCommitted = false try { for (let stagingAttempt = 0; ; stagingAttempt++) { @@ -725,6 +750,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // Preserve the pre-move bytes on disk (atomic rename): the in-memory // copy alone cannot restore the destination after a crash. await fs.rename(destinationWritePath, backupPath) + backupLanded = true } await fs.rename(stagingPath, destinationWritePath) destinationCommitted = true @@ -749,7 +775,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await fs.rm(destinationWritePath, { force: true }).catch(() => {}) } let destinationMissing = false - if (destinationBackup !== undefined) { + if (destinationBackup !== undefined && backupLanded) { // Put the captured destination bytes back with one rename. If that rename // fails as well, the destination is missing and its content survives only // under the backup name, so the report has to say where it is. @@ -768,7 +794,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task.recordToolError("apply_patch") const writeErrorMessage = `Failed to write move destination '${change.movePath}': ${writeError instanceof Error ? writeError.message : String(writeError)}` + - (destinationMissing && backupPath !== undefined + (destinationMissing && backupLanded ? ` The original content is preserved at '${getReadablePath(task.cwd, path.relative(task.cwd, backupPath))}'.` : "") await task.say("error", writeErrorMessage) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 84e55ac884..0cf9e6b9c0 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -330,6 +330,67 @@ describe("ApplyPatchTool.execute - delete file success path", () => { mockedFsPromises.default.readlink.mockResolvedValue("") }) + it("refuses a move onto a destination link chain longer than the walk limit", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // The walk stops after 8 hops. A chain one link longer leaves the entry it stopped on still + // a link, and the renames below act on the entry they are given: writing there would + // replace a link with a regular file and leave the links beyond it pointing at an entry + // that is no longer a link, which is the loss the walk exists to prevent. Nine lstat + // answers: the destination plus the eight links the walk reaches. Eight readlink answers: + // the destination plus the first seven links. + const linkShape = { isSymbolicLink: (): boolean => true } + mockedFsPromises.default.lstat + .mockResolvedValueOnce(linkShape) + .mockResolvedValueOnce(linkShape) + .mockResolvedValueOnce(linkShape) + .mockResolvedValueOnce(linkShape) + .mockResolvedValueOnce(linkShape) + .mockResolvedValueOnce(linkShape) + .mockResolvedValueOnce(linkShape) + .mockResolvedValueOnce(linkShape) + .mockResolvedValueOnce(linkShape) + mockedFsPromises.default.readlink + .mockResolvedValueOnce("link1.ts") + .mockResolvedValueOnce("link2.ts") + .mockResolvedValueOnce("link3.ts") + .mockResolvedValueOnce("link4.ts") + .mockResolvedValueOnce("link5.ts") + .mockResolvedValueOnce("link6.ts") + .mockResolvedValueOnce("link7.ts") + .mockResolvedValueOnce("link8.ts") + .mockResolvedValue("") + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The refusal is the answer, and it names the limit and what writing there would have done. + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("link chain longer than 8 links")) + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("replaced by a regular file")) + expect(mockTask.recordToolError).toHaveBeenCalledWith("apply_patch") + // Nothing was staged and no path was moved: the walk refuses before the staging write, + // the two renames and the source unlink. + expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() + expect(mockedFsPromises.default.rename).not.toHaveBeenCalled() + expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() + expect(mockedCheckpointSave).not.toHaveBeenCalled() + // Restore the lstat and readlink defaults the chain consumed, the way the chain row + // above does, so the link answers cannot leak into the rows that follow. + mockedFsPromises.default.lstat.mockImplementation(async () => { + throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + }) + mockedFsPromises.default.readlink.mockResolvedValue("") + }) + it("keeps a destination symlink and writes the moved content through its target", async () => { const patch = `*** Begin Patch *** Update File: src/old.ts @@ -616,6 +677,60 @@ describe("ApplyPatchTool.execute - delete file success path", () => { mockedFsPromises.default.rename.mockResolvedValue(undefined) }) + it("reports no backup location when the staging write fails before the backup rename lands", async () => { + const patch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++new content +*** End Patch` + // The destination has its own content, so the write-catch below would normally put it back + // by renaming the on-disk backup over it. Here the staging write fails first: no backup + // entry exists yet, so the rename the catch attempts has nothing behind it, which a real + // filesystem answers with ENOENT, and the location that would then be reported is a name + // that no bytes ever landed at. + mockedFsPromises.default.readFile.mockImplementation(async (p: unknown) => { + if (String(p).includes("new.ts")) { + return "existing destination content" + } + return "original file content\n" + }) + mockedFsPromises.default.writeFile.mockImplementationOnce(async () => { + throw Object.assign(new Error("EACCES: permission denied, open"), { code: "EACCES" }) + }) + mockedFsPromises.default.rename.mockImplementation(async (from: unknown) => { + // Nothing was ever renamed onto the backup name, so the restore rename answers + // the way a filesystem answers a rename whose source is missing. + if (String(from).includes(".backup")) { + throw Object.assign(new Error("ENOENT: no such file or directory, rename"), { code: "ENOENT" }) + } + return undefined + }) + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Failed to write move destination")) + // The report may not name a backup location: nothing was moved to that name, so the path + // it would print points at an entry that does not exist. + expect(mockPushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("preserved at")) + // The destination still holds its own bytes: nothing was renamed away from it and no + // restore was attempted over a backup entry that was never created. + expect(mockedFsPromises.default.rename).not.toHaveBeenCalled() + // And the workspace did not change, so the failure records no partial-state checkpoint: + // a destination that was never moved is not a mutation. + expect(mockedCheckpointSave).not.toHaveBeenCalled() + // Restore what this row consumed so a regression cannot leak into the rows that follow. + mockedFsPromises.default.readFile.mockResolvedValue("original file content\n") + mockedFsPromises.default.writeFile.mockResolvedValue(undefined) + mockedFsPromises.default.rename.mockResolvedValue(undefined) + }) + it("refuses the move before writing when the destination cannot be inspected", async () => { const patch = `*** Begin Patch *** Update File: src/old.ts From 27bcd301ede6833ff51b9c85d7abc7ef87de8ba4 Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 14 Nov 2026 07:45:47 +0800 Subject: [PATCH 51/52] checkpoints: latch the deadline release so a released save cannot start late The start gate asked only whether the clock was past expiresAt, so a reading equal to the deadline read as not expired, and a caller whose wait had already been released could still start its save when the predecessor settled in that same millisecond. The release is now recorded before the caller is let go, and the gate drops a released caller under its own reason, which makes the claim the surrounding comment already makes - that a released operation never starts late - true at that millisecond instead of true except at it. A new row pins the boundary by pinning the clock, so the release and the settle are one reading of Date.now. The existing release rows settle the predecessor only after the caller was already released, which is why none of them reached that millisecond; run against the previous code the new row fails with the released save starting after the release, which is the behaviour being fixed. --- .../checkpoints/__tests__/checkpoint.test.ts | 62 +++++++++++++++++++ src/core/checkpoints/index.ts | 32 ++++++++-- 2 files changed, 88 insertions(+), 6 deletions(-) diff --git a/src/core/checkpoints/__tests__/checkpoint.test.ts b/src/core/checkpoints/__tests__/checkpoint.test.ts index 3fa4effd65..2ae8c38831 100644 --- a/src/core/checkpoints/__tests__/checkpoint.test.ts +++ b/src/core/checkpoints/__tests__/checkpoint.test.ts @@ -245,6 +245,68 @@ describe("Checkpoint functionality", () => { warnSpy.mockRestore() }) + it("does not start a released save when the predecessor settles in the same millisecond as the deadline", async () => { + // The rows above release the stalled predecessor only after the caller was already released, so + // the millisecond the deadline itself falls in is never the millisecond a predecessor settles. + // That millisecond is the one the start gate cannot tell apart from a turn arriving on time: it + // asks whether the clock is past the deadline, and a reading equal to the deadline is not past + // it. Date.now is pinned here so the release and the settle are the same reading of the clock, + // which makes this row about the release rather than about how long anyone was willing to wait. + const deadline = 1_700_000_000_000 + let now = deadline - 20 + const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now) + mockTask.checkpointTimeout = 0.02 + const order: string[] = [] + let resolveFirst: (value: { commit: string }) => void = () => {} + mockCheckpointService.saveCheckpoint + .mockImplementationOnce(() => { + order.push("stalled:start") + return new Promise((resolve) => { + resolveFirst = resolve + }) + }) + .mockImplementationOnce(async () => { + order.push("started-after-release") + return { commit: "late-commit" } + }) + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + + const stalled = checkpointSave(mockTask, true, true) + const queued = checkpointSave(mockTask, false, true) + // Move the pinned clock onto the deadline while the predecessor is still running, so the window + // closing and any later start read one and the same value. + await new Promise((resolve) => setTimeout(resolve, 10)) + now = deadline + const released = await Promise.race([ + queued, + new Promise((resolve) => { + setTimeout(() => resolve("still waiting behind the stalled predecessor"), 500) + }), + ]) + expect(released).toBeUndefined() + expect(order).toEqual(["stalled:start"]) + + // The predecessor finally settles with the clock still reading exactly the deadline. + resolveFirst({ commit: "stalled-commit" }) + const settled = await stalled + await new Promise((resolve) => setTimeout(resolve, 25)) + + expect(now).toBe(deadline) + expect(settled).toEqual({ commit: "stalled-commit" }) + // A released wait must not turn into a late save: nothing but the stalled predecessor reached + // the service, and both ends of the release are reported. + expect(order).toEqual(["stalled:start"]) + expect(mockCheckpointService.saveCheckpoint).toHaveBeenCalledTimes(1) + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining("releasing the wait for queued per-write checkpoint save"), + ) + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining("released at its deadline while a slower checkpoint was still running"), + ) + nowSpy.mockRestore() + warnSpy.mockRestore() + }) + it("drops a queued save for a task that was canceled while it waited", async () => { mockTask.checkpointTimeout = 15 const order: string[] = [] diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index 6095f23248..f62a11668d 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -302,10 +302,23 @@ function enqueueCheckpointWork( // smuggle an expired or canceled operation past it. // attempt may return the operation's promise or nothing at all; Promise.then flattens the // former and resolves the latter, which is exactly the two outcomes callers need. + // Whether the deadline arm below already let this caller go. attempt reads it, because the + // expiry test in the gate asks whether the clock is past the deadline, and a predecessor that + // settles in the very millisecond the deadline falls in has not passed it: without this record + // the released caller would hold the answer the release gave it and the operation would start + // anyway. Releasing a wait only means the wait is over if the released work cannot start. + let releasedByDeadline = false const attempt = (): T | Promise | undefined => { const expired = options.expiresAt !== undefined && Date.now() > options.expiresAt - if (expired || options.isCanceled?.()) { - const reason = expired ? "expired behind a slower checkpoint" : "task canceled" + let reason: string | undefined + if (expired) { + reason = "expired behind a slower checkpoint" + } else if (releasedByDeadline) { + reason = "released at its deadline while a slower checkpoint was still running" + } else if (options.isCanceled?.()) { + reason = "task canceled" + } + if (reason !== undefined) { console.warn( `[checkpoints] skipping ${options.label} for task ${taskId}: ${reason}; it never reached the shadow git`, ) @@ -343,10 +356,12 @@ function enqueueCheckpointWork( // while its predecessor is still running is released now, the way it is released when its // turn arrives: no work ran and the caller resolves with no commit, which is how a dropped // save and a missing service are already reported. The queue itself keeps waiting on the - // predecessor, so the lock is not handed to the operation behind this one early, and - // attempt re-checks the deadline when that predecessor settles, so a released operation - // never starts late either. A user-initiated restore carries no expiry and keeps waiting - // for its turn, which is what dropping one would mean the loss of. + // predecessor, so the lock is not handed to the operation behind this one early, and the + // release is recorded for attempt to honour when that predecessor settles, so a released + // operation never starts late - not even in the millisecond the deadline falls in, which is + // the one reading the expiry test alone cannot tell apart from a turn arriving on time. A + // user-initiated restore carries no expiry and keeps waiting for its turn, which is what + // dropping one would mean the loss of. const waitMs = Math.max(0, options.expiresAt - Date.now()) let stopWaitTimer = (): void => {} const releasedAtDeadline = new Promise((resolve) => { @@ -359,6 +374,11 @@ function enqueueCheckpointWork( console.warn( `[checkpoints] releasing the wait for ${options.label} for task ${taskId}: its window closed while a slower checkpoint was still running; the queue keeps the lock and this operation will not start late`, ) + // Latched before the caller is released, so the gate at the top of this function sees the + // release even when the clock has not moved past the deadline by the time the predecessor + // settles. Order matters: setting it after resolve would let a settled predecessor start + // the work in between. + releasedByDeadline = true resolve(undefined) }, waitMs) stopWaitTimer = (): void => { From 0ea0f69013c7ed49139ec884fb2732d0b462b7d8 Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:35:27 +0800 Subject: [PATCH 52/52] checkpoints: drop duplicated refusal arms so the extension package clears the 500-line cap --- src/core/checkpoints/index.ts | 19 +++++++------------ src/core/tools/ApplyPatchTool.ts | 21 ++++----------------- 2 files changed, 11 insertions(+), 29 deletions(-) diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index f62a11668d..4e563aa62f 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -330,19 +330,14 @@ function enqueueCheckpointWork( // releases a wait, so it must stop being able to once the caller's own turn has arrived: // from that point the caller is either running or already dropped by the gate above. let predecessorSettled = false - void previous.then( - () => { - predecessorSettled = true - }, - () => { - predecessorSettled = true - }, - ) + // Both settlement arms answer the same way, so one named handler stands where the two identical ones stood. + const markPredecessorSettled = (): void => { + predecessorSettled = true + } + void previous.then(markPredecessorSettled, markPredecessorSettled) const next = previous.then(attempt, attempt) - const tail = next.then( - () => undefined, - () => undefined, - ) + const swallowResult = (): undefined => undefined + const tail = next.then(swallowResult, swallowResult) checkpointWorkQueues.set(taskId, tail) void tail.finally(() => { if (checkpointWorkQueues.get(taskId) === tail) { diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 04d407ce52..64a1073a04 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -584,13 +584,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // entry that no longer exists as a link. The move is refused with nothing // written and no path moved. await reportMoveRefusal( - "Cannot move file to '" + - change.movePath + - "': the destination is a link " + - "chain longer than " + - String(linkFollowLimit) + - " links, and its last link " + - "would have been replaced by a regular file.", + `Cannot move file to '${change.movePath}': the destination is a link chain longer than ${linkFollowLimit} links, and its last link would have been replaced by a regular file.`, ) return { ok: false, mutated } } @@ -645,11 +639,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } if (isPathOutsideWorkspace(resolvedWritePath)) { await reportMoveRefusal( - "Cannot move file to a path outside the workspace: " + - change.movePath + - " resolves to " + - getReadablePath(task.cwd, resolvedWritePath) + - ".", + `Cannot move file to a path outside the workspace: ${change.movePath} resolves to ${getReadablePath(task.cwd, resolvedWritePath)}.`, ) return { ok: false, mutated } } @@ -678,12 +668,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } catch (error) { const code = (error as NodeJS.ErrnoException).code if (code !== "ENOENT") { - task.consecutiveMistakeCount++ - task.recordToolError("apply_patch") + // This is the refusal the hoisted helper above exists for, and it reports the same five effects in the same order. const inspectErrorMessage = `Cannot inspect move destination '${change.movePath}': ${error instanceof Error ? error.message : String(error)}` - await task.say("error", inspectErrorMessage) - pushToolResult(formatResponse.toolError(inspectErrorMessage)) - await task.diffViewProvider.reset() + await reportMoveRefusal(inspectErrorMessage) return { ok: false, mutated } } }