Skip to content

Commit 6702cc0

Browse files
author
abort-merge
committed
fix(diff-view): give a recovery the edit it was asked to undo, not just its target
attemptRollbackRecovery() protected a live edit by comparing the target and the mode: the resolved relPath against the record absolutePath, and editType against the record editType. Those two fields say which file is being edited and in which mode. They do not say which attempt is doing it, and that is the whole hole: a retry that reopens the same file as the same kind of edit installs values identical in both, so a recovery waiting on a refused rollback accepted that retry as its own install, restored its own baseline into the buffer the retry had reopened, saved it, and reported a clean rollback over an edit it was never asked to undo. Same loss the ownership guards were written to prevent, narrower window, same missing information. Every install now stamps a session. captureRollbackRecoveryContext() records the stamp of the install it snapshots, attemptRollbackRecovery() carries the record stamp through its own re-install - the install is that recovery performing the edit the record describes - and all three ownership questions (the live edit, the failed acquisition, the settled acquisition) require the stamp unchanged alongside the target and the mode they already compared. originalContent and createdDirs differ in value between two sessions but neither is an identity: comparing them would confuse same bytes with same session, so they stay out of the ownership question. Reverting the record own session is untouched, and the new same-session case pins it: the live-edit branch still restores and saves exactly as before. Tests: four cases in the recovery suite - a same-file retry live under a newer session is left alone, a same-session live edit still reverts, a same-file reinstall during the acquisition refuses and keeps its own editor, directories and baseline, and a same-file reinstall followed by a rejected acquisition rethrows without writing this recovery own captured fields over it. Control with DiffViewProvider.ts restored byte-for-byte from e10d9d6 and the cases kept: the three newer-session cases fail (expected true to be false, expected true to be false, expected false to be true); the same-session case passes either way, so it is stated as a guard on what the stamp must not refuse rather than as proof of the stamp. Gates: focused spec 107 passed (107); integrations/editor 115 passed (115); misc shard 117 files 2128 passed | 13 skipped; core shard 198 files 4294 passed | 9 skipped; writeToFileTool, writeToFileTool partial-state and stream-cleanup specs 78 passed | 5 skipped; tsc --noEmit -p src/tsconfig.json clean; eslint --max-warnings=0 clean on the four touched files with eslint-suppressions.json unchanged; prettier --check clean. Local Stryker preflight not run.
1 parent e10d9d6 commit 6702cc0

4 files changed

Lines changed: 220 additions & 3 deletions

File tree

‎src/core/assistant-message/__tests__/presentAssistantMessage-write-to-file-stream-cleanup.spec.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,8 @@ function buildTask(): PresenterTask {
147147
relPath: openedRelPath,
148148
absolutePath: path.resolve(taskCwd, openedRelPath),
149149
editType: diffViewProvider.editType,
150+
// One open() install per live edit in this mirror, which is what the real provider stamps.
151+
editSession: 1,
150152
createdDirs: [],
151153
}
152154
: undefined,

‎src/core/tools/__tests__/writeToFileTool.spec.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,9 @@ describe("writeToFileTool", () => {
203203
relPath: opened,
204204
absolutePath: realPathResolve("/", opened),
205205
editType: provider.editType ?? "create",
206+
// The double stands for one open() install, so the record it hands back carries that install
207+
// identity: a recovery is answerable to the session the record names, not only to its target.
208+
editSession: 1,
206209
createdDirs: [],
207210
originalContent: provider.originalContent,
208211
}
@@ -1308,6 +1311,7 @@ describe("writeToFileTool", () => {
13081311
relPath,
13091312
absolutePath: realPathResolve("/", relPath),
13101313
editType: "create" as const,
1314+
editSession: 1,
13111315
createdDirs: [],
13121316
originalContent: "",
13131317
})

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@ export interface RollbackRecoveryContext {
4444
absolutePath: string
4545
/** create and modify roll back differently: one unlinks the file it made, the other restores content. */
4646
editType?: "create" | "modify"
47+
/**
48+
* The edit session this record was captured from. A target and an edit type are not an identity:
49+
* a retry that opens the same file as the same kind of edit installs values identical to the ones
50+
* in this record, and only the session says whether the edit in front of the provider is the one
51+
* this rollback was asked to undo.
52+
*/
53+
editSession: number
4754
/** Directories this edit made, so a recovery that unlinks the file can remove them too. */
4855
createdDirs: string[]
4956
/** The file content before the edit, for the modify branch. */
@@ -107,6 +114,11 @@ export class DiffViewProvider {
107114
scrollLine: number | undefined
108115
viewColumn: vscode.ViewColumn
109116
}> = []
117+
// Stamped whenever an edit is installed (open(), and the recovery's own re-install). It is the only
118+
// thing that tells two edits on one provider apart: relPath and editType say what is being edited,
119+
// not which attempt is doing it, so a retry that reopens the same file as the same kind of edit
120+
// looks exactly like the install a retained recovery record describes.
121+
private editSession = 0
110122
private taskRef: WeakRef<Task>
111123

112124
constructor(
@@ -117,6 +129,10 @@ export class DiffViewProvider {
117129
}
118130

119131
async open(relPath: string): Promise<void> {
132+
// A new edit session starts here, even when the target and the edit type are the same as the last
133+
// one: this install's baseline, directories and buffer are its own, and any recovery record captured
134+
// from an earlier install is now answerable to a different attempt.
135+
this.editSession++
120136
this.relPath = relPath
121137
const fileExists = this.editType === "modify"
122138
const absolutePath = path.resolve(this.cwd, relPath)
@@ -582,6 +598,7 @@ export class DiffViewProvider {
582598
relPath: this.relPath,
583599
absolutePath: path.resolve(this.cwd, this.relPath),
584600
editType: this.editType,
601+
editSession: this.editSession,
585602
createdDirs: [...this.createdDirs],
586603
originalContent: this.originalContent,
587604
}
@@ -609,7 +626,15 @@ export class DiffViewProvider {
609626
async attemptRollbackRecovery(context: RollbackRecoveryContext): Promise<boolean> {
610627
if (this.isEditing) {
611628
const livePath = this.relPath ? path.resolve(this.cwd, this.relPath) : undefined
612-
if (!livePath || !arePathsEqual(livePath, context.absolutePath)) {
629+
if (
630+
!livePath ||
631+
!arePathsEqual(livePath, context.absolutePath) ||
632+
this.editSession !== context.editSession
633+
) {
634+
// Either a different target is live, or the same target is live under a different session - a
635+
// retry that reopened this file and is mid-edit with its own baseline. Reverting here would undo
636+
// that attempt with an earlier attempt's record, which is the same loss the two guards below
637+
// refuse on the other side of the acquisition.
613638
return false
614639
}
615640
return this.revertChanges()
@@ -621,8 +646,13 @@ export class DiffViewProvider {
621646
const previousEditType = this.editType
622647
const previousCreatedDirs = this.createdDirs
623648
const previousOriginalContent = this.originalContent
649+
const previousEditSession = this.editSession
624650
this.relPath = context.relPath
625651
this.editType = context.editType
652+
// The install is this recovery performing the edit the record describes, so it wears that record
653+
// session: the comparison afterwards asks whether this install is still what the provider answers
654+
// to, and only a stamp that a later open() moved tells it when the target and the type stayed put.
655+
this.editSession = context.editSession
626656
this.createdDirs = [...context.createdDirs]
627657
this.originalContent = context.originalContent
628658
this.isEditing = true
@@ -651,7 +681,8 @@ export class DiffViewProvider {
651681
this.isEditing &&
652682
(!this.relPath ||
653683
!arePathsEqual(path.resolve(this.cwd, this.relPath), context.absolutePath) ||
654-
this.editType !== context.editType)
684+
this.editType !== context.editType ||
685+
this.editSession !== context.editSession)
655686
if (!heldForAnotherTarget) {
656687
// Nobody else holds an edit, or this install is still the one the provider answers to: put it
657688
// back exactly as it was found, which is what keeps a later attempt from walking past the
@@ -661,6 +692,7 @@ export class DiffViewProvider {
661692
this.editType = previousEditType
662693
this.createdDirs = previousCreatedDirs
663694
this.originalContent = previousOriginalContent
695+
this.editSession = previousEditSession
664696
}
665697
throw acquisitionError
666698
}
@@ -679,7 +711,8 @@ export class DiffViewProvider {
679711
!this.isEditing ||
680712
!this.relPath ||
681713
!arePathsEqual(path.resolve(this.cwd, this.relPath), context.absolutePath) ||
682-
this.editType !== context.editType
714+
this.editType !== context.editType ||
715+
this.editSession !== context.editSession
683716
) {
684717
// Somebody else owns this provider now, and its editor is theirs to install: the acquired editor
685718
// is dropped without being written into activeDiffEditor, because a recovery that no longer owns

‎src/integrations/editor/__tests__/DiffViewProvider.spec.ts‎

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2469,6 +2469,9 @@ describe("DiffViewProvider", () => {
24692469
absolutePath: `${mockCwd}/${relPath}`,
24702470
editType,
24712471
createdDirs,
2472+
// The record describes the install the provider answers to when it is captured, which is what lets a
2473+
// recovery tell a retry apart from the attempt it was asked to undo.
2474+
editSession: diffViewProvider["editSession"],
24722475
originalContent: editType === "modify" ? "on-disk original" : "",
24732476
})
24742477

@@ -2638,6 +2641,9 @@ describe("DiffViewProvider", () => {
26382641
relPath: otherRelPath,
26392642
editType: "modify",
26402643
createdDirs: otherCreatedDirs,
2644+
// open() stamps a new session on every install, so a retry is a new edit even when its target and
2645+
// edit type are the ones already on the provider.
2646+
editSession: diffViewProvider["editSession"] + 1,
26412647
originalContent: "the other file's own original",
26422648
activeDiffEditor: interloperEditor,
26432649
})
@@ -2700,6 +2706,9 @@ describe("DiffViewProvider", () => {
27002706
relPath: otherRelPath,
27012707
editType: "modify",
27022708
createdDirs: otherCreatedDirs,
2709+
// open() stamps a new session on every install, so a retry is a new edit even when its target and
2710+
// edit type are the ones already on the provider.
2711+
editSession: diffViewProvider["editSession"] + 1,
27032712
originalContent: "the other file's own original",
27042713
activeDiffEditor: interloperEditor,
27052714
})
@@ -2760,6 +2769,174 @@ describe("DiffViewProvider", () => {
27602769
// no longer owns the edit does not steer the provider with it either.
27612770
expect(diffViewProvider["activeDiffEditor"]).toBeUndefined()
27622771
})
2772+
it("leaves a retry of the same file alone when the record describes an earlier session", async () => {
2773+
const relPath = "mock-recovery-target.ts"
2774+
const absolutePath = `${mockCwd}/${relPath}`
2775+
simulateReset()
2776+
const restorePreStreamBuffer = vi.fn().mockResolvedValue(undefined)
2777+
const saveBufferClean = vi.fn().mockResolvedValue(undefined)
2778+
const keepOrCloseEditedFile = vi.fn().mockResolvedValue(undefined)
2779+
diffViewProvider["restorePreStreamBuffer"] = restorePreStreamBuffer
2780+
diffViewProvider["saveBufferClean"] = saveBufferClean
2781+
diffViewProvider["keepOrCloseEditedFile"] = keepOrCloseEditedFile
2782+
// Captured while the install it describes is still the one the provider answers to.
2783+
const record = recoveryContextFor(relPath, "modify")
2784+
// The retry the row is about: the same file, reopened as the same kind of edit, with its own
2785+
// baseline in its own buffer. Its target and its edit type are identical to the record's, so
2786+
// neither of those says whether this rollback belongs to the edit in front of it.
2787+
const retryEditor = makeTextEditor({
2788+
document: makeTextDocument({
2789+
uri: makeUri(absolutePath),
2790+
getText: vi.fn().mockReturnValue("the retry's own streamed buffer"),
2791+
isDirty: true,
2792+
}),
2793+
})
2794+
const retrySession = diffViewProvider["editSession"] + 1
2795+
Object.assign(diffViewProvider, {
2796+
isEditing: true,
2797+
relPath,
2798+
editType: "modify",
2799+
editSession: retrySession,
2800+
createdDirs: [],
2801+
originalContent: "the retry's own baseline",
2802+
activeDiffEditor: retryEditor,
2803+
})
2804+
2805+
await expect(diffViewProvider.attemptRollbackRecovery(record)).resolves.toBe(false)
2806+
2807+
// The caller keeps its refusal, which is the honest outcome: no rollback of the edit this record
2808+
// describes ran. The retry keeps its own edit - its buffer was not restored from an earlier
2809+
// attempt's baseline, nothing was saved out of it, and its own editor is still installed.
2810+
expect(restorePreStreamBuffer).not.toHaveBeenCalled()
2811+
expect(saveBufferClean).not.toHaveBeenCalled()
2812+
expect(keepOrCloseEditedFile).not.toHaveBeenCalled()
2813+
expect(diffViewProvider["isEditing"]).toBe(true)
2814+
expect(diffViewProvider["relPath"]).toBe(relPath)
2815+
expect(diffViewProvider["editSession"]).toBe(retrySession)
2816+
expect(diffViewProvider["originalContent"]).toBe("the retry's own baseline")
2817+
expect(diffViewProvider["activeDiffEditor"]).toBe(retryEditor)
2818+
})
2819+
2820+
it("reverts the live edit when it is the session the record describes", async () => {
2821+
const relPath = "mock-recovery-target.ts"
2822+
const absolutePath = `${mockCwd}/${relPath}`
2823+
const editor = simulateReset()
2824+
const restorePreStreamBuffer = vi.fn().mockResolvedValue(undefined)
2825+
const saveBufferClean = vi.fn().mockResolvedValue(undefined)
2826+
diffViewProvider["restorePreStreamBuffer"] = restorePreStreamBuffer
2827+
diffViewProvider["saveBufferClean"] = saveBufferClean
2828+
diffViewProvider["keepOrCloseEditedFile"] = vi.fn().mockResolvedValue(undefined)
2829+
// The pin the case above needs: the stamp refuses another attempt, it does not refuse the
2830+
// rollback that was asked for. The edit is live under the session this record names.
2831+
Object.assign(diffViewProvider, {
2832+
isEditing: true,
2833+
relPath,
2834+
editType: "modify",
2835+
createdDirs: [],
2836+
originalContent: "on-disk original",
2837+
activeDiffEditor: editor,
2838+
})
2839+
const record = recoveryContextFor(relPath, "modify")
2840+
2841+
await expect(diffViewProvider.attemptRollbackRecovery(record)).resolves.toBe(true)
2842+
2843+
expect(restorePreStreamBuffer).toHaveBeenCalledWith(absolutePath, editor.document, "on-disk original")
2844+
expect(saveBufferClean).toHaveBeenCalledWith(absolutePath, editor.document)
2845+
})
2846+
2847+
it("stops when the same file is reopened under a newer session while its editor is being acquired", async () => {
2848+
const relPath = "mock-recovery-target.ts"
2849+
const absolutePath = `${mockCwd}/${relPath}`
2850+
const editor = simulateReset()
2851+
const restorePreStreamBuffer = vi.fn().mockResolvedValue(undefined)
2852+
const saveBufferClean = vi.fn().mockResolvedValue(undefined)
2853+
diffViewProvider["restorePreStreamBuffer"] = restorePreStreamBuffer
2854+
diffViewProvider["saveBufferClean"] = saveBufferClean
2855+
diffViewProvider["keepOrCloseEditedFile"] = vi.fn().mockResolvedValue(undefined)
2856+
const record = recoveryContextFor(relPath, "modify")
2857+
const retryEditor = makeTextEditor({
2858+
document: makeTextDocument({
2859+
uri: makeUri(absolutePath),
2860+
getText: vi.fn().mockReturnValue("the retry's own streamed buffer"),
2861+
isDirty: true,
2862+
}),
2863+
})
2864+
const retryCreatedDirs: string[] = []
2865+
const retrySession = diffViewProvider["editSession"] + 1
2866+
// The retry lands during the acquisition, which is where this recovery spends its time.
2867+
diffViewProvider["openDiffEditor"] = vi.fn(async () => {
2868+
Object.assign(diffViewProvider, {
2869+
isEditing: true,
2870+
relPath,
2871+
editType: "modify",
2872+
editSession: retrySession,
2873+
createdDirs: retryCreatedDirs,
2874+
originalContent: "the retry's own baseline",
2875+
activeDiffEditor: retryEditor,
2876+
})
2877+
return editor
2878+
})
2879+
2880+
await expect(diffViewProvider.attemptRollbackRecovery(record)).resolves.toBe(false)
2881+
2882+
expect(restorePreStreamBuffer).not.toHaveBeenCalled()
2883+
expect(saveBufferClean).not.toHaveBeenCalled()
2884+
// The retry keeps its own install: the editor this recovery acquired is dropped rather than
2885+
// written into the slot, and the directories and baseline the retry own open() put there are
2886+
// untouched.
2887+
expect(diffViewProvider["activeDiffEditor"]).toBe(retryEditor)
2888+
expect(diffViewProvider["createdDirs"]).toBe(retryCreatedDirs)
2889+
expect(diffViewProvider["originalContent"]).toBe("the retry's own baseline")
2890+
expect(diffViewProvider["editSession"]).toBe(retrySession)
2891+
})
2892+
2893+
it("rethrows a failed acquisition without putting its own install back over a newer one on the same file", async () => {
2894+
const relPath = "mock-recovery-target.ts"
2895+
const absolutePath = `${mockCwd}/${relPath}`
2896+
const gone = new Error("the buffer this recovery needs cannot be reopened")
2897+
simulateReset()
2898+
const restorePreStreamBuffer = vi.fn().mockResolvedValue(undefined)
2899+
const saveBufferClean = vi.fn().mockResolvedValue(undefined)
2900+
diffViewProvider["restorePreStreamBuffer"] = restorePreStreamBuffer
2901+
diffViewProvider["saveBufferClean"] = saveBufferClean
2902+
diffViewProvider["keepOrCloseEditedFile"] = vi.fn().mockResolvedValue(undefined)
2903+
const record = recoveryContextFor(relPath, "modify")
2904+
const retryEditor = makeTextEditor({
2905+
document: makeTextDocument({
2906+
uri: makeUri(absolutePath),
2907+
getText: vi.fn().mockReturnValue("the retry's own streamed buffer"),
2908+
isDirty: true,
2909+
}),
2910+
})
2911+
const retryCreatedDirs: string[] = []
2912+
const retrySession = diffViewProvider["editSession"] + 1
2913+
// Same target, same edit type, newer session, and then the buffer cannot be reopened.
2914+
diffViewProvider["openDiffEditor"] = vi.fn(async () => {
2915+
Object.assign(diffViewProvider, {
2916+
isEditing: true,
2917+
relPath,
2918+
editType: "modify",
2919+
editSession: retrySession,
2920+
createdDirs: retryCreatedDirs,
2921+
originalContent: "the retry's own baseline",
2922+
activeDiffEditor: retryEditor,
2923+
})
2924+
throw gone
2925+
})
2926+
2927+
await expect(diffViewProvider.attemptRollbackRecovery(record)).rejects.toBe(gone)
2928+
2929+
// A rejection does not make this recovery the owner of an edit it does not answer to: the fields
2930+
// it captured stay its own to put back, and the retry keeps every one of its own.
2931+
expect(restorePreStreamBuffer).not.toHaveBeenCalled()
2932+
expect(saveBufferClean).not.toHaveBeenCalled()
2933+
expect(diffViewProvider["isEditing"]).toBe(true)
2934+
expect(diffViewProvider["relPath"]).toBe(relPath)
2935+
expect(diffViewProvider["editSession"]).toBe(retrySession)
2936+
expect(diffViewProvider["createdDirs"]).toBe(retryCreatedDirs)
2937+
expect(diffViewProvider["originalContent"]).toBe("the retry's own baseline")
2938+
expect(diffViewProvider["activeDiffEditor"]).toBe(retryEditor)
2939+
})
27632940
})
27642941
// The acquisition inside openDiffEditor() races a ten-second timer against a showTextDocument it cannot
27652942
// cancel. Both cases below are about what that leaves behind: a diff nobody is waiting for, and a diff
@@ -2772,6 +2949,7 @@ describe("DiffViewProvider", () => {
27722949
absolutePath: `${mockCwd}/${relPath}`,
27732950
editType,
27742951
createdDirs: [],
2952+
editSession: diffViewProvider["editSession"],
27752953
originalContent: editType === "modify" ? "captured at acquisition" : "",
27762954
})
27772955

0 commit comments

Comments
 (0)