Skip to content

Commit aa1a214

Browse files
committed
merge: file-write-safety trial — re-include updated PR Zoo-Code-Org#1411 (apply_diff per-write checkpoint and change card)
2 parents 4fc14c4 + 94fea2f commit aa1a214

3 files changed

Lines changed: 253 additions & 2 deletions

File tree

‎src/core/tools/ApplyDiffTool.ts‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
1414
import { computeDiffStats, sanitizeUnifiedDiff } from "../diff/stats"
1515
import type { ToolUse } from "../../shared/tools"
1616
import { versionTokenOfStat } from "../../utils/versionToken"
17+
import { checkAutoApproval } from "../auto-approval"
18+
import { checkpointSave } from "../checkpoints"
1719

1820
import { BaseTool, ToolCallbacks } from "./BaseTool"
1921

@@ -159,9 +161,13 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
159161
diff: diffContent,
160162
}
161163

164+
// Hoisted: both save branches build the same approval message, and the
165+
// B3a per-write checkpoint (below) needs it for auto-approval parity.
166+
let completeMessage = ""
167+
162168
if (isPreventFocusDisruptionEnabled) {
163169
// Direct file write without diff view
164-
const completeMessage = JSON.stringify({
170+
completeMessage = JSON.stringify({
165171
...sharedMessageProps,
166172
diff: diffContent,
167173
content: unifiedPatch,
@@ -208,7 +214,7 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
208214
await task.diffViewProvider.update(diffResult.content, true)
209215
task.diffViewProvider.scrollToFirstDiff()
210216

211-
const completeMessage = JSON.stringify({
217+
completeMessage = JSON.stringify({
212218
...sharedMessageProps,
213219
diff: diffContent,
214220
content: unifiedPatch,
@@ -241,6 +247,36 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
241247
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
242248
}
243249

250+
// B3a: per-write checkpoint + change card for the apply_diff write, with
251+
// the same parity as write_to_file / edit_file / apply_patch (this tool
252+
// previously wrote with no checkpoint and no card, so its edits had no
253+
// per-file rollback surface in chat). The applied unified diff and its
254+
// stats were already computed above for the tool message and are reused
255+
// verbatim; auto-approved steps always get the compact card. Live setting
256+
// with default-on semantics: skip only when explicitly false. apply_diff
257+
// only ever modifies an existing file (a missing file errors out before
258+
// the diff is applied), so the operation is always "update".
259+
const perWriteCheckpoints = state?.perWriteCheckpoints
260+
if (perWriteCheckpoints !== false) {
261+
const autoApproved =
262+
(
263+
await checkAutoApproval({
264+
state,
265+
cwd: task.cwd,
266+
ask: "tool",
267+
text: completeMessage,
268+
isProtected: isWriteProtected,
269+
})
270+
).decision === "approve"
271+
await checkpointSave(task, false, true, {
272+
path: relPath,
273+
operation: "update",
274+
...(diffStats ? { diffStats: { additions: diffStats.added, deletions: diffStats.removed } } : {}),
275+
...(unifiedPatch ? { diff: unifiedPatch } : {}),
276+
...(autoApproved ? { autoApproved: true } : {}),
277+
}).catch(() => {})
278+
}
279+
244280
// Track file edit operation
245281
if (relPath) {
246282
await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
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+
})

‎webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,16 @@ describe("ExtensionStateContext", () => {
351351
}
352352
})
353353

354+
it("initializes the change-card detail default before hydration", () => {
355+
// The initializer itself (not a merge fixture) must carry the change-card
356+
// detail default: a regression that dropped it from
357+
// createInitialExtensionState would otherwise stay hidden because the
358+
// merge tests supply the key manually.
359+
const state = createInitialExtensionState()
360+
361+
expect(state.changeCardDetail).toBe("summary")
362+
})
363+
354364
it("updates apiConfiguration through setApiConfiguration", () => {
355365
render(
356366
<ExtensionStateContextProvider>

0 commit comments

Comments
 (0)