import { DiffViewProvider, DIFF_VIEW_URI_SCHEME, DIFF_VIEW_LABEL_CHANGES, RollbackConflictError, } from "../DiffViewProvider" import { DecorationController } from "../DecorationController" import type { Mock } from "vitest" import * as vscode from "vscode" import * as path from "path" import delay from "delay" import { DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { makePosition, makeRange, makeSelection, makeTextDocument, makeTextEditor, makeUri, } from "../../../test-utils/vscode" import * as fs from "fs/promises" import { computeVersionToken, versionTokenOfStat } from "../../../utils/versionToken" import type { BigIntStats } from "fs" import { PostCommitDurabilityError, safeWriteText } from "../../../services/file-safety/safeWriteText" import { withFileLock } from "../../../utils/fileLock" import { createDirectoriesForFile } from "../../../utils/fs" import { ObservationRegistry } from "../../../core/task/observationRegistry" import { GuardRejectedError, GuardStaleVersionError } from "../../../core/tools/guardedWrite" import type { Task } from "../../../core/task/Task" // Mock delay vi.mock("delay", () => ({ default: vi.fn().mockResolvedValue(undefined), })) // Mock fs/promises vi.mock("fs/promises", () => ({ readFile: vi.fn().mockResolvedValue("file content"), writeFile: vi.fn().mockResolvedValue(undefined), access: vi.fn().mockResolvedValue(undefined), // The S4b follow-up (#44) preview observation stats the target before and // after reading it; undefined stats leave the target unobserved (fail closed). stat: vi.fn().mockResolvedValue(undefined), mkdir: vi.fn().mockResolvedValue(undefined), rename: vi.fn().mockResolvedValue(undefined), unlink: vi.fn().mockResolvedValue(undefined), rmdir: vi.fn().mockResolvedValue(undefined), // guardedWrite canonicalizes the workspace root and the caller's alias for the // containment check; identity keeps every fixture's paths stable. realpath: vi.fn(async (value: string) => String(value)), })) // Mock safeWriteText (used by saveDirectly) vi.mock("../../../services/file-safety/safeWriteText", () => ({ safeWriteText: vi.fn().mockResolvedValue(undefined), resolveLockKey: vi.fn(async (p: string) => p), // The guard fixes the publish target inside the lock through this helper; // the identity default keeps every path in this file unchanged. resolvePublishTarget: vi.fn(async (p: string) => p), // The dual-identity lock takes this alias-entry key beside the referent // key; the identity default folds both to one, as every path here is a // plain file. resolveLinkPathLockKey: vi.fn(async (p: string) => p), // The guarded write recognises a landed-but-not-durable publish by this error's // identity, and this spec replaces the whole module, so the class is restated // here with the real constructor shape rather than imported. PostCommitDurabilityError: class PostCommitDurabilityError extends Error { readonly targetPath: string constructor(targetPath: string, cause: unknown) { super("the rename committed but the parent directory could not be fsynced", { cause }) this.name = "PostCommitDurabilityError" this.targetPath = targetPath } }, })) // Mock the S1 version token (used by the S4 guarded write); the real // computeVersionToken needs fs.stat, which is not part of the fs/promises mock above. // Keep the real versionTokenOfStat: DiffViewProvider.open() (S4b follow-up #44) // derives the preview token from its synthetic stat mock with that pure function. vi.mock("../../../utils/versionToken", async () => { const actual = await vi.importActual("../../../utils/versionToken") return { computeVersionToken: vi.fn(), versionTokenOfStat: actual.versionTokenOfStat, } }) // Mock utils // Mock the shared advisory lock that the guarded-write path uses; the real // proper-lockfile would try to create a lock directory on the mocked fs. vi.mock("../../../utils/fileLock", () => ({ withFileLock: vi.fn(async (filePath: string, operation: (p: string) => Promise) => operation(filePath)), })) vi.mock("../../../utils/fs", () => ({ createDirectoriesForFile: vi.fn().mockResolvedValue([]), })) // Mock path vi.mock("path", () => ({ resolve: vi.fn((cwd: string, relPath?: string) => (relPath === undefined ? cwd : `${cwd}/${relPath}`)), isAbsolute: vi.fn((p: string) => p.startsWith("/")), basename: vi.fn((path) => path.split("/").pop()), dirname: vi.fn((path) => path.split("/").slice(0, -1).join("/") || "/"), join: (...args: string[]) => args.join("/"), })) // Mock vscode vi.mock("vscode", () => ({ workspace: { applyEdit: vi.fn(), // VS Code's own codec. The double returns bytes that differ from the plain // UTF-8 encoding of the same text, so an assertion can prove the publish // writes the codec's output rather than re-encoding the string itself. encode: vi.fn((content: string, options: { encoding: string }) => Promise.resolve( options.encoding === "utf8bom" ? Buffer.concat([Buffer.from("\uFEFF"), Buffer.from(content)]) : Buffer.from(content), ), ), onDidOpenTextDocument: vi.fn(() => ({ dispose: vi.fn() })), openTextDocument: vi.fn().mockResolvedValue({ isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), textDocuments: [], fs: { stat: vi.fn(), }, }, window: { createTextEditorDecorationType: vi.fn(), activeTextEditor: undefined as unknown, showTextDocument: vi.fn(), onDidChangeVisibleTextEditors: vi.fn(() => ({ dispose: vi.fn() })), onDidChangeActiveTextEditor: vi.fn(() => ({ dispose: vi.fn() })), onDidChangeTextEditorSelection: vi.fn(() => ({ dispose: vi.fn() })), onDidChangeTextEditorVisibleRanges: vi.fn(() => ({ dispose: vi.fn() })), tabGroups: { all: [], close: vi.fn(), activeTabGroup: { activeTab: undefined }, }, visibleTextEditors: [], }, commands: { executeCommand: vi.fn(), }, languages: { getDiagnostics: vi.fn(() => []), }, DiagnosticSeverity: { Error: 0, Warning: 1, Information: 2, Hint: 3, }, WorkspaceEdit: vi.fn().mockImplementation(function () { return { replace: vi.fn(), delete: vi.fn(), } }), ViewColumn: { Active: 1, Beside: 2, One: 1, Two: 2, Three: 3, Four: 4, Five: 5, Six: 6, Seven: 7, Eight: 8, Nine: 9, }, // Use regular functions (not arrows) so these mocks can be invoked with `new`. // vitest v4 / tinyspy invokes the implementation as a constructor for `new mock()`, // and arrow functions throw "is not a constructor". Range: vi.fn().mockImplementation(function (startLine, startChar, endLine, endChar) { return { start: { line: startLine, character: startChar }, end: { line: endLine, character: endChar }, } }), Position: vi.fn().mockImplementation(function (line, character) { return { line, character } }), Selection: vi.fn().mockImplementation(function (anchor, active) { return { anchor, active } }), TextEditorRevealType: { Default: 0, InCenter: 2, InCenterIfOutsideViewport: 3, AtTop: 4, }, TextEditorSelectionChangeKind: { Keyboard: 1, Mouse: 2, Command: 3, }, TabInputText: class TabInputText {}, TabInputTextDiff: class TabInputTextDiff {}, Uri: { file: vi.fn((path) => ({ fsPath: path })), parse: vi.fn((_uri) => ({ with: vi.fn(() => ({})) })), }, })) // Mock DecorationController vi.mock("../DecorationController", () => ({ DecorationController: vi.fn().mockImplementation(function () { return { setActiveLine: vi.fn(), updateOverlayAfterLine: vi.fn(), addLines: vi.fn(), clear: vi.fn(), } }), })) describe("DiffViewProvider", () => { let diffViewProvider: DiffViewProvider const mockCwd = "/mock/cwd" let mockWorkspaceEdit: { replace: Mock; delete: Mock } let mockTask: Task // Tab doubles: the mocked vscode classes ignore constructor arguments, so the // uri/original/modified members the source reads after `instanceof` checks are // assigned directly onto real mocked-class instances. const makeTextTab = (fsPath: string): vscode.TabInputText => Object.assign(new vscode.TabInputText(makeUri(fsPath)), { uri: makeUri(fsPath) }) const makeDiffTabInput = (originalScheme: string, modifiedFsPath: string): vscode.TabInputTextDiff => Object.assign(new vscode.TabInputTextDiff(makeUri(modifiedFsPath), makeUri(modifiedFsPath)), { original: { scheme: originalScheme }, modified: { fsPath: modifiedFsPath }, }) const makeTab = (input: vscode.Tab["input"], label: string, overrides: Partial = {}): vscode.Tab => ({ input, label, isDirty: false, isPinned: false, isPreview: false, isActive: false, group: { isActive: false, viewColumn: vscode.ViewColumn.One, activeTab: undefined, tabs: [] }, ...overrides, }) const makePreviewTab = (fsPath: string, isPreview = true): vscode.Tab => makeTab(makeTextTab(fsPath), fsPath, { isPreview }) // Minimal Uri double: provides only the fsPath/scheme members the restore // snapshot path reads, so toEqual assertions stay exact. const makeSnapshotUri = (fsPath: string): vscode.Uri => ({ fsPath, scheme: "file" }) as unknown as vscode.Uri // Task double provides providerRef.deref() -> getState() with provider settings, // plus the cwd and observation registry the guarded write path reads. const makeTaskDouble = ({ state = {}, cwd = mockCwd, observationRegistry = new ObservationRegistry(), }: { state?: Record cwd?: string observationRegistry?: ObservationRegistry } = {}): Task => ({ cwd, observationRegistry, providerRef: { deref: vi.fn().mockReturnValue({ getState: vi.fn().mockResolvedValue({ includeDiagnosticMessages: true, maxDiagnosticMessages: 50, ...state, }), }), }, }) as unknown as Task beforeEach(() => { vi.clearAllMocks() mockWorkspaceEdit = { replace: vi.fn(), delete: vi.fn(), } vi.mocked(vscode.WorkspaceEdit).mockImplementation(function () { // WorkspaceEdit double provides replace() and delete(), the only members // update()/revertChanges() call. return mockWorkspaceEdit as unknown as vscode.WorkspaceEdit }) // Create a mock Task instance. The double provides providerRef.deref() -> // getState() with provider settings (see makeTaskDouble above); the guarded // write (S4b) consults the task's S2 observation registry, so the double // carries a real (in-memory) instance. Auto-closing edited tabs is opt-in // by default; the legacy "close/keep behavior" suite below asserts the close // path, so enable it here. The opt-in default itself is covered by the // dedicated "auto-close settings decision table" suite. mockTask = makeTaskDouble({ state: { autoCloseZooOpenedFiles: true } }) diffViewProvider = new DiffViewProvider(mockCwd, mockTask) // Mock the necessary properties and methods diffViewProvider["relPath"] = "test.txt" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/test.txt`), lineCount: 10 }), }) // Decoration doubles provide setActiveLine/clear and // updateOverlayAfterLine/addLines/clear respectively. diffViewProvider["activeLineController"] = { setActiveLine: vi.fn(), clear: vi.fn(), } as unknown as DecorationController diffViewProvider["fadedOverlayController"] = { updateOverlayAfterLine: vi.fn(), addLines: vi.fn(), clear: vi.fn(), } as unknown as DecorationController // S4b follow-up (#44): saveChanges publishes the accepted diff through the // guarded write, which requires the target to be observed at the previewed // on-disk version. Seed the preconditions for the relPaths the suites below // use; the guarded-write suites override or clear as needed. mockTask.observationRegistry.observe(`${mockCwd}/test.txt`, "v1") mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, "v1") mockTask.observationRegistry.observe(`${mockCwd}/mock-target-file.ts`, "v1") vi.mocked(computeVersionToken).mockResolvedValue("v1") }) describe("update method", () => { it("should preserve empty last line when original content has one", async () => { diffViewProvider.originalContent = "Original content\n" await diffViewProvider.update("New content", true) expect(mockWorkspaceEdit.replace).toHaveBeenCalledWith( expect.anything(), expect.anything(), "New content\n", ) }) it("should not add extra newline when accumulated content already ends with one", async () => { diffViewProvider.originalContent = "Original content\n" await diffViewProvider.update("New content\n", true) expect(mockWorkspaceEdit.replace).toHaveBeenCalledWith( expect.anything(), expect.anything(), "New content\n", ) }) it("should not add newline when original content does not end with one", async () => { diffViewProvider.originalContent = "Original content" await diffViewProvider.update("New content", true) expect(mockWorkspaceEdit.replace).toHaveBeenCalledWith(expect.anything(), expect.anything(), "New content") }) }) describe("open method", () => { it("should pre-open file as text document before executing diff command", async () => { // Setup const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/test.md`) }), }) // Track the order of calls const callOrder: string[] = [] // Mock showTextDocument to track when it's called vi.mocked(vscode.window.showTextDocument).mockImplementation(async (_uri, options) => { callOrder.push("showTextDocument") expect(options).toEqual({ preview: false, viewColumn: vscode.ViewColumn.Active, preserveFocus: true }) return mockEditor }) // Mock executeCommand to track when it's called vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { callOrder.push("executeCommand") expect(command).toBe("vscode.diff") return undefined }) // Mock workspace.onDidOpenTextDocument to trigger immediately vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { // Trigger the callback immediately with the document setTimeout(() => { callback(makeTextDocument({ uri: makeUri(`${mockCwd}/test.md`) })) }, 0) return { dispose: vi.fn() } }) // Mock window.visibleTextEditors to return our editor vi.mocked(vscode.window).visibleTextEditors = [mockEditor] // Set up for file diffViewProvider.editType = "modify" // Execute open await diffViewProvider.open("test.md") // Verify that showTextDocument was called before executeCommand expect(callOrder).toEqual(["showTextDocument", "executeCommand"]) // Verify that showTextDocument was called with preview: false and preserveFocus: true expect(vscode.window.showTextDocument).toHaveBeenCalledWith( expect.objectContaining({ fsPath: `${mockCwd}/test.md` }), { preview: false, viewColumn: vscode.ViewColumn.Active, preserveFocus: true }, ) // Verify that the diff command was executed expect(vscode.commands.executeCommand).toHaveBeenCalledWith( "vscode.diff", expect.any(Object), expect.any(Object), `test.md: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`, { preserveFocus: true }, ) }) it.each([new Error("Cannot open file"), "Cannot open file"])( "should handle showTextDocument failure: %s", async (reason) => { // Mock showTextDocument to fail vi.mocked(vscode.window.showTextDocument).mockRejectedValue(reason) // Mock workspace.onDidOpenTextDocument const disposeOpenDocument = vi.fn() vi.mocked(vscode.workspace.onDidOpenTextDocument).mockReturnValue({ dispose: disposeOpenDocument }) // Mock window.onDidChangeVisibleTextEditors const disposeVisibleEditors = vi.fn() vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: disposeVisibleEditors, }) // Set up for file diffViewProvider.editType = "modify" // Try to open and expect rejection await expect(diffViewProvider.open("test.md")).rejects.toThrow( "Failed to execute diff command for /mock/cwd/test.md: Cannot open file", ) expect(disposeOpenDocument).toHaveBeenCalledOnce() expect(disposeVisibleEditors).toHaveBeenCalledOnce() }, ) it("records the pin state of an already-open pinned tab", async () => { const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/test.md`) }), }) // An open, pinned, non-dirty tab for the target file. const pinnedTab = makeTab(makeTextTab(`${mockCwd}/test.md`), "test.md", { isPinned: true }) Object.defineProperty(vscode.window.tabGroups, "all", { get: () => [{ tabs: [pinnedTab] }], configurable: true, }) vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => { callback(makeTextDocument({ uri: makeUri(`${mockCwd}/test.md`) })) }, 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] diffViewProvider.editType = "modify" await diffViewProvider.open("test.md") expect(diffViewProvider["documentWasPinned"]).toBe(true) expect(diffViewProvider["documentWasOpen"]).toBe(true) }) }) describe("scrollToFirstDiff method", () => { const setupEditor = (currentContent: string) => { const revealRange = vi.fn() const document = makeTextDocument({ uri: makeUri(`${mockCwd}/mock-file-target.txt`), getText: vi.fn().mockReturnValue(currentContent), }) const editor = makeTextEditor({ document, visibleRanges: [makeRange()], revealRange, }) diffViewProvider["activeDiffEditor"] = editor // Register the editor as the live modified-side editor so resolveLiveEditor // finds it by document identity, mirroring the runtime path. vi.mocked(vscode.window).visibleTextEditors = [editor] return revealRange } it("reveals the first changed line for an addition-only diff", () => { diffViewProvider.originalContent = "a\nb\nc\n" // Insert a new line between b and c (first change is at line index 2). const revealRange = setupEditor("a\nb\nNEW\nc\n") diffViewProvider.scrollToFirstDiff() expect(revealRange).toHaveBeenCalledTimes(1) const range = revealRange.mock.calls[0][0] expect(range.start.line).toBe(2) }) it("reveals the first changed line for a deletion-only diff", () => { diffViewProvider.originalContent = "a\nb\nc\nd\n" // Remove line c; the first change is the removed block at line index 2. const revealRange = setupEditor("a\nb\nd\n") diffViewProvider.scrollToFirstDiff() expect(revealRange).toHaveBeenCalledTimes(1) const range = revealRange.mock.calls[0][0] expect(range.start.line).toBe(2) }) it("clamps to the last line for a removal at the end of the file", () => { // Long file; remove the final lines. The first-change index lands past the // end of the shortened modified document, so it must be clamped to a real // line or the diff widget will not scroll. diffViewProvider.originalContent = "a\nb\nc\nd\ne\nf\n" const revealRange = setupEditor("a\nb\nc\n") diffViewProvider.scrollToFirstDiff() expect(revealRange).toHaveBeenCalledTimes(1) const range = revealRange.mock.calls[0][0] // Modified document has lines a,b,c (+ trailing empty) => lastLine index 3. // The removed block begins at index 3, which is within bounds here. expect(range.start.line).toBeLessThanOrEqual(3) expect(range.start.line).toBeGreaterThanOrEqual(0) }) it("reveals the first changed line for a mixed diff", () => { diffViewProvider.originalContent = "a\nb\nc\nd\n" // Change line b (index 1) -- first divergence from the original. const revealRange = setupEditor("a\nCHANGED\nc\nd\n") diffViewProvider.scrollToFirstDiff() expect(revealRange).toHaveBeenCalledTimes(1) const range = revealRange.mock.calls[0][0] expect(range.start.line).toBe(1) }) it("anchors the selection on the target line so an in-viewport diff still scrolls", () => { // Regression for the case where the file is already scrolled to the middle // and the diff target is inside the current viewport: a bare revealRange is // a no-op, leaving the viewport pinned at the top. Moving the selection to // the target first forces the diff widget to scroll to the change. diffViewProvider.originalContent = "a\nb\nc\nd\n" const revealRange = setupEditor("a\nCHANGED\nc\nd\n") diffViewProvider.scrollToFirstDiff() const editor = diffViewProvider["activeDiffEditor"] if (!editor) { throw new Error("activeDiffEditor was not set") } expect(editor.selection.active.line).toBe(1) expect(editor.selection.anchor.line).toBe(1) expect(revealRange).toHaveBeenCalledTimes(1) expect(revealRange.mock.calls[0][0].start.line).toBe(1) }) it("re-reveals the target line after layout settles", () => { // The diff editor can snap the viewport back to the top during its late // layout pass when the file was already scrolled. A deferred re-reveal // makes the scroll stick. Verify the second reveal fires on a timer. vi.useFakeTimers() try { diffViewProvider.originalContent = "a\nb\nc\nd\n" const revealRange = setupEditor("a\nCHANGED\nc\nd\n") diffViewProvider.scrollToFirstDiff() expect(revealRange).toHaveBeenCalledTimes(1) // Mock timer - no wall clock time elapses here vi.advanceTimersByTime(100) expect(revealRange).toHaveBeenCalledTimes(2) for (const call of revealRange.mock.calls) { expect(call[0].start.line).toBe(1) } } finally { vi.useRealTimers() } }) it("reveals on the live modified-side editor, not a stale captured reference", () => { // Regression for "scrolls to top": the captured activeDiffEditor can be a // detached editor whose visibleRanges no longer match the on-screen diff, // making revealRange a no-op. The reveal must target the live editor found // in visibleTextEditors for the same document. diffViewProvider.originalContent = "a\nb\nc\nd\n" const staleReveal = setupEditor("a\nCHANGED\nc\nd\n") const staleEditor = diffViewProvider["activeDiffEditor"] if (!staleEditor) { throw new Error("activeDiffEditor was not set") } // A live editor for the SAME document, distinct from the stale capture. const liveReveal = vi.fn() const liveEditor = makeTextEditor({ document: staleEditor.document, visibleRanges: [makeRange()], revealRange: liveReveal, }) vi.mocked(vscode.window).visibleTextEditors = [liveEditor] diffViewProvider.scrollToFirstDiff() expect(liveReveal).toHaveBeenCalledTimes(1) expect(staleReveal).not.toHaveBeenCalled() expect(liveReveal.mock.calls[0][0].start.line).toBe(1) }) it("does not re-reveal a stale line on a diff editor opened by a later edit", () => { // Regression for the "stuck at line 0" bug: a deferred reveal must not act // after a subsequent edit swapped in a different active diff editor. vi.useFakeTimers() try { diffViewProvider.originalContent = "a\nb\nc\nd\n" const firstReveal = setupEditor("a\nCHANGED\nc\nd\n") const firstEditor = diffViewProvider["activeDiffEditor"] diffViewProvider.scrollToFirstDiff() expect(firstReveal).toHaveBeenCalledTimes(1) // A later edit swaps in a brand new diff editor before the timer fires. const secondReveal = setupEditor("a\nb\nc\nd\n") expect(diffViewProvider["activeDiffEditor"]).not.toBe(firstEditor) vi.advanceTimersByTime(100) // The stale timer saw a different active editor and did nothing more. expect(firstReveal).toHaveBeenCalledTimes(1) expect(secondReveal).not.toHaveBeenCalled() } finally { vi.useRealTimers() } }) it("does nothing when there is no diff editor", () => { diffViewProvider["activeDiffEditor"] = undefined expect(() => diffViewProvider.scrollToFirstDiff()).not.toThrow() }) }) describe("preview tab snapshot and restore", () => { const setTabs = (tabs: vscode.Tab[], viewColumn: vscode.ViewColumn = vscode.ViewColumn.One) => { Object.defineProperty(vscode.window.tabGroups, "all", { get: (): vscode.TabGroup[] => [{ isActive: true, viewColumn, activeTab: tabs[0], tabs }], configurable: true, }) } it("captures unrelated preview tabs with their scroll position and group, excluding the diff target", () => { setTabs( [ makePreviewTab("/mock/cwd/file-1.txt"), makePreviewTab("/mock/cwd/file-2.txt"), // diff target -- excluded makePreviewTab("/mock/cwd/file-3.txt", false), // not a preview -- excluded ], vscode.ViewColumn.Two, ) vi.mocked(vscode.window).visibleTextEditors = [ makeTextEditor({ document: makeTextDocument({ uri: makeUri("/mock/cwd/file-1.txt") }), visibleRanges: [makeRange(12)], }), ] const snapshot = diffViewProvider["captureUnrelatedPreviewTabs"]("/mock/cwd/file-2.txt") expect(snapshot).toHaveLength(1) expect(snapshot[0].uri.fsPath).toBe("/mock/cwd/file-1.txt") expect(snapshot[0].scrollLine).toBe(12) expect(snapshot[0].viewColumn).toBe(vscode.ViewColumn.Two) }) it("restores an evicted preview tab in its original group and reapplies its scroll position", async () => { const revealRange = vi.fn() vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor({ revealRange })) // The captured file is no longer open (evicted by the diff). setTabs([]) diffViewProvider["snapshotPreviewTabs"] = [ { uri: makeSnapshotUri("/mock/cwd/file-1.txt"), scrollLine: 12, viewColumn: vscode.ViewColumn.Two, }, ] await diffViewProvider["restorePreviewTabs"]() expect(vscode.window.showTextDocument).toHaveBeenCalledWith( { fsPath: "/mock/cwd/file-1.txt", scheme: "file" }, { preview: true, preserveFocus: true, viewColumn: vscode.ViewColumn.Two }, ) expect(revealRange).toHaveBeenCalledWith( expect.objectContaining({ start: { line: 12, character: 0 } }), vscode.TextEditorRevealType.AtTop, ) expect(diffViewProvider["snapshotPreviewTabs"]).toEqual([]) }) it("does not restore a preview tab that is still open", async () => { setTabs([makePreviewTab("/mock/cwd/file-1.txt")]) diffViewProvider["snapshotPreviewTabs"] = [ { uri: makeSnapshotUri("/mock/cwd/file-1.txt"), scrollLine: 0, viewColumn: vscode.ViewColumn.One, }, ] await diffViewProvider["restorePreviewTabs"]() expect(vscode.window.showTextDocument).not.toHaveBeenCalled() }) it("skips restoring a preview tab whose file no longer exists", async () => { setTabs([]) const fs = await import("fs/promises") vi.mocked(fs.access).mockRejectedValueOnce(new Error("ENOENT")) diffViewProvider["snapshotPreviewTabs"] = [ { uri: makeSnapshotUri("/mock/cwd/deleted.txt"), scrollLine: 0, viewColumn: vscode.ViewColumn.One, }, ] await diffViewProvider["restorePreviewTabs"]() expect(vscode.window.showTextDocument).not.toHaveBeenCalled() expect(diffViewProvider["snapshotPreviewTabs"]).toEqual([]) }) }) describe("showEditedFileWithoutDisruptingFocus", () => { it("re-activates the user's editor when they navigated to a different file", async () => { // User is viewing file-1 while the edited file is file-2. Keeping file-2 // open must not yank focus/foreground onto it. const userActiveEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri("/mock/cwd/file-1.txt") }), }) vscode.window.activeTextEditor = userActiveEditor vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) diffViewProvider["preEditScrollLine"] = 5 await diffViewProvider["showEditedFileWithoutDisruptingFocus"]("/mock/cwd/file-2.txt") // First call re-shows the edited file (preserveFocus); last call restores // the user's editor with focus. const calls = vi.mocked(vscode.window.showTextDocument).mock.calls expect(calls[0][1]).toMatchObject({ preview: false, preserveFocus: true }) const restoreCall = calls[calls.length - 1] expect(restoreCall[0]).toBe(userActiveEditor.document) expect(restoreCall[1]).toMatchObject({ viewColumn: 1, preserveFocus: false }) }) it("does not re-activate when the user is already on the edited file", async () => { const userActiveEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri("/mock/cwd/file-2.txt") }), }) vscode.window.activeTextEditor = userActiveEditor vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) await diffViewProvider["showEditedFileWithoutDisruptingFocus"]("/mock/cwd/file-2.txt") // Only the single re-show of the edited file; no focus-restore round trip. expect(vscode.window.showTextDocument).toHaveBeenCalledTimes(1) }) it("re-pins the edited file when it was pinned before the diff", async () => { const userActiveEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri("/mock/cwd/file-2.txt") }), }) vscode.window.activeTextEditor = userActiveEditor vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) diffViewProvider["documentWasPinned"] = true await diffViewProvider["showEditedFileWithoutDisruptingFocus"]("/mock/cwd/file-2.txt") // The edited file must be focused (preserveFocus false) so pinEditor // targets the correct tab, then the pin command is issued. const calls = vi.mocked(vscode.window.showTextDocument).mock.calls expect(calls[0][1]).toMatchObject({ preview: false, preserveFocus: false }) expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.pinEditor") }) it("does not pin the edited file when it was not pinned before the diff", async () => { const userActiveEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri("/mock/cwd/file-2.txt") }), }) vscode.window.activeTextEditor = userActiveEditor vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) diffViewProvider["documentWasPinned"] = false await diffViewProvider["showEditedFileWithoutDisruptingFocus"]("/mock/cwd/file-2.txt") expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith("workbench.action.pinEditor") }) }) describe("closeAllDiffViews method", () => { it("should close diff views including those identified by label", async () => { // Mock tab groups with various types of tabs const mockTabs: vscode.Tab[] = [ // Normal diff view makeTab( makeDiffTabInput(DIFF_VIEW_URI_SCHEME, "/test/file1.ts"), `file1.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`, ), // Diff view identified by label (for pre-opened files) makeTab( // Different scheme due to pre-opening makeDiffTabInput("file", "/test/file2.md"), `file2.md: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`, ), // Regular file tab (should not be closed) makeTab(makeTextTab("/test/file3.js"), "file3.js"), // Dirty diff view (should not be closed) makeTab( makeDiffTabInput(DIFF_VIEW_URI_SCHEME, "/test/file4.ts"), `file4.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`, { isDirty: true }, ), ] // Mock the tabGroups getter Object.defineProperty(vscode.window.tabGroups, "all", { get: (): vscode.TabGroup[] => [ { isActive: true, viewColumn: vscode.ViewColumn.One, activeTab: undefined, tabs: mockTabs }, ], configurable: true, }) const closedTabs: vscode.Tab[] = [] vi.mocked(vscode.window.tabGroups.close).mockImplementation((tab) => { // The close API also accepts whole groups; this suite only closes tabs. if ("length" in tab || "tabs" in tab) { throw new Error("unexpected tab group close") } closedTabs.push(tab) return Promise.resolve(true) }) // Execute closeAllDiffViews await diffViewProvider["closeAllDiffViews"]() // Verify that only the appropriate tabs were closed expect(closedTabs).toHaveLength(2) expect(closedTabs[0].label).toBe(`file1.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`) expect(closedTabs[1].label).toBe(`file2.md: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`) // Verify that the regular file and dirty diff were not closed expect(closedTabs.find((t) => t.label === "file3.js")).toBeUndefined() expect( closedTabs.find((t) => t.label === `file4.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)` && t.isDirty), ).toBeUndefined() }) }) // A rejected save belongs to one task. closeAllDiffViews() closes every clean // diff tab in the workbench, so it would close another task's diff view while // that task's provider still holds its activation listener and deferred scroll // timer against a tab that is gone. describe("closeOwnDiffView method", () => { it("closes only this provider's tab and leaves another task's diff view open", async () => { const ownTab = { input: { constructor: { name: "TabInputTextDiff" }, original: { scheme: DIFF_VIEW_URI_SCHEME }, modified: { fsPath: `${mockCwd}/test.ts` }, }, isDirty: false, } const otherTaskTab = { input: { constructor: { name: "TabInputTextDiff" }, original: { scheme: DIFF_VIEW_URI_SCHEME }, modified: { fsPath: `${mockCwd}/other-task.ts` }, }, isDirty: false, } for (const tab of [ownTab, otherTaskTab]) { Object.setPrototypeOf(tab.input, vscode.TabInputTextDiff.prototype) } Object.defineProperty(vscode.window.tabGroups, "all", { get: () => [{ tabs: [ownTab, otherTaskTab] }], configurable: true, }) const closedTabs: unknown[] = [] vi.mocked(vscode.window.tabGroups.close).mockImplementation((tab) => { closedTabs.push(tab) return Promise.resolve(true) }) await diffViewProvider["closeOwnDiffView"](path.join(mockCwd, "test.ts")) expect(closedTabs).toEqual([ownTab]) }) it.skipIf(process.platform !== "win32")( "closes the tab when the drive-letter casing differs from the resolved target", async () => { // Uri.fsPath reports a lowercase drive letter while this provider's absolutePath keeps // the casing the workspace handed it (the Desktop fallback can supply the uppercase // spelling). An exact string compare misses this provider's own tab on Windows, and a // rejected save then leaves the tab open over the discarded buffer. const ownTab = { input: { constructor: { name: "TabInputTextDiff" }, original: { scheme: DIFF_VIEW_URI_SCHEME }, modified: { fsPath: "c:\\work\\zoo\\test.ts" }, }, isDirty: false, } Object.setPrototypeOf(ownTab.input, vscode.TabInputTextDiff.prototype) Object.defineProperty(vscode.window.tabGroups, "all", { get: () => [{ tabs: [ownTab] }], configurable: true, }) const closedTabs: unknown[] = [] vi.mocked(vscode.window.tabGroups.close).mockImplementation((tab) => { closedTabs.push(tab) return Promise.resolve(true) }) await diffViewProvider["closeOwnDiffView"]("C:\\work\\zoo\\test.ts") expect(closedTabs).toEqual([ownTab]) }, ) it("leaves another task's tab when the same basename sits in another directory", async () => { // Two tasks can edit files with the same name. Matching by basename alone // would close the other task's clean tab, so the tab's own URI has to decide. const ownTab = { input: { constructor: { name: "TabInputTextDiff" }, original: { scheme: DIFF_VIEW_URI_SCHEME }, modified: { fsPath: `${mockCwd}/test.ts` }, }, label: `test.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`, isDirty: false, } const sameNameOtherDir = { input: { constructor: { name: "TabInputTextDiff" }, original: { scheme: DIFF_VIEW_URI_SCHEME }, modified: { fsPath: "/other-cwd/test.ts" }, }, label: `test.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`, isDirty: false, } // A pre-opened file's tab is identified by its label, so the URI check is the // only thing that can tell the two apart here. const labelOnlyOtherDir = { input: { uri: { fsPath: "/other-cwd/test.ts" } }, label: `test.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`, isDirty: false, } const labelOnlyOwn = { input: { uri: { fsPath: `${mockCwd}/test.ts` } }, label: `test.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`, isDirty: false, } for (const tab of [ownTab, sameNameOtherDir]) { Object.setPrototypeOf(tab.input, vscode.TabInputTextDiff.prototype) } Object.defineProperty(vscode.window.tabGroups, "all", { get: () => [{ tabs: [ownTab, sameNameOtherDir, labelOnlyOtherDir, labelOnlyOwn] }], configurable: true, }) const closedTabs: unknown[] = [] vi.mocked(vscode.window.tabGroups.close).mockImplementation((tab) => { closedTabs.push(tab) return Promise.resolve(true) }) await diffViewProvider["closeOwnDiffView"](path.join(mockCwd, "test.ts")) expect(closedTabs).toEqual([ownTab, labelOnlyOwn]) }) it("leaves a Source Control diff the user has open for the same file", async () => { // A git diff of the same file is the user's tab, not this task's, so a reset // must not close it. const ownTab = { input: { constructor: { name: "TabInputTextDiff" }, original: { scheme: DIFF_VIEW_URI_SCHEME }, modified: { fsPath: `${mockCwd}/test.ts` }, }, isDirty: false, } const gitDiffTab = { input: { constructor: { name: "TabInputTextDiff" }, original: { scheme: "git" }, modified: { fsPath: `${mockCwd}/test.ts` }, }, isDirty: false, } for (const tab of [ownTab, gitDiffTab]) { Object.setPrototypeOf(tab.input, vscode.TabInputTextDiff.prototype) } Object.defineProperty(vscode.window.tabGroups, "all", { get: () => [{ tabs: [ownTab, gitDiffTab] }], configurable: true, }) const closedTabs: unknown[] = [] vi.mocked(vscode.window.tabGroups.close).mockImplementation((tab) => { closedTabs.push(tab) return Promise.resolve(true) }) await diffViewProvider["closeOwnDiffView"](path.join(mockCwd, "test.ts")) expect(closedTabs).toEqual([ownTab]) }) }) it("reset() closes only this provider's tab, not another task's", async () => { // A guard rejection belongs to one task, and every tool caller resets that // task's provider in its catch block, so the teardown must stay inside this // provider's view. const ownTab = { input: { constructor: { name: "TabInputTextDiff" }, original: { scheme: DIFF_VIEW_URI_SCHEME }, modified: { fsPath: `${mockCwd}/test.ts` }, }, label: `test.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`, isDirty: false, } const otherTaskTab = { input: { constructor: { name: "TabInputTextDiff" }, original: { scheme: DIFF_VIEW_URI_SCHEME }, modified: { fsPath: `${mockCwd}/other-task.ts` }, }, label: `other-task.ts: ${DIFF_VIEW_LABEL_CHANGES} (Editable)`, isDirty: false, } for (const tab of [ownTab, otherTaskTab]) { Object.setPrototypeOf(tab.input, vscode.TabInputTextDiff.prototype) } Object.defineProperty(vscode.window.tabGroups, "all", { get: () => [{ tabs: [ownTab, otherTaskTab] }], configurable: true, }) const closedTabs: unknown[] = [] vi.mocked(vscode.window.tabGroups.close).mockImplementation((tab) => { closedTabs.push(tab) return Promise.resolve(true) }) diffViewProvider["relPath"] = "test.ts" await diffViewProvider.reset() expect(closedTabs).toEqual([ownTab]) }) describe("saveDirectly method", () => { beforeEach(() => { // Mock vscode functions vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) // Baseline for the single-writer flow these tests encode: the file was read // before the write, so the observation registry holds the version token the // guarded write recomputes and compares, and the target exists on disk. mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, "v1") vi.mocked(computeVersionToken).mockResolvedValue("v1") vi.mocked(fs.access).mockResolvedValue(undefined) }) it("should write content directly to file without opening diff view", async () => { const mockDelay = vi.mocked(delay) mockDelay.mockClear() const result = await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 2000) // Verify file was written via safeWriteText const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { backup: true }) // Verify file was opened without focus expect(vscode.window.showTextDocument).toHaveBeenCalledWith( expect.objectContaining({ fsPath: `${mockCwd}/test.ts` }), { preview: false, preserveFocus: true }, ) // Verify diagnostics were checked after delay expect(mockDelay).toHaveBeenCalledWith(2000) expect(vscode.languages.getDiagnostics).toHaveBeenCalled() // Verify result expect(result.newProblemsMessage).toBe("") expect(result.userEdits).toBeUndefined() expect(result.finalContent).toBe("new content") }) it("should not open file when openWithoutFocus is false", async () => { await diffViewProvider.saveDirectly("test.ts", "new content", false, true, 1000) // Verify file was written via safeWriteText const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { backup: true }) // Verify file was NOT opened expect(vscode.window.showTextDocument).not.toHaveBeenCalled() }) it("does not save a dirty buffer in the memory-only diagnostics path", async () => { // The guarded publish already committed the accepted content. Saving a dirty // buffer here would republish its stale bytes through VS Code's unguarded save // path, over what the guard wrote. const dirtyDoc = { isDirty: true, save: vi.fn().mockResolvedValue(undefined), } as unknown as vscode.TextDocument vi.mocked(vscode.workspace.openTextDocument).mockResolvedValue(dirtyDoc) await diffViewProvider.saveDirectly("test.ts", "new content", false, true, 0) expect(vscode.workspace.openTextDocument).toHaveBeenCalledWith( expect.objectContaining({ fsPath: `${mockCwd}/test.ts` }), ) expect(dirtyDoc.save).not.toHaveBeenCalled() }) it("should skip diagnostics when diagnosticsEnabled is false", async () => { const mockDelay = vi.mocked(delay) mockDelay.mockClear() vi.mocked(vscode.languages.getDiagnostics).mockClear() await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 1000) // Verify file was written via safeWriteText const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { backup: true }) // Verify delay was NOT called expect(mockDelay).not.toHaveBeenCalled() // getDiagnostics is called once for pre-diagnostics, but not for post-diagnostics expect(vscode.languages.getDiagnostics).toHaveBeenCalledTimes(1) }) it("should handle negative delay values", async () => { const mockDelay = vi.mocked(delay) mockDelay.mockClear() await diffViewProvider.saveDirectly("test.ts", "new content", true, true, -500) // Verify delay was called with 0 (safe minimum) expect(mockDelay).toHaveBeenCalledWith(0) }) it("should store results for formatFileWriteResponse", async () => { await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 1000) // Verify internal state was updated expect(diffViewProvider.newProblemsMessage).toBe("") expect(diffViewProvider.userEdits).toBeUndefined() expect(diffViewProvider["relPath"]).toBe("test.ts") expect(diffViewProvider["newContent"]).toBe("new content") }) describe("guarded write (S4b, epic #1375)", () => { const enoent = () => Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) it("rejects an unobserved write to an existing file with the read-first remediation", async () => { mockTask.observationRegistry.clear() await expect(diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0)).rejects.toThrow( "File already exists at test.ts and was not read before this write -- read the file first, then retry.", ) expect(safeWriteText).not.toHaveBeenCalled() }) it("creates an unobserved file when the target is absent", async () => { mockTask.observationRegistry.clear() vi.mocked(fs.access).mockRejectedValue(enoent()) await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { backup: true, }) }) it("forwards a caller-supplied completeness through the direct publish", async () => { // The move path: the destination's registry entry must carry the completeness // the caller earned from the source's view, not the fresh-create default. A // fresh create records complete by default, so the discriminating spelling is // the explicit false; the explicit true on a second fresh target shows the // parameter reaches the refresh in both directions. mockTask.observationRegistry.clear() vi.mocked(fs.access).mockRejectedValue(enoent()) await diffViewProvider.saveDirectly("moved-out.ts", "content", false, false, 0, "create", true, false) expect(mockTask.observationRegistry.get(`${mockCwd}/moved-out.ts`)).toMatchObject({ version: "v1", complete: false, }) await diffViewProvider.saveDirectly("moved-in.ts", "content", false, false, 0, "create", true, true) expect(mockTask.observationRegistry.get(`${mockCwd}/moved-in.ts`)).toMatchObject({ version: "v1", complete: true, }) }) it("rejects an observed write whose version token is stale", async () => { // The file changed on disk after the read that recorded "v1". vi.mocked(computeVersionToken).mockResolvedValue("v2") const result = diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) await expect(result).rejects.toThrow("Stale version") await expect(result).rejects.toThrow("re-read the file, then retry.") expect(safeWriteText).not.toHaveBeenCalled() }) it("rejects an unobserved edit-kind write before any I/O", async () => { mockTask.observationRegistry.clear() await expect( diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0, "edit"), ).rejects.toThrow("File not read yet -- read the file, then retry.") expect(safeWriteText).not.toHaveBeenCalled() expect(fs.access).not.toHaveBeenCalled() }) it("recreates an observed file that vanished after the read", async () => { vi.mocked(fs.access).mockRejectedValue(enoent()) await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { backup: true, }) }) it("fails closed when the owning task has been collected", async () => { // A real WeakRef cannot be forced to deref to undefined deterministically // (GC timing), so a structural stub stands in for the collected reference. diffViewProvider["taskRef"] = { deref: () => undefined } as unknown as WeakRef await expect(diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0)).rejects.toThrow( "Cannot guard the write: the owning task is no longer available", ) expect(safeWriteText).not.toHaveBeenCalled() }) it("reconciles the observation when a direct save landed but was not durable", async () => { // saveDirectly calls guardedWrite directly, so it has no catch of its own to // reconcile with: the commit rename put the bytes at the target and only the // parent-directory fsync after it failed. Left on "v1", the next save from // this task would be rejected stale against the version this save published // itself. const landed = new PostCommitDurabilityError(`${mockCwd}/test.ts`, new Error("EIO")) // v1 for the compare-and-swap, v2 for the post-publish read under the same // lock, then v2 again for the follow-up save. The queue is handed back in a // finally: this spec clears but does not reset mocks between tests, so a // half-consumed once-queue would leak into the tests that follow. vi.mocked(computeVersionToken) .mockResolvedValueOnce("v1") .mockResolvedValueOnce("v2") .mockResolvedValueOnce("v2") .mockResolvedValueOnce("v2") vi.mocked(safeWriteText).mockRejectedValueOnce(landed) try { const save = diffViewProvider.saveDirectly("test.ts", "new content", false, false, 0) await expect(save).rejects.toBe(landed) expect(mockTask.observationRegistry.get(`${mockCwd}/test.ts`)?.version).toBe("v2") // The follow-up save is accepted: the disk already carries the bytes // this save published, so the guard must not call them a stale version. const followUp = diffViewProvider.saveDirectly("test.ts", "later content", false, false, 0) await expect(followUp).resolves.toMatchObject({ finalContent: "later content" }) expect(safeWriteText).toHaveBeenCalledTimes(2) } finally { vi.mocked(computeVersionToken).mockReset().mockResolvedValue("v1") } }) }) }) describe("saveChanges guarded publish (S4b follow-up #44)", () => { // Synthetic stat the preview observation tokenizes with the real (unmocked) // versionTokenOfStat. Cast: the mock only implements the members the tool // and versionToken read. const previewStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats // Structural TextEditor double for the open()/saveChanges flow: only the // members they touch. One documented unknown cast stands in for the full // vscode.TextEditor type (avoids any casts; see AGENTS.md). const mockTextEditor = (fsPath: string, text = ""): vscode.TextEditor => ({ document: { uri: { fsPath, scheme: "file" }, getText: vi.fn().mockReturnValue(text), lineCount: 0, encoding: "utf8", }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), }) as unknown as vscode.TextEditor // Structural TextDocument double for the onDidOpenTextDocument callback. const mockTextDocument = (fsPath: string): vscode.TextDocument => ({ uri: { fsPath, scheme: "file" } }) as unknown as vscode.TextDocument // The workbench revert clears the model's dirty flag; the double must model // that so the cleanup can tell a completed discard from a failed one. const revertClearsDirty = (document: { isDirty: boolean }, onRevert?: () => void): void => { vi.mocked(vscode.commands.executeCommand).mockImplementation((command: string) => { if (command === "workbench.action.files.revert") { document.isDirty = false onRevert?.() } return Promise.resolve(undefined) }) } beforeEach(() => { // Private members are set via bracket notation (spec convention). // Reset the focus the revert helper reads: a test that sets it must not leak // into the next one, where cleanup could restore a stale editor. vi.mocked(vscode.window).activeTextEditor = undefined diffViewProvider["relPath"] = "test.ts" diffViewProvider["newContent"] = "new content" diffViewProvider["activeDiffEditor"] = mockTextEditor(`${mockCwd}/test.ts`, "new content") diffViewProvider["preDiagnostics"] = [] diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeOwnDiffView"] = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockTextEditor(`${mockCwd}/test.ts`)) vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) }) it("open() observes the previewed version of an existing file as a partial read, not a model read", async () => { const mockEditor = mockTextEditor(`${mockCwd}/observed.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/observed.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValue(previewStats) diffViewProvider.editType = "modify" mockTask.observationRegistry.clear() await diffViewProvider.open("observed.ts") const obs = mockTask.observationRegistry.get(`${mockCwd}/observed.ts`) expect(obs).toBeDefined() expect(obs!.version).toBe(versionTokenOfStat(previewStats)) // The preview is the tool's own read, not a read the model made, so it must // not claim completeness for content the model never saw. expect(obs!.complete).toBe(false) expect(vi.mocked(fs.stat)).toHaveBeenNthCalledWith(1, `${mockCwd}/observed.ts`, { bigint: true }) expect(vi.mocked(fs.stat)).toHaveBeenNthCalledWith(2, `${mockCwd}/observed.ts`, { bigint: true }) }) it("open() records no observation when the post-read stat rejects", async () => { const mockEditor = mockTextEditor(`${mockCwd}/observed.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/observed.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat) .mockResolvedValueOnce(previewStats) .mockRejectedValueOnce(Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" })) diffViewProvider.editType = "modify" mockTask.observationRegistry.clear() await diffViewProvider.open("observed.ts") expect(mockTask.observationRegistry.has(`${mockCwd}/observed.ts`)).toBe(false) // A direct save brackets its own basis read now: stat, read, stat, and the observation it // records carries the token of that bracket. The refusal is therefore a compare-and-swap // miss against the version the bracket recorded - still fail closed, still nothing // written - rather than the blanket "was not read" refusal, because the bytes were read // here, just not tie-ably to the preview this session opened. await expect( diffViewProvider.saveDirectly("observed.ts", "new content", false, false, 0, "update", true), ).rejects.toThrow(/Stale version -- the file changed since you read it/) }) it("saveDirectly records a complete observation for the bytes its content was built from", async () => { // A direct save has no preview to authorize it, so it brackets the basis read it was // handed: stat, compare the target against originalContent, stat again. All three agree // here, so the publish replaces content the consumer saw in full and may claim // completeness - which is what lets the guard's compare-and-swap authorize it. mockTask.observationRegistry.clear() diffViewProvider.originalContent = "basis content" vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("basis content") vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) await expect( diffViewProvider.saveDirectly("basis.ts", "replacement content", false, false, 0, "update", true), ).resolves.toMatchObject({ finalContent: "replacement content" }) const observation = mockTask.observationRegistry.get(`${mockCwd}/basis.ts`) expect(observation?.version).toBe(versionTokenOfStat(previewStats)) expect(observation?.complete).toBe(true) }) it("saveDirectly records only a partial observation when the target is not the basis", async () => { // The consumer built its content from bytes the target no longer holds. The bracket still // records the current version, but it cannot claim completeness for bytes nobody read, so // the observation stays partial and the completeness gate refuses the full-file // replacement instead of publishing over somebody else's write. mockTask.observationRegistry.clear() diffViewProvider.originalContent = "basis content the consumer built on" vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("someone else's content") await expect( diffViewProvider.saveDirectly("basis.ts", "replacement content", false, false, 0, "update", true), ).rejects.toThrow(/only partially read/) expect(safeWriteText).not.toHaveBeenCalled() const observation = mockTask.observationRegistry.get(`${mockCwd}/basis.ts`) expect(observation?.version).toBe(versionTokenOfStat(previewStats)) expect(observation?.complete).toBe(false) }) it("a reset() landing during open() joins the reserved session transition", async () => { // The row's interleaving: open() suspends while the previous session's cleanup settles, and // a reset() arrives in that gap. open() reserves the transition before its first await, so // the finalization waits for the session that is starting and tears down what that session // actually set up. Without the reservation the teardown runs and finishes first, and open() // resumes to claim a session no live owner exists for. The gate pins open() inside its // reservation, so the interleaving is the one under test and not a race the harness // happens to lose. const mockEditor = mockTextEditor(`${mockCwd}/raced.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/raced.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValue(previewStats) diffViewProvider.editType = "modify" let releaseGate: () => void = () => {} const gate = new Promise((resolve) => { releaseGate = resolve }) diffViewProvider["teardownInFlight"] = gate diffViewProvider["sessionFinalizationClaimed"] = false const opening = diffViewProvider.open("raced.ts") await Promise.resolve() const resetting = diffViewProvider.reset() await Promise.resolve() releaseGate() await Promise.all([opening, resetting]) // The leak this ordering prevents is a preview observation a finished teardown never // withdraws because it had not been recorded yet: left behind, it authorizes a later // targeted edit for a file the model never read in a session nobody owns. Joining the // reservation makes the finalization see the session that started, so its own withdrawal // hook covers that session's entry. expect(mockTask.observationRegistry.has(`${mockCwd}/raced.ts`)).toBe(false) expect(diffViewProvider["sessionStartInFlight"]).toBeUndefined() expect(diffViewProvider.isEditing).toBe(false) }) it("saveDirectly does not downgrade a CRLF target whose consumer normalized to LF", async () => { // EditTool and SearchReplaceTool normalize the content they build on to LF before assigning // originalContent (EditTool.ts:94, SearchReplaceTool.ts:99) while the file on disk is still // CRLF. Compared raw, that difference looks like an unread-in-full basis and the "update" gets // refused as partially read under preventFocusDisruption, so both sides of the comparison are // normalized before they are compared. mockTask.observationRegistry.clear() diffViewProvider.originalContent = "line one\nline two" vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("line one\r\nline two") vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) await expect( diffViewProvider.saveDirectly("crlf.ts", "replacement content", false, false, 0, "update", true), ).resolves.toMatchObject({ finalContent: "replacement content" }) const observation = mockTask.observationRegistry.get(`${mockCwd}/crlf.ts`) expect(observation?.complete).toBe(true) expect(observation?.version).toBe(versionTokenOfStat(previewStats)) }) it("settles the session reservation when open() throws out of the existing-file read", async () => { // The exits the manual settlements missed: only the openDiffEditor failure path and normal // completion used to settle the reservation, so a throw from the existing-file read - or from // existingDocument.save(), directory or placeholder creation, or undoPartialOpen() - left a // pending reservation that reset() then joined forever while isEditing stayed set. The // transition now runs inside try/finally, so every exit settles it. vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.window).visibleTextEditors = [] vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockRejectedValue( Object.assign(new Error("EACCES: permission denied, open 'read-throws.ts'"), { code: "EACCES" }), ) diffViewProvider.editType = "modify" diffViewProvider["sessionFinalizationClaimed"] = false diffViewProvider["teardownInFlight"] = undefined await expect(diffViewProvider.open("read-throws.ts")).rejects.toThrow(/EACCES/) // reset() has to be able to finish: before the finally it joined a reservation that no exit // would ever settle, and the session's flags stayed claimed by nobody. await diffViewProvider.reset() expect(diffViewProvider["sessionStartInFlight"]).toBeUndefined() expect(diffViewProvider.isEditing).toBe(false) }) it("saveDirectly leaves a partial observation partial for an edit save", async () => { // The other half of the same preservation: a patch over a file the model only read part of must // not upgrade the claim to a complete read on the strength of the bytes this save is about to // write. Whether the guard then publishes the patch or refuses it, the entry it recorded for the // read is what stays in the registry, so a later full-file replacement is still refused. mockTask.observationRegistry.clear() // The content the patch was built from, and the bytes the target still holds: a whole-file // basis observation would call this a complete read, which is exactly the upgrade a patch must // not buy for a file the model only read part of. diffViewProvider.originalContent = "basis content" mockTask.observationRegistry.observe(`${mockCwd}/slice-edit.ts`, versionTokenOfStat(previewStats), false) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("basis content") vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) await diffViewProvider.saveDirectly("slice-edit.ts", "replacement content", false, false, 0, "edit", false) expect(mockTask.observationRegistry.get(`${mockCwd}/slice-edit.ts`)?.complete).toBe(false) }) it("saveDirectly leaves a stale observation stale for an edit save", async () => { // ApplyDiffTool keeps the observation its own read recorded even after the file moved on, so // that the guard refuses the patch against the newer disk version. Re-observing the whole-file // basis here - which is what a full-file "update" caller needs - would refresh the stale token // to the current one and hand the guard a compare-and-swap win it never earned. mockTask.observationRegistry.clear() diffViewProvider.originalContent = "replacement content" const staleToken = "1:2:300:1000000000:1000000000" mockTask.observationRegistry.observe(`${mockCwd}/stale-edit.ts`, staleToken, true) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("basis content") vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) await expect( diffViewProvider.saveDirectly("stale-edit.ts", "replacement content", false, false, 0, "edit", false), ).rejects.toThrow(/Stale version/) expect(mockTask.observationRegistry.get(`${mockCwd}/stale-edit.ts`)?.version).toBe(staleToken) }) it("open() observes the empty placeholder of a new file so the accepted save can be guarded", async () => { const mockEditor = mockTextEditor(`${mockCwd}/brand-new.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/brand-new.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("") diffViewProvider.editType = "create" mockTask.observationRegistry.clear() await diffViewProvider.open("brand-new.ts") const obs = mockTask.observationRegistry.get(`${mockCwd}/brand-new.ts`) expect(obs).toBeDefined() expect(obs!.version).toBe(versionTokenOfStat(previewStats)) expect(obs!.complete).toBe(true) // The create path stat-matches the placeholder (pre + post read), so // both calls carry the bigint requirement, and the verification read // uses utf-8. expect(vi.mocked(fs.stat)).toHaveBeenNthCalledWith(1, `${mockCwd}/brand-new.ts`, { bigint: true }) expect(vi.mocked(fs.stat)).toHaveBeenNthCalledWith(2, `${mockCwd}/brand-new.ts`, { bigint: true }) expect(vi.mocked(fs.stat)).toHaveBeenCalledTimes(2) expect(vi.mocked(fs.readFile)).toHaveBeenCalledWith(`${mockCwd}/brand-new.ts`, "utf-8") }) it("open() leaves the target unobserved when the pre/post stat mismatch (mid-preview mutation)", async () => { const mutatedStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(301), mtimeNs: BigInt(4_000_000_001n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/mutated.ts`)), 0) return { dispose: vi.fn() } }) const mockEditor = mockTextEditor(`${mockCwd}/mutated.ts`) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValueOnce(previewStats).mockResolvedValueOnce(mutatedStats) diffViewProvider.editType = "modify" mockTask.observationRegistry.clear() await diffViewProvider.open("mutated.ts") expect(mockTask.observationRegistry.get(`${mockCwd}/mutated.ts`)).toBeUndefined() expect(vi.mocked(fs.stat)).toHaveBeenNthCalledWith(1, `${mockCwd}/mutated.ts`, { bigint: true }) expect(vi.mocked(fs.stat)).toHaveBeenNthCalledWith(2, `${mockCwd}/mutated.ts`, { bigint: true }) }) it("open() leaves the target unobserved when the pre-read stat fails (stat gap)", async () => { const mockEditor = mockTextEditor(`${mockCwd}/gap.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/gap.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) // The pre-read stat fails and only the post-read stat resolves: the // on-disk version the preview is built on is unproven, so open() must // leave the target unobserved even though a post stat is available. vi.mocked(fs.stat) .mockRejectedValueOnce(new Error("EPERM: operation not permitted")) .mockResolvedValueOnce(previewStats) diffViewProvider.editType = "modify" mockTask.observationRegistry.clear() await diffViewProvider.open("gap.ts") expect(mockTask.observationRegistry.get(`${mockCwd}/gap.ts`)).toBeUndefined() }) it("open() leaves a new file unobserved when the placeholder stat fails", async () => { const mockEditor = mockTextEditor(`${mockCwd}/gap-create.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/gap-create.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockRejectedValue(new Error("EPERM: operation not permitted")) diffViewProvider.editType = "create" mockTask.observationRegistry.clear() await diffViewProvider.open("gap-create.ts") expect(mockTask.observationRegistry.get(`${mockCwd}/gap-create.ts`)).toBeUndefined() }) it("publishes the accepted content through the guarded write (safeWriteText)", async () => { const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") const result = await diffViewProvider.saveChanges(false) expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, Buffer.from("new content"), { backup: true, }) expect(result.newProblemsMessage).toBe("") }) const openPreview = async () => { // Enough of the editor double for open() to find the diff editor again. const editor = { document: { uri: { fsPath: `${mockCwd}/test.txt`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 1, }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } vi.mocked(vscode.window.showTextDocument).mockResolvedValue(editor as unknown as vscode.TextEditor) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.window).visibleTextEditors = [editor as unknown as vscode.TextEditor] // openDiffEditor resolves from the document-open event, so fire it. vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => { callback({ uri: { fsPath: `${mockCwd}/test.txt`, scheme: "file" }, } as unknown as vscode.TextDocument) }, 0) return { dispose: vi.fn() } }) // fs/promises is mocked; open() only reads these BigIntStats fields when it // stat-matches the preview read. vi.mocked(fs.stat).mockResolvedValue({ dev: 1n, ino: 2n, size: 5n, mtimeNs: 100n, ctimeNs: 100n, } as unknown as BigIntStats) diffViewProvider.editType = "modify" await diffViewProvider.open("test.txt") diffViewProvider["newContent"] = "new content" } it("does not let the preview's own observation authorize a targeted edit", async () => { // The tool read never observed this path, so the only entry the save could // point at is the one open() records for the preview. Authorizing from that // entry publishes the tool's content over anything that changed between the // read and the preview, so the save must fall back to the unobserved-edit // guard and be rejected with the re-read remediation. mockTask.observationRegistry.clear() await openPreview() // The preview did record an observation - that is the entry under test. expect(mockTask.observationRegistry.has(`${mockCwd}/test.txt`)).toBe(true) await expect(diffViewProvider.saveChanges(false, 0, "edit")).rejects.toThrow(/File not read yet/) expect(safeWriteText).not.toHaveBeenCalled() // The preview's authorization was withdrawn rather than left behind. expect(mockTask.observationRegistry.has(`${mockCwd}/test.txt`)).toBe(false) }) it("withdraws the preview observation on a rejected update save once reset runs", async () => { // The full trigger: the model never read the file, open() records the // preview entry (complete: false), and saveChanges(..., "update") is // rejected as only-partially-read. The discard cleanup reloads the // buffer; nothing wrote, so the token is unchanged and nothing forgets // the entry. Finalization - reached by every tool catch and by // revertChanges through finalizeSession - must withdraw it, or a later // apply_diff is authorized by a look the model never made (the // edit-path test above covers only the first attempt). mockTask.observationRegistry.clear() await openPreview() expect(mockTask.observationRegistry.has(`${mockCwd}/test.txt`)).toBe(true) await expect(diffViewProvider.saveChanges(false, 0, "update")).rejects.toThrow(/only partially read/) // The rejected update leaves the preview entry in place - the leftover // the withdrawal must catch. expect(mockTask.observationRegistry.has(`${mockCwd}/test.txt`)).toBe(true) await diffViewProvider.reset() expect(mockTask.observationRegistry.has(`${mockCwd}/test.txt`)).toBe(false) }) it("keeps an observation the model earned at the same token after the preview", async () => { // A read_file after the preview records complete: true at the same // version token (nothing wrote in between). The withdrawal must not // touch it: the model did read the file, and its earned authorization // outlives the preview. mockTask.observationRegistry.clear() await openPreview() const previewEntry = mockTask.observationRegistry.get(`${mockCwd}/test.txt`) expect(previewEntry).toBeDefined() mockTask.observationRegistry.observe(`${mockCwd}/test.txt`, previewEntry!.version, true) await diffViewProvider.reset() expect(mockTask.observationRegistry.get(`${mockCwd}/test.txt`)?.complete).toBe(true) }) it("keeps a model partial read that replaced the preview entry at the same token", async () => { // A partial read_file while the diff is open replaces the preview // observation with a fresh entry at the SAME token and the SAME // incomplete flag - indistinguishable by content, but a different // owner. The withdrawal is by entry identity, so the model's earned // partial authorization survives the reset and a later targeted edit // stays authorized. mockTask.observationRegistry.clear() await openPreview() const previewEntry = mockTask.observationRegistry.get(`${mockCwd}/test.txt`) expect(previewEntry).toBeDefined() mockTask.observationRegistry.observe(`${mockCwd}/test.txt`, previewEntry!.version, false) const modelEntry = mockTask.observationRegistry.get(`${mockCwd}/test.txt`) await diffViewProvider.reset() expect(mockTask.observationRegistry.get(`${mockCwd}/test.txt`)).toBeDefined() // Same token and same completeness as the preview entry, so only identity tells // the model entry from the preview entry the reset is allowed to remove. expect(modelEntry).toBeDefined() expect(modelEntry).not.toBe(previewEntry) expect(mockTask.observationRegistry.get(`${mockCwd}/test.txt`)).toBe(modelEntry) }) it("keeps an entry whose token moved on - the preview no longer owns it", async () => { // A landed publish (or a later session) replaced the entry: the version // no longer names the preview's token, so the withdrawal leaves it // alone even though the flag still reads incomplete. mockTask.observationRegistry.clear() await openPreview() mockTask.observationRegistry.observe(`${mockCwd}/test.txt`, "landed-token", false) await diffViewProvider.reset() expect(mockTask.observationRegistry.get(`${mockCwd}/test.txt`)?.version).toBe("landed-token") }) it("still publishes a targeted edit authorized by a pre-preview observation", async () => { // The same preview must not break the legitimate case: the model read the // file (partially) and nothing changed before the preview, so the restored // pre-open observation authorizes the targeted edit. mockTask.observationRegistry.observe(`${mockCwd}/test.txt`, "v1", false) await openPreview() await diffViewProvider.saveChanges(false, 0, "edit") expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.txt`, Buffer.from("new content"), { backup: true, }) }) it("publishes the accepted content in the document's own encoding", async () => { // A utf8bom document: getText() returns the text without the BOM, so the // publish must go through VS Code's codec for the document's own // encoding rather than re-encoding the text as plain UTF-8. const bomEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8bom", }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = bomEditor await diffViewProvider.saveChanges(false) expect(vi.mocked(vscode.workspace.encode)).toHaveBeenCalledWith("new content", { encoding: "utf8bom", }) expect(safeWriteText).toHaveBeenCalledWith( `${mockCwd}/test.ts`, Buffer.concat([Buffer.from("\uFEFF"), Buffer.from("new content")]), { backup: true }, ) }) it("rejects the accepted save when the file changed after the preview (stale version)", async () => { vi.mocked(computeVersionToken).mockResolvedValue("v2") const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow( "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", ) expect(safeWriteText).not.toHaveBeenCalled() }) it("rejects the accepted save when the target was never observed (fail closed)", async () => { mockTask.observationRegistry.clear() const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow( "File already exists at test.ts and was not read before this write -- read the file first, then retry.", ) expect(safeWriteText).not.toHaveBeenCalled() }) it("rejects the accepted save when the observation was only a partial read", async () => { // A partial observation (slice/range/truncated/indentation read) must not // authorize the full-file replacement the accept path performs, even when // the version is current. mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, "v1", false) const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow( "File was only partially read (line slice, range, truncated view, or indentation block) -- " + "a full-file replacement needs the complete content; re-read the whole file, then retry.", ) expect(safeWriteText).not.toHaveBeenCalled() }) it("publishes a targeted edit that a partial observation authorizes", async () => { // The same partial observation rejects a full-file replacement but // authorizes the targeted edit the tool performed, so the write kind // the tool passed must reach the guard. mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, "v1", false) const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") await diffViewProvider.saveChanges(false, 0, "edit") expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, Buffer.from("new content"), { backup: true, }) }) it("fails closed when the owning task has been collected", async () => { // A real WeakRef cannot be forced to deref to undefined deterministically // (GC timing), so a structural stub stands in for the collected reference. diffViewProvider["taskRef"] = { deref: () => undefined } as unknown as WeakRef await expect(diffViewProvider.saveChanges(false)).rejects.toThrow( "Cannot guard the write: the owning task is no longer available", ) // Nothing may be published for a collected task, and the discard-only // cleanup still runs before the error is rethrown. const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") expect(safeWriteText).not.toHaveBeenCalled() expect(diffViewProvider["closeOwnDiffView"]).toHaveBeenCalledTimes(1) }) it("open() keeps the model's existing observation instead of replacing it with the preview token", async () => { const mockEditor = mockTextEditor(`${mockCwd}/t3-modify.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/t3-modify.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValue(previewStats) diffViewProvider.editType = "modify" mockTask.observationRegistry.clear() // The model read the file before the preview: its observation must // survive so the accept-time guard compares against the version the // model's content was built on, not the on-disk version at preview // time. mockTask.observationRegistry.observe(`${mockCwd}/t3-modify.ts`, "model-token", true) await diffViewProvider.open("t3-modify.ts") const obs = mockTask.observationRegistry.get(`${mockCwd}/t3-modify.ts`) expect(obs?.version).toBe("model-token") expect(obs?.version).not.toBe(versionTokenOfStat(previewStats)) // the stat-matched pair is still taken; only the observation is kept expect(vi.mocked(fs.stat)).toHaveBeenCalledTimes(2) }) it("open() records the placeholder token for a create even when the model read the file before it vanished", async () => { // The vanished file's old observation must NOT win here: it describes // a file that no longer exists, and keeping it would make the // accept-time CAS (placeholder token on disk vs. the vanished file's // token) fail every time, so recreating the file would always fail // and the placeholder would leak. The placeholder token is the // correct baseline for the new file. const mockEditor = mockTextEditor(`${mockCwd}/t3-create.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/t3-create.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("") diffViewProvider.editType = "create" mockTask.observationRegistry.clear() mockTask.observationRegistry.observe(`${mockCwd}/t3-create.ts`, "model-token", true) await diffViewProvider.open("t3-create.ts") const placeholderToken = versionTokenOfStat(previewStats) // the placeholder is written, stat-matched, observed (replacing the // vanished file's stale token), and remembered for cleanup expect(vi.mocked(fs.writeFile)).toHaveBeenCalledWith(`${mockCwd}/t3-create.ts`, "") expect(vi.mocked(fs.stat)).toHaveBeenCalledTimes(2) expect(mockTask.observationRegistry.get(`${mockCwd}/t3-create.ts`)?.version).toBe(placeholderToken) expect(diffViewProvider["placeholderVersion"]).toBe(placeholderToken) }) it("open() removes the placeholder and its new directories when the diff editor never opens", async () => { // open() creates the parent directories and writes the empty placeholder before // it opens the diff. If the diff never opens there is no active diff editor for // revertChanges() to undo, so an unapproved empty file (and the directories made // for it) would stay on disk. const createdDirs = [`${mockCwd}/t3-partial`, `${mockCwd}/t3-partial/nested`] vi.mocked(createDirectoriesForFile).mockResolvedValueOnce(createdDirs) vi.mocked(vscode.window.showTextDocument).mockRejectedValue(new Error("Cannot open file")) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockReturnValue({ dispose: vi.fn() }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("") diffViewProvider.editType = "create" await expect(diffViewProvider.open("t3-partial/nested/new.ts")).rejects.toThrow(/Failed to/) // The placeholder this open() wrote is removed, and the directories it created // go with it, innermost first. expect(vi.mocked(fs.unlink)).toHaveBeenCalledWith(`${mockCwd}/t3-partial/nested/new.ts`) expect(vi.mocked(fs.rmdir)).toHaveBeenNthCalledWith(1, `${mockCwd}/t3-partial/nested`) expect(vi.mocked(fs.rmdir)).toHaveBeenNthCalledWith(2, `${mockCwd}/t3-partial`) expect(diffViewProvider["createdDirs"]).toEqual([]) expect(diffViewProvider["placeholderVersion"]).toBeUndefined() }) it("open() leaves a peer's file and the created directories when the placeholder token moved before the failed-open cleanup", async () => { // The failed-open cleanup is data-preserving: when another writer owns the path by // the time open() fails, undoPartialOpen must leave their file AND the directories // that now hold it, while open() still rethrows its own failure. const createdDirs = [`${mockCwd}/t3-peer`, `${mockCwd}/t3-peer/nested`] vi.mocked(createDirectoriesForFile).mockResolvedValueOnce(createdDirs) vi.mocked(vscode.window.showTextDocument).mockRejectedValue(new Error("Cannot open file")) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockReturnValue({ dispose: vi.fn() }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) // open() wrote the placeholder (first stat), then a peer replaced it before the // bracketing post-stat: the tokens disagree, so no cleanup token is recorded. const peerStats = { isDirectory: () => false, dev: BigInt(9), ino: BigInt(11), size: BigInt(64), mtimeNs: BigInt(4_000_000_009n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats vi.mocked(fs.stat).mockResolvedValueOnce(previewStats).mockResolvedValueOnce(peerStats) // The stat the cleanup itself performs sees the peer's file. vi.mocked(fs.stat).mockResolvedValue(peerStats) vi.mocked(fs.readFile).mockResolvedValue("peer content") diffViewProvider.editType = "create" await expect(diffViewProvider.open("t3-peer/nested/new.ts")).rejects.toThrow(/Failed to/) expect(vi.mocked(fs.unlink)).not.toHaveBeenCalled() expect(vi.mocked(fs.rmdir)).not.toHaveBeenCalled() expect(diffViewProvider["placeholderVersion"]).toBeUndefined() expect(diffViewProvider["createdDirs"]).toEqual([]) }) it("open() removes its own empty placeholder when no stat-matched token was recorded", async () => { // The bracketing read failed, so placeholderVersion is undefined - but the file on // disk is still the empty one this open() created. Ownership is provable from the // identity captured at creation, so the placeholder must not be left behind. const createdDirs = [`${mockCwd}/t3-notoken`, `${mockCwd}/t3-notoken/nested`] vi.mocked(createDirectoriesForFile).mockResolvedValueOnce(createdDirs) vi.mocked(vscode.window.showTextDocument).mockRejectedValue(new Error("Cannot open file")) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockReturnValue({ dispose: vi.fn() }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) const emptyOurs = { isDirectory: () => false, dev: BigInt(7), ino: BigInt(8), size: BigInt(0), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats const movedAway = { ...emptyOurs, mtimeNs: BigInt(4_000_000_005n) } as unknown as BigIntStats // pre/post stats disagree -> no token; the identity is still ours. vi.mocked(fs.stat).mockResolvedValueOnce(emptyOurs).mockResolvedValueOnce(movedAway) vi.mocked(fs.stat).mockResolvedValue(emptyOurs) vi.mocked(fs.readFile).mockResolvedValue("") diffViewProvider.editType = "create" await expect(diffViewProvider.open("t3-notoken/nested/new.ts")).rejects.toThrow(/Failed to/) expect(diffViewProvider["placeholderVersion"]).toBeUndefined() expect(vi.mocked(fs.unlink)).toHaveBeenCalledWith(`${mockCwd}/t3-notoken/nested/new.ts`) expect(vi.mocked(fs.rmdir)).toHaveBeenNthCalledWith(1, `${mockCwd}/t3-notoken/nested`) expect(vi.mocked(fs.rmdir)).toHaveBeenNthCalledWith(2, `${mockCwd}/t3-notoken`) expect(diffViewProvider["placeholderIdentity"]).toBeUndefined() }) it("keeps a placeholder that gained content when no stat-matched token was recorded", async () => { // The identity fallback may only ever remove an EMPTY file: a writer that put // content through the same inode keeps it, and so do the directories holding it. const createdDirs = [`${mockCwd}/t3-filled`, `${mockCwd}/t3-filled/nested`] vi.mocked(createDirectoriesForFile).mockResolvedValueOnce(createdDirs) vi.mocked(vscode.window.showTextDocument).mockRejectedValue(new Error("Cannot open file")) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockReturnValue({ dispose: vi.fn() }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) const emptyOurs = { isDirectory: () => false, dev: BigInt(7), ino: BigInt(8), size: BigInt(0), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats const movedAway = { ...emptyOurs, mtimeNs: BigInt(4_000_000_005n) } as unknown as BigIntStats const nowFilled = { ...emptyOurs, size: BigInt(24), mtimeNs: BigInt(4_000_000_007n), } as unknown as BigIntStats vi.mocked(fs.stat).mockResolvedValueOnce(emptyOurs).mockResolvedValueOnce(movedAway) vi.mocked(fs.stat).mockResolvedValue(nowFilled) vi.mocked(fs.readFile).mockResolvedValue("") diffViewProvider.editType = "create" await expect(diffViewProvider.open("t3-filled/nested/new.ts")).rejects.toThrow(/Failed to/) expect(vi.mocked(fs.unlink)).not.toHaveBeenCalled() expect(vi.mocked(fs.rmdir)).not.toHaveBeenCalled() }) it("open() on a create with a collected task writes the placeholder but tracks nothing", async () => { // The task has been collected (dead WeakRef): the placeholder is still // written (the file must exist to open the diff), but there is no live // task to observe - the later save fails closed through the taskRef // fail-closed path. const mockEditor = mockTextEditor(`${mockCwd}/t3-dead-task.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/t3-dead-task.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("") diffViewProvider.editType = "create" mockTask.observationRegistry.clear() diffViewProvider["taskRef"] = { deref: () => undefined } as unknown as WeakRef await diffViewProvider.open("t3-dead-task.ts") expect(vi.mocked(fs.writeFile)).toHaveBeenCalledWith(`${mockCwd}/t3-dead-task.ts`, "") // no live task: nothing observed, but the cleanup token is still // captured (provider state) so the fail-closed save rejection can // remove the placeholder instead of leaking it expect(mockTask.observationRegistry.get(`${mockCwd}/t3-dead-task.ts`)).toBeUndefined() expect(diffViewProvider["placeholderVersion"]).toBe(versionTokenOfStat(previewStats)) }) it("open() does not record a placeholder another writer touched after the write", async () => { // CR d037753 finding: a writer that touched the placeholder between // open()'s fs.writeFile() and the observation would have its token // recorded as a complete observation of content open() never read. // The stat-matched verification must reject it: no observation (the // prior observation stays untouched), no cleanup token (so a rejected // save cannot unlink the writer's file), and the save fails closed. const mockEditor = mockTextEditor(`${mockCwd}/contested.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/contested.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("external content") diffViewProvider.editType = "create" mockTask.observationRegistry.clear() mockTask.observationRegistry.observe(`${mockCwd}/contested.ts`, "model-token", true) await diffViewProvider.open("contested.ts") expect(vi.mocked(fs.writeFile)).toHaveBeenCalledWith(`${mockCwd}/contested.ts`, "") // nothing recorded, and the vanished file's prior observation was // not replaced with the writer's token expect(mockTask.observationRegistry.get(`${mockCwd}/contested.ts`)?.version).toBe("model-token") expect(diffViewProvider["placeholderVersion"]).toBeUndefined() }) it("open() does not record the placeholder when the post-stat fails after the write", async () => { // The bracketing stats must both succeed: a failed post-stat means // the read is not trustworthy, so nothing is recorded. const mockEditor = mockTextEditor(`${mockCwd}/statfail.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/statfail.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat) .mockResolvedValueOnce(previewStats) .mockRejectedValueOnce(Object.assign(new Error("ENOENT: no such file"), { code: "ENOENT" })) vi.mocked(fs.readFile).mockResolvedValue("") diffViewProvider.editType = "create" mockTask.observationRegistry.clear() await diffViewProvider.open("statfail.ts") expect(mockTask.observationRegistry.get(`${mockCwd}/statfail.ts`)).toBeUndefined() expect(diffViewProvider["placeholderVersion"]).toBeUndefined() }) it("open() does not record the placeholder when the bracketing stats disagree (mid-preview mutation)", async () => { // A token change between the bracketing stats means the placeholder // was replaced or rewritten while open() was reading it - same S2 // rule as the modify branch: nothing is recorded. const mutatedStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(301), mtimeNs: BigInt(4_000_000_001n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats const mockEditor = mockTextEditor(`${mockCwd}/mutated-new.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/mutated-new.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValueOnce(previewStats).mockResolvedValueOnce(mutatedStats) vi.mocked(fs.readFile).mockResolvedValue("") diffViewProvider.editType = "create" mockTask.observationRegistry.clear() await diffViewProvider.open("mutated-new.ts") expect(mockTask.observationRegistry.get(`${mockCwd}/mutated-new.ts`)).toBeUndefined() expect(diffViewProvider["placeholderVersion"]).toBeUndefined() }) it("saveChanges() accepts a recreate after a prior read - the accept-time CAS checks the placeholder token", async () => { // The exact recreate-always-failed trace: the model read the file // (observed "v1" by the outer beforeEach), the file then vanished, // open() wrote the placeholder, and the accept must succeed against // the placeholder token (not the vanished file's stale token). const mockEditor = mockTextEditor(`${mockCwd}/test.ts`, "new content") vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/test.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("") diffViewProvider.editType = "create" // prior read observation (the file has since vanished) expect(mockTask.observationRegistry.get(`${mockCwd}/test.ts`)?.version).toBe("v1") await diffViewProvider.open("test.ts") // the placeholder is untouched on disk: the accept-time token matches // the placeholder token open() recorded vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) const result = await diffViewProvider.saveChanges(false) expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, Buffer.from("new content"), { backup: true, }) expect(result.newProblemsMessage).toBe("") }) it("saveChanges() checks the placeholder token and unlinks inside the same lock", async () => { // A peer writer that commits between the token check and the unlink would lose // its write, so the cleanup runs under the same resolved-path advisory lock every // other writer to this file uses. A token that moved inside the lock window means // the file is no longer the placeholder and must be left in place. const mockEditor = mockTextEditor(`${mockCwd}/test.ts`, "new content") vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/test.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("") diffViewProvider.editType = "create" await diffViewProvider.open("test.ts") const lockImpl = vi.mocked(withFileLock).getMockImplementation() const statImpl = vi.mocked(fs.stat).getMockImplementation() try { const lockKeys: string[] = [] vi.mocked(withFileLock).mockImplementation(async (lockKey, operation) => { lockKeys.push(lockKey) if (lockKeys.length === 2) { // the peer committed while the cleanup waited for the lock vi.mocked(fs.stat).mockResolvedValue({ ...previewStats, size: 9999n, mtimeNs: 5n, ctimeNs: 6n }) } return operation(lockKey) }) // The publish is rejected against the peer's token, so the discard cleanup runs. vi.mocked(computeVersionToken).mockResolvedValue("peer-token") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow( /Stale version|not read before this write/, ) // One acquisition for the guarded publish, one for the cleanup. expect(lockKeys).toEqual([`${mockCwd}/test.ts`, `${mockCwd}/test.ts`]) expect(vi.mocked(fs.unlink)).not.toHaveBeenCalled() } finally { if (lockImpl) { vi.mocked(withFileLock).mockImplementation(lockImpl) } else { vi.mocked(withFileLock).mockReset() } if (statImpl) { vi.mocked(fs.stat).mockImplementation(statImpl) } else { vi.mocked(fs.stat).mockReset() } } }) it("clears the dirty buffer via a disk revert after a successful guarded publish", async () => { // The user edited the buffer before accepting, so the document is // dirty: the publish wrote the exact buffer content, and the dirty // flag must be cleared by reverting from disk rather than saving the // buffer (which would republish through the unguarded file service). const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) const result = await diffViewProvider.saveChanges(false) expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, Buffer.from("new content"), { backup: true, }) // the revert activates the exact document with the exact options: // preserveFocus keeps the user's focus, preview: false pins the tab // the target is activated so the revert command is scoped to this document // (no active editor to restore in this case) expect(vi.mocked(vscode.window.showTextDocument)).toHaveBeenCalledWith(dirtyEditor.document, { preserveFocus: false, preview: false, }) expect(vi.mocked(vscode.commands.executeCommand)).toHaveBeenCalledWith("workbench.action.files.revert") expect(dirtyEditor.document.save).not.toHaveBeenCalled() expect(result.newProblemsMessage).toBe("") }) it("discards the dirty buffer and removes the new-file placeholder after a guarded rejection, then rethrows", async () => { const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) diffViewProvider.editType = "create" // open() wrote and observed the empty placeholder; the on-disk token // then moved past it, so the guard rejects the publish. const placeholderToken = versionTokenOfStat(previewStats) mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, placeholderToken, true) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(computeVersionToken).mockResolvedValue("moved-past-placeholder") diffViewProvider["placeholderVersion"] = placeholderToken await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") expect(safeWriteText).not.toHaveBeenCalled() // discard-only cleanup: the newer disk content is reloaded into the // buffer (never re-saved from originalContent), and the placeholder // is unlinked while it is still exactly the file open() wrote expect(vi.mocked(vscode.window.showTextDocument)).toHaveBeenCalledWith(dirtyEditor.document, { preserveFocus: false, preview: false, }) expect(vi.mocked(vscode.commands.executeCommand)).toHaveBeenCalledWith("workbench.action.files.revert") // the placeholder stat uses the bigint stat options (the version // token requires the full-precision fields) // The read must be attributed to the bigint stat that produced the token: expect(vi.mocked(fs.stat).mock.calls[0][1]).toEqual({ bigint: true }) expect(fs.unlink).toHaveBeenCalledWith(`${mockCwd}/test.ts`) expect(diffViewProvider["closeOwnDiffView"]).toHaveBeenCalled() }) it("disposes the active-editor listener before the programmatic revert", async () => { // showTextDocument can change the active editor even with // preserveFocus, so the listener must be gone before the revert // activates the document: otherwise this programmatic activation is // recorded as a user touch and the auto-close preference is overridden. const order: string[] = [] const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor diffViewProvider["disposeActiveEditorListener"] = vi.fn(() => { order.push("dispose") }) revertClearsDirty(dirtyEditor.document, () => order.push("revert")) await diffViewProvider.saveChanges(false) expect(order).toEqual(["dispose", "revert"]) }) it("disposes the listener before the discard revert and closes the deleted file's tab after a successful unlink", async () => { const order: string[] = [] const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) diffViewProvider.editType = "create" const placeholderToken = versionTokenOfStat(previewStats) mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, placeholderToken, true) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(computeVersionToken).mockResolvedValue("moved-past-placeholder") diffViewProvider["placeholderVersion"] = placeholderToken const unlinkObserved: number[] = [] vi.mocked(fs.unlink).mockImplementation(async () => { unlinkObserved.push(order.length) return undefined }) diffViewProvider["disposeActiveEditorListener"] = vi.fn(() => { order.push("dispose") }) diffViewProvider["cancelDeferredScroll"] = vi.fn(() => { order.push("cancel") }) diffViewProvider["closeFileTab"] = vi.fn().mockImplementation(() => { order.push("closeTab") return Promise.resolve() }) revertClearsDirty(dirtyEditor.document, () => order.push("revert")) await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") // The tab for the file that was just unlinked is closed, and only // after the revert; closing only the diff views would leave a clean // plain-text tab for a deleted file behind. expect(order).toEqual(["dispose", "cancel", "revert", "closeTab"]) // The unlink must be observed, and it must land after the disk revert and before // the tab close: closing first would leave a clean tab over a deleted file. expect(unlinkObserved).toHaveLength(1) expect(unlinkObserved[0]).toBeGreaterThanOrEqual(order.indexOf("revert") + 1) expect(unlinkObserved[0]).toBe(order.indexOf("closeTab")) }) it("does not close the file tab when the placeholder unlink fails", async () => { const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) diffViewProvider.editType = "create" const placeholderToken = versionTokenOfStat(previewStats) mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, placeholderToken, true) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(computeVersionToken).mockResolvedValue("moved-past-placeholder") diffViewProvider["placeholderVersion"] = placeholderToken const closeFileTab = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = closeFileTab vi.mocked(fs.unlink).mockRejectedValueOnce(new Error("EACCES: permission denied, unlink")) await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") // Nothing was deleted, so there is no deleted-file tab to close. expect(closeFileTab).not.toHaveBeenCalled() }) it("removes the directories open() created, innermost first, after the placeholder unlink", async () => { const order: string[] = [] const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) diffViewProvider.editType = "create" const placeholderToken = versionTokenOfStat(previewStats) mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, placeholderToken, true) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(computeVersionToken).mockResolvedValue("moved-past-placeholder") diffViewProvider["placeholderVersion"] = placeholderToken diffViewProvider["createdDirs"] = [`${mockCwd}/new`, `${mockCwd}/new/dir`] diffViewProvider["closeFileTab"] = vi.fn().mockImplementation(() => { order.push("closeTab") return Promise.resolve() }) vi.mocked(fs.rmdir).mockImplementation(async (p) => { order.push("rmdir:" + p) }) await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") // The empty directories open() made for the rejected new file go with the // placeholder, innermost first, and only after the unlink succeeded. expect(order).toEqual(["closeTab", "rmdir:" + `${mockCwd}/new/dir`, "rmdir:" + `${mockCwd}/new`]) }) it("stops removing created directories when one cannot be removed", async () => { const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) diffViewProvider.editType = "create" const placeholderToken = versionTokenOfStat(previewStats) mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, placeholderToken, true) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(computeVersionToken).mockResolvedValue("moved-past-placeholder") diffViewProvider["placeholderVersion"] = placeholderToken diffViewProvider["createdDirs"] = [`${mockCwd}/a`, `${mockCwd}/a/b`, `${mockCwd}/a/b/c`] vi.mocked(fs.rmdir).mockRejectedValueOnce(new Error("ENOTEMPTY: directory not empty")) await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") // A directory another writer populated in the meantime must not be removed, // and the best-effort cleanup must still finish so the guard verdict stays // the outcome. expect(fs.rmdir).toHaveBeenCalledTimes(1) expect(fs.rmdir).toHaveBeenCalledWith(`${mockCwd}/a/b/c`) expect(diffViewProvider["closeOwnDiffView"]).toHaveBeenCalled() }) it("does not revert a buffer the user changed during the publish", async () => { // The publish captured the buffer text before awaiting the write; a keystroke // typed during that wait is newer than the published bytes, so the buffer must // stay dirty instead of being reverted to disk. const getText = vi.fn() getText.mockReturnValueOnce("new content").mockReturnValueOnce("new content typed during the publish") const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText, lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) await diffViewProvider.saveChanges(false) expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, Buffer.from("new content"), { backup: true, }) expect(vi.mocked(vscode.commands.executeCommand)).not.toHaveBeenCalledWith("workbench.action.files.revert") expect(vi.mocked(vscode.window.showTextDocument)).not.toHaveBeenCalled() }) it("activates the document before the revert so the command is scoped to it, then restores the focus", async () => { // workbench.action.files.revert takes no resource argument: with the Open // Editors view focused it force-reverts every selected editor, otherwise the // active editor. Activating the target keeps the revert scoped to this // document, and the user's previous focus is given back afterwards. const previousEditor = mockTextEditor(`${mockCwd}/other.ts`, "other") vi.mocked(vscode.window).activeTextEditor = previousEditor const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) await diffViewProvider.saveChanges(false) const calls = vi.mocked(vscode.window.showTextDocument).mock.calls expect(calls[0]).toEqual([dirtyEditor.document, { preserveFocus: false, preview: false }]) expect(vi.mocked(vscode.commands.executeCommand)).toHaveBeenCalledWith("workbench.action.files.revert") expect(calls[1]).toEqual([previousEditor.document, { preserveFocus: false, preview: false }]) }) it("does not restore focus when the user had no active editor", async () => { vi.mocked(vscode.window).activeTextEditor = undefined const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) await diffViewProvider.saveChanges(false) // Only the activation happened; there was no focus to give back. expect(vi.mocked(vscode.window.showTextDocument).mock.calls).toEqual([ [dirtyEditor.document, { preserveFocus: false, preview: false }], ]) expect(vi.mocked(vscode.commands.executeCommand)).toHaveBeenCalledWith("workbench.action.files.revert") }) it("does not restore focus when the active editor is already the target document", async () => { // The user was already looking at this document, so there is nothing to give // back: re-showing it would be a redundant activation. const editor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor vi.mocked(vscode.window).activeTextEditor = editor diffViewProvider["activeDiffEditor"] = editor revertClearsDirty(editor.document) await diffViewProvider.saveChanges(false) // Only the activation happened: the focus was already on the target, so there // was nothing to give back. expect(vi.mocked(vscode.window.showTextDocument).mock.calls).toEqual([ [editor.document, { preserveFocus: false, preview: false }], ]) expect(vi.mocked(vscode.commands.executeCommand)).toHaveBeenCalledWith("workbench.action.files.revert") }) it("keeps the placeholder when the discard fails, so a later save cannot recreate the rejected content", async () => { // The revert command can fail (a locked or orphaned model). While the buffer // is still dirty, VS Code's ordinary file service can save it back to the path, // so the placeholder open() wrote must survive and the tab must stay open. const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor vi.mocked(vscode.commands.executeCommand).mockRejectedValue(new Error("revert failed")) diffViewProvider.editType = "create" const placeholderToken = versionTokenOfStat(previewStats) mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, placeholderToken, true) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(computeVersionToken).mockResolvedValue("moved-past-placeholder") diffViewProvider["placeholderVersion"] = placeholderToken const closeFileTab = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = closeFileTab await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") expect(vi.mocked(vscode.commands.executeCommand)).toHaveBeenCalledWith("workbench.action.files.revert") expect(fs.unlink).not.toHaveBeenCalled() expect(closeFileTab).not.toHaveBeenCalled() }) it("does not reload a clean buffer when the guard rejects - only dirty buffers are discarded", async () => { // The buffer was never touched (isDirty is falsy): there is nothing // to discard, so the failure cleanup must not activate the document // or run the revert command. const cleanEditor = mockTextEditor(`${mockCwd}/test.ts`, "new content") diffViewProvider["activeDiffEditor"] = cleanEditor vi.mocked(computeVersionToken).mockResolvedValue("v2") // The placeholder on disk is still exactly what open() wrote, so the cleanup // can still remove it. diffViewProvider.editType = "create" const placeholderToken = versionTokenOfStat(previewStats) mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, placeholderToken, true) vi.mocked(fs.stat).mockResolvedValue(previewStats) diffViewProvider["placeholderVersion"] = placeholderToken await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") expect(safeWriteText).not.toHaveBeenCalled() expect(vi.mocked(vscode.window.showTextDocument)).not.toHaveBeenCalled() expect(vi.mocked(vscode.commands.executeCommand)).not.toHaveBeenCalled() // A clean buffer has nothing that can be saved back, so the placeholder // cleanup still runs even though no revert was needed. expect(fs.unlink).toHaveBeenCalledWith(`${mockCwd}/test.ts`) expect(diffViewProvider["closeOwnDiffView"]).toHaveBeenCalled() }) it("does not unlink the placeholder when the edit type is not create - the outer gate short-circuits", async () => { // placeholderVersion is remembered (open() took the placeholder path) // but the edit type is not create: the outer gate must short-circuit // before statting or unlinking, so the placeholder on disk is left // untouched. const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) diffViewProvider.editType = "modify" const placeholderToken = versionTokenOfStat(previewStats) mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, placeholderToken, true) vi.mocked(fs.stat).mockResolvedValue(previewStats) // placeholder still on disk vi.mocked(computeVersionToken).mockResolvedValue("moved") // stale rejection diffViewProvider["placeholderVersion"] = placeholderToken await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") expect(fs.stat).not.toHaveBeenCalled() expect(fs.unlink).not.toHaveBeenCalled() // the dirty discard and the view close still ran expect(vi.mocked(vscode.commands.executeCommand)).toHaveBeenCalledWith("workbench.action.files.revert") expect(diffViewProvider["closeOwnDiffView"]).toHaveBeenCalled() }) // The refusals are decided against the reason the guard rejected, and before the baseline // branches, so adoption does not depend on which baseline the session happened to have. Pinned // directly on the predicate because no scenario above reaches these combinations: the suite // never pairs a create placeholder with a never-read or partial-read preview. const stale = new GuardStaleVersionError( "Stale version -- the file changed since you read it (expected v1, current v2).", "/test.ts", ) const unread = new GuardRejectedError( "File already exists at /test.ts and was not read before this write -- read the file first, then retry.", "/test.ts", ) it("refuses to adopt a published match when a create placeholder previewed a never-read existing file", () => { diffViewProvider["placeholderVersion"] = undefined diffViewProvider["preOpenObservation"] = null expect(diffViewProvider["canAdoptPublishedContent"]("update", stale)).toBe(false) }) it("adopts a published match for the placeholder open() created, whose only rejection is the moved token", () => { diffViewProvider["placeholderVersion"] = "placeholder-token" diffViewProvider["preOpenObservation"] = null expect(diffViewProvider["canAdoptPublishedContent"]("update", stale)).toBe(true) }) it("refuses to adopt for an owned placeholder when the rejection is not the moved token", () => { diffViewProvider["placeholderVersion"] = "placeholder-token" diffViewProvider["preOpenObservation"] = null // A peer created the file between open() and the save: the placeholder is still this // session's, but the bytes on disk are not this write's, so a matching read proves nothing. expect(diffViewProvider["canAdoptPublishedContent"]("update", unread)).toBe(false) }) it("adopts for an owned placeholder whose pre-open snapshot was only a partial read", () => { diffViewProvider["placeholderVersion"] = "placeholder-token" // The snapshot describes the target as it stood before open() ran: a slice of a file that the // create path then replaced with the verified empty placeholder. It cannot stand in for a // refusal on behalf of the placeholder the registry now holds. diffViewProvider["preOpenObservation"] = { version: "gone-file-partial", complete: false } expect(diffViewProvider["canAdoptPublishedContent"]("update", stale)).toBe(true) expect(diffViewProvider["canAdoptPublishedContent"]("edit", stale)).toBe(true) // The reason gate still binds: a rejection the placeholder cannot explain keeps refusing. expect(diffViewProvider["canAdoptPublishedContent"]("update", unread)).toBe(false) }) it("still adopts for a create placeholder when no preview snapshot exists to check", () => { diffViewProvider["placeholderVersion"] = "placeholder-token" diffViewProvider["preOpenObservation"] = undefined expect(diffViewProvider["canAdoptPublishedContent"]("update", stale)).toBe(true) }) it("adopts the bytes Auto Save published for a new file open() created", async () => { // The create shape of the autosave race, end to end through saveChanges(): open() made the // file, verified the empty placeholder as this session's baseline and left preOpenObservation // null because there was no prior content to read. Auto Save wrote the accepted bytes, so the // compare-and-swap finds a moved token and the guard rejects. The file already holds exactly // what this save was going to write, and the rejected-save cleanup could not remove it - it is // no longer the empty placeholder open() wrote - so reporting a failure would leave a new file // holding the accepted content with the task told the write had failed. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider.editType = "create" // open()'s record of the file it created: the placeholder token in the registry, the // ownership identity, and a null prior observation because nothing was there to read. mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, "placeholder-token", true) diffViewProvider["placeholderVersion"] = "placeholder-token" diffViewProvider["placeholderIdentity"] = { dev: 1n, ino: 1n } diffViewProvider["preOpenObservation"] = null diffViewProvider["openToken"] = "placeholder-token" // Auto Save moved the token: the disk now reports these stats and holds the accepted bytes. vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") // A rejected save reports the guard's diagnostic; an adopted publish reports the normal // post-save outcome for the content that is already on disk. await expect(diffViewProvider.saveChanges(false)).resolves.toMatchObject({ newProblemsMessage: "", finalContent: "new content", }) // Adopted rather than cleaned up: the file stayed where it is, and the session's observation // now vouches for the version that is actually on disk instead of the placeholder that is gone. expect(fs.unlink).not.toHaveBeenCalled() const observation = mockTask.observationRegistry.get(`${mockCwd}/test.ts`) expect(observation?.version).toBe(versionTokenOfStat(previewStats)) expect(observation?.complete).toBe(true) }) it("adopts the bytes Auto Save published when open() recreated a partially read file", async () => { // The thread's trigger, end to end: the model read the file partially, the file was removed, // and open() took the create path - the registry now holds the verified empty placeholder // marked complete and placeholderVersion is set, while preOpenObservation still describes the // slice of a file that is gone. Auto Save wrote the accepted bytes, and the guard rejected with // GuardStaleVersionError because the completeness gate never ran - the registry entry is // complete. Adoption has to be decided from the placeholder the session owns, not from the // stale snapshot: refusing here reports a failure for a new file that already holds the // accepted bytes, and the cleanup cannot unlink it because it is no longer the empty // placeholder open() wrote. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider.editType = "create" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, "placeholder-token", true) diffViewProvider["placeholderVersion"] = "placeholder-token" diffViewProvider["placeholderIdentity"] = { dev: 1n, ino: 1n } diffViewProvider["preOpenObservation"] = { version: "gone-file-partial", complete: false } diffViewProvider["openToken"] = "gone-file-partial" vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).resolves.toMatchObject({ newProblemsMessage: "", finalContent: "new content", }) expect(fs.unlink).not.toHaveBeenCalled() const observation = mockTask.observationRegistry.get(`${mockCwd}/test.ts`) expect(observation?.version).toBe(versionTokenOfStat(previewStats)) expect(observation?.complete).toBe(true) }) it("adopts content autosave already published instead of reporting a stale rejection", async () => { // Autosave wrote the buffer before acceptance: the document is clean and the // disk already holds exactly the bytes this save intended, but the version // token moved, so the compare-and-swap still rejects. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider.editType = "modify" // A partial observation must stay partial: adopting content that is already on // disk cannot upgrade it into authority for a full-file replacement. mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), false) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).resolves.toMatchObject({ newProblemsMessage: "" }) // The observation now points at the state that already matches, keeping the // completeness of the original read. const observation = mockTask.observationRegistry.get(`${mockCwd}/test.ts`) expect(observation?.version).toBe(versionTokenOfStat(previewStats)) expect(observation?.complete).toBe(false) // Nothing was clobbered, so the buffer is not reloaded and no placeholder is // unlinked; the normal post-save close flow still ran. expect(fs.unlink).not.toHaveBeenCalled() expect(vi.mocked(vscode.window.showTextDocument)).not.toHaveBeenCalled() expect(diffViewProvider["closeAllDiffViews"]).toHaveBeenCalled() }) it("does not adopt an autosaved match when the completeness gate rejected the update", async () => { // The model read a slice, so its observation is partial, and open() stat-matched // that same version - the version gate passes. But the guarded write was refused // by the completeness gate before any compare-and-swap ran: adopting the // matching bytes would report a successful full-file replacement for a write the // completeness gate rejected, with the lines the model never read gone and // nothing telling the model. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), false) diffViewProvider["preOpenObservation"] = { version: versionTokenOfStat(previewStats), complete: false } diffViewProvider["openToken"] = versionTokenOfStat(previewStats) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("File was only partially read") // The adoption probe never runs once the completeness gate refuses, and the // observation stays the partial read the model actually made. expect(fs.readFile).not.toHaveBeenCalled() const observation = mockTask.observationRegistry.get(`${mockCwd}/test.ts`) expect(observation?.complete).toBe(false) expect(observation?.version).toBe(versionTokenOfStat(previewStats)) }) it("adopts an autosaved match when the preview ran against the model's complete observation", async () => { // The autosave shape with the preview's own pairing: the model read the whole // file, open() stat-matched that version, and autosave published the accepted // bytes. Only the version token moved, which is exactly what adoption exists // for, so the completeness gate must not refuse this one. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) diffViewProvider["preOpenObservation"] = { version: versionTokenOfStat(previewStats), complete: true } diffViewProvider["openToken"] = versionTokenOfStat(previewStats) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).resolves.toMatchObject({ newProblemsMessage: "" }) const observation = mockTask.observationRegistry.get(`${mockCwd}/test.ts`) expect(observation?.version).toBe(versionTokenOfStat(previewStats)) expect(observation?.complete).toBe(true) }) it("still adopts an autosaved match for a targeted edit after a partial read", async () => { // A targeted edit is authorized by a partial read, so the completeness gate // never rejects it; when autosave published the edit's bytes, the moved-token // rejection is exactly the adoption shape and must stay adopted. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), false) diffViewProvider["preOpenObservation"] = { version: versionTokenOfStat(previewStats), complete: false } diffViewProvider["openToken"] = versionTokenOfStat(previewStats) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false, 0, "edit")).resolves.toMatchObject({ newProblemsMessage: "", }) // The edit's publish keeps the read's completeness: a partial read stays // partial and cannot authorize a later full-file replacement. const observation = mockTask.observationRegistry.get(`${mockCwd}/test.ts`) expect(observation?.complete).toBe(false) }) it("does not adopt a match when an external writer moved the file before the preview", async () => { const mockEditor = mockTextEditor(`${mockCwd}/ext-writer.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/ext-writer.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) diffViewProvider.editType = "modify" mockTask.observationRegistry.clear() const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/ext-writer.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // The model read v1. A different writer then moved the file to v2, and the preview // stat-matched v2. Autosave published the model's bytes over v2, so the disk now // matches this save byte for byte - which is exactly what the clobber the guard // rejected looks like from here. const externalStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(9), size: BigInt(300), mtimeNs: BigInt(4_000_000_001n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats mockTask.observationRegistry.observe(`${mockCwd}/ext-writer.ts`, versionTokenOfStat(previewStats), true) vi.mocked(fs.stat).mockResolvedValue(externalStats) vi.mocked(fs.readFile).mockResolvedValue("external bytes") await diffViewProvider.open("ext-writer.ts") // The autosave shape: a clean buffer holding exactly the accepted content. diffViewProvider["activeDiffEditor"] = cleanEditor // The autosave shape: a clean buffer holding exactly the accepted content, and a // disk token that moved past the version the save was authorized against. vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") // No adoption: the observation is not moved onto the state that was clobbered, // so the model's next write is not authorized by it. expect(mockTask.observationRegistry.get(`${mockCwd}/ext-writer.ts`)?.version).toBe( versionTokenOfStat(previewStats), ) }) it("does not adopt a match for an update over a target the model never read", async () => { const mockEditor = mockTextEditor(`${mockCwd}/unread-target.ts`) vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(mockTextDocument(`${mockCwd}/unread-target.ts`)), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) diffViewProvider.editType = "modify" mockTask.observationRegistry.clear() const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/unread-target.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // open() found no observation for the path, so the preview is the only read and // the rejection is about authorization rather than a moved token. The exclusion // used to cover an "edit" with no pre-open observation only, so an // "update" over the same unread target was adopted as a success. vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("on disk bytes") await diffViewProvider.open("unread-target.ts") // The autosave shape: a clean buffer holding exactly the accepted content. diffViewProvider["activeDiffEditor"] = cleanEditor vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("File was only partially read") // The rejection is the outcome: under the old gate the byte match was adopted // and saveChanges resolved as a success, granting the model a clean result for // a write that never happened. expect(mockTask.observationRegistry.get(`${mockCwd}/unread-target.ts`)?.complete).toBe(false) }) it("does not adopt an autosaved match for an edit that was never authorized", async () => { // Same autosave shape, different verdict: with no observation from before open() // the guard rejects for AUTHORIZATION. Adopting the byte match would report a // modified result and record a partial observation for a file the model never // read, which would then authorize a later targeted publish. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider.editType = "modify" diffViewProvider["preOpenObservation"] = null mockTask.observationRegistry.clear() vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false, 0, "edit")).rejects.toThrow(/File not read yet/) // No adoption read, and no observation granted. expect(fs.readFile).not.toHaveBeenCalled() expect(mockTask.observationRegistry.get(`${mockCwd}/test.ts`)).toBeUndefined() }) it("still rejects when the disk content does not match what the save intended", async () => { // Same autosave shape, different bytes: the guard verdict stands. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("someone else") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") // The observation is left at the state the read saw, not upgraded to the // autosaved content the save did not author. expect(mockTask.observationRegistry.get(`${mockCwd}/test.ts`)?.version).toBe( versionTokenOfStat(previewStats), ) // The rejection still stands: the buffer is discarded and the views close, // so the caller sees the guard verdict, not a silent success. expect(diffViewProvider["closeOwnDiffView"]).toHaveBeenCalled() }) it("keeps the rejection when the buffer is still dirty even though the disk matches", async () => { // A dirty buffer means the disk content came from someone else, so the // discard cleanup is still the outcome even when the bytes happen to match. // Without the clean-document gate this test would adopt the match and skip // the discard. const editor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = editor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") expect(vi.mocked(vscode.commands.executeCommand)).toHaveBeenCalledWith("workbench.action.files.revert") // The clean-document gate short-circuits before the adoption check, so the // rejection path never stats or reads the file. expect(fs.stat).not.toHaveBeenCalled() expect(fs.readFile).not.toHaveBeenCalled() }) it("keeps the rejection when the file moved between the stat and the read", async () => { // Same bytes, but the second stat differs: the read is not attributable to // the state the token describes, so a match cannot be adopted. const movedStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(9), size: BigInt(300), mtimeNs: BigInt(4_000_000_001n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats const editor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = editor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValueOnce(previewStats).mockResolvedValueOnce(movedStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") expect(mockTask.observationRegistry.get(`${mockCwd}/test.ts`)?.version).toBe( versionTokenOfStat(previewStats), ) }) it("keeps a complete observation complete when adopting an autosaved match", async () => { // The completeness of the original read must survive the adoption unchanged: // a complete read stays complete, so the fallback default must not silently // downgrade it. const editor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = editor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).resolves.toMatchObject({ newProblemsMessage: "" }) const observation = mockTask.observationRegistry.get(`${mockCwd}/test.ts`) expect(observation?.version).toBe(versionTokenOfStat(previewStats)) expect(observation?.complete).toBe(true) // The stat that pairs with the read must be the bigint form, otherwise the // token is built from truncated fields. expect(fs.stat).toHaveBeenCalledWith(`${mockCwd}/test.ts`, { bigint: true }) }) it("keeps the rejection when the stat paired with the read is unavailable", async () => { // There is no version to attribute the read to, so a match cannot be adopted. const editor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = editor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockRejectedValueOnce(new Error("stat failed")) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") expect(mockTask.observationRegistry.get(`${mockCwd}/test.ts`)?.version).toBe( versionTokenOfStat(previewStats), ) }) it("keeps the rejection when the paired read fails", async () => { // The bytes cannot be compared, so a match cannot be assumed. const editor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = editor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockRejectedValueOnce(new Error("read failed")) await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") }) it("records an incomplete observation when the path was never observed", async () => { // Nothing was read in full, so the adopted state must be recorded as an // incomplete observation rather than dereferencing a missing entry. A path the // registry has never seen keeps the case independent of earlier tests. const editor = { document: { uri: { fsPath: `${mockCwd}/never-observed.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = editor diffViewProvider.editType = "modify" diffViewProvider["relPath"] = "never-observed.ts" vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).resolves.toMatchObject({ newProblemsMessage: "" }) const freshObservation = mockTask.observationRegistry.get(`${mockCwd}/never-observed.ts`) expect(freshObservation?.version).toBe(versionTokenOfStat(previewStats)) expect(freshObservation?.complete).toBe(false) }) it("keeps a non-guard write failure a failure even when the disk already matches", async () => { // The guard passed and the write itself failed. The disk happens to hold the // same bytes, but this save did not publish them, so the failure must not be // reinterpreted as a success. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") vi.mocked(safeWriteText).mockRejectedValueOnce(new Error("EACCES: permission denied")) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("EACCES: permission denied") // No adoption read, so the guard verdict is the outcome. expect(fs.readFile).not.toHaveBeenCalled() expect(diffViewProvider["closeOwnDiffView"]).toHaveBeenCalled() }) it("does not adopt content when the failure is not a guard verdict", async () => { // The bytes match and the buffer is clean, but the failure is the dead-task // error, not a guard rejection: adoption must not turn an unrelated failure // into a success. const editor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = editor diffViewProvider.editType = "modify" diffViewProvider["taskRef"] = { deref: () => undefined } as unknown as WeakRef mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow( "Cannot guard the write: the owning task is no longer available", ) // The adoption check never runs, so the file is neither stat-ed nor read. expect(fs.stat).not.toHaveBeenCalled() expect(fs.readFile).not.toHaveBeenCalled() }) it("pairs the read with the bigint form on both sides of the comparison", async () => { // A non-bigint stat truncates the fields the version token is built from, so // both stats around the read must request the bigint form. const editor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = editor diffViewProvider.editType = "modify" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("new content") await expect(diffViewProvider.saveChanges(false)).resolves.toMatchObject({ newProblemsMessage: "" }) expect(vi.mocked(fs.stat).mock.calls.map((call) => call[1])).toEqual([{ bigint: true }, { bigint: true }]) }) it("does not unlink when the placeholder stat is unavailable and still closes the diff views", async () => { // The placeholder vanished between open() and the rejected save: the // stat guard must short-circuit BEFORE the token comparison (no // unlink) and the best-effort cleanup must not skip the view close. const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) diffViewProvider.editType = "create" const placeholderToken = versionTokenOfStat(previewStats) mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, placeholderToken, true) // the placeholder vanished: stat rejects and the guard's .catch // normalizes it to undefined stats vi.mocked(fs.stat).mockRejectedValue(new Error("ENOENT: no such file or directory")) vi.mocked(computeVersionToken).mockResolvedValue("moved") // stale rejection diffViewProvider["placeholderVersion"] = placeholderToken await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") expect(fs.unlink).not.toHaveBeenCalled() expect(diffViewProvider["closeOwnDiffView"]).toHaveBeenCalled() }) it("does not unlink a placeholder whose content changed after open() - the token gate refuses", async () => { // The placeholder is still on disk, but its stats no longer match the // token open() recorded: another writer touched the file, so the // cleanup must refuse to unlink (it would destroy the other // writer's content). const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) diffViewProvider.editType = "create" const placeholderToken = versionTokenOfStat(previewStats) mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, placeholderToken, true) // the on-disk placeholder moved on since open(): same identity, new // size -> a different token than the one open() recorded const movedStats = { ...previewStats, size: BigInt(301) } as unknown as BigIntStats vi.mocked(fs.stat).mockResolvedValue(movedStats) vi.mocked(computeVersionToken).mockResolvedValue("moved") // stale rejection diffViewProvider["placeholderVersion"] = placeholderToken await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") expect(fs.stat).toHaveBeenCalledWith(`${mockCwd}/test.ts`, { bigint: true }) // token mismatch -> the placeholder is NOT ours anymore: no unlink expect(fs.unlink).not.toHaveBeenCalled() expect(diffViewProvider["closeOwnDiffView"]).toHaveBeenCalled() }) it("a cancellation that lands during the adoption probe waits for the probe's decision", async () => { // The publish gate releases when guardedWrite settles, but a rejected publish // keeps reading the disk in the adoption probe. A rollback that wrote // originalContent inside that window would be judged against its own write - // the probe would match the rollback's bytes, not the published ones - so the // rollback has to wait for the probe's decision before touching the document. let probeEntered = false let probeDone = false let releaseProbe: () => void = () => {} const probeGate = new Promise((resolve) => { releaseProbe = resolve }) vi.mocked(fs.readFile).mockImplementation(async () => { probeEntered = true await probeGate probeDone = true return "new content" }) // Records whether the probe read had completed at each rollback write, so the // ordering assertion is about the writes themselves, not call counts. const rollbackWritesAfterProbe: boolean[] = [] const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockImplementation(() => { rollbackWritesAfterProbe.push(probeDone) return Promise.resolve(true) }) const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockImplementation(() => { rollbackWritesAfterProbe.push(probeDone) return Promise.resolve(undefined) }), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider.editType = "modify" diffViewProvider["originalContent"] = "original" // The token moved (the CAS rejects) but the disk still carries exactly the // bytes this save intended: the probe's decision is to adopt the publish. mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) // The reviewer's point stands on its own terms: applyEdit and document.save are the // buffer writers, while the rollback puts its bytes on the target through the DISK // writer - the module mock at the top of this file. Sample that writer itself, and // record for every call the bytes it was handed, whether the probe had already // decided when it was made, and how many disk reads had happened by then: a rollback // that published while the probe still owned the target, or that skipped the wait and // re-read the target to judge it a second time, cannot hide behind a correctly // ordered buffer write. const diskWritesAtEntry: { bytes: string probeDecided: boolean diskReadsBeforePublish: number }[] = [] vi.mocked(safeWriteText).mockImplementation(async (publishTarget, content) => { diskWritesAtEntry.push({ bytes: typeof content === "string" ? content : Buffer.from(content).toString("utf8"), probeDecided: probeDone, diskReadsBeforePublish: vi.mocked(fs.readFile).mock.calls.length, }) }) try { const save = diffViewProvider.saveChanges(false) while (!probeEntered) { await new Promise((resolve) => setImmediate(resolve)) } const revert = diffViewProvider.revertChanges() await new Promise((resolve) => setImmediate(resolve)) // The rollback has not touched the document: the probe still owns the decision. expect(applyEdit).not.toHaveBeenCalled() // The probe is about to adopt the publish: from here the disk carries this // session's own token again, so the rollback's compare-and-swap can match it. vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) releaseProbe() const [result] = await Promise.all([save, revert]) // The probe adopted the publish, but the cancellation claimed the session, so // the save reports no completed flow of its own... expect(result).toEqual({ newProblemsMessage: undefined, userEdits: undefined, finalContent: undefined, }) // ...and the rollback is the last writer: its document write happened after // the probe read, never against the bytes it was matching. The disk publish // went through the compare-and-swap (not the buffer save), and the buffer was // then reconciled by reverting onto the published bytes. expect(rollbackWritesAfterProbe).toEqual([true]) // The rollback's guarded publish is the only disk write in this scenario: it entered // the writer carrying the rollback's own bytes, after the probe had decided, and // after exactly one disk read - the probe's. The rollback waited for that decision // instead of re-reading the target to judge it a second time. expect(diskWritesAtEntry).toEqual([ { bytes: "original", probeDecided: true, diskReadsBeforePublish: 1 }, ]) expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.files.revert") // One pass over the tabs: the save added no cleanup of its own. expect(diffViewProvider["closeAllDiffViews"]).toHaveBeenCalledTimes(1) } finally { vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } }) it("preserves a peer publish that landed after this session's write during rollback", async () => { // The guarded publish settled, a peer published before the rollback // claimed the file lock, and the unguarded restore clobbered the peer's // bytes. Under the lock the disk token no longer carries this session's // write: the peer's content is preserved and the conflict is reported // instead of a silent overwrite. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["lastWrittenToken"] = "our-token" // The peer's stat: a different token than the one this session left. vi.mocked(fs.stat).mockResolvedValue({ ...previewStats, size: 999n, mtimeNs: 7n, ctimeNs: 8n, } as unknown as BigIntStats) await expect(diffViewProvider.revertChanges()).rejects.toBeInstanceOf(RollbackConflictError) // The restore never ran: the peer's bytes stay on disk. expect(vscode.workspace.applyEdit).not.toHaveBeenCalled() // The rejected rollback still finalized the session: the finalization is // claimed so no preview authorization survives the rejection. expect(diffViewProvider["sessionFinalizationClaimed"]).toBe(true) }) it("revertChanges() binds the rollback publish to the version it checked (barrier)", async () => { // Barrier: the rollback reads the disk version, a peer publishes while that // read is in flight, and the publish must still be bound to the checked // version. The old check-then-save wrote originalContent over the peer // regardless of what the check found; the compare-and-swap re-reads the // version under the lock at publish time, sees the peer token, and leaves // the peer bytes on disk. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["lastWrittenToken"] = versionTokenOfStat(previewStats) const peerStats = { ...previewStats, size: 999n, mtimeNs: 7n, ctimeNs: 8n, } as unknown as BigIntStats vi.mocked(fs.stat).mockResolvedValue(previewStats) let releasePeer: () => void = () => {} const peerWindow = new Promise((resolve) => { releasePeer = resolve }) vi.mocked(computeVersionToken).mockImplementation(async () => { // The rollback's authoritative version read pauses here; the test lets // a peer publish land inside the pause, and the read returns the peer // version the publish then has to be compared against. await peerWindow return versionTokenOfStat(peerStats) }) const revert = diffViewProvider.revertChanges() while (vi.mocked(computeVersionToken).mock.calls.length === 0) { await new Promise((resolve) => setImmediate(resolve)) } // The peer publishes while the rollback is mid-check. vi.mocked(fs.stat).mockResolvedValue(peerStats) releasePeer() // The publish rejected on the peer version and named it as the conflict. await expect(revert).rejects.toMatchObject({ name: "RollbackConflictError", diskToken: versionTokenOfStat(peerStats), }) // The peer's content remains: the rollback never published over the peer // and never touched the buffer. expect(safeWriteText).not.toHaveBeenCalledWith(expect.any(String), "original") expect(vscode.workspace.applyEdit).not.toHaveBeenCalled() }) it("revertChanges() preserves the disk when the session has no rollback baseline", async () => { // A guarded publish whose token read failed leaves the session without a // version to bind the restore to. The old fallback saved originalContent // unguarded - over any peer write landing in that window. The rollback // now preserves the disk state and reports the conflict explicitly. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["lastWrittenToken"] = undefined // The disk holds bytes this session never wrote: no baseline plus a peer write, which is // the case the conflict exists for. (Bytes equal to the buffer would be this session's own // Auto Save, and the rollback recognises those instead of reporting a conflict.) vi.mocked(fs.readFile).mockResolvedValue("peer bytes") vi.mocked(fs.stat).mockResolvedValue(previewStats) await expect(diffViewProvider.revertChanges()).rejects.toMatchObject({ name: "RollbackConflictError", oursToken: "", diskToken: versionTokenOfStat(previewStats), }) // The disk was preserved: no publish of originalContent, no buffer write. expect(safeWriteText).not.toHaveBeenCalledWith(expect.any(String), "original") expect(vscode.workspace.applyEdit).not.toHaveBeenCalled() }) it("revertChanges() preserves the disk when the disk reports no version", async () => { // The mirror case: the session recorded a token but the disk reports no // version to compare against (absent or unreadable). Saving here would // recreate or clobber a path whose state this session cannot prove. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["lastWrittenToken"] = versionTokenOfStat(previewStats) vi.mocked(fs.stat).mockResolvedValue(undefined as unknown as Awaited>) // No stat evidence. await expect(diffViewProvider.revertChanges()).rejects.toMatchObject({ name: "RollbackConflictError", oursToken: versionTokenOfStat(previewStats), diskToken: "", }) expect(safeWriteText).not.toHaveBeenCalledWith(expect.any(String), "original") expect(vscode.workspace.applyEdit).not.toHaveBeenCalled() }) it("revertChanges() keeps a peer replacement when the create recorded an identity only", async () => { // A create whose placeholder token is unavailable (identity-only or failed // stat-bracketed open) cannot prove ownership of the path it is about to // unlink: a peer replacement landing in that window would be deleted by a // rollback that never saw it. The unlink runs only on a proven token match; // an unknown owner keeps the path and the created directories. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("placeholder content"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "create" diffViewProvider["lastWrittenToken"] = undefined diffViewProvider["placeholderVersion"] = undefined diffViewProvider["placeholderIdentity"] = { dev: BigInt(1), ino: BigInt(2) } diffViewProvider["createdDirs"] = [`${mockCwd}/newdir`] vi.mocked(fs.stat).mockResolvedValue(previewStats) await expect(diffViewProvider.revertChanges()).rejects.toMatchObject({ name: "RollbackConflictError", oursToken: "", diskToken: versionTokenOfStat(previewStats), }) // Ownership unknown: neither the unlink nor the directory cleanup ran. expect(fs.unlink).not.toHaveBeenCalled() expect(fs.rmdir).not.toHaveBeenCalled() }) it("reports a peer publish that landed after a real successful save as a rollback conflict", async () => { // The rollback baseline must come from this session's own publish: a real // saveChanges() records the token its publish left on disk, so a peer that // republishes before the rollback is reported as a conflict instead of // being silently overwritten. While guardedWrite resolved void the // baseline stayed undefined and this exact sequence clobbered the peer. await diffViewProvider.saveChanges(false) // The rollback baseline belongs to this session: a save that records no token would let // the conflict below pass on the placeholder fallback instead. const savedBaseline = diffViewProvider["lastWrittenToken"] expect(savedBaseline).toBeDefined() const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "modify" diffViewProvider["originalContent"] = "original" // No manual lastWrittenToken: the successful save above must have recorded it. const peerStats = { ...previewStats, size: 999n, mtimeNs: 7n, ctimeNs: 8n, } as unknown as BigIntStats vi.mocked(fs.stat).mockResolvedValue(peerStats) // The rollback compare-and-swap reads the version through the same source // the publish uses: the peer token, not this session token. vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(peerStats)) await expect(diffViewProvider.revertChanges()).rejects.toBeInstanceOf(RollbackConflictError) expect(vscode.workspace.applyEdit).not.toHaveBeenCalled() }) it("does not carry the previous session's rollback baseline into a new session", async () => { // The baseline belongs to the session that wrote it: a new session that // is cancelled before writing anything must not compare its file's disk // token against a token left by the previous session and report a false // conflict that leaves the preview edit unreverted. diffViewProvider["lastWrittenToken"] = "previous-session-token" await openPreview() diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/test.txt`), getText: vi.fn().mockReturnValue("new content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) // The disk still carries the bytes open() read, which are not this session's buffer text: // nothing moved, so there is no session write to recognise and the rollback reloads instead. vi.mocked(fs.readFile).mockResolvedValue("bytes open() read") vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) // A session with no baseline, whose disk still carries exactly the version // open() read, has no peer content to protect: the rollback reloads the // original bytes (the same workbench revert the success path uses) and the // session is finalized instead of stranding the rejected edit in a dirty tab. await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined() expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.files.revert") // No CAS publish ran: nothing was ever written by this session to bind to. expect(safeWriteText).not.toHaveBeenCalled() // The session is finalized: a later rollback has nothing left to restore. expect(diffViewProvider.isEditing).toBe(false) }) it("saveDirectly does not upgrade a stale observation for a caller that never read the basis", async () => { // WriteToFileTool's shape: its bytes come from the model, and the previewed basis still // matches the target, so a whole-file re-observation would record the current token and let // a full replacement built from v1 overwrite v2. The diff-view path for that same tool // refuses this, so the direct path must keep the model's stale entry for the guard. mockTask.observationRegistry.clear() diffViewProvider.originalContent = "basis content" const staleToken = "1:2:300:1000000000:1000000000" mockTask.observationRegistry.observe(`${mockCwd}/stale-direct.ts`, staleToken, true) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("basis content") vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) await expect( diffViewProvider.saveDirectly( "stale-direct.ts", "replacement content", false, false, 0, "update", false, ), ).rejects.toThrow(/Stale version/) expect(mockTask.observationRegistry.get(`${mockCwd}/stale-direct.ts`)?.version).toBe(staleToken) }) it("saveDirectly does not upgrade a partial observation for a caller that never read the basis", async () => { // The other half of the same shape: the target holds exactly the bytes the tool previewed, so // a whole-file re-observation would upgrade the model's partial read to complete and accept a // replacement built from a partial view. Without basis authority the guard sees // complete: false and refuses, which is what the diff-view path does. mockTask.observationRegistry.clear() diffViewProvider.originalContent = "basis content" mockTask.observationRegistry.observe( `${mockCwd}/partial-direct.ts`, versionTokenOfStat(previewStats), false, ) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("basis content") vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) await expect( diffViewProvider.saveDirectly( "partial-direct.ts", "replacement content", false, false, 0, "update", false, ), ).rejects.toThrow( "File was only partially read (line slice, range, truncated view, or indentation block) -- ", ) expect(mockTask.observationRegistry.get(`${mockCwd}/partial-direct.ts`)?.complete).toBe(false) }) it("saveDirectly authorizes nothing for an unread target when the caller never read the basis", async () => { // The third effect the finding names: an existing file the model never read. A whole-file // re-observation against the tool's own preview would hand the guard a complete observation // for a target nobody read, authorizing the write. With no basis authority the registry stays // empty and the guard asks for the read first. mockTask.observationRegistry.clear() diffViewProvider.originalContent = "model written content" vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("existing bytes the model never read") vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) await expect( diffViewProvider.saveDirectly( "unread-direct.ts", "model written content", false, false, 0, "update", false, ), ).rejects.toBeInstanceOf(GuardRejectedError) expect(mockTask.observationRegistry.get(`${mockCwd}/unread-direct.ts`)).toBeUndefined() }) it("revertChanges() recognises this session's own Auto Save bytes instead of reporting a conflict", async () => { // A rejection never publishes, so lastWrittenToken is undefined and the rollback would bind // to openToken. Auto Save of the diff's modified document - the real file URI - already wrote // this session's proposed edit, moving the disk version off openToken. Reporting a conflict // here strands the rejected edit on disk and blames a peer that never wrote, so the rollback // recognises its own bytes and restores originalContent under the disk's current version. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("proposed edit"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["lastWrittenToken"] = undefined diffViewProvider["openToken"] = "token-open-recorded" vi.mocked(vscode.workspace.encode).mockImplementation(async (content: string) => new TextEncoder().encode(content), ) // Auto Save moved the version: the disk holds the proposed edit, not what open() read. vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("proposed edit") vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined() // The restore published under the Auto Save version, and the buffer came back to the original. expect(safeWriteText).toHaveBeenCalledTimes(1) // The rollback encoded originalContent and published once - under the version Auto Save left, // which the resolve above already proves it bound to. expect(vscode.workspace.encode).toHaveBeenCalledWith("original", { encoding: "utf8" }) expect(vscode.workspace.applyEdit).toHaveBeenCalled() }) it("revertChanges() still reports a peer write when Auto Save is on and the bytes are not the session's", async () => { // The recognition must not become a blank cheque: Auto Save moved the version, but the file // holds neither this session's buffer nor originalContent, so a peer wrote it and the rollback // has to preserve those bytes and report the conflict. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("proposed edit"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["lastWrittenToken"] = undefined diffViewProvider["openToken"] = "token-open-recorded" vi.mocked(vscode.workspace.encode).mockImplementation(async (content: string) => new TextEncoder().encode(content), ) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("peer bytes") vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats)) await expect(diffViewProvider.revertChanges()).rejects.toMatchObject({ name: "RollbackConflictError" }) expect(safeWriteText).not.toHaveBeenCalled() expect(vscode.workspace.applyEdit).not.toHaveBeenCalled() }) it("revertChanges() unlinks a created file whose Auto Save bytes are this session's own", async () => { // The create path fails the same way: Auto Save moves the token off placeholderVersion, so the // file carrying the rejected edit survives the rollback and the session stays open on a file it // created itself. Those bytes are the session's, so the unlink binds to that version. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/new-file.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("proposed new file"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "new-file.ts" diffViewProvider.editType = "create" diffViewProvider["originalContent"] = "" diffViewProvider["placeholderVersion"] = "token-placeholder" diffViewProvider["lastWrittenToken"] = undefined vi.mocked(vscode.workspace.encode).mockImplementation(async (content: string) => new TextEncoder().encode(content), ) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("proposed new file") vi.mocked(fs.unlink).mockResolvedValue(undefined) await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined() expect(fs.unlink).toHaveBeenCalledWith(`${mockCwd}/new-file.ts`) }) it("revertChanges() keeps a peer's file when the created path holds bytes this session never wrote", async () => { // Same create path, peer content: Auto Save moved the version, but the bytes are not this // session's buffer, so the unlink would delete a file this session no longer owns. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/new-file.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("proposed new file"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "new-file.ts" diffViewProvider.editType = "create" diffViewProvider["originalContent"] = "" diffViewProvider["placeholderVersion"] = "token-placeholder" diffViewProvider["lastWrittenToken"] = undefined vi.mocked(vscode.workspace.encode).mockImplementation(async (content: string) => new TextEncoder().encode(content), ) vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.readFile).mockResolvedValue("peer bytes") await expect(diffViewProvider.revertChanges()).rejects.toMatchObject({ name: "RollbackConflictError" }) expect(fs.unlink).not.toHaveBeenCalled() }) it("drops the rollback baseline when the session is finalized", async () => { // performFinalReset clears the other per-session fields; the rollback // baseline must not survive it, or a reused provider compares the next // session's file against the previous session's bytes. diffViewProvider["lastWrittenToken"] = "our-token" await diffViewProvider.reset() expect(diffViewProvider["lastWrittenToken"]).toBeUndefined() }) it("revertChanges() stops removing created directories at the first failure instead of abandoning the cleanup", async () => { // undoPartialOpen() and the rejected-save cleanup already stop at the first rmdir failure; this // loop did not. A peer that drops a file into one of the directories open() created makes rmdir // reject with ENOTEMPTY, and a rejection escaping the cleanup aborted the teardown before // restorePreviewTabs() and reset() could run: isEditing stayed set, the preview observation // stayed registered, and abortStream() received a raw rejection for a cleanup that had nothing // left to protect. The delete that matters - the placeholder this session owns - still lands. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("placeholder"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "create" diffViewProvider["placeholderVersion"] = versionTokenOfStat(previewStats) diffViewProvider["createdDirs"] = [`${mockCwd}/r6-dirs`, `${mockCwd}/r6-dirs/nested`] vi.mocked(fs.stat).mockResolvedValue(previewStats) vi.mocked(fs.rmdir).mockRejectedValue( Object.assign(new Error("ENOTEMPTY: directory not empty, rmdir"), { code: "ENOTEMPTY" }), ) await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined() // The placeholder is gone, the directories stop at the one that refused, and the teardown's tail // still runs: isEditing is cleared rather than left claimed by a session nobody is rolling back. expect(vi.mocked(fs.unlink)).toHaveBeenCalledWith(`${mockCwd}/test.ts`) expect(vi.mocked(fs.rmdir)).toHaveBeenCalledTimes(1) expect(vi.mocked(fs.rmdir)).toHaveBeenCalledWith(`${mockCwd}/r6-dirs/nested`) expect(diffViewProvider.isEditing).toBe(false) }) it("keeps a peer's file when the create placeholder was replaced before the rollback", async () => { // The unlink must run only while the path still carries THIS session's // placeholder: a peer that published after the placeholder owns the // file, and deleting it would discard content this session never wrote. const cleanEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("placeholder"), lineCount: 0, encoding: "utf8", isDirty: false, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: vi.fn().mockResolvedValue(undefined), }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = cleanEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "create" diffViewProvider["placeholderVersion"] = "placeholder-token" vi.mocked(fs.stat).mockResolvedValue({ ...previewStats, size: 999n, mtimeNs: 7n, ctimeNs: 8n, } as unknown as BigIntStats) await expect(diffViewProvider.revertChanges()).rejects.toBeInstanceOf(RollbackConflictError) expect(fs.unlink).not.toHaveBeenCalled() }) it("revertChanges() deletes the create placeholder without saving the diff buffer first", async () => { // Saving the dirty diff buffer before the delete would publish the // cancelled edit's content to disk for one moment before removing it - // a write the rollback never intended and one that is not bound to the // placeholder check. The buffer must be discarded by reloading, and the delete // must be the only disk write action. const documentSave = vi.fn().mockResolvedValue(undefined) const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("placeholder content"), lineCount: 0, encoding: "utf8", isDirty: true, positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), save: documentSave, }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface. diffViewProvider["activeDiffEditor"] = dirtyEditor diffViewProvider["relPath"] = "test.ts" diffViewProvider.editType = "create" diffViewProvider["placeholderVersion"] = versionTokenOfStat(previewStats) // The path still carries this session's placeholder token. vi.mocked(fs.stat).mockResolvedValue(previewStats) // The buffer is discarded by reloading the empty placeholder from disk (the // editor clears the dirty flag), never by saving it: the placeholder file is // already empty, so the reload writes nothing. vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command: string) => { if (command === "workbench.action.files.revert") { ;(dirtyEditor.document as unknown as { isDirty: boolean }).isDirty = false } }) await diffViewProvider.revertChanges() expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.files.revert") expect(documentSave).not.toHaveBeenCalled() expect(fs.unlink).toHaveBeenCalledWith(`${mockCwd}/test.ts`) }) it("a cancellation that lands after the rejected-save cleanup skips the rollback and finalizes", async () => { // The discard cleanup reloaded the newer disk content and closed this // session's views. A rollback after it would apply originalContent and save // it over the bytes the cleanup just preserved - the same loss, one pass // later - so a cancellation that arrives once the cleanup has finished must // finalize the session without a second revert. const documentSave = vi.fn().mockResolvedValue(undefined) const dirtyEditor = { document: { uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, getText: vi.fn().mockReturnValue("new content"), lineCount: 0, encoding: "utf8", isDirty: true, save: documentSave, }, selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), } as unknown as vscode.TextEditor diffViewProvider["activeDiffEditor"] = dirtyEditor revertClearsDirty(dirtyEditor.document) diffViewProvider.editType = "modify" diffViewProvider["originalContent"] = "original" mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, versionTokenOfStat(previewStats), true) vi.mocked(computeVersionToken).mockResolvedValue("moved") vi.mocked(fs.stat).mockResolvedValue(previewStats) // The disk carries someone else's bytes and the buffer is dirty: adoption // refuses, so the discard cleanup runs and handles the session. vi.mocked(fs.readFile).mockResolvedValue("external bytes") await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("Stale version") const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) await diffViewProvider.revertChanges() // No rollback: originalContent is neither applied to the buffer nor saved. expect(applyEdit).not.toHaveBeenCalled() expect(documentSave).not.toHaveBeenCalled() // No second pass over the tabs either - the cleanup already closed this // provider's diff view, and the newer disk bytes stand untouched. expect(diffViewProvider["closeAllDiffViews"]).not.toHaveBeenCalled() // The session is finalized exactly once. expect(diffViewProvider["sessionFinalizationClaimed"]).toBe(true) expect(diffViewProvider["isEditing"]).toBe(false) }) }) describe("saveChanges method with diagnostic settings", () => { beforeEach(() => { // Setup common mocks for saveChanges tests diffViewProvider["relPath"] = "test.ts" diffViewProvider["newContent"] = "new content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ getText: vi.fn().mockReturnValue("new content") }), }) diffViewProvider["preDiagnostics"] = [] // Mock vscode functions vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) }) it("should apply diagnostic delay when diagnosticsEnabled is true", async () => { const mockDelay = vi.mocked(delay) mockDelay.mockClear() // Mock closeAllDiffViews diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) const result = await diffViewProvider.saveChanges(true, 3000) // Verify delay was called with correct duration expect(mockDelay).toHaveBeenCalledWith(3000) expect(vscode.languages.getDiagnostics).toHaveBeenCalled() expect(result.newProblemsMessage).toBe("") }) it("should skip diagnostics when diagnosticsEnabled is false", async () => { const mockDelay = vi.mocked(delay) mockDelay.mockClear() // Mock closeAllDiffViews diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) const result = await diffViewProvider.saveChanges(false, 2000) // Verify delay was NOT called and diagnostics were NOT checked expect(mockDelay).not.toHaveBeenCalled() expect(vscode.languages.getDiagnostics).not.toHaveBeenCalled() expect(result.newProblemsMessage).toBe("") }) it("should use default values when no parameters provided", async () => { const mockDelay = vi.mocked(delay) mockDelay.mockClear() // Mock closeAllDiffViews diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) const result = await diffViewProvider.saveChanges() // Verify default behavior (enabled=true, delay falls back to DEFAULT_WRITE_DELAY_MS) expect(mockDelay).toHaveBeenCalledWith(0) expect(vscode.languages.getDiagnostics).toHaveBeenCalled() expect(result.newProblemsMessage).toBe("") }) it("pins the default write delay to zero", () => { // The tests above compare against the constant, so they would still pass if the // default were changed back to 1000. Pin the value the write path actually uses. expect(DEFAULT_WRITE_DELAY_MS).toBe(0) }) it("should handle custom delay values", async () => { const mockDelay = vi.mocked(delay) mockDelay.mockClear() // Mock closeAllDiffViews diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) await diffViewProvider.saveChanges(true, 5000) // Verify custom delay was used expect(mockDelay).toHaveBeenCalledWith(5000) expect(vscode.languages.getDiagnostics).toHaveBeenCalled() }) }) describe("preEditScrollLine capture and restore", () => { it("should capture scroll line from visible editor at open() time", async () => { const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/scroll.ts`) }), visibleRanges: [makeRange(42)], }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(makeTextDocument({ uri: makeUri(`${mockCwd}/scroll.ts`) })), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) diffViewProvider.editType = "modify" await diffViewProvider.open("scroll.ts") expect(diffViewProvider["preEditScrollLine"]).toBe(42) }) it("should set preEditScrollLine to undefined when the visible editor has no visibleRanges", async () => { const mockEditorNoRanges = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/new.ts`) }), // No visibleRanges, so the capture in open() yields undefined. visibleRanges: [], }) vi.mocked(vscode.window).visibleTextEditors = [mockEditorNoRanges] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditorNoRanges) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(makeTextDocument({ uri: makeUri(`${mockCwd}/new.ts`) })), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) diffViewProvider.editType = "modify" await diffViewProvider.open("new.ts") expect(diffViewProvider["preEditScrollLine"]).toBeUndefined() }) it("open() waits for a finalization still in flight before starting the new session", async () => { // performFinalReset() clears the session fields when it resumes from its awaits. // A session started underneath it would have its flags, listeners and deferred // scroll timer wiped by the old cleanup, and the old finalization would leave the // new session already claimed. open() has to serialize with the prior finalization. let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) const closeOwnDiffView = vi.fn().mockImplementation(async () => { await gate }) diffViewProvider["closeOwnDiffView"] = closeOwnDiffView diffViewProvider["relPath"] = "old.ts" diffViewProvider.isEditing = true const reset = diffViewProvider.reset() while (closeOwnDiffView.mock.calls.length === 0) { await new Promise((resolve) => setImmediate(resolve)) } const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/new.ts`), getText: vi.fn().mockReturnValue(""), lineCount: 0, }), selection: makeSelection(), edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(makeTextDocument({ uri: makeUri(`${mockCwd}/new.ts`) })), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) diffViewProvider.editType = "modify" let openDone = false const open = diffViewProvider.open("new.ts").then(() => { openDone = true }) await new Promise((resolve) => setImmediate(resolve)) // The new session has not started: the old finalization still owns the provider. expect(openDone).toBe(false) expect(closeOwnDiffView).toHaveBeenCalledTimes(1) release() await Promise.all([reset, open]) // The old finalization completed before the new session claimed the provider, so // it could neither clear the new session's flags nor claim its finalization. expect(openDone).toBe(true) expect(diffViewProvider.isEditing).toBe(true) expect(diffViewProvider["relPath"]).toBe("new.ts") // The new session is finalizable: its own reset closes it and closes its own // diff view - the old finalization's single close did not consume it. await diffViewProvider.reset() expect(diffViewProvider.isEditing).toBe(false) expect(closeOwnDiffView).toHaveBeenCalledTimes(2) }) it("saveChanges() calls revealRange(AtTop) when documentWasOpen and preEditScrollLine is set", async () => { const mockRevealRange = vi.fn() const mockSavedEditor = makeTextEditor({ revealRange: mockRevealRange }) vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockSavedEditor) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["documentWasOpen"] = true diffViewProvider["preEditScrollLine"] = 30 // saveChanges early-exits without relPath, newContent, activeDiffEditor diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ getText: vi.fn().mockReturnValue("content") }), }) await diffViewProvider.saveChanges(false) expect(mockRevealRange).toHaveBeenCalledWith( expect.objectContaining({ start: { line: 30, character: 0 } }), vscode.TextEditorRevealType.AtTop, ) }) it("saveChanges() does NOT call revealRange when preEditScrollLine is undefined", async () => { const mockRevealRange = vi.fn() const mockSavedEditor = makeTextEditor({ revealRange: mockRevealRange }) vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockSavedEditor) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["documentWasOpen"] = true diffViewProvider["preEditScrollLine"] = undefined diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ getText: vi.fn().mockReturnValue("content") }), }) await diffViewProvider.saveChanges(false) expect(mockRevealRange).not.toHaveBeenCalled() }) it("saveChanges() cancels a pending deferred scroll so it cannot fight scroll-restore", async () => { // With auto-approve, saveChanges runs immediately after scrollToFirstDiff. // A late deferred reveal must not fire after the viewport is restored. vi.useFakeTimers() try { const deferredReveal = vi.fn() const liveEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/race.ts`), getText: vi.fn().mockReturnValue("a\nCHANGED\nc\nd\n"), lineCount: 5, }), visibleRanges: [makeRange()], revealRange: deferredReveal, }) diffViewProvider.originalContent = "a\nb\nc\nd\n" diffViewProvider["activeDiffEditor"] = liveEditor vi.mocked(vscode.window).visibleTextEditors = [liveEditor] // Schedule the deferred reveal, then accept the edit before it fires. diffViewProvider.scrollToFirstDiff() expect(deferredReveal).toHaveBeenCalledTimes(1) vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["documentWasOpen"] = true diffViewProvider["preEditScrollLine"] = 0 diffViewProvider["newContent"] = "a\nCHANGED\nc\nd\n" await diffViewProvider.saveChanges(false) // The timer was cancelled; advancing past it produces no extra reveal. vi.advanceTimersByTime(100) expect(deferredReveal).toHaveBeenCalledTimes(1) expect(diffViewProvider["deferredScrollTimer"]).toBeUndefined() } finally { vi.useRealTimers() } }) it("revertChanges() calls revealRange(AtTop) when documentWasOpen and preEditScrollLine is set", async () => { const mockRevealRange = vi.fn() const mockSavedEditor = makeTextEditor({ revealRange: mockRevealRange }) vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockSavedEditor) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) // The CAS rollback needs both sides of the version comparison: this session // left the token and the disk still reports it. const scrollStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats vi.mocked(fs.stat).mockResolvedValue(scrollStats) vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(scrollStats)) diffViewProvider["lastWrittenToken"] = versionTokenOfStat(scrollStats) diffViewProvider["documentWasOpen"] = true diffViewProvider["preEditScrollLine"] = 15 diffViewProvider.editType = "modify" diffViewProvider.originalContent = "original" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/test.txt`), getText: vi.fn().mockReturnValue("modified"), positionAt: vi.fn().mockReturnValue(makePosition()), }), }) vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) await diffViewProvider.revertChanges() expect(mockRevealRange).toHaveBeenCalledWith( expect.objectContaining({ start: { line: 15, character: 0 } }), vscode.TextEditorRevealType.AtTop, ) }) }) describe("userTouchedDocument close/keep behavior", () => { const mockTargetPath = `${mockCwd}/mock-target-file.ts` // Synthetic stat for the session's own publish, tokenized with the real // versionTokenOfStat so the rollback's compare-and-swap sees a matching pair. const ownStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats beforeEach(() => { // The guarded-publish describe queues a stat mock that clearAllMocks does // not undo. These tests model a session whose own publish is the last // writer, so pin the disk evidence and the session baseline to the same // token instead of letting a foreign token pose as a peer write - the // rollback now refuses to act without both sides of the comparison. vi.mocked(fs.stat).mockResolvedValue(ownStats) // The file-wide observation and version source are "v1" (see the top-level // beforeEach): the session baseline must be the token the guarded publish // actually recorded, and the stat above only has to exist for the rollback // to have disk evidence to bind to. diffViewProvider["lastWrittenToken"] = "v1" }) const buildActiveDiffEditor = () => makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), positionAt: vi.fn().mockReturnValue(makePosition()), }), }) it("saveChanges() closes the file tab when the file was not open and untouched", async () => { const closeFileTab = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = closeFileTab diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["documentWasOpen"] = false diffViewProvider["userTouchedDocument"] = false diffViewProvider["preEditScrollLine"] = undefined diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = buildActiveDiffEditor() await diffViewProvider.saveChanges(false) expect(closeFileTab).toHaveBeenCalledWith(mockTargetPath) expect(vscode.window.showTextDocument).not.toHaveBeenCalled() }) it("revertChanges() does not run a second teardown while one is already in flight", async () => { // Cancellation can reach revertChanges() while a rejected save is still // discarding the same buffer. Both paths acting on the document and the same // tabs is duplicate cleanup, so the second caller waits for the first. const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" const editor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) diffViewProvider["activeDiffEditor"] = editor const first = diffViewProvider.revertChanges() const second = diffViewProvider.revertChanges() await Promise.all([first, second]) expect(applyEdit).toHaveBeenCalledTimes(1) }) // The save's post-publish cleanup touches the same buffers and tabs a cancellation's // teardown does, so it has to be one serialized pass - and a save whose session was torn // down while the guarded publish was still awaiting must not run a cleanup of its own. it("saveChanges() skips its post-publish cleanup when a teardown began during the publish", async () => { // A cancellation can reach revertChanges() while the publish is awaiting. That teardown // already closed the diff views and applied the auto-close preferences; a second pass // would close the same tabs and re-run the same document revert. const closeAllDiffViews = vi.fn().mockResolvedValue(undefined) const restorePreviewTabs = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeAllDiffViews"] = closeAllDiffViews diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = restorePreviewTabs const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) // The cancellation lands while the guarded publish is in flight. It is started // without being awaited inside the publish: the rollback waits for the publish to // settle before touching the document, so a rollback awaited inside the publish // would deadlock against that wait. The implementation has to be restored // afterwards: clearAllMocks() drops call records but keeps queued // implementations, and a leaked publish would cancel every later save in this file. let cancellation: Promise | undefined vi.mocked(safeWriteText).mockImplementation(async () => { cancellation = diffViewProvider.revertChanges() }) let result: Awaited> | undefined try { result = await diffViewProvider.saveChanges(false) await cancellation } finally { vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } expect(result).toEqual({ newProblemsMessage: undefined, userEdits: undefined, finalContent: undefined, }) // Exactly one teardown ran - the cancellation's - and the save added no cleanup of its // own on top of it. expect(applyEdit).toHaveBeenCalledTimes(1) expect(closeAllDiffViews).toHaveBeenCalledTimes(1) expect(restorePreviewTabs).toHaveBeenCalledTimes(1) }) it("a cancellation that lands while the save is still encoding publishes nothing after the claim", async () => { // The finding is about the window between the codec encode and the registration of the // publish below it: nothing in between asks whether the session was cancelled. A rollback // that started inside that window already owns the target, so a publish on the far side of // the encode would put the cancelled edit on top of the rollback restore. This test holds // the encode open, lands a cancellation inside the window, and then asks the only question // that decides the outcome: which bytes reached the disk writer. const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) // The disk writer is the witness: only the rollback restore should ever reach it. Its // first write is held open so that teardown pass still owns the session - and the // cancellation claim still stands - when the save leaves its encode. const diskWriteBytes: string[] = [] let releaseWrite: () => void = () => {} const rollbackWriteHeld = new Promise((resolve) => { releaseWrite = resolve }) let markWriteEntered: () => void = () => {} const rollbackWriteEntered = new Promise((resolve) => { markWriteEntered = resolve }) vi.mocked(safeWriteText).mockImplementation(async (publishTarget, content) => { diskWriteBytes.push(typeof content === "string" ? content : Buffer.from(content).toString("utf8")) if (diskWriteBytes.length === 1) { markWriteEntered() await rollbackWriteHeld } }) // The window itself. The rollback encodes originalContent, so the edited content is the // call this test parks, and every other encode keeps the module double bytes. The // implementation is restored in the finally: clearAllMocks keeps implementations, and a // leaked encode gate would stall every later save in this file. const encodeImpl = vi.mocked(vscode.workspace.encode).getMockImplementation() let releaseEncode: () => void = () => {} const encodeHeld = new Promise((resolve) => { releaseEncode = resolve }) let encodeEntered = false vi.mocked(vscode.workspace.encode).mockImplementation(async (content, options) => { if (content === "content") { encodeEntered = true await encodeHeld } else if (encodeImpl) { return encodeImpl(content, options) } return Buffer.from(content) }) type SaveResult = Awaited> let result: SaveResult | undefined let rollback: Promise | undefined let cancellation: Promise | undefined let save: Promise | undefined try { rollback = diffViewProvider.revertChanges() void rollback.catch(() => {}) // The checkpoint above only resolves from inside the disk writer. A rollback that // rejects - or one that finishes - before ever reaching that writer never resolves // it, and a bare await would then sit in the vitest timeout with the encode gate and // the writer gate still latched: a finally does not run while its await is pending. // Race the checkpoint against the teardown outcome - fail the moment the rollback // settles without writing, and let a rejection surface with the error it carried. const wroteBeforeTeardown = await Promise.race([ rollbackWriteEntered.then(() => true), rollback.then( () => false, (error: unknown) => Promise.reject(error), ), ]) if (!wroteBeforeTeardown) { throw new Error( `the rollback teardown finished before reaching the disk writer - the window this test holds open never opened`, ) } save = diffViewProvider.saveChanges(false) void save.catch(() => {}) for (let attempt = 0; !encodeEntered; attempt++) { if (attempt === 5000) { throw new Error( "the save never reached its encode - the window this test holds open never opened", ) } await new Promise((resolve) => setImmediate(resolve)) } // The cancellation lands inside the window: a second revertChanges joins the pass that // already owns the session, and joining is what records the claim. cancellation = diffViewProvider.revertChanges() void cancellation.catch(() => {}) // Proof the window was really open when it landed: the claim is standing, the only disk // write so far is the rollback restore that holds the pass, and this save is already // registered as in flight (the placeholder registered before its encode, replaced by the // publish promise once one exists). Earlier this field stayed undefined until the // publish was built, and that pin - a save inside its encode being invisible to a // cancellation - is exactly what the review asked to retire. expect(diffViewProvider["guardedSaveInFlight"]).toBeDefined() expect(diffViewProvider["teardownCancellationRequested"]).toBe(true) expect(diskWriteBytes).toEqual(["original"]) releaseEncode() result = await save expect(result).toEqual({ newProblemsMessage: undefined, userEdits: undefined, finalContent: undefined, }) // The load-bearing one: the cancelled edit never entered the writer. The save own // report reads the same either way, so the bytes are the verdict. expect(diskWriteBytes).toEqual(["original"]) // The claim this save was cancelled for is answered by this save, so it is read once // and cleared, as the post-publish report clears one it sees. expect(diffViewProvider["teardownCancellationRequested"]).toBe(false) // Both cancellations have to have FULFILLED, not merely been awaited. A rollback // that broke after its restore wrote would still report no completed save, and the // byte list above would still read exactly this, because the guarded waits in the // finally swallow rejections on purpose - they are the cleanup path for a test that // already failed. Release the held write here and await both revert promises on the // success path, so a teardown that broke after its write fails this test by name. releaseWrite() await rollback await cancellation } finally { releaseEncode() releaseWrite() if (save) { await save.catch(() => {}) } if (rollback) { await rollback.catch(() => {}) } if (cancellation) { await cancellation.catch(() => {}) } if (encodeImpl) { vi.mocked(vscode.workspace.encode).mockImplementation(encodeImpl) } else { vi.mocked(vscode.workspace.encode).mockReset() } vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } }) it("a failed encode after Auto Save leaves the rollback the cancellation asked for", async () => { // Auto Save can put the accepted preview on disk before this save publishes it: the buffer // is clean below because its own save call already ran. When the codec then refuses the // content, nothing on this side has dispatched a publish, so the only thing that can put // the pre-edit bytes back is the rollback the cancellation claimed. If the failed save // ran its discard cleanup instead, that cleanup marks the session handled and the waiting // rollback skips its restore - leaving the preview of the cancelled edit as the final // content of the file. The encode fails exactly once, from this test. const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeOwnDiffView"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue(`content`), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) // The disk writer is the witness for who was last to touch the target file. const diskWriteBytes: string[] = [] vi.mocked(safeWriteText).mockImplementation(async (target, content) => { diskWriteBytes.push(typeof content === `string` ? content : Buffer.from(content).toString(`utf8`)) }) // The codec fails once, for the accepted content only. The rollback encodes // originalContent, so every other encode keeps the module double bytes. The implementation // is restored in the finally: clearAllMocks keeps implementations, and a leaked encode // failure would fail every later save in this file. const encodeImpl = vi.mocked(vscode.workspace.encode).getMockImplementation() const encodeError = new Error(`the codec refused the accepted content after Auto Save`) let failEncode: (error: unknown) => void = () => {} const encodeGate = new Promise((resolve, reject) => { failEncode = reject }) let encodeEntered = false vi.mocked(vscode.workspace.encode).mockImplementation(async (content, options) => { if (content === `content`) { encodeEntered = true await encodeGate } else if (encodeImpl) { return encodeImpl(content, options) } return Buffer.from(content) }) type SaveResult = Awaited> let save: Promise | undefined let rollback: Promise | undefined try { save = diffViewProvider.saveChanges(false) void save.catch(() => {}) // The cancellation has to land inside the encode: while the save is still registered // and before anything was dispatched. for (let attempt = 0; attempt < 40 && !encodeEntered; attempt++) { await new Promise((resolve) => setTimeout(resolve, 1)) } if (!encodeEntered) { throw new Error( `this save never reached the codec encode - the window this test needs never opened`, ) } rollback = diffViewProvider.revertChanges() void rollback.catch(() => {}) await new Promise((resolve) => setTimeout(resolve, 5)) // The five-millisecond wait above only moves a clock: it checks nothing about // the pending state, and every assertion below runs after the rejection has // already unwound the window this test is about. Ask directly, before telling // the codec to fail: the rollback this revertChanges started must still be // unfinished, and nothing may have reached the writer yet. The race gives the // rollback a bounded window to prove it can move; structurally it cannot, // because the save it waits on is parked on this very encode gate. const rollbackBeforeFailure = await Promise.race([ rollback.then(() => "settled"), new Promise((resolve) => setTimeout(() => resolve("pending"), 25)), ]) expect(rollbackBeforeFailure).toBe("pending") expect(diskWriteBytes).toEqual([]) failEncode(encodeError) // The save reports the error it earned, unchanged, to its own caller. await expect(save).rejects.toBe(encodeError) // The cancellation completed: it was never told the session was already handled. await rollback // The rollback restored the pre-edit bytes, and they are all the writer ever saw. expect(diskWriteBytes).toEqual([`original`]) // The failed save handed the session over rather than handling it with its discard // cleanup - which is what let the rollback above be the last writer. expect(diffViewProvider[`rejectedSaveCleanupHandled`]).toBe(false) } finally { if (encodeImpl) { vi.mocked(vscode.workspace.encode).mockImplementation(encodeImpl) } else { vi.mocked(vscode.workspace.encode).mockReset() } vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } }) it("a single revertChanges waits for the save it cancelled and that save publishes nothing", async () => { // The other half of the window: ONE cancellation, no second revertChanges to join an // already-owns-the-session pass. A cancellation that lands while the save is still encoding // must make the rollback wait for that save, because a save that resumed underneath the // cancellation would otherwise publish the cancelled edit on top of the restore. The // revert's teardown tail is held open so the assertions below run while the rollback is // still the pending half of the session. const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) // The tail revertChanges owes after its cleanup: held here so the pass stays owned while // the writer sequence is read. let releaseTail: () => void = () => {} const tailHeld = new Promise((resolve) => { releaseTail = resolve }) diffViewProvider["restorePreviewTabs"] = vi.fn().mockImplementation(async () => { await tailHeld }) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) const diskWriteBytes: string[] = [] // The disk writer is the witness for who last touched the target file. The recorder is // named here so the cleanup below can prove with implementation identity that this // recorder is gone afterwards: the clearAllMocks in this file beforeEach only clears // call history, never implementations. const writerRecorder = async (publishTarget: string, content: string | Uint8Array): Promise => { diskWriteBytes.push(typeof content === "string" ? content : Buffer.from(content).toString("utf8")) } vi.mocked(safeWriteText).mockImplementation(writerRecorder) const encodeImpl = vi.mocked(vscode.workspace.encode).getMockImplementation() let releaseEncode: () => void = () => {} const encodeHeld = new Promise((resolve) => { releaseEncode = resolve }) let encodeEntered = false vi.mocked(vscode.workspace.encode).mockImplementation(async (content, options) => { if (content === "content") { encodeEntered = true await encodeHeld } else if (encodeImpl) { return encodeImpl(content, options) } return Buffer.from(content) }) type SaveResult = Awaited> let result: SaveResult | undefined let cancellation: Promise | undefined let save: Promise | undefined // Everything downstream runs under these watchdog budgets instead of the harness // timeout. The reason is the cancellation itself: if the save answers the cancellation // without releasing the waiter that settle exists for, this cancellation never // settles, an unbounded await here never reaches the finally, and the timeout that // would fail the test does not run the finally of a hung await either - the codec and // writer implementations installed above would then leak into every later test in // this file, because the beforeEach clearAllMocks only clears call history, never // implementations. These budgets sit far above the settle latencies the settle clock // records on the healthy pass, so they are places to fail fast by name, not // thresholds the flow sits near. const handleBudgetMs = 4000 const drainBudgetMs = 1000 // Each flag is set as its gate opens, so every settle and every deadline says which // side of the release it was sampled on: inside the window, or after this release. let encodeGateReleased = false let tailGateReleased = false // The stage probe is what tells the two stalls this window has to keep apart at a // deadline: with no bytes on disk while the claim and the registration are already // cleared, the save answered but the rollback is still waiting for its write to be // released (stalled before the write); with bytes already carrying the restore, the // rollback wrote and the cancellation is stuck behind the teardown tail (stalled // after the write). It also names which gates had opened when the deadline fired. const stageProbe = () => { const stalledSide = diskWriteBytes.length === 0 ? "the rollback has posted no restore yet - it is still waiting for the save it cancelled to release the write" : "the restore is already posted - the cancellation is stuck behind the teardown tail" return ( `bytes=${JSON.stringify(diskWriteBytes)} - ${stalledSide} ` + `claim=${String(diffViewProvider["teardownCancellationRequested"])} ` + `registered=${String(diffViewProvider["guardedSaveInFlight"] !== undefined)} ` + `cleanupInFlight=${String(diffViewProvider["rejectedSaveCleanupInFlight"] !== undefined)} ` + `handled=${String(diffViewProvider["rejectedSaveCleanupHandled"])} ` + `passes=${String(diffViewProvider["teardownPasses"])} ` + `gatesOpened=${String(encodeGateReleased)}:${String(tailGateReleased)}` ) } type HandleOutcome = | { status: "settled"; value: T; ms: number } | { status: "rejected"; error: unknown; ms: number } | { status: "pending"; ms: number } const handleWithinBudget = async (handle: Promise, budgetMs: number): Promise> => { const startedAtMs = Date.now() const elapsed = () => Date.now() - startedAtMs let timer: ReturnType | undefined try { return await Promise.race([ handle.then( (value: T) => ({ status: "settled" as const, value, ms: elapsed() }), (error: unknown) => ({ status: "rejected" as const, error, ms: elapsed() }), ), new Promise>((resolve) => { timer = setTimeout(() => resolve({ status: "pending", ms: elapsed() }), budgetMs) }), ]) } finally { if (timer !== undefined) { clearTimeout(timer) } } } // Settle latency of each bounded wait in ms, counted from the moment that wait began; // -1 means the wait never observed a settle at all. These are the sampling clocks. const settleClock = { saveMs: -1, cancellationMs: -1 } // What the cleanup proves about the doubles themselves rather than any call counter: // the codec double must carry the exact implementation object captured above again, // and the writer double any implementation except this test recorder. The drain // statuses record what each handle did after the restore, without gating the restore. const cleanupWitness: { encodeImplementationIsPreTestImpl?: boolean writerImplementationIsNotRecorder?: boolean saveDrain?: string cancellationDrain?: string } = {} let scenarioFailure: unknown try { save = diffViewProvider.saveChanges(false) void save.catch(() => {}) for (let attempt = 0; !encodeEntered; attempt++) { if (attempt === 5000) { throw new Error( "the save never reached its encode - the window this test holds open never opened", ) } await new Promise((resolve) => setImmediate(resolve)) } // One cancellation, inside the window. cancellation = diffViewProvider.revertChanges() void cancellation.catch(() => {}) // The window proof: the claim stands, this save is registered as in flight, and the // rollback has not written anything yet - it is waiting for the save it cancelled. expect(diffViewProvider["teardownCancellationRequested"]).toBe(true) expect(diffViewProvider["guardedSaveInFlight"]).toBeDefined() expect(diskWriteBytes).toEqual([]) releaseEncode() encodeGateReleased = true // The save-side wait is sampled after the encode gate opened: the save answers the // claim on this side of the window while the rollback has posted nothing yet. The // deadline below names this handle, so a save that stops answering fails here instead // of hanging the await until the harness times the test out. const saveOutcome = await handleWithinBudget(save, handleBudgetMs) settleClock.saveMs = saveOutcome.ms if (saveOutcome.status === "pending") { throw new Error( `this save never answered even ${handleBudgetMs} ms after the encode gate opened - stage probe: ${stageProbe()}`, ) } if (saveOutcome.status === "rejected") { throw saveOutcome.error } result = saveOutcome.value expect(result).toEqual({ newProblemsMessage: undefined, userEdits: undefined, finalContent: undefined, }) // The load-bearing one: the cancelled proposal never reached the writer. The save own // report reads the same either way, so the bytes are the verdict. expect(diskWriteBytes).toEqual([]) // The placeholder this save was registered under is dropped once the save answers the // cancellation, so a later cancellation never waits on a settled promise. expect(diffViewProvider["guardedSaveInFlight"]).toBeUndefined() expect(diffViewProvider["teardownCancellationRequested"]).toBe(false) releaseTail() tailGateReleased = true // The cancellation-side wait is sampled after the rollback's own teardown tail was // released. Its deadline reads the stage probe from this spot, and one reading // there tells the two stalls apart: empty bytes with the claim and the registration // already cleared mean the rollback is still waiting on the write that was never // released for it, while bytes carrying the restore mean the rollback wrote and the // cancellation is stuck behind the teardown tail instead. const cancellationOutcome = await handleWithinBudget(cancellation, handleBudgetMs) settleClock.cancellationMs = cancellationOutcome.ms if (cancellationOutcome.status === "pending") { throw new Error( `this cancellation never settled even ${handleBudgetMs} ms after the tail gate opened - stage probe: ${stageProbe()}`, ) } if (cancellationOutcome.status === "rejected") { throw cancellationOutcome.error } // The rollback is the session's only writer. expect(diskWriteBytes).toEqual(["original"]) expect(diffViewProvider["teardownPasses"]).toBe(1) // Where the samples sat and how much headroom the budgets carry: both settles landed // after the gate each one waits behind, at latencies a multiple of the budgets // cannot approach - the budgets are places to fail fast, not thresholds the healthy // flow sits near. expect(encodeGateReleased).toBe(true) expect(tailGateReleased).toBe(true) expect(settleClock.saveMs).toBeGreaterThanOrEqual(0) expect(settleClock.saveMs).toBeLessThan(handleBudgetMs) expect(settleClock.cancellationMs).toBeGreaterThanOrEqual(0) expect(settleClock.cancellationMs).toBeLessThan(handleBudgetMs) } catch (error) { scenarioFailure = error } finally { releaseEncode() releaseTail() // The mocks come back before anything waits on a handle: a cancellation that stalls // forever must not be able to strand the codec or the writer double for the rest of // this file - the next beforeEach clearAllMocks wipes call history only, so nothing // downstream would put these implementations back. if (encodeImpl) { vi.mocked(vscode.workspace.encode).mockImplementation(encodeImpl) } else { vi.mocked(vscode.workspace.encode).mockReset() } vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) // The restore is proven by implementation identity, not by a cleared call counter: // clearAllMocks counts as a reset for counters while leaving a leaked // implementation installed, so the proof here is that the codec double carries the // exact implementation object captured above again and the writer double answers // with some implementation except this test recorder. cleanupWitness.encodeImplementationIsPreTestImpl = vi.mocked(vscode.workspace.encode).getMockImplementation() === encodeImpl cleanupWitness.writerImplementationIsNotRecorder = vi.mocked(safeWriteText).getMockImplementation() !== writerRecorder // Then, and only then, drain both handles best-effort - bounded, each rejection // observed here - so a handle that never settles cannot hold the cleanup open // either, and its status lands in the witness instead of gating it. if (save) { cleanupWitness.saveDrain = (await handleWithinBudget(save, drainBudgetMs)).status } if (cancellation) { cleanupWitness.cancellationDrain = (await handleWithinBudget(cancellation, drainBudgetMs)).status } } expect(cleanupWitness.encodeImplementationIsPreTestImpl).toBe(true) expect(cleanupWitness.writerImplementationIsNotRecorder).toBe(true) // A scenario failure surfaces only after the cleanup has proven the doubles are back, // so the failure this test is about keeps its own name while the two witness lines // above always speak first. if (scenarioFailure !== undefined) { throw scenarioFailure } }) it("a cancellation that lands during the guarded publish waits for it and keeps the rollback last", async () => { // The commit rename is the commit point: a rollback that wrote originalContent // while the rename was still pending would be overwritten by the cancelled edit. // The rollback has to wait for the publish to settle, the save has to report no // completion of its own, and the rollback's write must be the last one. let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) let publishEntered = false let publishSettled = false // The finding names this writer: the save's publish and the rollback's restore both // reach the target through it, and the buffer recorders below cannot see a disk // write at all. Record what each call was handed and what had settled when it ran. const diskWritesAtEntry: { bytes: string; publishSettledAtEntry: boolean }[] = [] vi.mocked(safeWriteText).mockImplementation(async (publishTarget, content) => { diskWritesAtEntry.push({ bytes: typeof content === "string" ? content : Buffer.from(content).toString("utf8"), publishSettledAtEntry: publishSettled, }) publishEntered = true await gate publishSettled = true }) // Records whether the publish had already settled at each rollback write, so // the ordering assertion is about the writes themselves, not call counts. const rollbackWritesAfterPublishSettled: boolean[] = [] const closeAllDiffViews = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeAllDiffViews"] = closeAllDiffViews diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = vi.fn().mockResolvedValue(undefined) const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockImplementation(() => { rollbackWritesAfterPublishSettled.push(publishSettled) return Promise.resolve(true) }) const documentSave = vi.fn().mockImplementation(() => { rollbackWritesAfterPublishSettled.push(publishSettled) return Promise.resolve(undefined) }) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: documentSave, }), }) const save = diffViewProvider.saveChanges(false) // A rejection before the phases below settle must not leak as an unhandled rejection while the // poll below is still spinning. void save.catch(() => {}) try { for (let attempt = 0; !publishEntered; attempt++) { if (attempt === 5000) { throw new Error( "the guarded publish never entered its write - the phase this test holds open did not run", ) } await new Promise((resolve) => setImmediate(resolve)) } const revert = diffViewProvider.revertChanges() await new Promise((resolve) => setImmediate(resolve)) // The rollback has not touched the document: the publish still owns the bytes. expect(applyEdit).not.toHaveBeenCalled() release() const [result] = await Promise.all([save, revert]) // The rollback's document write happened after the publish settled; the // disk publish went through the compare-and-swap (not the buffer save), so // the final bytes on disk are the rollback's originalContent, not the // cancelled edit, and the buffer was reconciled by reverting onto them. expect(rollbackWritesAfterPublishSettled).toEqual([true]) // Sampled at the writer that actually carries bytes to the target, not at the // buffers: the save's publish entered first (that is the write this test holds // open), and the rollback's restore entered only after it had settled, carrying // its own bytes - so the cancelled edit never landed on top of the rollback. expect(diskWritesAtEntry).toEqual([ { bytes: "content", publishSettledAtEntry: false }, { bytes: "original", publishSettledAtEntry: true }, ]) expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.files.revert") expect(result).toEqual({ newProblemsMessage: undefined, userEdits: undefined, finalContent: undefined, }) // One pass over the tabs: the save added no cleanup of its own. expect(closeAllDiffViews).toHaveBeenCalledTimes(1) } finally { release() vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } }) it("saveChanges() serializes its post-publish cleanup with a revertChanges() that lands during it", async () => { // The cleanup closes the same tabs a cancellation would close. Going through the shared // teardown state means the cancellation waits for the save instead of racing it. let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) let cleanupEntered = false const closeAllDiffViews = vi.fn().mockImplementation(async () => { cleanupEntered = true await gate }) diffViewProvider["closeAllDiffViews"] = closeAllDiffViews diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = vi.fn().mockResolvedValue(undefined) const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) const save = diffViewProvider.saveChanges(false) while (!cleanupEntered) { await new Promise((resolve) => setImmediate(resolve)) } const revert = diffViewProvider.revertChanges() await new Promise((resolve) => setImmediate(resolve)) // The revert has not touched the document: it is waiting for the save's cleanup. expect(applyEdit).not.toHaveBeenCalled() release() await Promise.all([save, revert]) // One pass over the tabs, and the cancellation did not repeat the document revert. expect(closeAllDiffViews).toHaveBeenCalledTimes(1) expect(applyEdit).not.toHaveBeenCalled() }) // The pass that started the teardown owns the tab work, so a waiting caller must not // restore the preview tabs twice. It still has to leave the session closed: the owning // pass here is a save's post-publish cleanup, which never resets on its own. it("revertChanges() restores no preview tabs twice but finalizes the session the owning pass left open", async () => { let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) let cleanupEntered = false const closeAllDiffViews = vi.fn().mockImplementation(async () => { cleanupEntered = true await gate }) const restorePreviewTabs = vi.fn().mockResolvedValue(undefined) const reset = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeAllDiffViews"] = closeAllDiffViews diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = restorePreviewTabs // The guard sits on the public reset(), so the stub stands in for the teardown it // guards: what has to happen exactly once is the teardown, not the call. diffViewProvider["performFinalReset"] = reset const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) const save = diffViewProvider.saveChanges(false) while (!cleanupEntered) { await new Promise((resolve) => setImmediate(resolve)) } // The revert waits for the save's pass instead of starting one of its own. const revert = diffViewProvider.revertChanges() await new Promise((resolve) => setImmediate(resolve)) release() await Promise.all([save, revert]) // The owning pass restored the preview tabs exactly once, and the waiting caller // finalized the session exactly once - the pass that ran the tabs does not reset, so // the cancellation that waited on it closes the session instead of leaving it active. expect(restorePreviewTabs).toHaveBeenCalledTimes(1) expect(reset).toHaveBeenCalledTimes(1) expect(applyEdit).not.toHaveBeenCalled() }) // The pre-merge row this covers: a cancellation or disposal that lands while the save owns // its post-publish teardown used to leave the provider mid-edit. The save's pass closes the // views and restores the tabs but never resets, the waiting revertChanges() returned without // finalizing, and Task.disposeOnce() only awaits the reversion promise - so isEditing and the // active editor survived the task that owned them. it("saveChanges() finalizes the session when a cancellation lands during its post-publish teardown", async () => { let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) let cleanupEntered = false const closeAllDiffViews = vi.fn().mockImplementation(async () => { cleanupEntered = true await gate }) const restorePreviewTabs = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeAllDiffViews"] = closeAllDiffViews diffViewProvider["closeOwnDiffView"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = restorePreviewTabs const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider.isEditing = true diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) const listener = { dispose: vi.fn() } diffViewProvider["activeEditorListener"] = listener diffViewProvider["deferredScrollTimer"] = setTimeout(() => {}, 10_000) const save = diffViewProvider.saveChanges(false) while (!cleanupEntered) { await new Promise((resolve) => setImmediate(resolve)) } // Task.disposeOnce() reaches revertChanges() while the save's pass owns the session. const revert = diffViewProvider.revertChanges() await new Promise((resolve) => setImmediate(resolve)) release() const [saveResult] = await Promise.all([save, revert]) // The session is closed: no edit flag, no retained editor, listeners and timer gone. expect(diffViewProvider.isEditing).toBe(false) expect(diffViewProvider["activeDiffEditor"]).toBeUndefined() expect(listener.dispose).toHaveBeenCalledTimes(1) expect(diffViewProvider["activeEditorListener"]).toBeUndefined() expect(diffViewProvider["deferredScrollTimer"]).toBeUndefined() // One pass over the tabs and buffers: the waiting cancellation repeated neither the // document revert nor the preview-tab restoration. expect(applyEdit).not.toHaveBeenCalled() expect(closeAllDiffViews).toHaveBeenCalledTimes(1) expect(restorePreviewTabs).toHaveBeenCalledTimes(1) // A session a cancellation is closing reports no completed save, so no caller can present // diagnostics or user-edit output for provider state that is already gone. expect(saveResult).toEqual({ newProblemsMessage: undefined, userEdits: undefined, finalContent: undefined, }) }) // The same gap on the other teardown owner: a rejected publish's discard cleanup never resets // (the tool caller's error handling owns that), so a cancellation that only waited for it left // the session mid-edit with nobody finalizing it. it("a cancellation that waits for a rejected save's discard cleanup still finalizes the session", async () => { let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) let cleanupEntered = false const closeOwnDiffView = vi.fn().mockImplementation(async () => { cleanupEntered = true await gate }) diffViewProvider["closeOwnDiffView"] = closeOwnDiffView diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = vi.fn().mockResolvedValue(undefined) const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider.isEditing = true diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) // Restore the publish mock afterwards: a queued rejection would fail every later save. vi.mocked(safeWriteText).mockRejectedValue(new Error("guard rejected for test")) type SaveResult = Awaited> let settled: PromiseSettledResult[] | undefined try { const save: Promise = diffViewProvider.saveChanges(false) while (!cleanupEntered) { await new Promise((resolve) => setImmediate(resolve)) } const revert = diffViewProvider.revertChanges() await new Promise((resolve) => setImmediate(resolve)) release() settled = await Promise.allSettled([save, revert]) } finally { vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } // The guard verdict still surfaces... expect(settled?.[0].status).toBe("rejected") // ...and the session that cancellation was waiting on is finalized. expect(diffViewProvider.isEditing).toBe(false) expect(diffViewProvider["activeDiffEditor"]).toBeUndefined() // The waiting cancellation did not repeat the document revert. expect(applyEdit).not.toHaveBeenCalled() }) // A rejected publish closes its own diff view and rethrows, so the preview tabs the diff // evicted are restored by that pass - and only by that pass. it("saveChanges() restores preview tabs when a rejected publish tears the session down", async () => { const restorePreviewTabs = vi.fn().mockResolvedValue(undefined) const closeOwnDiffView = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = restorePreviewTabs diffViewProvider["closeOwnDiffView"] = closeOwnDiffView diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) // The publish is rejected, so the discard-only cleanup runs and the guard verdict is // rethrown. Restore the publish mock afterwards: a queued rejection would fail every // later save in this file. vi.mocked(safeWriteText).mockRejectedValue(new Error("guard rejected for test")) try { await expect(diffViewProvider.saveChanges(false)).rejects.toThrow("guard rejected for test") } finally { vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } expect(closeOwnDiffView).toHaveBeenCalledTimes(1) expect(restorePreviewTabs).toHaveBeenCalledTimes(1) }) // The rejected save's discard cleanup restores the tabs once, and it never resets - the // tool caller's error handling owns that reset. A cancellation that only waited for that // pass still has to leave the session closed, so it performs the finalization. it("saveChanges() restores preview tabs once and the waiting revert finalizes the session it left open", async () => { let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) let cleanupEntered = false const closeOwnDiffView = vi.fn().mockImplementation(async () => { cleanupEntered = true await gate }) const restorePreviewTabs = vi.fn().mockResolvedValue(undefined) const reset = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeOwnDiffView"] = closeOwnDiffView diffViewProvider["restorePreviewTabs"] = restorePreviewTabs // The guard sits on the public reset(), so the stub stands in for the teardown it // guards: what has to happen exactly once is the teardown, not the call. diffViewProvider["performFinalReset"] = reset diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) vi.mocked(safeWriteText).mockRejectedValue(new Error("guard rejected for test")) let save: Promise = Promise.resolve() try { save = diffViewProvider.saveChanges(false) while (!cleanupEntered) { await new Promise((resolve) => setImmediate(resolve)) } // The revert joins the rejected save's pass instead of starting its own. const revert = diffViewProvider.revertChanges() await new Promise((resolve) => setImmediate(resolve)) release() await expect(save).rejects.toThrow("guard rejected for test") await revert } finally { vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } expect(restorePreviewTabs).toHaveBeenCalledTimes(1) expect(reset).toHaveBeenCalledTimes(1) }) // The row: the rejected save's pass ended at closeOwnDiffView(), and the preview tabs were // restored after the pass was over. A cancellation that landed in that window started a // second teardown pass over a session the first pass had already closed, and restored the // preview tabs a second time. The pass now owns the session through preview restoration. it("saveChanges() keeps the teardown pass occupied while it restores the preview tabs of a rejected save", async () => { let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) let restoreEntered = false const restorePreviewTabs = vi.fn().mockImplementation(async () => { restoreEntered = true await gate }) const closeOwnDiffView = vi.fn().mockResolvedValue(undefined) const reset = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = restorePreviewTabs diffViewProvider["closeOwnDiffView"] = closeOwnDiffView // The guard sits on the public reset(), so the stub stands in for the teardown it // guards: what has to happen exactly once is the teardown, not the call. diffViewProvider["performFinalReset"] = reset diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) vi.mocked(safeWriteText).mockRejectedValue(new Error("guard rejected for test")) let save: Promise = Promise.resolve() try { save = diffViewProvider.saveChanges(false) while (!restoreEntered) { await new Promise((resolve) => setImmediate(resolve)) } // The cancellation arrives while preview restoration is still running - the // window in which the pass used to have already ended. const revert = diffViewProvider.revertChanges() await new Promise((resolve) => setImmediate(resolve)) release() await expect(save).rejects.toThrow("guard rejected for test") await revert } finally { vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } // One pass, one preview restoration, one finalization. expect(closeOwnDiffView).toHaveBeenCalledTimes(1) expect(restorePreviewTabs).toHaveBeenCalledTimes(1) expect(reset).toHaveBeenCalledTimes(1) }) it("revertChanges() finalizes the session once when two cancellations wait on the same pass", async () => { let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) let cleanupEntered = false const closeOwnDiffView = vi.fn().mockImplementation(async () => { cleanupEntered = true await gate }) const restorePreviewTabs = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeOwnDiffView"] = closeOwnDiffView diffViewProvider["restorePreviewTabs"] = restorePreviewTabs // Scenario-local and calling through, per the review row: with a blind stub the count // below is a statement about a call into a double, not about the teardown. The spy still // counts the single pass the guard allows, and the real final reset runs underneath it, so // the state assertions after it measure the finalization the count claims to have counted. const realFinalReset = diffViewProvider["performFinalReset"] const reset = vi.fn(async () => { await realFinalReset.call(diffViewProvider) }) diffViewProvider["performFinalReset"] = reset diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) vi.mocked(safeWriteText).mockRejectedValue(new Error("guard rejected for test")) let save: Promise = Promise.resolve() try { save = diffViewProvider.saveChanges(false) while (!cleanupEntered) { await new Promise((resolve) => setImmediate(resolve)) } // Two cancellations - a tool caller and a disposal, say - both join the pass that is // already running. Neither owns it, and the owning pass never finalizes the session, // so exactly one of them may close it. const first = diffViewProvider.revertChanges() const second = diffViewProvider.revertChanges() await new Promise((resolve) => setImmediate(resolve)) release() await expect(save).rejects.toThrow("guard rejected for test") await Promise.all([first, second]) } finally { vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } expect(restorePreviewTabs).toHaveBeenCalledTimes(1) expect(reset).toHaveBeenCalledTimes(1) // The finalization the count is supposed to stand for: the final reset owns these fields. // A call into a stub that never ran them would pass the count and fail here. expect(diffViewProvider["activeDiffEditor"]).toBeUndefined() expect(diffViewProvider["originalContent"]).toBeUndefined() }) it("revertChanges() does not finalize a session a second time after the first cancellation closed it", async () => { const restorePreviewTabs = vi.fn().mockResolvedValue(undefined) const reset = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeOwnDiffView"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = restorePreviewTabs // The guard sits on the public reset(), so the stub stands in for the teardown it // guards: what has to happen exactly once is the teardown, not the call. diffViewProvider["performFinalReset"] = reset diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) // Two cancellations one after the other: the first owns its pass and closes the session, // the second starts a pass of its own and must still not close the session a second time. await diffViewProvider.revertChanges() await diffViewProvider.revertChanges() expect(restorePreviewTabs).toHaveBeenCalledTimes(2) expect(reset).toHaveBeenCalledTimes(1) }) // A cancellation that lands while the owning pass is finalizing must join it. The claim used to // be released before the owner ran its own preview-tab restore and finalization, so a second // revertChanges() in that window started a SECOND rollback pass: a second guarded publish over // the same target and, for a create, a RollbackConflictError that abortStream() - which awaits // revertChanges() with no catch - turns into a skipped partial-save report. it("revertChanges() joins a teardown whose owner is still finalizing instead of rolling back twice", async () => { const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") let releaseRollback: () => void = () => {} const rollbackGate = new Promise((resolve) => { releaseRollback = resolve }) let rollbackEntered = false vi.mocked(safeWriteText).mockImplementation(async () => { rollbackEntered = true await rollbackGate }) let releaseFinalize: () => void = () => {} const finalizeGate = new Promise((resolve) => { releaseFinalize = resolve }) let finalizeEntered = false const restorePreviewTabs = vi.fn(async () => { finalizeEntered = true await finalizeGate }) // The guard sits on the public reset(), so the stub stands in for the teardown it guards: // what must happen exactly once is the finalization, not the call. const performFinalReset = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = restorePreviewTabs diffViewProvider["performFinalReset"] = performFinalReset diffViewProvider["closeOwnDiffView"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) const first = diffViewProvider.revertChanges() while (!rollbackEntered) { await new Promise((resolve) => setImmediate(resolve)) } releaseRollback() while (!finalizeEntered) { await new Promise((resolve) => setImmediate(resolve)) } // The owner sits between its rollback and its finalization: the claim is still held, so this // second cancellation must wait for the pass instead of publishing a rollback of its own. const second = diffViewProvider.revertChanges() await new Promise((resolve) => setImmediate(resolve)) expect(vi.mocked(safeWriteText)).toHaveBeenCalledTimes(1) releaseFinalize() let publishCalls = 0 try { await Promise.all([first, second]) publishCalls = vi.mocked(safeWriteText).mock.calls.length } finally { // The gated double belongs to this test only; the rest of the file expects the plain // resolving default. vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } expect(publishCalls).toBe(1) expect(restorePreviewTabs).toHaveBeenCalledTimes(1) expect(performFinalReset).toHaveBeenCalledTimes(1) }) it("two concurrent resets finalize the session exactly once", async () => { // The guard sits on the public entry point, which is the shape a cancellation and a // disposal produce: both call reset() on the same session at the same time. const disposeListener = vi.fn() const closeAllDiffViews = vi.fn().mockResolvedValue(undefined) diffViewProvider["relPath"] = undefined diffViewProvider["disposeActiveEditorListener"] = disposeListener diffViewProvider["closeAllDiffViews"] = closeAllDiffViews await Promise.all([diffViewProvider.reset(), diffViewProvider.reset()]) // Asserted on the teardown's own side effects rather than on a flag: the second caller // joined the attempt already running instead of starting a second teardown. expect(disposeListener).toHaveBeenCalledTimes(1) expect(closeAllDiffViews).toHaveBeenCalledTimes(1) }) it("revertChanges() does not finalize a session that a direct reset already closed", async () => { const realReset = diffViewProvider["reset"].bind(diffViewProvider) let resetCalls = 0 diffViewProvider["reset"] = async () => { resetCalls++ await realReset() } diffViewProvider["closeOwnDiffView"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["restorePreviewTabs"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) // A reset outside the teardown paths closes the session for everyone, so the claim has to // come from the reset itself and not only from the caller that went through the helper. await diffViewProvider["reset"]() await diffViewProvider.revertChanges() expect(resetCalls).toBe(1) }) // The other direction: the rejected save is the one that joins an existing pass. It then // runs no cleanup of its own, and the pass that started the teardown restores the tabs once. it("saveChanges() restores no preview tabs when a revert already owns the teardown", async () => { let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) let cleanupEntered = false const closeAllDiffViews = vi.fn().mockImplementation(async () => { cleanupEntered = true await gate }) const restorePreviewTabs = vi.fn().mockResolvedValue(undefined) const closeOwnDiffView = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeAllDiffViews"] = closeAllDiffViews diffViewProvider["restorePreviewTabs"] = restorePreviewTabs diffViewProvider["closeOwnDiffView"] = closeOwnDiffView // reset() closes this provider's diff tab; stub it so closeOwnDiffView counts only the // save's own cleanup pass. diffViewProvider["reset"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) const applyEdit = vi.mocked(vscode.workspace.applyEdit) applyEdit.mockResolvedValue(true) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) // The revert starts its pass first and is held inside it. const revert = diffViewProvider.revertChanges() while (!cleanupEntered) { await new Promise((resolve) => setImmediate(resolve)) } vi.mocked(safeWriteText).mockRejectedValue(new Error("guard rejected for test")) let save: Promise = Promise.resolve() try { save = diffViewProvider.saveChanges(false) await new Promise((resolve) => setImmediate(resolve)) release() await expect(save).rejects.toThrow("guard rejected for test") await revert } finally { vi.mocked(safeWriteText).mockReset() vi.mocked(safeWriteText).mockResolvedValue(undefined) } // The save's cleanup never ran standalone: it joined the owning revert pass, so it // restored no preview tabs. The owning pass' tail restores once, and its finalization // (which now settles without waiting on a session-start reservation) closes this // provider's own diff view - exactly one close, owed by the owner. expect(closeOwnDiffView).toHaveBeenCalledTimes(1) expect(restorePreviewTabs).toHaveBeenCalledTimes(1) }) // Ownership, not the counter, is what decides the post-publish flow. Every interleaving the // public API can produce is already caught by the counter check, so this drives the branch // directly: a pass is held open across the save's post-publish call, and the save must report // that it did not complete a save flow of its own. it("saveChanges() reports no completed save when another teardown owns the post-publish pass", async () => { let release: () => void = () => {} const held = new Promise((resolve) => { release = resolve }) const closeAllDiffViews = vi.fn().mockResolvedValue(undefined) const restorePreviewTabs = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeAllDiffViews"] = closeAllDiffViews diffViewProvider["restorePreviewTabs"] = restorePreviewTabs diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["editType"] = "modify" diffViewProvider["originalContent"] = "original" diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), isDirty: false, save: vi.fn().mockResolvedValue(undefined), }), }) diffViewProvider["teardownInFlight"] = held const save = diffViewProvider.saveChanges(false) await new Promise((resolve) => setImmediate(resolve)) release() const result = await save expect(result).toEqual({ newProblemsMessage: undefined, userEdits: undefined, finalContent: undefined, }) expect(closeAllDiffViews).not.toHaveBeenCalled() expect(restorePreviewTabs).not.toHaveBeenCalled() }) it("saveChanges() keeps the file open when the user touched it", async () => { const closeFileTab = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = closeFileTab diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["documentWasOpen"] = false diffViewProvider["userTouchedDocument"] = true diffViewProvider["preEditScrollLine"] = undefined diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = buildActiveDiffEditor() await diffViewProvider.saveChanges(false) expect(closeFileTab).not.toHaveBeenCalled() expect(vscode.window.showTextDocument).toHaveBeenCalled() }) it("revertChanges() closes the file tab when the file was not open and untouched", async () => { const closeFileTab = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = closeFileTab diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["documentWasOpen"] = false diffViewProvider["userTouchedDocument"] = false diffViewProvider["preEditScrollLine"] = undefined diffViewProvider.editType = "modify" diffViewProvider.originalContent = "original" diffViewProvider["activeDiffEditor"] = buildActiveDiffEditor() await diffViewProvider.revertChanges() expect(closeFileTab).toHaveBeenCalledWith(mockTargetPath) // The CAS-published rollback reconciles the buffer by reverting, which // activates the document once; the tab itself is closed by closeFileTab. expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.files.revert") }) it("revertChanges() keeps the file open when the user touched it", async () => { const closeFileTab = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = closeFileTab diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["documentWasOpen"] = false diffViewProvider["userTouchedDocument"] = true diffViewProvider["preEditScrollLine"] = undefined diffViewProvider.editType = "modify" diffViewProvider.originalContent = "original" diffViewProvider["activeDiffEditor"] = buildActiveDiffEditor() await diffViewProvider.revertChanges() expect(closeFileTab).not.toHaveBeenCalled() expect(vscode.window.showTextDocument).toHaveBeenCalled() }) it("marks userTouchedDocument when the file editor is activated during the diff", async () => { let activeCallback: ((editor: vscode.TextEditor) => void) | undefined vi.mocked(vscode.window.onDidChangeActiveTextEditor).mockImplementation((cb) => { activeCallback = cb return { dispose: vi.fn() } }) const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath) }), }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(makeTextDocument({ uri: makeUri(mockTargetPath) })), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) diffViewProvider.editType = "modify" diffViewProvider["documentWasOpen"] = false await diffViewProvider.open("mock-target-file.ts") // Simulate the user activating the plain file editor (no diff tab active). // TabGroup double provides the activeTab.input the touch-guard inspects. const activeGroup: vscode.TabGroup = { isActive: true, viewColumn: vscode.ViewColumn.One, activeTab: makeTab(makeTextTab(mockTargetPath), "mock-target-file.ts"), tabs: [], } Object.defineProperty(vscode.window.tabGroups, "activeTabGroup", { value: activeGroup, configurable: true, }) activeCallback?.(makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath) }) })) expect(diffViewProvider["userTouchedDocument"]).toBe(true) }) }) describe("userTouchedDiffEditor keep/close behavior", () => { const mockTargetPath = `${mockCwd}/mock-target-file.ts` const buildActiveDiffEditor = () => makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), positionAt: vi.fn().mockReturnValue(makePosition()), }), }) it("saveChanges() keeps the file open when the user clicked inside the diff editor", async () => { const closeFileTab = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = closeFileTab diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["documentWasOpen"] = false diffViewProvider["userTouchedDocument"] = false // The user clicked in the diff editor -- the flag is true. diffViewProvider["userTouchedDiffEditor"] = true diffViewProvider["preEditScrollLine"] = undefined diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = buildActiveDiffEditor() await diffViewProvider.saveChanges(false) expect(closeFileTab).not.toHaveBeenCalled() expect(vscode.window.showTextDocument).toHaveBeenCalled() }) it("saveChanges() closes the file tab when the user only scrolled (not clicked) in the diff", async () => { const closeFileTab = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = closeFileTab diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["documentWasOpen"] = false diffViewProvider["userTouchedDocument"] = false // The user only scrolled -- the flag stays false. diffViewProvider["userTouchedDiffEditor"] = false diffViewProvider["preEditScrollLine"] = undefined diffViewProvider["newContent"] = "content" diffViewProvider["activeDiffEditor"] = buildActiveDiffEditor() await diffViewProvider.saveChanges(false) expect(closeFileTab).toHaveBeenCalledWith(mockTargetPath) expect(vscode.window.showTextDocument).not.toHaveBeenCalled() }) it("open() registers onDidChangeTextEditorSelection and sets userTouchedDiffEditor on event", async () => { let selectionCallback: ((event: vscode.TextEditorSelectionChangeEvent) => void) | undefined vi.mocked(vscode.window.onDidChangeTextEditorSelection).mockImplementation((cb) => { selectionCallback = cb return { dispose: vi.fn() } }) const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/sel.ts`) }), }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(makeTextDocument({ uri: makeUri(`${mockCwd}/sel.ts`) })), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) diffViewProvider.editType = "modify" await diffViewProvider.open("sel.ts") expect(diffViewProvider["userTouchedDiffEditor"]).toBe(false) // Simulate a Mouse selection-change event on the captured diff editor. const activeDiffEditor = diffViewProvider["activeDiffEditor"] if (!activeDiffEditor) { throw new Error("activeDiffEditor was not set") } selectionCallback?.({ textEditor: activeDiffEditor, selections: [], kind: vscode.TextEditorSelectionChangeKind.Mouse, }) expect(diffViewProvider["userTouchedDiffEditor"]).toBe(true) }) it("open() does NOT set userTouchedDiffEditor for programmatic selection changes (kind=Command or undefined)", async () => { let selectionCallback: ((event: vscode.TextEditorSelectionChangeEvent) => void) | undefined vi.mocked(vscode.window.onDidChangeTextEditorSelection).mockImplementation((cb) => { selectionCallback = cb return { dispose: vi.fn() } }) const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/prog.ts`) }), }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(makeTextDocument({ uri: makeUri(`${mockCwd}/prog.ts`) })), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) diffViewProvider.editType = "modify" await diffViewProvider.open("prog.ts") const activeDiffEditor = diffViewProvider["activeDiffEditor"] if (!activeDiffEditor) { throw new Error("activeDiffEditor was not set") } // Programmatic change via editor.selection= (kind undefined) -- e.g. revealDiffLine selectionCallback?.({ textEditor: activeDiffEditor, selections: [], kind: undefined }) expect(diffViewProvider["userTouchedDiffEditor"]).toBe(false) // Programmatic change via command (kind=Command) selectionCallback?.({ textEditor: activeDiffEditor, selections: [], kind: vscode.TextEditorSelectionChangeKind.Command, }) expect(diffViewProvider["userTouchedDiffEditor"]).toBe(false) }) it("open() sets userTouchedDiffEditor when event comes from a fresh editor instance wrapping the same document (stale ref fix)", async () => { let selectionCallback: ((event: vscode.TextEditorSelectionChangeEvent) => void) | undefined vi.mocked(vscode.window.onDidChangeTextEditorSelection).mockImplementation((cb) => { selectionCallback = cb return { dispose: vi.fn() } }) const sharedDocument = makeTextDocument({ uri: makeUri(`${mockCwd}/stale.ts`) }) const originalEditor = makeTextEditor({ document: sharedDocument }) vi.mocked(vscode.window).visibleTextEditors = [originalEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(originalEditor) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(makeTextDocument({ uri: makeUri(`${mockCwd}/stale.ts`) })), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) diffViewProvider.editType = "modify" await diffViewProvider.open("stale.ts") // Simulate VS Code giving us a NEW editor object that wraps the same // document -- this is the real-world stale reference scenario. const freshEditorSameDoc = makeTextEditor({ document: sharedDocument }) selectionCallback?.({ textEditor: freshEditorSameDoc, selections: [], kind: vscode.TextEditorSelectionChangeKind.Mouse, }) expect(diffViewProvider["userTouchedDiffEditor"]).toBe(true) }) it("open() ignores selection events on editors other than the diff editor", async () => { let selectionCallback: ((event: vscode.TextEditorSelectionChangeEvent) => void) | undefined vi.mocked(vscode.window.onDidChangeTextEditorSelection).mockImplementation((cb) => { selectionCallback = cb return { dispose: vi.fn() } }) const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/other.ts`) }), }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(makeTextDocument({ uri: makeUri(`${mockCwd}/other.ts`) })), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) diffViewProvider.editType = "modify" await diffViewProvider.open("other.ts") // Fire the event with a completely different editor object. const unrelatedEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri("/some/other/file.ts") }), }) selectionCallback?.({ textEditor: unrelatedEditor, selections: [], kind: undefined }) expect(diffViewProvider["userTouchedDiffEditor"]).toBe(false) }) it("revertChanges() closes the file tab even when userTouchedDiffEditor is true (deny ignores diff-touch)", async () => { // Asymmetry guard: only saveChanges() passes userTouchedDiffEditor through to // keepOrCloseEditedFile(). revertChanges() (deny) must NOT honor a diff-pane // touch -- a denied edit on a not-previously-open, document-untouched file // should still close the transient tab. This protects the documented intent // from accidental regression. const closeFileTab = vi.fn().mockResolvedValue(undefined) vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = closeFileTab // The CAS rollback needs both sides of the version comparison: this session // left "v1" (the file-wide observation) and the disk reports evidence. vi.mocked(fs.stat).mockResolvedValue({ isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats) diffViewProvider["lastWrittenToken"] = "v1" diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["documentWasOpen"] = false diffViewProvider["userTouchedDocument"] = false // The user clicked inside the diff pane -- but this is a deny, so it must be ignored. diffViewProvider["userTouchedDiffEditor"] = true diffViewProvider["preEditScrollLine"] = undefined diffViewProvider.editType = "modify" diffViewProvider.originalContent = "original" diffViewProvider["activeDiffEditor"] = buildActiveDiffEditor() await diffViewProvider.revertChanges() expect(closeFileTab).toHaveBeenCalledWith(mockTargetPath) // The CAS-published rollback reconciles the buffer by reverting, which // activates the document once; the tab itself is closed by closeFileTab. expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.files.revert") }) it("revertChanges' tail does not deadlock when open() starts during the pass", async () => { // The tail (preview-tab restore + finalization) runs INSIDE the teardown // claim, and open() serializes with that claim. If the tail's finalization // joined the session-start reservation open() had just set, the callers // would form the cycle reset -> reservation -> open -> teardownInFlight -> // this very tail, and neither side would ever finish. vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) vi.mocked(fs.stat).mockResolvedValue({ isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } as unknown as BigIntStats) diffViewProvider["lastWrittenToken"] = "v1" diffViewProvider["relPath"] = "mock-target-file.ts" diffViewProvider["documentWasOpen"] = false diffViewProvider["userTouchedDocument"] = false diffViewProvider["userTouchedDiffEditor"] = false diffViewProvider["preEditScrollLine"] = undefined diffViewProvider.editType = "modify" diffViewProvider.originalContent = "original" diffViewProvider["activeDiffEditor"] = buildActiveDiffEditor() let release: () => void = () => {} const gate = new Promise((resolve) => { release = resolve }) const restorePreviewTabs = vi.fn().mockImplementation(async () => { await gate }) diffViewProvider["restorePreviewTabs"] = restorePreviewTabs const revert = diffViewProvider.revertChanges() while (restorePreviewTabs.mock.calls.length === 0) { await new Promise((resolve) => setImmediate(resolve)) } // A new session starts while the teardown tail is still inside the claim. const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/new.ts`), getText: vi.fn().mockReturnValue(""), lineCount: 0, }), selection: makeSelection(), edit: vi.fn().mockResolvedValue(true), revealRange: vi.fn(), }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(makeTextDocument({ uri: makeUri(`${mockCwd}/new.ts`) })), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) const open = diffViewProvider.open("new.ts") await new Promise((resolve) => setImmediate(resolve)) release() // Under the joined variant this await never settles: the tail's finalization // waits on the reservation, the reservation's open() waits on the pass, and // the pass waits on the tail. Here both promises complete. await Promise.all([revert, open]) expect(restorePreviewTabs).toHaveBeenCalledTimes(1) expect(diffViewProvider.isEditing).toBe(true) expect(diffViewProvider["relPath"]).toBe("new.ts") // The new session is finalizable: open() started clean after the old pass // finished, so its own reset closes it. await diffViewProvider.reset() expect(diffViewProvider.isEditing).toBe(false) }) }) describe("scroll position precedence in showEditedFileWithoutDisruptingFocus", () => { const setupForScroll = ( lastScrolledSource: "diff" | "targetFile" | undefined, diffScrollLine: number | undefined, targetFileScrollLine: number | undefined, preEditScrollLine: number | undefined, ) => { const mockRevealRange = vi.fn() vi.mocked(vscode.window.showTextDocument).mockResolvedValue( makeTextEditor({ revealRange: mockRevealRange }), ) const userActiveEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(`${mockCwd}/target.ts`) }), }) vscode.window.activeTextEditor = userActiveEditor diffViewProvider["lastScrolledSource"] = lastScrolledSource diffViewProvider["diffScrollLine"] = diffScrollLine diffViewProvider["targetFileScrollLine"] = targetFileScrollLine diffViewProvider["preEditScrollLine"] = preEditScrollLine diffViewProvider["documentWasPinned"] = false return mockRevealRange } it("uses diffScrollLine when lastScrolledSource is 'diff'", async () => { const mockRevealRange = setupForScroll("diff", 20, 5, 0) await diffViewProvider["showEditedFileWithoutDisruptingFocus"](`${mockCwd}/target.ts`) expect(mockRevealRange).toHaveBeenCalledWith( expect.objectContaining({ start: { line: 20, character: 0 } }), vscode.TextEditorRevealType.AtTop, ) }) it("uses targetFileScrollLine when lastScrolledSource is 'targetFile'", async () => { const mockRevealRange = setupForScroll("targetFile", 20, 8, 0) await diffViewProvider["showEditedFileWithoutDisruptingFocus"](`${mockCwd}/target.ts`) expect(mockRevealRange).toHaveBeenCalledWith( expect.objectContaining({ start: { line: 8, character: 0 } }), vscode.TextEditorRevealType.AtTop, ) }) it("falls back to preEditScrollLine when lastScrolledSource is undefined", async () => { const mockRevealRange = setupForScroll(undefined, 20, 8, 3) await diffViewProvider["showEditedFileWithoutDisruptingFocus"](`${mockCwd}/target.ts`) expect(mockRevealRange).toHaveBeenCalledWith( expect.objectContaining({ start: { line: 3, character: 0 } }), vscode.TextEditorRevealType.AtTop, ) }) it("does not call revealRange when all scroll sources are undefined", async () => { const mockRevealRange = setupForScroll(undefined, undefined, undefined, undefined) await diffViewProvider["showEditedFileWithoutDisruptingFocus"](`${mockCwd}/target.ts`) expect(mockRevealRange).not.toHaveBeenCalled() }) it("targetFile scroll overrides diff scroll regardless of their values", async () => { // lastScrolledSource=targetFile means the user scrolled there AFTER the diff, // so targetFileScrollLine must win even when diffScrollLine is higher. const mockRevealRange = setupForScroll("targetFile", 100, 2, 0) await diffViewProvider["showEditedFileWithoutDisruptingFocus"](`${mockCwd}/target.ts`) expect(mockRevealRange).toHaveBeenCalledWith( expect.objectContaining({ start: { line: 2, character: 0 } }), vscode.TextEditorRevealType.AtTop, ) }) }) describe("diffScrollListener wiring in open()", () => { const openWithScrollListener = async (relPath: string) => { let scrollCallback: ((event: vscode.TextEditorVisibleRangesChangeEvent) => void) | undefined vi.mocked(vscode.window.onDidChangeTextEditorVisibleRanges).mockImplementation((cb) => { scrollCallback = cb return { dispose: vi.fn() } }) const fsPath = `${mockCwd}/${relPath}` const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(fsPath) }), }) vi.mocked(vscode.window).visibleTextEditors = [mockEditor] vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor) vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { setTimeout(() => callback(makeTextDocument({ uri: makeUri(fsPath) })), 0) return { dispose: vi.fn() } }) vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) diffViewProvider.editType = "modify" await diffViewProvider.open(relPath) if (!scrollCallback) { throw new Error( "onDidChangeTextEditorVisibleRanges mock was not invoked during open() - scroll listener setup changed", ) } const activeDiffEditor = diffViewProvider["activeDiffEditor"] if (!activeDiffEditor) { throw new Error("activeDiffEditor was not set") } return { scrollCallback, activeDiffEditor, fsPath, } } it("records diffScrollLine and sets lastScrolledSource to 'diff' on diff editor scroll", async () => { const { scrollCallback, activeDiffEditor } = await openWithScrollListener("scroll-diff.ts") scrollCallback({ textEditor: activeDiffEditor, visibleRanges: [makeRange(42)] }) expect(diffViewProvider["diffScrollLine"]).toBe(42) expect(diffViewProvider["lastScrolledSource"]).toBe("diff") }) it("records targetFileScrollLine and sets lastScrolledSource to 'targetFile' on target file scroll", async () => { const { scrollCallback, fsPath } = await openWithScrollListener("scroll-target.ts") const targetFileEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(fsPath) }) }) scrollCallback({ textEditor: targetFileEditor, visibleRanges: [makeRange(17)] }) expect(diffViewProvider["targetFileScrollLine"]).toBe(17) expect(diffViewProvider["lastScrolledSource"]).toBe("targetFile") }) it("ignores scroll events from unrelated editors", async () => { const { scrollCallback } = await openWithScrollListener("scroll-unrelated.ts") const unrelatedEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri("/some/other/file.ts") }), }) scrollCallback({ textEditor: unrelatedEditor, visibleRanges: [makeRange(99)] }) expect(diffViewProvider["diffScrollLine"]).toBeUndefined() expect(diffViewProvider["targetFileScrollLine"]).toBeUndefined() expect(diffViewProvider["lastScrolledSource"]).toBeUndefined() }) it("lastScrolledSource reflects the most recent scroll between diff and target file", async () => { const { scrollCallback, activeDiffEditor, fsPath } = await openWithScrollListener("scroll-recency.ts") // First scroll in diff. scrollCallback({ textEditor: activeDiffEditor, visibleRanges: [makeRange(10)] }) expect(diffViewProvider["lastScrolledSource"]).toBe("diff") // Then scroll in the target file -- this must win. const targetFileEditor = makeTextEditor({ document: makeTextDocument({ uri: makeUri(fsPath) }) }) scrollCallback({ textEditor: targetFileEditor, visibleRanges: [makeRange(5)] }) expect(diffViewProvider["lastScrolledSource"]).toBe("targetFile") // Back to diff again. scrollCallback({ textEditor: activeDiffEditor, visibleRanges: [makeRange(20)] }) expect(diffViewProvider["lastScrolledSource"]).toBe("diff") }) }) describe("auto-close settings decision table", () => { const mockTargetPath = `${mockCwd}/auto-close-test.ts` const buildActiveDiffEditor = () => makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), getText: vi.fn().mockReturnValue("content"), positionAt: vi.fn().mockReturnValue(makePosition()), }), }) const setupProvider = (stateOverrides: Record = {}) => { const task = makeTaskDouble({ state: stateOverrides }) const provider = new DiffViewProvider(mockCwd, task) // S4b follow-up (#44): saveChanges publishes through the guarded write, which // resolves the path against task.cwd and consults the task's observation // registry - the preview observation + matching version token let the guarded // save proceed so these tests stay focused on the auto-close decision table. task.observationRegistry.observe(`${mockTargetPath}`, "v1") vi.mocked(computeVersionToken).mockResolvedValue("v1") provider["relPath"] = "auto-close-test.ts" provider["newContent"] = "content" provider["activeDiffEditor"] = buildActiveDiffEditor() provider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) provider["preEditScrollLine"] = undefined return provider } it("already-open file is never auto-closed regardless of settings", async () => { const provider = setupProvider({ autoCloseZooOpenedFiles: true }) const closeFileTab = vi.fn().mockResolvedValue(undefined) provider["closeFileTab"] = closeFileTab provider["documentWasOpen"] = true provider["userTouchedDocument"] = false vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) await provider.saveChanges(false) expect(closeFileTab).not.toHaveBeenCalled() }) it("transient tab is kept when autoCloseZooOpenedFiles is false", async () => { const provider = setupProvider({ autoCloseZooOpenedFiles: false }) const closeFileTab = vi.fn().mockResolvedValue(undefined) provider["closeFileTab"] = closeFileTab provider["documentWasOpen"] = false provider["userTouchedDocument"] = false provider["userTouchedDiffEditor"] = false vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) await provider.saveChanges(false) expect(closeFileTab).not.toHaveBeenCalled() expect(vscode.window.showTextDocument).toHaveBeenCalled() }) it("transient tab is kept by default when autoCloseZooOpenedFiles is unset (opt-in)", async () => { // Empty state -> autoCloseZooOpenedFiles is undefined and falls back to the // centralized default (false), so an untouched transient tab is kept. const provider = setupProvider({}) const closeFileTab = vi.fn().mockResolvedValue(undefined) provider["closeFileTab"] = closeFileTab provider["documentWasOpen"] = false provider["userTouchedDocument"] = false provider["userTouchedDiffEditor"] = false vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) await provider.saveChanges(false) expect(closeFileTab).not.toHaveBeenCalled() expect(vscode.window.showTextDocument).toHaveBeenCalled() }) it("transient tab is closed when autoCloseZooOpenedFiles is true", async () => { const provider = setupProvider({ autoCloseZooOpenedFiles: true }) const closeFileTab = vi.fn().mockResolvedValue(undefined) provider["closeFileTab"] = closeFileTab provider["documentWasOpen"] = false provider["userTouchedDocument"] = false provider["userTouchedDiffEditor"] = false await provider.saveChanges(false) expect(closeFileTab).toHaveBeenCalledWith(mockTargetPath) }) it("touched tab is kept by default (autoCloseZooOpenedFilesAfterUserEdited unset)", async () => { const provider = setupProvider({}) const closeFileTab = vi.fn().mockResolvedValue(undefined) provider["closeFileTab"] = closeFileTab provider["documentWasOpen"] = false provider["userTouchedDocument"] = true provider["userTouchedDiffEditor"] = false vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) await provider.saveChanges(false) expect(closeFileTab).not.toHaveBeenCalled() }) it("touched tab is closed when autoCloseZooOpenedFilesAfterUserEdited is true", async () => { // The after-edit override only closes when the base auto-close is also // enabled, so set both (the base default is now opt-in/false). const provider = setupProvider({ autoCloseZooOpenedFiles: true, autoCloseZooOpenedFilesAfterUserEdited: true, }) const closeFileTab = vi.fn().mockResolvedValue(undefined) provider["closeFileTab"] = closeFileTab provider["documentWasOpen"] = false provider["userTouchedDocument"] = true provider["userTouchedDiffEditor"] = false await provider.saveChanges(false) expect(closeFileTab).toHaveBeenCalledWith(mockTargetPath) }) it("touched tab is kept when autoCloseZooOpenedFilesAfterUserEdited is true but autoCloseZooOpenedFiles is false", async () => { // The after-edit override is a refinement of the base auto-close, so it // has no effect when autoCloseZooOpenedFiles is disabled. const provider = setupProvider({ autoCloseZooOpenedFiles: false, autoCloseZooOpenedFilesAfterUserEdited: true, }) const closeFileTab = vi.fn().mockResolvedValue(undefined) provider["closeFileTab"] = closeFileTab provider["documentWasOpen"] = false provider["userTouchedDocument"] = true provider["userTouchedDiffEditor"] = false vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) await provider.saveChanges(false) expect(closeFileTab).not.toHaveBeenCalled() expect(vscode.window.showTextDocument).toHaveBeenCalled() }) it("new file tab is closed when autoCloseZooOpenedNewFiles is true (accept path)", async () => { const provider = setupProvider({ autoCloseZooOpenedNewFiles: true }) const closeFileTab = vi.fn().mockResolvedValue(undefined) provider["closeFileTab"] = closeFileTab provider["documentWasOpen"] = false provider["userTouchedDocument"] = false provider["userTouchedDiffEditor"] = false provider.editType = "create" await provider.saveChanges(false) expect(closeFileTab).toHaveBeenCalledWith(mockTargetPath) }) it("new file tab follows transient-tab rule when autoCloseZooOpenedNewFiles is false and autoCloseZooOpenedFiles is also false", async () => { // autoCloseZooOpenedNewFiles=false means the new-file fast-path is skipped; // the file then falls through to the normal transient-tab rule. // With autoCloseZooOpenedFiles=false the tab should be kept. const provider = setupProvider({ autoCloseZooOpenedNewFiles: false, autoCloseZooOpenedFiles: false, }) const closeFileTab = vi.fn().mockResolvedValue(undefined) provider["closeFileTab"] = closeFileTab provider["documentWasOpen"] = false provider["userTouchedDocument"] = false provider["userTouchedDiffEditor"] = false provider.editType = "create" vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) await provider.saveChanges(false) expect(closeFileTab).not.toHaveBeenCalled() expect(vscode.window.showTextDocument).toHaveBeenCalled() }) it("defaults keep the transient tab open when all settings are unset", async () => { // No auto-close settings in state: auto-closing is opt-in, so an // untouched transient tab is kept and re-shown (long-standing behavior). const provider = setupProvider({}) const closeFileTab = vi.fn().mockResolvedValue(undefined) provider["closeFileTab"] = closeFileTab provider["documentWasOpen"] = false provider["userTouchedDocument"] = false provider["userTouchedDiffEditor"] = false vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) await provider.saveChanges(false) expect(closeFileTab).not.toHaveBeenCalled() expect(vscode.window.showTextDocument).toHaveBeenCalled() }) }) })