|
| 1 | +// npx vitest run core/tools/__tests__/applyDiffTool.changeCard.spec.ts |
| 2 | + |
| 3 | +import type { MockedFunction } from "vitest" |
| 4 | + |
| 5 | +import { fileExistsAtPath } from "../../../utils/fs" |
| 6 | +import { checkAutoApproval } from "../../auto-approval" |
| 7 | +import { checkpointSave } from "../../checkpoints" |
| 8 | +import type { Task } from "../../task/Task" |
| 9 | +import { ApplyDiffTool } from "../ApplyDiffTool" |
| 10 | + |
| 11 | +vi.mock("fs/promises", () => ({ |
| 12 | + default: { |
| 13 | + readFile: vi.fn().mockResolvedValue("original file content\n"), |
| 14 | + // The trial aggregate adds the S4b stat-pair self-observation around this |
| 15 | + // read (ApplyDiffTool records its own read under the ReadFileTool contract); |
| 16 | + // its `.catch(() => undefined)` fallback keeps the observation no-op when |
| 17 | + // stat rejects, so this spec stays green on both the component branch and |
| 18 | + // the trial aggregate. |
| 19 | + stat: vi.fn().mockRejectedValue(new Error("stat unavailable in this spec")), |
| 20 | + }, |
| 21 | +})) |
| 22 | + |
| 23 | +vi.mock("../../../utils/fs", () => ({ |
| 24 | + fileExistsAtPath: vi.fn().mockResolvedValue(true), |
| 25 | +})) |
| 26 | + |
| 27 | +vi.mock("../../prompts/responses", () => ({ |
| 28 | + formatResponse: { |
| 29 | + toolError: vi.fn((msg: string) => `Error: ${msg}`), |
| 30 | + rooIgnoreError: vi.fn((filePath: string) => `Access denied: ${filePath}`), |
| 31 | + createPrettyPatch: vi.fn(() => "mock-diff"), |
| 32 | + }, |
| 33 | +})) |
| 34 | + |
| 35 | +vi.mock("../../diff/stats", () => ({ |
| 36 | + // The real DiffStats shape is { added, removed } (the tool maps it to the |
| 37 | + // change-card { additions, deletions } pair). |
| 38 | + sanitizeUnifiedDiff: vi.fn((diff: string) => diff), |
| 39 | + computeDiffStats: vi.fn(() => ({ added: 1, removed: 1 })), |
| 40 | +})) |
| 41 | + |
| 42 | +vi.mock("../../checkpoints", () => ({ |
| 43 | + checkpointSave: vi.fn().mockResolvedValue(undefined), |
| 44 | +})) |
| 45 | + |
| 46 | +vi.mock("../../auto-approval", () => ({ |
| 47 | + checkAutoApproval: vi.fn().mockResolvedValue({ decision: "ask" }), |
| 48 | +})) |
| 49 | + |
| 50 | +describe("ApplyDiffTool.execute - per-write checkpoint and change card (B3a, epic #1375)", () => { |
| 51 | + const mockedFileExistsAtPath = fileExistsAtPath as MockedFunction<typeof fileExistsAtPath> |
| 52 | + const mockCheckpointSave = checkpointSave as MockedFunction<typeof checkpointSave> |
| 53 | + const mockCheckAutoApproval = checkAutoApproval as MockedFunction<typeof checkAutoApproval> |
| 54 | + |
| 55 | + let tool: ApplyDiffTool |
| 56 | + let mockTask: Pick< |
| 57 | + Task, |
| 58 | + | "cwd" |
| 59 | + | "consecutiveMistakeCount" |
| 60 | + | "consecutiveMistakeCountForApplyDiff" |
| 61 | + | "recordToolError" |
| 62 | + | "rooIgnoreController" |
| 63 | + | "rooProtectedController" |
| 64 | + | "processQueuedMessages" |
| 65 | + | "didEditFile" |
| 66 | + | "api" |
| 67 | + | "diffStrategy" |
| 68 | + | "diffViewProvider" |
| 69 | + | "providerRef" |
| 70 | + | "fileContextTracker" |
| 71 | + > |
| 72 | + let mockSaveDirectly: MockedFunction<(...args: unknown[]) => Promise<unknown>> |
| 73 | + let mockGetState: MockedFunction<() => Promise<Record<string, unknown>>> |
| 74 | + let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise<boolean>> |
| 75 | + let mockHandleError: MockedFunction<(...args: unknown[]) => Promise<void>> |
| 76 | + let mockPushToolResult: MockedFunction<(...args: unknown[]) => void> |
| 77 | + |
| 78 | + beforeEach(() => { |
| 79 | + vi.clearAllMocks() |
| 80 | + |
| 81 | + mockedFileExistsAtPath.mockResolvedValue(true) |
| 82 | + |
| 83 | + // Structural stubs for the prevent-focus-disruption save path: the real |
| 84 | + // DiffViewProvider is out of scope here, so vi.fn() doubles stand in for |
| 85 | + // the members the tool touches. |
| 86 | + mockSaveDirectly = vi.fn().mockResolvedValue({ |
| 87 | + newProblemsMessage: "", |
| 88 | + userEdits: undefined, |
| 89 | + finalContent: "new content", |
| 90 | + }) |
| 91 | + const diffViewProviderStub = { |
| 92 | + editType: undefined as "create" | "modify" | undefined, |
| 93 | + originalContent: undefined as string | undefined, |
| 94 | + saveDirectly: mockSaveDirectly, |
| 95 | + pushToolWriteResult: vi.fn().mockResolvedValue("Saved file"), |
| 96 | + reset: vi.fn().mockResolvedValue(undefined), |
| 97 | + } |
| 98 | + |
| 99 | + mockGetState = vi.fn().mockResolvedValue({ |
| 100 | + diagnosticsEnabled: true, |
| 101 | + writeDelayMs: 1000, |
| 102 | + // Exercise the focus-disruption (saveDirectly) save path. |
| 103 | + experiments: { preventFocusDisruption: true }, |
| 104 | + }) |
| 105 | + |
| 106 | + mockTask = { |
| 107 | + cwd: "/workspace/project", |
| 108 | + consecutiveMistakeCount: 0, |
| 109 | + consecutiveMistakeCountForApplyDiff: new Map(), |
| 110 | + recordToolError: vi.fn(), |
| 111 | + rooIgnoreController: { |
| 112 | + validateAccess: vi.fn().mockReturnValue(true), |
| 113 | + } as unknown as Task["rooIgnoreController"], |
| 114 | + rooProtectedController: { |
| 115 | + isWriteProtected: vi.fn().mockReturnValue(false), |
| 116 | + } as unknown as Task["rooProtectedController"], |
| 117 | + processQueuedMessages: vi.fn(), |
| 118 | + didEditFile: false, |
| 119 | + api: { |
| 120 | + getModel: () => ({ id: "claude-sonnet-4-5" }), |
| 121 | + } as unknown as Task["api"], |
| 122 | + diffStrategy: { |
| 123 | + applyDiff: vi.fn().mockResolvedValue({ success: true, content: "modified file content\n" }), |
| 124 | + } as unknown as Task["diffStrategy"], |
| 125 | + diffViewProvider: diffViewProviderStub as unknown as Task["diffViewProvider"], |
| 126 | + providerRef: { |
| 127 | + deref: vi.fn().mockReturnValue({ |
| 128 | + getState: mockGetState, |
| 129 | + }), |
| 130 | + } as unknown as Task["providerRef"], |
| 131 | + fileContextTracker: { |
| 132 | + trackFileContext: vi.fn().mockResolvedValue(undefined), |
| 133 | + } as unknown as Task["fileContextTracker"], |
| 134 | + } |
| 135 | + |
| 136 | + mockAskApproval = vi.fn().mockResolvedValue(true) |
| 137 | + mockHandleError = vi.fn().mockResolvedValue(undefined) |
| 138 | + mockPushToolResult = vi.fn() |
| 139 | + |
| 140 | + tool = new ApplyDiffTool() |
| 141 | + }) |
| 142 | + |
| 143 | + it("records a per-write checkpoint with the applied diff after a successful write", async () => { |
| 144 | + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { |
| 145 | + askApproval: mockAskApproval, |
| 146 | + handleError: mockHandleError, |
| 147 | + pushToolResult: mockPushToolResult, |
| 148 | + }) |
| 149 | + |
| 150 | + expect(mockCheckpointSave).toHaveBeenCalledTimes(1) |
| 151 | + expect(mockCheckpointSave).toHaveBeenCalledWith(mockTask, false, true, { |
| 152 | + path: "src/thing.ts", |
| 153 | + operation: "update", |
| 154 | + diffStats: { additions: 1, deletions: 1 }, |
| 155 | + diff: "mock-diff", |
| 156 | + }) |
| 157 | + }) |
| 158 | + |
| 159 | + it("marks auto-approved steps so the card renders compact", async () => { |
| 160 | + mockCheckAutoApproval.mockResolvedValueOnce({ decision: "approve" }) |
| 161 | + |
| 162 | + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { |
| 163 | + askApproval: mockAskApproval, |
| 164 | + handleError: mockHandleError, |
| 165 | + pushToolResult: mockPushToolResult, |
| 166 | + }) |
| 167 | + |
| 168 | + expect(mockCheckpointSave).toHaveBeenCalledTimes(1) |
| 169 | + expect(mockCheckpointSave.mock.calls[0]?.[3]).toEqual(expect.objectContaining({ autoApproved: true })) |
| 170 | + }) |
| 171 | + |
| 172 | + it("skips the checkpoint when perWriteCheckpoints is explicitly disabled", async () => { |
| 173 | + mockGetState.mockResolvedValueOnce({ |
| 174 | + diagnosticsEnabled: true, |
| 175 | + writeDelayMs: 1000, |
| 176 | + experiments: { preventFocusDisruption: true }, |
| 177 | + perWriteCheckpoints: false, |
| 178 | + }) |
| 179 | + |
| 180 | + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { |
| 181 | + askApproval: mockAskApproval, |
| 182 | + handleError: mockHandleError, |
| 183 | + pushToolResult: mockPushToolResult, |
| 184 | + }) |
| 185 | + |
| 186 | + expect(mockCheckpointSave).not.toHaveBeenCalled() |
| 187 | + // The write itself still happens (the setting gates the checkpoint only), |
| 188 | + // and auto-approval is never consulted when there is no card to build. |
| 189 | + expect(mockSaveDirectly).toHaveBeenCalled() |
| 190 | + expect(mockCheckAutoApproval).not.toHaveBeenCalled() |
| 191 | + }) |
| 192 | + |
| 193 | + it("records nothing when the approval is declined", async () => { |
| 194 | + mockAskApproval.mockResolvedValue(false) |
| 195 | + |
| 196 | + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { |
| 197 | + askApproval: mockAskApproval, |
| 198 | + handleError: mockHandleError, |
| 199 | + pushToolResult: mockPushToolResult, |
| 200 | + }) |
| 201 | + |
| 202 | + expect(mockCheckpointSave).not.toHaveBeenCalled() |
| 203 | + expect(mockSaveDirectly).not.toHaveBeenCalled() |
| 204 | + }) |
| 205 | +}) |
0 commit comments