Skip to content

Commit 23213ef

Browse files
author
easonLiangWorldedtech
committed
fix(editor): fail the existing-file rollback when the revert edit or save reports false
revertChanges() awaited the workspace edit and the document save of its existing-file branch and dropped both returned booleans, so a refused edit or a refused save was reported to the caller as a completed rollback. The parse-failure and partial-stream cleanup paths gate their failure report on revertDiffChangesBeforeReset(), which can only see a throw, so the user was told the teardown was complete while the document could still hold the unapproved content, or the restored original content could still be missing from disk. Validate the edit result before the save runs and the save result before any later bookkeeping, capture each result the way the pre-stream restore and the refused close already do, and keep a rejection as the cause. An applied edit plus a landed save behaves exactly as before; the new-file branch is untouched, its close check is already pinned. This is the second call site of the defect family this branch already fixed twice - the discarded document-save result in saveChanges() and the ignored restore edit in restorePreStreamBuffer() - and the shape is taken from them. The site was registered rather than fixed in the previous round; a registration does not clear a pre-merge row, only code at the head does, so it is fixed here. The regression doubles resolve an explicit false, so a double resolving undefined cannot pass by accident; a test pins each rejection as the cause and a success guard pins the unchanged applied-and-saved flow. The shared editor double now reports a save that landed, because the rollback reads the result. Negative controls: reverting the edit call site to the bare await reddens exactly the two edit tests (2/96), reverting the save call site reddens exactly the two save tests (2/96), and the pre-fix production file reddens exactly the four failure tests (4/96) with the success guard green. Restored byte for byte, hash verified. see tracking item 6095623016
1 parent 3daf338 commit 23213ef

2 files changed

Lines changed: 227 additions & 7 deletions

File tree

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -652,9 +652,42 @@ export class DiffViewProvider {
652652

653653
// Apply the edit and save, since contents shouldn't have changed
654654
// this won't show in local history unless of course the user made
655-
// changes and saved during the edit.
656-
await vscode.workspace.applyEdit(edit)
657-
await updatedDocument.save()
655+
// changes and saved during the edit. applyEdit() resolves false when the workspace
656+
// refused the edit and save() resolves false when the editor refused the save: both
657+
// booleans were dropped, so a rollback whose restore never applied or whose save never
658+
// landed was reported to the caller as a completed rollback. Capture each result the
659+
// way the pre-stream restore and the refused close do, keep a rejection as the cause,
660+
// and throw before any later bookkeeping so nothing proceeds on the assumption that
661+
// the original content came back and reached disk.
662+
let applied: boolean
663+
let applyError: Error | undefined
664+
try {
665+
applied = await vscode.workspace.applyEdit(edit)
666+
} catch (error) {
667+
applied = false
668+
applyError = error instanceof Error ? error : new Error(String(error))
669+
}
670+
if (!applied) {
671+
throw new Error(
672+
`Rollback could not restore the original content for ${absolutePath}; the workspace edit was not applied, so the document may still hold the unapproved content.`,
673+
{ cause: applyError },
674+
)
675+
}
676+
677+
let saved: boolean
678+
let saveError: Error | undefined
679+
try {
680+
saved = await updatedDocument.save()
681+
} catch (error) {
682+
saved = false
683+
saveError = error instanceof Error ? error : new Error(String(error))
684+
}
685+
if (!saved) {
686+
throw new Error(
687+
`Rollback could not save the restored document for ${absolutePath}; the original content may not be on disk.`,
688+
{ cause: saveError },
689+
)
690+
}
658691

659692
await this.closeAllDiffViews()
660693

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

Lines changed: 191 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,7 +1226,8 @@ describe("DiffViewProvider", () => {
12261226
uri: { fsPath: `${mockCwd}/test.txt` },
12271227
getText: vi.fn().mockReturnValue("modified"),
12281228
isDirty: false,
1229-
save: vi.fn().mockResolvedValue(undefined),
1229+
// The revert branch reads the save result; report a save that landed.
1230+
save: vi.fn().mockResolvedValue(true),
12301231
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
12311232
},
12321233
}
@@ -1245,12 +1246,15 @@ describe("DiffViewProvider", () => {
12451246
describe("userTouchedDocument close/keep behavior", () => {
12461247
const mockTargetPath = `${mockCwd}/mock-target-file.ts`
12471248

1249+
// Both the approved save (saveChanges) and the existing-file rollback (revertChanges) read
1250+
// the save result, so the shared double reports a save that landed; an undefined-
1251+
// resolving double would read as a refused save.
12481252
const buildActiveDiffEditor = () => ({
12491253
document: {
12501254
uri: { fsPath: mockTargetPath, scheme: "file" },
12511255
getText: vi.fn().mockReturnValue("content"),
12521256
isDirty: false,
1253-
save: vi.fn().mockResolvedValue(undefined),
1257+
save: vi.fn().mockResolvedValue(true),
12541258
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
12551259
},
12561260
})
@@ -1790,6 +1794,183 @@ describe("DiffViewProvider", () => {
17901794
expect(vscode.window.showTextDocument).toHaveBeenCalled()
17911795
})
17921796

1797+
it("revertChanges() fails the existing-file rollback when the revert edit is not applied", async () => {
1798+
// applyEdit() resolves false when the workspace refuses the edit. Dropping that boolean let
1799+
// the rollback save anyway and report a completed rollback for a restore that never
1800+
// happened: the document could still hold the unapproved content, and the caller's
1801+
// failure reporting - the whole point of the revertDiffChangesBeforeReset return value -
1802+
// was skipped. The edit result is validated before the save runs.
1803+
const editor = buildActiveDiffEditor()
1804+
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(false)
1805+
const closeAllDiffViews = vi.fn().mockResolvedValue(undefined)
1806+
const closeFileTab = vi.fn().mockResolvedValue(undefined)
1807+
diffViewProvider["closeAllDiffViews"] = closeAllDiffViews
1808+
diffViewProvider["closeFileTab"] = closeFileTab
1809+
Object.assign(diffViewProvider, {
1810+
isEditing: true,
1811+
relPath: "mock-target-file.ts",
1812+
editType: "modify",
1813+
originalContent: "original",
1814+
documentWasOpen: false,
1815+
userTouchedDocument: false,
1816+
preEditScrollLine: undefined,
1817+
activeDiffEditor: editor,
1818+
})
1819+
1820+
await expect(diffViewProvider.revertChanges()).rejects.toThrow("could not restore the original content")
1821+
1822+
// Counts, not call shapes: the save and both close paths each have exactly one legitimate
1823+
// caller on this branch, and all of them sit behind the edit check.
1824+
expect(editor.document.save).toHaveBeenCalledTimes(0)
1825+
expect(closeAllDiffViews).toHaveBeenCalledTimes(0)
1826+
expect(closeFileTab).toHaveBeenCalledTimes(0)
1827+
})
1828+
1829+
it("revertChanges() keeps the workspace rejection as the cause of a failed existing-file revert", async () => {
1830+
// A revert that fails because the workspace rejected the edit keeps its reason: the
1831+
// rollback error carries the rejection as its cause, the shape the refused close and the
1832+
// pre-stream restore use.
1833+
const editor = buildActiveDiffEditor()
1834+
const rejection = new Error("edit rejected by the workspace")
1835+
vi.mocked(vscode.workspace.applyEdit).mockRejectedValue(rejection)
1836+
const closeAllDiffViews = vi.fn().mockResolvedValue(undefined)
1837+
const closeFileTab = vi.fn().mockResolvedValue(undefined)
1838+
diffViewProvider["closeAllDiffViews"] = closeAllDiffViews
1839+
diffViewProvider["closeFileTab"] = closeFileTab
1840+
Object.assign(diffViewProvider, {
1841+
isEditing: true,
1842+
relPath: "mock-target-file.ts",
1843+
editType: "modify",
1844+
originalContent: "original",
1845+
documentWasOpen: false,
1846+
userTouchedDocument: false,
1847+
preEditScrollLine: undefined,
1848+
activeDiffEditor: editor,
1849+
})
1850+
1851+
let revertFailure: unknown
1852+
try {
1853+
await diffViewProvider.revertChanges()
1854+
} catch (error) {
1855+
revertFailure = error
1856+
}
1857+
1858+
expect(revertFailure).toBeInstanceOf(Error)
1859+
if (revertFailure instanceof Error) {
1860+
expect(revertFailure.message).toContain("could not restore the original content")
1861+
expect(revertFailure.cause).toBe(rejection)
1862+
}
1863+
expect(editor.document.save).toHaveBeenCalledTimes(0)
1864+
expect(closeAllDiffViews).toHaveBeenCalledTimes(0)
1865+
expect(closeFileTab).toHaveBeenCalledTimes(0)
1866+
})
1867+
1868+
it("revertChanges() fails the existing-file rollback when the restored document save reports false", async () => {
1869+
// The double resolves an explicit false, not undefined: a bare await would let a double
1870+
// resolving undefined pass by accident, so the reported-failure contract is pinned with a
1871+
// real false. A refused save means the restored original content never reached disk; the
1872+
// rollback must fail before the close and tab bookkeeping assume it did.
1873+
const editor = buildActiveDiffEditor()
1874+
editor.document.save = vi.fn().mockResolvedValue(false)
1875+
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true)
1876+
const closeAllDiffViews = vi.fn().mockResolvedValue(undefined)
1877+
const closeFileTab = vi.fn().mockResolvedValue(undefined)
1878+
diffViewProvider["closeAllDiffViews"] = closeAllDiffViews
1879+
diffViewProvider["closeFileTab"] = closeFileTab
1880+
Object.assign(diffViewProvider, {
1881+
isEditing: true,
1882+
relPath: "mock-target-file.ts",
1883+
editType: "modify",
1884+
originalContent: "original",
1885+
documentWasOpen: false,
1886+
userTouchedDocument: false,
1887+
preEditScrollLine: undefined,
1888+
activeDiffEditor: editor,
1889+
})
1890+
1891+
await expect(diffViewProvider.revertChanges()).rejects.toThrow("could not save the restored document")
1892+
1893+
expect(editor.document.save).toHaveBeenCalledTimes(1)
1894+
// Throw before any later bookkeeping: the diff views stay open and the tab decision
1895+
// never runs on a document whose restored content may not be on disk.
1896+
expect(closeAllDiffViews).toHaveBeenCalledTimes(0)
1897+
expect(closeFileTab).toHaveBeenCalledTimes(0)
1898+
})
1899+
1900+
it("revertChanges() keeps the save rejection as the cause of a failed existing-file revert", async () => {
1901+
// Same shape as the edit rejection: a save that rejects is a failed rollback, and the
1902+
// rejection is kept as the cause rather than ending up as a reported success.
1903+
const editor = buildActiveDiffEditor()
1904+
const rejection = new Error("save refused by the editor host")
1905+
editor.document.save = vi.fn().mockRejectedValue(rejection)
1906+
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true)
1907+
const closeAllDiffViews = vi.fn().mockResolvedValue(undefined)
1908+
const closeFileTab = vi.fn().mockResolvedValue(undefined)
1909+
diffViewProvider["closeAllDiffViews"] = closeAllDiffViews
1910+
diffViewProvider["closeFileTab"] = closeFileTab
1911+
Object.assign(diffViewProvider, {
1912+
isEditing: true,
1913+
relPath: "mock-target-file.ts",
1914+
editType: "modify",
1915+
originalContent: "original",
1916+
documentWasOpen: false,
1917+
userTouchedDocument: false,
1918+
preEditScrollLine: undefined,
1919+
activeDiffEditor: editor,
1920+
})
1921+
1922+
let revertFailure: unknown
1923+
try {
1924+
await diffViewProvider.revertChanges()
1925+
} catch (error) {
1926+
revertFailure = error
1927+
}
1928+
1929+
expect(revertFailure).toBeInstanceOf(Error)
1930+
if (revertFailure instanceof Error) {
1931+
expect(revertFailure.message).toContain("could not save the restored document")
1932+
expect(revertFailure.cause).toBe(rejection)
1933+
}
1934+
expect(closeAllDiffViews).toHaveBeenCalledTimes(0)
1935+
expect(closeFileTab).toHaveBeenCalledTimes(0)
1936+
})
1937+
1938+
it("revertChanges() reverts, saves and closes when the edit is applied and the save reports true", async () => {
1939+
// Guard for the fix itself: an applied edit plus a save that reports true keeps the
1940+
// revert-save-close flow exactly as it was; only a refused edit or refused save changes
1941+
// behaviour.
1942+
const editor = buildActiveDiffEditor()
1943+
editor.document.save = vi.fn().mockResolvedValue(true)
1944+
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true)
1945+
const closeAllDiffViews = vi.fn().mockResolvedValue(undefined)
1946+
const closeFileTab = vi.fn().mockResolvedValue(undefined)
1947+
diffViewProvider["closeAllDiffViews"] = closeAllDiffViews
1948+
diffViewProvider["closeFileTab"] = closeFileTab
1949+
Object.assign(diffViewProvider, {
1950+
isEditing: true,
1951+
relPath: "mock-target-file.ts",
1952+
editType: "modify",
1953+
originalContent: "original",
1954+
documentWasOpen: false,
1955+
userTouchedDocument: false,
1956+
preEditScrollLine: undefined,
1957+
activeDiffEditor: editor,
1958+
})
1959+
1960+
await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined()
1961+
1962+
// The revert edit carried the original content back, the save ran once, and the full
1963+
// close and tab flow proceeded exactly as before the fix. closeAllDiffViews also runs
1964+
// inside the trailing reset(), so the success evidence is "at least once, before the
1965+
// tab decision", not an exact count.
1966+
expect(mockWorkspaceEdit.replace).toHaveBeenCalledTimes(1)
1967+
expect(mockWorkspaceEdit.replace.mock.calls[0]?.[2]).toBe("original")
1968+
expect(editor.document.save).toHaveBeenCalledTimes(1)
1969+
expect(closeAllDiffViews.mock.calls.length).toBeGreaterThanOrEqual(1)
1970+
expect(closeAllDiffViews.mock.invocationCallOrder[0]).toBeLessThan(closeFileTab.mock.invocationCallOrder[0])
1971+
expect(closeFileTab).toHaveBeenCalledTimes(1)
1972+
})
1973+
17931974
it("marks userTouchedDocument when the file editor is activated during the diff", async () => {
17941975
let activeCallback: ((editor: any) => void) | undefined
17951976
vi.mocked(vscode.window.onDidChangeActiveTextEditor).mockImplementation((cb: any) => {
@@ -1832,12 +2013,15 @@ describe("DiffViewProvider", () => {
18322013
describe("userTouchedDiffEditor keep/close behavior", () => {
18332014
const mockTargetPath = `${mockCwd}/mock-target-file.ts`
18342015

2016+
// Both the approved save (saveChanges) and the existing-file rollback (revertChanges) read
2017+
// the save result, so the shared double reports a save that landed; an undefined-
2018+
// resolving double would read as a refused save.
18352019
const buildActiveDiffEditor = () => ({
18362020
document: {
18372021
uri: { fsPath: mockTargetPath, scheme: "file" },
18382022
getText: vi.fn().mockReturnValue("content"),
18392023
isDirty: false,
1840-
save: vi.fn().mockResolvedValue(undefined),
2024+
save: vi.fn().mockResolvedValue(true),
18412025
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
18422026
},
18432027
})
@@ -2240,12 +2424,15 @@ describe("DiffViewProvider", () => {
22402424
describe("auto-close settings decision table", () => {
22412425
const mockTargetPath = `${mockCwd}/auto-close-test.ts`
22422426

2427+
// Both the approved save (saveChanges) and the existing-file rollback (revertChanges) read
2428+
// the save result, so the shared double reports a save that landed; an undefined-
2429+
// resolving double would read as a refused save.
22432430
const buildActiveDiffEditor = () => ({
22442431
document: {
22452432
uri: { fsPath: mockTargetPath, scheme: "file" },
22462433
getText: vi.fn().mockReturnValue("content"),
22472434
isDirty: false,
2248-
save: vi.fn().mockResolvedValue(undefined),
2435+
save: vi.fn().mockResolvedValue(true),
22492436
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
22502437
},
22512438
})

0 commit comments

Comments
 (0)