Skip to content

Commit 9c54765

Browse files
author
easonLiangWorldedtech
committed
fix(editor): fail closed when a rollback restore or save is refused
The pre-merge table still reported the Persistence Integrity error at the previous head. The last round fixed one call site - the new-file rollback - but the defect class has a second call site: the existing-file branch of revertChanges() built its own WorkspaceEdit, discarded the boolean result of workspace.applyEdit(), and saved unconditionally, so a refused restore wrote unapproved streamed content into an existing file. Fixing one call site is not fixing the defect class. The branch now runs through the same callee-owned contract as the new-file rollback instead of adding a third inline copy of the check: restorePreStreamBuffer() throws when the editor refuses the restore, so the save that follows cannot run, and saveBufferClean() now treats a save that did not happen as a failure rather than a success. Both methods accept the document explicitly, because this branch reached it through activeDiffEditor; resolving it again by path could pick a different buffer or none, and none would skip the restore in silence. One test leaves the path lookup empty on purpose so that assumption is pinned rather than assumed. Same-class call sites in the same file that this change deliberately does not sweep, registered here rather than changed: the save in showEditedFileWithoutDisruptingFocus, the three applyEdit calls in saveChanges and its append path, the save in saveChanges, and the save in keepOrCloseEditedFile. None is on the rollback path this unit changed; each needs its own row or issue. Nine test fixtures mocked TextDocument.save() as resolving undefined; the API resolves a boolean, so they now resolve true - the new failure check would otherwise be reading a fixture inaccuracy. Verified: integrations/editor 95 passed (three new tests: real restore-and-save for an existing file, no save on a refused restore, failure on a save that did not happen), core/tools 669, core/task 829; eslint . --ext=ts --max-warnings=0 exit 0 with no suppression count increase; tsc --noEmit 0 errors; prettier --check . reports 0 offenders in a worktree checked out with core.autocrlf=false. Negative controls, each restored byte-for-byte: dropping the refused-restore check turns exactly the two refused-restore tests red (the contract now guards both branches); dropping the failed-save check turns exactly its own test red; resolving the existing-file document by path again turns three tests red, which is the evidence that passing the document explicitly is load-bearing.
1 parent e41ebe0 commit 9c54765

2 files changed

Lines changed: 153 additions & 36 deletions

File tree

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 40 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -599,21 +599,20 @@ export class DiffViewProvider {
599599
return
600600
}
601601

602-
// Revert document.
603-
const edit = new vscode.WorkspaceEdit()
604-
605-
const fullRange = new vscode.Range(
606-
updatedDocument.positionAt(0),
607-
updatedDocument.positionAt(updatedDocument.getText().length),
608-
)
609-
610-
edit.replace(updatedDocument.uri, fullRange, this.stripAllBOMs(this.originalContent ?? ""))
611-
612-
// Apply the edit and save, since contents shouldn't have changed
613-
// this won't show in local history unless of course the user made
602+
// Revert the document through the same contract the new-file rollback uses, so a
603+
// refused restore cannot be followed by a save here either. The document is passed
604+
// explicitly: this branch reached it through activeDiffEditor, and resolving it again
605+
// by path could silently pick a different buffer - or none, which would skip the
606+
// restore entirely.
607+
//
608+
// Applying and saving the restore does not show in local history unless the user made
614609
// changes and saved during the edit.
615-
await vscode.workspace.applyEdit(edit)
616-
await updatedDocument.save()
610+
await this.restorePreStreamBuffer(
611+
absolutePath,
612+
updatedDocument,
613+
this.stripAllBOMs(this.originalContent ?? ""),
614+
)
615+
await this.saveBufferClean(absolutePath, updatedDocument)
617616

618617
await this.closeAllDiffViews()
619618

@@ -967,16 +966,22 @@ export class DiffViewProvider {
967966
* content still one save from disk. Returning quietly would be worse than returning false:
968967
* it would swallow the failure.
969968
*/
970-
private async restorePreStreamBuffer(absolutePath: string): Promise<void> {
971-
const document = vscode.workspace.textDocuments.find(
972-
(document) => document.uri.scheme === "file" && arePathsEqual(document.uri.fsPath, absolutePath),
973-
)
974-
if (!document) {
969+
private async restorePreStreamBuffer(
970+
absolutePath: string,
971+
document?: vscode.TextDocument,
972+
content?: string,
973+
): Promise<void> {
974+
const target =
975+
document ??
976+
vscode.workspace.textDocuments.find(
977+
(document) => document.uri.scheme === "file" && arePathsEqual(document.uri.fsPath, absolutePath),
978+
)
979+
if (!target) {
975980
return
976981
}
977982
const edit = new vscode.WorkspaceEdit()
978-
const range = new vscode.Range(document.positionAt(0), document.positionAt(document.getText().length))
979-
edit.replace(document.uri, range, this.originalContent ?? "")
983+
const range = new vscode.Range(target.positionAt(0), target.positionAt(target.getText().length))
984+
edit.replace(target.uri, range, content ?? this.originalContent ?? "")
980985
const restored = await vscode.workspace.applyEdit(edit)
981986
if (!restored) {
982987
throw new Error(
@@ -995,12 +1000,20 @@ export class DiffViewProvider {
9951000
* buffer whose restore failed still holds the unapproved content this rollback discards and
9961001
* must never be saved.
9971002
*/
998-
private async saveBufferClean(absolutePath: string): Promise<void> {
999-
const document = vscode.workspace.textDocuments.find(
1000-
(document) => document.uri.scheme === "file" && arePathsEqual(document.uri.fsPath, absolutePath),
1001-
)
1002-
if (document?.isDirty) {
1003-
await document.save()
1003+
private async saveBufferClean(absolutePath: string, document?: vscode.TextDocument): Promise<void> {
1004+
const target =
1005+
document ??
1006+
vscode.workspace.textDocuments.find(
1007+
(document) => document.uri.scheme === "file" && arePathsEqual(document.uri.fsPath, absolutePath),
1008+
)
1009+
if (!target?.isDirty) {
1010+
return
1011+
}
1012+
const saved = await target.save()
1013+
if (!saved) {
1014+
throw new Error(
1015+
`Rollback could not save the restored buffer for ${absolutePath}; the editor did not persist the restored content, so the buffer is still dirty and one save away from holding what this rollback undid.`,
1016+
)
10041017
}
10051018
}
10061019

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

Lines changed: 113 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ vi.mock("vscode", () => ({
4141
onDidOpenTextDocument: vi.fn(() => ({ dispose: vi.fn() })),
4242
openTextDocument: vi.fn().mockResolvedValue({
4343
isDirty: false,
44-
save: vi.fn().mockResolvedValue(undefined),
44+
save: vi.fn().mockResolvedValue(true),
4545
}),
4646
textDocuments: [],
4747
fs: {
@@ -875,7 +875,7 @@ describe("DiffViewProvider", () => {
875875
document: {
876876
getText: vi.fn().mockReturnValue("new content"),
877877
isDirty: false,
878-
save: vi.fn().mockResolvedValue(undefined),
878+
save: vi.fn().mockResolvedValue(true),
879879
},
880880
}
881881
;(diffViewProvider as any).preDiagnostics = []
@@ -1020,7 +1020,7 @@ describe("DiffViewProvider", () => {
10201020
document: {
10211021
getText: vi.fn().mockReturnValue("content"),
10221022
isDirty: false,
1023-
save: vi.fn().mockResolvedValue(undefined),
1023+
save: vi.fn().mockResolvedValue(true),
10241024
},
10251025
}
10261026

@@ -1045,7 +1045,7 @@ describe("DiffViewProvider", () => {
10451045
document: {
10461046
getText: vi.fn().mockReturnValue("content"),
10471047
isDirty: false,
1048-
save: vi.fn().mockResolvedValue(undefined),
1048+
save: vi.fn().mockResolvedValue(true),
10491049
},
10501050
}
10511051

@@ -1065,7 +1065,7 @@ describe("DiffViewProvider", () => {
10651065
uri: { fsPath: `${mockCwd}/race.ts`, scheme: "file" },
10661066
getText: vi.fn().mockReturnValue("a\nCHANGED\nc\nd\n"),
10671067
isDirty: false,
1068-
save: vi.fn().mockResolvedValue(undefined),
1068+
save: vi.fn().mockResolvedValue(true),
10691069
lineCount: 5,
10701070
lineAt: vi.fn().mockReturnValue({ text: "" }),
10711071
},
@@ -1116,7 +1116,7 @@ describe("DiffViewProvider", () => {
11161116
uri: { fsPath: `${mockCwd}/test.txt` },
11171117
getText: vi.fn().mockReturnValue("modified"),
11181118
isDirty: false,
1119-
save: vi.fn().mockResolvedValue(undefined),
1119+
save: vi.fn().mockResolvedValue(true),
11201120
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
11211121
},
11221122
}
@@ -1140,7 +1140,7 @@ describe("DiffViewProvider", () => {
11401140
uri: { fsPath: mockTargetPath, scheme: "file" },
11411141
getText: vi.fn().mockReturnValue("content"),
11421142
isDirty: false,
1143-
save: vi.fn().mockResolvedValue(undefined),
1143+
save: vi.fn().mockResolvedValue(true),
11441144
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
11451145
},
11461146
})
@@ -1439,6 +1439,110 @@ describe("DiffViewProvider", () => {
14391439
expect(fs.unlink).toHaveBeenCalledWith(mockTargetPath)
14401440
})
14411441

1442+
it("revertChanges() restores and saves an existing file through the real rollback path", async () => {
1443+
// The existing-file branch used to build its own WorkspaceEdit, discard applyEdit()'s boolean,
1444+
// and save unconditionally, so a refused restore wrote the unapproved streamed content to an
1445+
// existing file. It now runs through the same contract as the new-file branch. textDocuments is
1446+
// deliberately left empty: the branch reached this document through activeDiffEditor, and if the
1447+
// restore resolved it by path again it would find nothing and skip the restore in silence.
1448+
const editor = buildActiveDiffEditor()
1449+
editor.document.isDirty = true
1450+
editor.document.getText = vi.fn().mockReturnValue("streamed content")
1451+
const originalDocs = Object.getOwnPropertyDescriptor(vscode.workspace, "textDocuments")
1452+
Object.defineProperty(vscode.workspace, "textDocuments", { get: () => [], configurable: true })
1453+
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true)
1454+
Object.assign(diffViewProvider, {
1455+
isEditing: true,
1456+
relPath: "mock-target-file.ts",
1457+
activeDiffEditor: editor,
1458+
editType: "modify",
1459+
createdDirs: [],
1460+
originalContent: "pre-stream content",
1461+
})
1462+
diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined)
1463+
diffViewProvider["keepOrCloseEditedFile"] = vi.fn().mockResolvedValue(undefined)
1464+
1465+
try {
1466+
await diffViewProvider.revertChanges()
1467+
} finally {
1468+
if (originalDocs) {
1469+
Object.defineProperty(vscode.workspace, "textDocuments", originalDocs)
1470+
}
1471+
}
1472+
1473+
expect(vscode.workspace.applyEdit).toHaveBeenCalledTimes(1)
1474+
expect(mockWorkspaceEdit.replace).toHaveBeenCalledWith(
1475+
editor.document.uri,
1476+
expect.anything(),
1477+
"pre-stream content",
1478+
)
1479+
expect(editor.document.save).toHaveBeenCalledTimes(1)
1480+
expect(fs.unlink).not.toHaveBeenCalled()
1481+
})
1482+
1483+
it("revertChanges() does not save an existing file when the editor refuses the restore", async () => {
1484+
// The user must not be told the write was rolled back while the existing file still holds
1485+
// content they never approved: the refusal has to reach the reporting layer, and the save
1486+
// that would persist it must not run.
1487+
const editor = buildActiveDiffEditor()
1488+
editor.document.isDirty = true
1489+
editor.document.getText = vi.fn().mockReturnValue("streamed content")
1490+
const originalDocs = Object.getOwnPropertyDescriptor(vscode.workspace, "textDocuments")
1491+
Object.defineProperty(vscode.workspace, "textDocuments", { get: () => [], configurable: true })
1492+
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(false)
1493+
Object.assign(diffViewProvider, {
1494+
isEditing: true,
1495+
relPath: "mock-target-file.ts",
1496+
activeDiffEditor: editor,
1497+
editType: "modify",
1498+
createdDirs: [],
1499+
originalContent: "pre-stream content",
1500+
})
1501+
diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined)
1502+
diffViewProvider["keepOrCloseEditedFile"] = vi.fn().mockResolvedValue(undefined)
1503+
1504+
try {
1505+
await expect(diffViewProvider.revertChanges()).rejects.toThrow("could not restore the streamed buffer")
1506+
expect(editor.document.save).not.toHaveBeenCalled()
1507+
expect(diffViewProvider["keepOrCloseEditedFile"]).not.toHaveBeenCalled()
1508+
} finally {
1509+
if (originalDocs) {
1510+
Object.defineProperty(vscode.workspace, "textDocuments", originalDocs)
1511+
}
1512+
}
1513+
})
1514+
1515+
it("revertChanges() reports a save the editor did not perform for an existing file", async () => {
1516+
// A restore that applied but did not persist leaves a dirty buffer one save away from disk.
1517+
// save() resolves false in that case, and treating it as success would report a rollback that
1518+
// never completed.
1519+
const editor = buildActiveDiffEditor()
1520+
editor.document.isDirty = true
1521+
editor.document.getText = vi.fn().mockReturnValue("streamed content")
1522+
editor.document.save = vi.fn().mockResolvedValue(false)
1523+
const originalDocs = Object.getOwnPropertyDescriptor(vscode.workspace, "textDocuments")
1524+
Object.defineProperty(vscode.workspace, "textDocuments", { get: () => [], configurable: true })
1525+
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true)
1526+
Object.assign(diffViewProvider, {
1527+
isEditing: true,
1528+
relPath: "mock-target-file.ts",
1529+
activeDiffEditor: editor,
1530+
editType: "modify",
1531+
createdDirs: [],
1532+
originalContent: "pre-stream content",
1533+
})
1534+
diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined)
1535+
diffViewProvider["keepOrCloseEditedFile"] = vi.fn().mockResolvedValue(undefined)
1536+
1537+
try {
1538+
await expect(diffViewProvider.revertChanges()).rejects.toThrow("could not save the restored buffer")
1539+
expect(diffViewProvider["keepOrCloseEditedFile"]).not.toHaveBeenCalled()
1540+
} finally {
1541+
if (originalDocs) {
1542+
Object.defineProperty(vscode.workspace, "textDocuments", originalDocs)
1543+
}
1544+
}
1545+
})
14421546
it("revertChanges() reports a close the editor refused instead of deleting underneath it", async () => {
14431547
// Even a restored, saved buffer can fail to close (a vetoing editor). Swallowing that let
14441548
// the rollback delete the file underneath an open tab. The failure must propagate, and
@@ -1620,7 +1724,7 @@ describe("DiffViewProvider", () => {
16201724
uri: { fsPath: mockTargetPath, scheme: "file" },
16211725
getText: vi.fn().mockReturnValue("content"),
16221726
isDirty: false,
1623-
save: vi.fn().mockResolvedValue(undefined),
1727+
save: vi.fn().mockResolvedValue(true),
16241728
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
16251729
},
16261730
})
@@ -2109,7 +2213,7 @@ describe("DiffViewProvider", () => {
21092213
uri: { fsPath: mockTargetPath, scheme: "file" },
21102214
getText: vi.fn().mockReturnValue("content"),
21112215
isDirty: false,
2112-
save: vi.fn().mockResolvedValue(undefined),
2216+
save: vi.fn().mockResolvedValue(true),
21132217
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
21142218
},
21152219
})

0 commit comments

Comments
 (0)