|
| 1 | +// npx vitest run core/tools/__tests__/applyDiffTool.writeKind.spec.ts |
| 2 | + |
| 3 | +import fs from "fs/promises" |
| 4 | +import path from "path" |
| 5 | +import type { BigIntStats } from "fs" |
| 6 | + |
| 7 | +import type { Task } from "../../task/Task" |
| 8 | +import { versionTokenOfStat } from "../../../utils/versionToken" |
| 9 | +import { fileExistsAtPath } from "../../../utils/fs" |
| 10 | +import { isPathOutsideWorkspace } from "../../../utils/pathUtils" |
| 11 | +import type { ToolCallbacks } from "../BaseTool" |
| 12 | +import { applyDiffTool } from "../ApplyDiffTool" |
| 13 | + |
| 14 | +// The version token the guarded publish consumes comes from the bigint stats that bracket the |
| 15 | +// tool's own read. BigIntStats is a class-backed interface without a public constructor, so a |
| 16 | +// plain-object double is the only way to pin that token without real files; single-step |
| 17 | +// downcast from Partial to the full type (test-local, per AGENTS.md). Every call returns a |
| 18 | +// fresh object so one case cannot leak a mutated stat into the next. |
| 19 | +const { readStats, statDouble, armStatDrift } = vi.hoisted(() => { |
| 20 | + const base: Partial<BigIntStats> = { |
| 21 | + dev: 7n, |
| 22 | + ino: 4242n, |
| 23 | + size: 1234n, |
| 24 | + atimeMs: 1_700_000_000_000n, |
| 25 | + mtimeMs: 1_700_000_000_123n, |
| 26 | + ctimeMs: 1_700_000_000_789n, |
| 27 | + birthtimeMs: 1_700_000_000_000n, |
| 28 | + atimeNs: 1_700_000_000_000_000_000n, |
| 29 | + mtimeNs: 1_700_000_000_123_456_789n, |
| 30 | + ctimeNs: 1_700_000_000_789_999_999n, |
| 31 | + birthtimeNs: 1_700_000_000_000_000_000n, |
| 32 | + } |
| 33 | + const state = { calls: 0, drift: false } |
| 34 | + return { |
| 35 | + readStats: (overrides: Partial<BigIntStats> = {}): BigIntStats => ({ ...base, ...overrides }) as BigIntStats, |
| 36 | + // Arming the drift makes the SECOND of the two bracketing stats disagree, which is the |
| 37 | + // S2 condition under which the read records nothing. |
| 38 | + statDouble: (): BigIntStats => { |
| 39 | + const drifted = state.drift && state.calls > 0 |
| 40 | + state.calls += 1 |
| 41 | + return (drifted ? { ...base, mtimeNs: 1_700_000_000_123_456_790n } : { ...base }) as BigIntStats |
| 42 | + }, |
| 43 | + armStatDrift: (drift: boolean): void => { |
| 44 | + state.drift = drift |
| 45 | + state.calls = 0 |
| 46 | + }, |
| 47 | + } |
| 48 | +}) |
| 49 | + |
| 50 | +vi.mock("@roo-code/telemetry", () => ({ |
| 51 | + TelemetryService: { instance: { captureDiffApplicationError: vi.fn() } }, |
| 52 | +})) |
| 53 | + |
| 54 | +vi.mock("fs/promises", () => ({ |
| 55 | + default: { |
| 56 | + readFile: vi.fn().mockResolvedValue("old\n"), |
| 57 | + stat: vi.fn().mockImplementation(async () => statDouble()), |
| 58 | + }, |
| 59 | +})) |
| 60 | + |
| 61 | +vi.mock("../../../utils/fs", () => ({ |
| 62 | + fileExistsAtPath: vi.fn().mockResolvedValue(true), |
| 63 | +})) |
| 64 | + |
| 65 | +vi.mock("../../../utils/path", () => ({ |
| 66 | + getReadablePath: vi.fn((_cwd: string, relPath?: string) => relPath ?? ""), |
| 67 | +})) |
| 68 | + |
| 69 | +vi.mock("../../../utils/pathUtils", () => ({ |
| 70 | + isPathOutsideWorkspace: vi.fn().mockReturnValue(false), |
| 71 | +})) |
| 72 | + |
| 73 | +vi.mock("../../prompts/responses", () => ({ |
| 74 | + formatResponse: { |
| 75 | + toolError: vi.fn((message: string) => `Error: ${message}`), |
| 76 | + rooIgnoreError: vi.fn((filePath: string) => `Access denied: ${filePath}`), |
| 77 | + createPrettyPatch: vi.fn(() => "mock-diff"), |
| 78 | + }, |
| 79 | +})) |
| 80 | + |
| 81 | +vi.mock("../../diff/stats", () => ({ |
| 82 | + sanitizeUnifiedDiff: vi.fn((diff: string) => diff), |
| 83 | + computeDiffStats: vi.fn(() => ({ additions: 1, deletions: 1 })), |
| 84 | +})) |
| 85 | + |
| 86 | +vi.mock("vscode", () => ({ |
| 87 | + window: { showWarningMessage: vi.fn() }, |
| 88 | + env: { openExternal: vi.fn() }, |
| 89 | + Uri: { parse: vi.fn() }, |
| 90 | + workspace: { |
| 91 | + get workspaceFolders() { |
| 92 | + return [{ uri: { fsPath: path.resolve(CWD) } }] |
| 93 | + }, |
| 94 | + }, |
| 95 | +})) |
| 96 | + |
| 97 | +const CWD = "/workspace" |
| 98 | +const REL_PATH = "src/index.ts" |
| 99 | +const ABSOLUTE_PATH = path.resolve(CWD, REL_PATH) |
| 100 | +const DIFF = "<<<<<<< SEARCH\nold\n=======\nnew\n>>>>>>> REPLACE" |
| 101 | +const READ_TOKEN = versionTokenOfStat(readStats()) |
| 102 | + |
| 103 | +// The two saves and the observation registry are shared spies, so each case asserts on the one |
| 104 | +// publish the flow performs; a fresh double per task would let a second, differently-kinded |
| 105 | +// publish slip past an assertion that only ever inspected the first. |
| 106 | +const saveChanges = vi.fn().mockResolvedValue(undefined) |
| 107 | +const saveDirectly = vi.fn().mockResolvedValue(undefined) |
| 108 | +const registryGet = vi.fn().mockReturnValue(undefined) |
| 109 | +const registryObserve = vi.fn() |
| 110 | +const registryHas = vi.fn().mockReturnValue(false) |
| 111 | +const askApproval = vi.fn<ToolCallbacks["askApproval"]>().mockResolvedValue(true) |
| 112 | + |
| 113 | +function createTask(preventFocusDisruption = false): Task { |
| 114 | + const task = { |
| 115 | + cwd: CWD, |
| 116 | + consecutiveMistakeCount: 0, |
| 117 | + consecutiveMistakeCountForApplyDiff: new Map<string, number>(), |
| 118 | + didEditFile: false, |
| 119 | + api: { getModel: () => ({ id: "claude-test" }) }, |
| 120 | + rooIgnoreController: { validateAccess: vi.fn().mockReturnValue(true) }, |
| 121 | + rooProtectedController: { isWriteProtected: vi.fn().mockReturnValue(false) }, |
| 122 | + providerRef: { |
| 123 | + deref: vi.fn().mockReturnValue({ |
| 124 | + getState: vi.fn().mockResolvedValue({ |
| 125 | + diagnosticsEnabled: false, |
| 126 | + writeDelayMs: 0, |
| 127 | + experiments: { preventFocusDisruption }, |
| 128 | + }), |
| 129 | + }), |
| 130 | + }, |
| 131 | + diffStrategy: { |
| 132 | + getName: () => "test", |
| 133 | + applyDiff: vi.fn().mockResolvedValue({ success: true, content: "new\n" }), |
| 134 | + }, |
| 135 | + diffViewProvider: { |
| 136 | + editType: undefined, |
| 137 | + originalContent: "", |
| 138 | + open: vi.fn().mockResolvedValue(undefined), |
| 139 | + update: vi.fn().mockResolvedValue(undefined), |
| 140 | + reset: vi.fn().mockResolvedValue(undefined), |
| 141 | + revertChanges: vi.fn().mockResolvedValue(undefined), |
| 142 | + saveChanges, |
| 143 | + saveDirectly, |
| 144 | + scrollToFirstDiff: vi.fn(), |
| 145 | + pushToolWriteResult: vi |
| 146 | + .fn() |
| 147 | + .mockResolvedValue('{"path":"src/index.ts","operation":"modified","notice":"baseline"}'), |
| 148 | + }, |
| 149 | + observationRegistry: { |
| 150 | + get: registryGet, |
| 151 | + has: registryHas, |
| 152 | + observe: registryObserve, |
| 153 | + forget: vi.fn(), |
| 154 | + }, |
| 155 | + fileContextTracker: { trackFileContext: vi.fn().mockResolvedValue(undefined) }, |
| 156 | + say: vi.fn().mockResolvedValue(undefined), |
| 157 | + ask: vi.fn().mockResolvedValue(undefined), |
| 158 | + recordToolError: vi.fn(), |
| 159 | + processQueuedMessages: vi.fn(), |
| 160 | + sayAndCreateMissingParamError: vi.fn().mockResolvedValue("Missing param error"), |
| 161 | + } |
| 162 | + // The double provides only the Task members that ApplyDiffTool.execute reads. |
| 163 | + return task as unknown as Task |
| 164 | +} |
| 165 | + |
| 166 | +async function runExecute(preventFocusDisruption = false): Promise<void> { |
| 167 | + await applyDiffTool.execute({ path: REL_PATH, diff: DIFF }, createTask(preventFocusDisruption), { |
| 168 | + askApproval, |
| 169 | + handleError: vi.fn().mockResolvedValue(undefined), |
| 170 | + pushToolResult: vi.fn(), |
| 171 | + toolCallId: "tool-call-write-kind", |
| 172 | + }) |
| 173 | +} |
| 174 | + |
| 175 | +// The mocked-provider suite replays an apply_diff turn that is matched on a tool result of |
| 176 | +// {"path":...,"operation":"modified"}. While the diff-view save ran on its "update" default the |
| 177 | +// guard read the accepted preview as a full-file replacement, refused it behind the partial-read |
| 178 | +// remediation, and the tool result the provider was promised never existed. The write kind the |
| 179 | +// tool asks for, and the observation its own read records to authorize that kind, are the |
| 180 | +// contract these cases pin. |
| 181 | +describe("ApplyDiffTool write kind", () => { |
| 182 | + beforeEach(() => { |
| 183 | + vi.clearAllMocks() |
| 184 | + applyDiffTool.resetPartialState() |
| 185 | + armStatDrift(false) |
| 186 | + registryGet.mockReturnValue(undefined) |
| 187 | + registryHas.mockReturnValue(false) |
| 188 | + registryObserve.mockImplementation(() => undefined) |
| 189 | + saveChanges.mockResolvedValue(undefined) |
| 190 | + saveDirectly.mockResolvedValue(undefined) |
| 191 | + askApproval.mockResolvedValue(true) |
| 192 | + vi.mocked(fs.readFile).mockResolvedValue("old\n") |
| 193 | + vi.mocked(fileExistsAtPath).mockResolvedValue(true) |
| 194 | + vi.mocked(isPathOutsideWorkspace).mockReturnValue(false) |
| 195 | + }) |
| 196 | + |
| 197 | + it("publishes the accepted hunk through the diff-view save as an edit", async () => { |
| 198 | + await runExecute() |
| 199 | + |
| 200 | + expect(saveChanges).toHaveBeenCalledTimes(1) |
| 201 | + expect(saveChanges).toHaveBeenCalledWith(false, 0, "edit") |
| 202 | + expect(saveDirectly).not.toHaveBeenCalled() |
| 203 | + }) |
| 204 | + |
| 205 | + it("publishes the accepted hunk through the guarded direct save as an edit", async () => { |
| 206 | + await runExecute(true) |
| 207 | + |
| 208 | + expect(saveDirectly).toHaveBeenCalledTimes(1) |
| 209 | + expect(saveDirectly).toHaveBeenCalledWith(REL_PATH, "new\n", false, false, 0, "edit") |
| 210 | + expect(saveChanges).not.toHaveBeenCalled() |
| 211 | + }) |
| 212 | + |
| 213 | + it("records its own read as an incomplete observation so the edit guard accepts the publish", async () => { |
| 214 | + await runExecute() |
| 215 | + |
| 216 | + expect(registryObserve).toHaveBeenCalledTimes(1) |
| 217 | + expect(registryObserve).toHaveBeenCalledWith(ABSOLUTE_PATH, READ_TOKEN, false) |
| 218 | + }) |
| 219 | + |
| 220 | + it("keeps a matching complete read complete rather than downgrading it to the hunk", async () => { |
| 221 | + registryGet.mockReturnValue({ version: READ_TOKEN, complete: true }) |
| 222 | + |
| 223 | + await runExecute() |
| 224 | + |
| 225 | + expect(registryObserve).toHaveBeenCalledTimes(1) |
| 226 | + expect(registryObserve).toHaveBeenCalledWith(ABSOLUTE_PATH, READ_TOKEN, true) |
| 227 | + }) |
| 228 | + |
| 229 | + it("leaves an observation of an older version exactly as the model earned it", async () => { |
| 230 | + registryGet.mockReturnValue({ version: "9:9:9:9:9", complete: true }) |
| 231 | + |
| 232 | + await runExecute() |
| 233 | + |
| 234 | + expect(registryObserve).not.toHaveBeenCalled() |
| 235 | + expect(saveChanges).toHaveBeenCalledWith(false, 0, "edit") |
| 236 | + }) |
| 237 | + |
| 238 | + it("records nothing when the read is not stat-matched, leaving the publish unobserved", async () => { |
| 239 | + armStatDrift(true) |
| 240 | + |
| 241 | + await runExecute() |
| 242 | + |
| 243 | + expect(registryObserve).not.toHaveBeenCalled() |
| 244 | + expect(saveChanges).toHaveBeenCalledWith(false, 0, "edit") |
| 245 | + }) |
| 246 | +}) |
0 commit comments