Skip to content

Commit 52628eb

Browse files
fix(#1918 r112): narrow four over-broad behaviours flagged in review
Review round r112, one change per thread, in the order the findings came in: - ApplyPatchTool: forget a withdrawn observation only while the registry still holds the exact entry this tool published, so a failed apply_patch can no longer drop another writer's newer observation of the same file. - DiffViewProvider: the three teardown sites that already know the absolute path close only their own diff view; closeAllDiffViews stays as reset()'s fallback for the case where no path is known. - safeWriteText: create the target's parent directory before the private staging directory, so a self-staged write no longer publishes its target into a directory that only the staging mkdir made, with the staging mode. - safeWriteText.spec: the two win32 cases that hand in their own platform no longer skip themselves on a non-Windows host. - safeWriteJson.test: undo the proper-lockfile capture with vi.doUnmock, the runtime form, so a later import in the same file resolves the real module again. Specs: applyPatchTool.execute 26/26, DiffViewProvider 158/158, safeWriteText 68/68 (also 68/68 with process.platform reported as linux), safeWriteJson 27 passed / 4 skipped, safeWriteJson.stagingDirectory 7/7. Reverting each fix reddens exactly the test that names it: 4, 8, 1, 1 and one skipped case off Windows.
1 parent 002b34f commit 52628eb

7 files changed

Lines changed: 496 additions & 96 deletions

File tree

‎src/core/tools/ApplyPatchTool.ts‎

Lines changed: 81 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types"
66
import { getReadablePath } from "../../utils/path"
77
import { isPathOutsideWorkspace } from "../../utils/pathUtils"
88
import { Task } from "../task/Task"
9+
import type { FileObservation } from "../task/observationRegistry"
910
import { formatResponse } from "../prompts/responses"
1011
import { RecordSource } from "../context-tracking/FileContextTrackerTypes"
1112
import { fileExistsAtPath } from "../../utils/fs"
@@ -58,6 +59,25 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
5859
const { patch } = params
5960
const { handleError, pushToolResult } = callbacks
6061

62+
// Every observation this call creates is tracked here by path -> the exact entry the
63+
// registry stored. A hunk read is the tool read, not a model read: an exit that does
64+
// not publish must withdraw what this call recorded, otherwise a later edit,
65+
// search_replace, edit_file or apply_diff finds the leftover partial entry, the
66+
// compare-and-swap matches, and the file publishes without the model ever reading it.
67+
// Withdrawal is keyed to the stored entry, so an entry a publish re-earned or one a
68+
// concurrent read replaced is never discarded here. Declared outside the try because
69+
// the finally exit needs it. ApplyDiffTool enforces the same contract for its single
70+
// read with forgetPartialObservationIfCurrent; apply_patch reads several files per
71+
// call, so this side keeps one entry per path.
72+
const toolObservations = new Map<string, FileObservation>()
73+
const forgetToolObservationsIfCurrent = (): void => {
74+
for (const [observedPath, entry] of toolObservations) {
75+
if (task.observationRegistry.get(observedPath) === entry) {
76+
task.observationRegistry.forget(observedPath)
77+
}
78+
}
79+
toolObservations.clear()
80+
}
6181
try {
6282
// Validate required parameters
6383
if (!patch) {
@@ -114,6 +134,12 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
114134
const complete =
115135
prior === undefined ? false : prior.complete === true && prior.version === preReadToken
116136
task.observationRegistry.observe(absolutePath, preReadToken, complete)
137+
// Keep the stored entry so a non-publishing exit can withdraw exactly this
138+
// observation later.
139+
const storedObservation = task.observationRegistry.get(absolutePath)
140+
if (storedObservation) {
141+
toolObservations.set(absolutePath, storedObservation)
142+
}
117143
}
118144
}
119145
return content
@@ -148,20 +174,49 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
148174

149175
if (change.type === "add") {
150176
// Create new file
151-
await this.handleAddFile(change, absolutePath, relPath, task, callbacks, isWriteProtected)
177+
await this.handleAddFile(
178+
change,
179+
absolutePath,
180+
relPath,
181+
task,
182+
callbacks,
183+
isWriteProtected,
184+
toolObservations,
185+
)
152186
} else if (change.type === "delete") {
153187
// Delete file
154-
await this.handleDeleteFile(absolutePath, relPath, task, callbacks, isWriteProtected)
188+
await this.handleDeleteFile(
189+
absolutePath,
190+
relPath,
191+
task,
192+
callbacks,
193+
isWriteProtected,
194+
toolObservations,
195+
)
155196
} else if (change.type === "update") {
156197
// Update file
157-
await this.handleUpdateFile(change, absolutePath, relPath, task, callbacks, isWriteProtected)
198+
await this.handleUpdateFile(
199+
change,
200+
absolutePath,
201+
relPath,
202+
task,
203+
callbacks,
204+
isWriteProtected,
205+
toolObservations,
206+
)
158207
}
159208
}
160209

161210
task.consecutiveMistakeCount = 0
162211
} catch (error) {
163212
await handleError("apply patch", error as Error)
164213
await task.diffViewProvider.reset()
214+
} finally {
215+
// Every exit that did not publish passes through here: processAllHunks throwing (the
216+
// files read before the failure stay observed), a refused approval, a rooignore or
217+
// outside-workspace refusal, and the outer catch. Paths that published were removed
218+
// from the tracker at the publish site, so this withdraws only what no publish earned.
219+
forgetToolObservationsIfCurrent()
165220
}
166221
}
167222

@@ -172,6 +227,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
172227
task: Task,
173228
callbacks: ToolCallbacks,
174229
isWriteProtected: boolean,
230+
toolObservations: Map<string, FileObservation>,
175231
): Promise<void> {
176232
const { askApproval, pushToolResult } = callbacks
177233

@@ -277,6 +333,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
277333

278334
// Track file edit operation
279335
await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
336+
// This call published the path, so the observation it carries is earned: the sweep in
337+
// the finally block leaves it alone.
338+
toolObservations.delete(absolutePath)
280339
task.didEditFile = true
281340

282341
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, true)
@@ -291,6 +350,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
291350
task: Task,
292351
callbacks: ToolCallbacks,
293352
isWriteProtected: boolean,
353+
toolObservations: Map<string, FileObservation>,
294354
): Promise<void> {
295355
const { askApproval, pushToolResult } = callbacks
296356

@@ -337,6 +397,10 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
337397
return
338398
}
339399

400+
// The delete consumed the observation: the version the hunk read recorded is no longer
401+
// reachable at this path, so there is nothing here for the sweep to withdraw.
402+
toolObservations.delete(absolutePath)
403+
340404
task.didEditFile = true
341405
pushToolResult(`Successfully deleted ${relPath}`)
342406
task.processQueuedMessages()
@@ -349,6 +413,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
349413
task: Task,
350414
callbacks: ToolCallbacks,
351415
isWriteProtected: boolean,
416+
toolObservations: Map<string, FileObservation>,
352417
): Promise<void> {
353418
const { askApproval, pushToolResult } = callbacks
354419

@@ -519,6 +584,12 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
519584
// had of the source, so carry the source's completeness instead of the
520585
// destination's stale one.
521586
task.observationRegistry.observe(moveAbsolutePath, destObs.version, false)
587+
// Tracked like a hunk read: if the move does not publish, this partial entry must
588+
// not survive as authority for a destination the model never read.
589+
const storedDestObservation = task.observationRegistry.get(moveAbsolutePath)
590+
if (storedDestObservation) {
591+
toolObservations.set(moveAbsolutePath, storedDestObservation)
592+
}
522593
}
523594
}
524595
await task.diffViewProvider.saveDirectly(
@@ -549,6 +620,10 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
549620
}
550621

551622
await task.fileContextTracker.trackFileContext(change.movePath, "roo_edited" as RecordSource)
623+
// Both paths published: the destination through the save above and the source by being
624+
// moved out of the way. Neither observation is left for the sweep to withdraw.
625+
toolObservations.delete(moveAbsolutePath)
626+
toolObservations.delete(absolutePath)
552627
} else {
553628
// Save changes to the same file
554629
if (isPreventFocusDisruptionEnabled) {
@@ -582,6 +657,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
582657
}
583658

584659
await task.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
660+
// The publish owns this path now, so the sweep in the finally block leaves its
661+
// observation alone.
662+
toolObservations.delete(absolutePath)
585663
}
586664

587665
task.didEditFile = true

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

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,27 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => {
188188
@@
189189
-original file content
190190
+modified file content
191+
*** End Patch`
192+
const mismatchedSecondPatch = `*** Begin Patch
193+
*** Update File: src/first.ts
194+
@@
195+
-original file content
196+
+modified first content
197+
*** Update File: src/second.ts
198+
@@
199+
-context the mocked file does not contain
200+
+modified second content
201+
*** End Patch`
202+
203+
const twoUpdatePatch = `*** Begin Patch
204+
*** Update File: src/first.ts
205+
@@
206+
-original file content
207+
+modified first content
208+
*** Update File: src/second.ts
209+
@@
210+
-original file content
211+
+modified second content
191212
*** End Patch`
192213

193214
beforeEach(() => {
@@ -377,6 +398,85 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => {
377398
"a full-file replacement needs the complete content; re-read the whole file, then retry.",
378399
)
379400
})
401+
it("update: withdraws the hunk-read observation when the user denies the publish", async () => {
402+
// apply_patch read the file to compute the hunk, so the tool owns that observation.
403+
// The user said no, nothing published, and a leftover partial entry would let a later
404+
// edit, search_replace, edit_file or apply_diff publish against a version the model
405+
// never read. This is the exit that made apply_patch the remaining tool-read path.
406+
const key = path.resolve(mockTask.cwd, "src/thing.ts")
407+
const reg = mockTask.observationRegistry
408+
mockAskApproval.mockResolvedValue(false)
409+
410+
await tool.execute({ patch: updatePatch }, mockTask as Task, {
411+
askApproval: mockAskApproval,
412+
handleError: mockHandleError,
413+
pushToolResult: mockPushToolResult,
414+
toolCallId: "test-tool-call-id",
415+
})
416+
417+
expect(mockPushToolResult).toHaveBeenCalledWith("Changes were rejected by the user.")
418+
expect(reg.has(key)).toBe(false)
419+
})
420+
421+
it("update: withdraws the hunk-read observation when the publish throws", async () => {
422+
// The outer-catch exit: the hunk read happened, the save blew up before publishing,
423+
// and the observation must not survive as authority for a later write.
424+
const key = path.resolve(mockTask.cwd, "src/thing.ts")
425+
const reg = mockTask.observationRegistry
426+
mockSaveDirectly.mockRejectedValue(new Error("extension host went away"))
427+
428+
await tool.execute({ patch: updatePatch }, mockTask as Task, {
429+
askApproval: mockAskApproval,
430+
handleError: mockHandleError,
431+
pushToolResult: mockPushToolResult,
432+
toolCallId: "test-tool-call-id",
433+
})
434+
435+
expect(mockHandleError).toHaveBeenCalled()
436+
expect(reg.has(key)).toBe(false)
437+
})
438+
439+
it("withdraws observations for files read before a hunk failure", async () => {
440+
// processAllHunks throws on the second file context mismatch, so the first file was
441+
// read, observed and then never published. Its leftover entry is the state a later
442+
// targeted edit would wrongly accept.
443+
const firstKey = path.resolve(mockTask.cwd, "src/first.ts")
444+
const secondKey = path.resolve(mockTask.cwd, "src/second.ts")
445+
const reg = mockTask.observationRegistry
446+
447+
await tool.execute({ patch: mismatchedSecondPatch }, mockTask as Task, {
448+
askApproval: mockAskApproval,
449+
handleError: mockHandleError,
450+
pushToolResult: mockPushToolResult,
451+
toolCallId: "test-tool-call-id",
452+
})
453+
454+
expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Failed to process patch"))
455+
expect(reg.has(firstKey)).toBe(false)
456+
expect(reg.has(secondKey)).toBe(false)
457+
})
458+
459+
it("keeps the observation of a path that published while withdrawing a denied one", async () => {
460+
// Two updates in one patch: the first approves and publishes, the second is denied.
461+
// Withdrawal is scoped by path and by the exact stored entry, so the published file
462+
// keeps the observation its publish ran on (partial, as the hunk read recorded it)
463+
// while the denied path is left with nothing.
464+
const publishedKey = path.resolve(mockTask.cwd, "src/first.ts")
465+
const deniedKey = path.resolve(mockTask.cwd, "src/second.ts")
466+
const reg = mockTask.observationRegistry
467+
mockAskApproval.mockResolvedValueOnce(true).mockResolvedValueOnce(false)
468+
469+
await tool.execute({ patch: twoUpdatePatch }, mockTask as Task, {
470+
askApproval: mockAskApproval,
471+
handleError: mockHandleError,
472+
pushToolResult: mockPushToolResult,
473+
toolCallId: "test-tool-call-id",
474+
})
475+
476+
expect(reg.has(publishedKey)).toBe(true)
477+
expect(reg.get(publishedKey)?.complete).toBe(false)
478+
expect(reg.has(deniedKey)).toBe(false)
479+
})
380480

381481
it("update: observes the hunk read so the guarded publish is not unobserved", async () => {
382482
await tool.execute({ patch: updatePatch }, mockTask as Task, {

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -762,7 +762,12 @@ export class DiffViewProvider {
762762
await this.revertDocument(updatedDocument)
763763
}
764764

765-
await this.closeAllDiffViews()
765+
// A save belongs to one task, so its post-publish cleanup closes only this provider's
766+
// diff tab. closeAllDiffViews() would also close a concurrent task's clean diff view
767+
// while that task still holds its activation listener and deferred scroll timer against
768+
// a tab that is gone - the same reason the failure teardown above and reset() scope the
769+
// close to this provider's own file.
770+
await this.closeOwnDiffView(absolutePath)
766771

767772
// Read auto-close preferences from state; fall back to defaults that
768773
// preserve the existing behavior when unset (saveTask was resolved above
@@ -959,7 +964,9 @@ export class DiffViewProvider {
959964
await updatedDocument.save()
960965
}
961966

962-
await this.closeAllDiffViews()
967+
// A rejection belongs to one task, so this teardown closes only this provider's
968+
// diff tab rather than every clean diff view in the workbench.
969+
await this.closeOwnDiffView(absolutePath)
963970
// The file was newly created for this edit; close its transiently
964971
// opened tab before deleting it from disk.
965972
await this.closeFileTab(absolutePath)
@@ -986,7 +993,9 @@ export class DiffViewProvider {
986993
await vscode.workspace.applyEdit(edit)
987994
await updatedDocument.save()
988995

989-
await this.closeAllDiffViews()
996+
// Same scoping as the create branch above: the revert is this task's, so only this
997+
// provider's diff tab goes.
998+
await this.closeOwnDiffView(absolutePath)
990999

9911000
// Read auto-close preferences from state; fall back to defaults that
9921001
// preserve the existing behavior when unset.
@@ -1032,6 +1041,13 @@ export class DiffViewProvider {
10321041
}
10331042
}
10341043

1044+
/**
1045+
* Close every clean Zoo diff tab in the workbench. After the per-task teardowns were
1046+
* scoped, only the fallback in reset() still calls this, for the case where the provider
1047+
* no longer knows which file it was editing; every teardown that has a path in scope
1048+
* closes just its own view, so one task's rejected or saved edit cannot disturb another
1049+
* task's open diff view.
1050+
*/
10351051
private async closeAllDiffViews(): Promise<void> {
10361052
const closeOps = vscode.window.tabGroups.all
10371053
.flatMap((group) => group.tabs)

0 commit comments

Comments
 (0)