Skip to content

Commit feeaf07

Browse files
fix(core): keep a placeholder whose content is not the one open() wrote
The abandoned cleanup unlinked placeholderPath whatever had landed in it between open() and the discard, so content the user typed into the preview, a formatter's output or a later edit could be deleted by an edit nobody had approved. open() now records the exact content it wrote at that path and the discard reads the file back before unlinking: it unlinks only while the bytes still match, treats an already-deleted placeholder as the cleanup having done its job, and otherwise keeps the file and reports it instead of removing it. The keep is reported through the channel this site already uses - the catch around this cleanup logs it and the method already rejects as a cleanup failure - so no new reporting channel is introduced here. Choosing a different one, for example a dedicated revert-failure path of the kind the review names, is a design call for a maintainer; this change uses the channel the file has. Tests: a mismatching read keeps the file, writes nothing over it and surfaces as a cleanup failure; a placeholder somebody else already deleted resolves without a report; and the pre-existing placeholder test now answers the guard's read with the empty content open() wrote. The record is cleared wherever placeholderPath is cleared, and a placeholder installed without open() having written it keeps the unconditional behaviour it always had.
1 parent af8b816 commit feeaf07

2 files changed

Lines changed: 166 additions & 6 deletions

File tree

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ export class DiffViewProvider {
4141
* unlink.
4242
*/
4343
private placeholderPath: string | undefined
44+
/**
45+
* The exact content open() wrote at placeholderPath, recorded so the abandoned cleanup can
46+
* tell its own empty placeholder from content something else put in the same path between
47+
* open() and the discard. Cleared wherever placeholderPath is cleared.
48+
*/
49+
private placeholderContent: string | undefined
4450
private documentWasOpen = false
4551
// Tracks whether the target file's tab was pinned before the diff session.
4652
// Closing the tab to open the diff drops VS Code's pin state, so we restore
@@ -144,6 +150,9 @@ export class DiffViewProvider {
144150
// the write succeeds, so a failed write does not claim ownership of a file we did
145151
// not create.
146152
this.placeholderPath = absolutePath
153+
// Record what was written, not only where: the placeholder is empty by construction, and the
154+
// abandoned cleanup below removes a file only while it still holds exactly this.
155+
this.placeholderContent = ""
147156
}
148157

149158
// If the file was already open, close it (must happen after showing the
@@ -369,6 +378,7 @@ export class DiffViewProvider {
369378
// The write below is the approved one: whatever placeholder open() created at this path
370379
// becomes real content, so it is no longer an artifact this edit may remove.
371380
this.placeholderPath = undefined
381+
this.placeholderContent = undefined
372382
const updatedDocument = this.activeDiffEditor.document
373383
const editedContent = updatedDocument.getText()
374384

@@ -582,7 +592,9 @@ export class DiffViewProvider {
582592
// Same reason for the placeholder and its recorded content: an await below may reject and
583593
// the caller then runs reset(), which drops both fields too.
584594
const placeholderPath = this.placeholderPath
595+
const placeholderContent = this.placeholderContent
585596
this.placeholderPath = undefined
597+
this.placeholderContent = undefined
586598

587599
let editorFailure: unknown
588600
// open() creates the directories and the empty placeholder BEFORE it assigns
@@ -640,13 +652,43 @@ export class DiffViewProvider {
640652
// saveDirectly() sets it for a file that was written with approval, so unlinking
641653
// absolutePath unconditionally can delete content the user approved.
642654
if (placeholderPath) {
643-
await fs.unlink(placeholderPath).catch((error: unknown) => {
644-
// open() creates the placeholder; if it is already gone there is nothing
645-
// left to remove and the discard did its job.
646-
if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {
647-
throw error
655+
// Remove the placeholder only while it still holds what open() wrote there. Content can
656+
// land in that path between open() and this discard - the user typing into the preview, a
657+
// formatter, a later edit - and unlinking it here would delete bytes nobody approved. A
658+
// placeholder with no recorded content is a path a caller installed without open() having
659+
// written it, and it keeps the unconditional behaviour it has always had.
660+
let placeholderAlreadyGone = false
661+
let placeholderStillMatches = true
662+
if (placeholderContent !== undefined) {
663+
try {
664+
placeholderStillMatches = (await fs.readFile(placeholderPath, "utf-8")) === placeholderContent
665+
} catch (error) {
666+
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
667+
placeholderAlreadyGone = true
668+
} else {
669+
throw error
670+
}
648671
}
649-
})
672+
}
673+
if (!placeholderAlreadyGone) {
674+
if (placeholderStillMatches) {
675+
await fs.unlink(placeholderPath).catch((error: unknown) => {
676+
// open() creates the placeholder; if it is already gone there is nothing
677+
// left to remove and the discard did its job.
678+
if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {
679+
throw error
680+
}
681+
})
682+
} else {
683+
// Kept on disk and reported through the catch below, which is the channel this site
684+
// already uses for a cleanup it could not finish, and surfaced to the caller as a
685+
// cleanup failure exactly the way an unlink failure is. No new reporting channel is
686+
// introduced here; the file does not have one to name.
687+
throw new Error(
688+
`Kept ${placeholderPath}: it no longer holds the empty placeholder this edit wrote.`,
689+
)
690+
}
691+
}
650692
}
651693

652694
// Remove only the directories this edit created, in reverse order.
@@ -709,6 +751,7 @@ export class DiffViewProvider {
709751
await this.closeFileTab(absolutePath)
710752
await fs.unlink(absolutePath)
711753
this.placeholderPath = undefined
754+
this.placeholderContent = undefined
712755

713756
// Remove only the directories we created, in reverse order.
714757
for (let i = this.createdDirs.length - 1; i >= 0; i--) {
@@ -1287,6 +1330,7 @@ export class DiffViewProvider {
12871330
this.originalContent = undefined
12881331
this.createdDirs = []
12891332
this.placeholderPath = undefined
1333+
this.placeholderContent = undefined
12901334
this.documentWasOpen = false
12911335
this.documentWasPinned = false
12921336
this.activeDiffEditor = undefined

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

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2195,6 +2195,118 @@ describe("DiffViewProvider", () => {
21952195
// this test installed.
21962196
Object.defineProperty(vscode.window.tabGroups, "all", { value: [], configurable: true })
21972197
})
2198+
2199+
it("keeps a placeholder that no longer holds the content open() wrote, and reports it as a cleanup failure", async () => {
2200+
// The persistence ask, at the public-method layer: open() writes an empty placeholder and
2201+
// records what it wrote; if something else puts content in that path before the discard,
2202+
// the discard leaves the file alone. This spec's fs is a double, so the content is the
2203+
// answer the double gives the guard's read - what the test pins is that a mismatch keeps
2204+
// the file, writes nothing over it, and reports through the channel this site already uses.
2205+
const relPath = "kept-placeholder.ts"
2206+
const fsPath = `${mockCwd}/${relPath}`
2207+
const mockEditor = {
2208+
document: {
2209+
uri: { fsPath, scheme: "file" },
2210+
getText: vi.fn().mockReturnValue(""),
2211+
isDirty: false,
2212+
save: vi.fn().mockResolvedValue(undefined),
2213+
lineCount: 0,
2214+
},
2215+
selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } },
2216+
edit: vi.fn().mockResolvedValue(true),
2217+
revealRange: vi.fn(),
2218+
}
2219+
// Structural double routed through unknown rather than any: it carries only the members
2220+
// open() touches, the same double shape the placeholder test below uses.
2221+
const editor = mockEditor as unknown as vscode.TextEditor
2222+
vi.mocked(vscode.window).visibleTextEditors = [editor]
2223+
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(editor)
2224+
vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => {
2225+
setTimeout(() => callback({ uri: { fsPath, scheme: "file" } } as vscode.TextDocument), 0)
2226+
return { dispose: vi.fn() }
2227+
})
2228+
vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() })
2229+
vi.mocked(vscode.window.onDidChangeTextEditorVisibleRanges).mockReturnValue({ dispose: vi.fn() })
2230+
vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([])
2231+
diffViewProvider.editType = "create"
2232+
vi.mocked(fs.readFile).mockResolvedValue("")
2233+
2234+
await diffViewProvider.open(relPath)
2235+
expect(fs.writeFile).toHaveBeenCalledWith(fsPath, "")
2236+
2237+
// Content lands in the placeholder between open() and the discard.
2238+
vi.mocked(fs.readFile).mockResolvedValue("content the user typed into the preview\n")
2239+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
2240+
2241+
await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow(
2242+
/no longer holds the empty placeholder/,
2243+
)
2244+
2245+
expect(fs.unlink).not.toHaveBeenCalledWith(fsPath)
2246+
// Nothing wrote over it: the only write to that path in this test is the one open() did.
2247+
expect(fs.writeFile).toHaveBeenCalledTimes(1)
2248+
// The kept file is reported through the console.error call this cleanup site already
2249+
// makes for a cleanup it could not finish, with the error that names it.
2250+
expect(errorSpy).toHaveBeenCalledWith(
2251+
"Error removing abandoned write_to_file artifacts:",
2252+
expect.any(Error),
2253+
)
2254+
// The edit drops its claim on the path even though the file stays: a later discard has
2255+
// nothing to remove and does not report the same kept file twice.
2256+
expect(diffViewProvider["placeholderPath"]).toBeUndefined()
2257+
expect(diffViewProvider["placeholderContent"]).toBeUndefined()
2258+
})
2259+
2260+
it("tolerates a placeholder somebody else already deleted instead of reporting a cleanup failure", async () => {
2261+
// The guard reads the file before removing it, so a placeholder that is already gone is not
2262+
// a failure: there is nothing left to remove. That is the ENOENT tolerance this site had
2263+
// before the read was added, kept on the new path rather than lost to it.
2264+
const relPath = "already-gone-placeholder.ts"
2265+
const fsPath = `${mockCwd}/${relPath}`
2266+
const mockEditor = {
2267+
document: {
2268+
uri: { fsPath, scheme: "file" },
2269+
getText: vi.fn().mockReturnValue(""),
2270+
isDirty: false,
2271+
save: vi.fn().mockResolvedValue(undefined),
2272+
lineCount: 0,
2273+
},
2274+
selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } },
2275+
edit: vi.fn().mockResolvedValue(true),
2276+
revealRange: vi.fn(),
2277+
}
2278+
// Structural double routed through unknown rather than any: only the members open() touches.
2279+
const editor = mockEditor as unknown as vscode.TextEditor
2280+
vi.mocked(vscode.window).visibleTextEditors = [editor]
2281+
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(editor)
2282+
vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => {
2283+
setTimeout(() => callback({ uri: { fsPath, scheme: "file" } } as vscode.TextDocument), 0)
2284+
return { dispose: vi.fn() }
2285+
})
2286+
vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() })
2287+
vi.mocked(vscode.window.onDidChangeTextEditorVisibleRanges).mockReturnValue({ dispose: vi.fn() })
2288+
vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([])
2289+
diffViewProvider.editType = "create"
2290+
vi.mocked(fs.readFile).mockResolvedValue("")
2291+
2292+
await diffViewProvider.open(relPath)
2293+
expect(fs.writeFile).toHaveBeenCalledWith(fsPath, "")
2294+
2295+
// Somebody else removed the file before the discard ran.
2296+
const missing: NodeJS.ErrnoException = new Error("ENOENT: no such file, already removed")
2297+
missing.code = "ENOENT"
2298+
vi.mocked(fs.readFile).mockRejectedValue(missing)
2299+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
2300+
2301+
await expect(diffViewProvider.discardUnapprovedStream()).resolves.toBeUndefined()
2302+
2303+
expect(fs.unlink).not.toHaveBeenCalledWith(fsPath)
2304+
expect(errorSpy).not.toHaveBeenCalledWith(
2305+
"Error removing abandoned write_to_file artifacts:",
2306+
expect.anything(),
2307+
)
2308+
})
2309+
21982310
it("removes the placeholder that a new-file open() wrote, driven through the public methods", async () => {
21992311
// The ownership lifecycle lives at the public-method layer, so exercise it there:
22002312
// open() writes the empty placeholder and records it, and the discard of an abandoned
@@ -2226,6 +2338,10 @@ describe("DiffViewProvider", () => {
22262338
vi.mocked(vscode.window.onDidChangeTextEditorVisibleRanges).mockReturnValue({ dispose: vi.fn() })
22272339
vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([])
22282340
diffViewProvider.editType = "create"
2341+
// The discard reads the placeholder back before unlinking it, so the double has to answer
2342+
// with the empty content open() wrote; the test above covers the mismatching answer.
2343+
vi.mocked(fs.readFile).mockResolvedValue("")
2344+
22292345
await diffViewProvider.open(relPath)
22302346

22312347
// open() created the placeholder, and this edit now owns it.

0 commit comments

Comments
 (0)