Skip to content

Commit 22969c6

Browse files
fix(u5): stop a timed-out acquisition from opening a diff nobody is waiting for
openDiffEditor() races a ten-second timer against a showTextDocument it cannot cancel. The timeout rejected the acquisition and disposed the listeners, but nothing stopped the follow-up callback from running the diff command anyway: the tab opened after the caller had already been told the acquisition failed, with no listener left to adopt it, and the original side of that diff was built from whatever the provider field held at that moment rather than the content the acquisition was asked to compare against. That second half matters more now than it did, because a failed recovery re-acquisition restores the previous baseline: a late callback used to see the captured one and now sees the restored one. The command is skipped once the acquisition has abandoned the path, and the compared content is captured when the acquisition starts. Behaviour is unchanged for an acquisition that settles in time: the captured value is the live value there. The capture is not extended into the buffer restore, which still reads the live field - that is a second decision this row did not ask for, and it is said in-thread rather than slipped in. Gates and controls at node v22.23.4: this spec 97 passed (97), status 0; the whole misc layer 117 passed | 1 skipped files, 2118 passed | 13 skipped (2131), status 0; vitest.core.config.ts 198 files 4294 passed | 9 skipped, status 0; tsc --noEmit -p tsconfig.json 0 errors; eslint --max-warnings=0 --no-cache over src status 0; prettier --check clean; suppression counts unchanged at 265 files / 2870 entries. Controls: deleting the abandon check makes the timeout case fail ('expected vi.fn() to not be called at all, but actually been called 1 times', status 1), and reading the live field instead of the captured one makes the baseline case fail (expected ['c3dhcHBlZCBtaWQtZmxpZ2h0'] to deeply equal ['Y2FwdHVyZWQgYXQgYWNxdWlzaXRpb24='], status 1). The component was written back byte-for-byte after each control and re-run green. Not pushed with 7a1a710: that round's single push was spent, and the Lead fixed 7bf8573 as the next head, so which head carries this commit is the Lead's call.
1 parent 7bf8573 commit 22969c6

2 files changed

Lines changed: 188 additions & 1 deletion

File tree

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1176,6 +1176,13 @@ export class DiffViewProvider {
11761176
const fileName = path.basename(uri.fsPath)
11771177
const fileExists = this.editType === "modify"
11781178
const DIFF_EDITOR_TIMEOUT = 10_000 // ms
1179+
// The diff original side is built when the pre-open settles below, which can be after this
1180+
// promise already settled. Captured at acquisition time so a late callback cannot compare against
1181+
// a baseline some other flow installed in the meantime.
1182+
const capturedOriginalContent = this.originalContent
1183+
// Set when this acquisition gives up. The timeout rejects the promise but cannot cancel
1184+
// showTextDocument, so without this the diff command still runs for a caller that left.
1185+
let acquisitionAbandoned = false
11791186

11801187
let timeoutId: NodeJS.Timeout | undefined
11811188
const disposables: vscode.Disposable[] = []
@@ -1191,6 +1198,7 @@ export class DiffViewProvider {
11911198

11921199
// Set timeout for the entire operation
11931200
timeoutId = setTimeout(() => {
1201+
acquisitionAbandoned = true
11941202
cleanup()
11951203
reject(
11961204
new Error(
@@ -1240,11 +1248,17 @@ export class DiffViewProvider {
12401248
vscode.window
12411249
.showTextDocument(uri, { preview: false, viewColumn: vscode.ViewColumn.Active, preserveFocus: true })
12421250
.then(() => {
1251+
if (acquisitionAbandoned) {
1252+
// Nobody is waiting for this acquisition any more. The tab would outlive every listener it
1253+
// needed (the disposables went with the timeout) and the caller has already put the provider
1254+
// back the way it found it, so the diff would compare against somebody else baseline.
1255+
return
1256+
}
12431257
// Execute the diff command after ensuring the file is open as text
12441258
return vscode.commands.executeCommand(
12451259
"vscode.diff",
12461260
vscode.Uri.parse(`${DIFF_VIEW_URI_SCHEME}:${fileName}`).with({
1247-
query: Buffer.from(this.originalContent ?? "").toString("base64"),
1261+
query: Buffer.from(capturedOriginalContent ?? "").toString("base64"),
12481262
}),
12491263
uri,
12501264
`${fileName}: ${fileExists ? `${DIFF_VIEW_LABEL_CHANGES}` : "New File"} (Editable)`,

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

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2607,4 +2607,177 @@ describe("DiffViewProvider", () => {
26072607
expect(saveBufferClean).toHaveBeenCalledWith(absolutePath, editor.document)
26082608
})
26092609
})
2610+
// The acquisition inside openDiffEditor() races a ten-second timer against a showTextDocument it cannot
2611+
// cancel. Both cases below are about what that leaves behind: a diff nobody is waiting for, and a diff
2612+
// original side built from whatever the field holds when the callback finally runs.
2613+
describe("openDiffEditor() gives up on a diff nobody is waiting for", () => {
2614+
// Local to this suite on purpose: the fixture here is the real acquisition, while the recovery suite
2615+
// above stubs openDiffEditor() out to keep its cases off the tab plumbing and the timer.
2616+
const recoveryFor = (relPath: string, editType: "create" | "modify") => ({
2617+
relPath,
2618+
absolutePath: `${mockCwd}/${relPath}`,
2619+
editType,
2620+
createdDirs: [],
2621+
originalContent: editType === "modify" ? "captured at acquisition" : "",
2622+
})
2623+
2624+
const wireAcquisition = (editor: vscode.TextEditor) => {
2625+
// A tab already open on this path takes the activate-existing-diff fast path inside
2626+
// openDiffEditor() and skips the acquisition this suite is about, so the tab list is pinned empty
2627+
// here instead of inherited from whichever suite ran last.
2628+
Object.defineProperty(vscode.window.tabGroups, "all", {
2629+
get: (): vscode.TabGroup[] => [],
2630+
configurable: true,
2631+
})
2632+
let settleShow: (() => void) | undefined
2633+
// Recorded so a case can prove the pre-open really did settle late; otherwise the assertion that
2634+
// nothing opened would pass on an acquisition that never reached its follow-up callback.
2635+
let showSettled = false
2636+
const showDeferred = new Promise<vscode.TextEditor>((resolve) => {
2637+
settleShow = () => {
2638+
showSettled = true
2639+
resolve(editor)
2640+
}
2641+
})
2642+
vi.mocked(vscode.window.showTextDocument).mockImplementation(() => showDeferred)
2643+
let documentOpened: ((document: vscode.TextDocument) => unknown) | undefined
2644+
const disposeOpenDocument = vi.fn()
2645+
vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => {
2646+
documentOpened = callback
2647+
return { dispose: disposeOpenDocument }
2648+
})
2649+
const disposeVisibleEditors = vi.fn()
2650+
vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: disposeVisibleEditors })
2651+
vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined)
2652+
// Accessors rather than the values: the component fills both in after this returns, so a snapshot
2653+
// would hand back undefined and a case would pass without ever reaching the acquisition.
2654+
return {
2655+
settleShow: () => settleShow?.(),
2656+
showSettled: () => showSettled,
2657+
documentOpened: (document: vscode.TextDocument) => documentOpened?.(document),
2658+
registered: () => documentOpened !== undefined,
2659+
disposeOpenDocument,
2660+
disposeVisibleEditors,
2661+
}
2662+
}
2663+
2664+
const inactiveProvider = (originalContent: string | undefined) => {
2665+
Object.assign(diffViewProvider, {
2666+
isEditing: false,
2667+
relPath: undefined,
2668+
editType: undefined,
2669+
createdDirs: [],
2670+
originalContent,
2671+
activeDiffEditor: undefined,
2672+
})
2673+
}
2674+
2675+
const recoveryDocument = (absolutePath: string): vscode.TextDocument =>
2676+
makeTextDocument({
2677+
uri: makeUri(absolutePath),
2678+
getText: vi.fn().mockReturnValue("streamed, never approved"),
2679+
isDirty: true,
2680+
})
2681+
2682+
it("does not open the diff once the acquisition has timed out on the path", async () => {
2683+
const relPath = "mock-recovery-target.ts"
2684+
const absolutePath = `${mockCwd}/${relPath}`
2685+
const document = recoveryDocument(absolutePath)
2686+
const editor = makeTextEditor({ document })
2687+
// Nothing on screen for this path, so no listener resolves the acquisition early.
2688+
vi.mocked(vscode.window).visibleTextEditors = []
2689+
const wire = wireAcquisition(editor)
2690+
inactiveProvider(undefined)
2691+
vi.useFakeTimers()
2692+
let failure: unknown
2693+
try {
2694+
// Kicked off without awaiting: the recovery awaits the acquisition, and the acquisition only
2695+
// ever settles on the timer.
2696+
const recovery = diffViewProvider.attemptRollbackRecovery(recoveryFor(relPath, "modify"))
2697+
// Attached at kickoff: the timeout rejects while the clock below is being advanced, and a
2698+
// handler fitted only afterwards would let the runtime log it as an unhandled rejection first.
2699+
const rejection = recovery.catch((reason: unknown) => reason)
2700+
// The pre-open starts in the same synchronous stretch that installs the edit context.
2701+
expect(vscode.window.showTextDocument).toHaveBeenCalledTimes(1)
2702+
expect(vscode.commands.executeCommand).not.toHaveBeenCalled()
2703+
expect(wire.registered()).toBe(true)
2704+
await vi.advanceTimersByTimeAsync(10_000)
2705+
failure = await rejection
2706+
expect(String(failure)).toContain("Failed to open diff editor for /mock/cwd/mock-recovery-target.ts")
2707+
expect(String(failure)).toContain("within 10 seconds")
2708+
expect(wire.disposeOpenDocument).toHaveBeenCalledTimes(1)
2709+
expect(wire.disposeVisibleEditors).toHaveBeenCalledTimes(1)
2710+
expect(diffViewProvider["isEditing"]).toBe(false)
2711+
expect(diffViewProvider["relPath"]).toBeUndefined()
2712+
expect(diffViewProvider["originalContent"]).toBeUndefined()
2713+
// The pre-open the timeout could not cancel settles here, so the follow-up callback runs on a
2714+
// path whose acquisition already reported failure to its caller.
2715+
wire.settleShow()
2716+
expect(wire.showSettled()).toBe(true)
2717+
await vi.advanceTimersByTimeAsync(0)
2718+
} finally {
2719+
vi.useRealTimers()
2720+
}
2721+
expect(vscode.commands.executeCommand).not.toHaveBeenCalled()
2722+
expect(diffViewProvider["activeDiffEditor"]).toBeUndefined()
2723+
})
2724+
2725+
it("builds the diff original side from the baseline the acquisition captured", async () => {
2726+
const relPath = "mock-recovery-target.ts"
2727+
const absolutePath = `${mockCwd}/${relPath}`
2728+
const document = recoveryDocument(absolutePath)
2729+
const editor = makeTextEditor({ document })
2730+
vi.mocked(vscode.window).visibleTextEditors = [editor]
2731+
const wire = wireAcquisition(editor)
2732+
const restorePreStreamBuffer = vi.fn().mockResolvedValue(undefined)
2733+
const saveBufferClean = vi.fn().mockResolvedValue(undefined)
2734+
diffViewProvider["restorePreStreamBuffer"] = restorePreStreamBuffer
2735+
diffViewProvider["saveBufferClean"] = saveBufferClean
2736+
diffViewProvider["keepOrCloseEditedFile"] = vi.fn().mockResolvedValue(undefined)
2737+
// The original side carries the compared content base64-encoded in its query, which is the only
2738+
// observable trace of the baseline the diff command was handed. The double provides with(), the
2739+
// one member the acquisition reads off the parsed uri.
2740+
const originalQueries: string[] = []
2741+
vi.mocked(vscode.Uri.parse).mockImplementation((value: string) => {
2742+
return {
2743+
with: (change: { query?: string }) => {
2744+
originalQueries.push(String(change.query))
2745+
// Only forwarded to the doubled diff command; the double carries nothing else.
2746+
return { fsPath: value } as unknown as vscode.Uri
2747+
},
2748+
} as unknown as vscode.Uri
2749+
})
2750+
inactiveProvider("left over from the previous edit")
2751+
vi.useFakeTimers()
2752+
let listenerRun: unknown
2753+
try {
2754+
const recovery = diffViewProvider.attemptRollbackRecovery(recoveryFor(relPath, "modify"))
2755+
recovery.catch(() => undefined)
2756+
// Mid-flight another flow installs a different baseline on the same provider. A callback that
2757+
// read the field when it ran would build this diff from that other content instead.
2758+
diffViewProvider["originalContent"] = "swapped mid-flight"
2759+
wire.settleShow()
2760+
// The listener awaits a tick before it looks the editor up, so the tick has to advance.
2761+
listenerRun = wire.documentOpened(recoveryDocument(absolutePath))
2762+
await vi.advanceTimersByTimeAsync(1)
2763+
await listenerRun
2764+
await expect(recovery).resolves.toBe(true)
2765+
} finally {
2766+
vi.useRealTimers()
2767+
}
2768+
// The capture is for the diff original side, which is what this row names. What the buffer restore
2769+
// is handed is still the live field, so the mid-flight value is what the rollback writes back; that
2770+
// half is stated here rather than changed, because widening the guard into the restore would be a
2771+
// second decision the row did not ask for.
2772+
expect(restorePreStreamBuffer).toHaveBeenCalledWith(absolutePath, editor.document, "swapped mid-flight")
2773+
expect(originalQueries).toEqual([Buffer.from("captured at acquisition").toString("base64")])
2774+
expect(vscode.commands.executeCommand).toHaveBeenCalledWith(
2775+
"vscode.diff",
2776+
expect.anything(),
2777+
expect.anything(),
2778+
`mock-recovery-target.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`,
2779+
{ preserveFocus: true },
2780+
)
2781+
})
2782+
})
26102783
})

0 commit comments

Comments
 (0)