Skip to content

Commit 7699e36

Browse files
fix(tools): close a dirty diff tab before unlinking, and stop saveChanges reading fields a reset clears
This answers the live review rows on head 2fa500a (main 73931fe is its parent; this commit adds no merge, so no new main was merged here). discardFileTab() matched only TabInputText tabs. A rollback of a new file whose plain tab was already closed therefore unlinked the file under a still open, still dirty TabInputTextDiff: TabInputTextDiff is not a TabInputText, and closeAllDiffViews() skips dirty tabs, so nothing in the rollback could reach it. Measured against this head before the change: fs.unlink called once with the target, vscode.window.tabGroups.close called zero times. The filter now also matches a composite diff tab whose modified uri is the target, so the buffer is restored and saved and the tab closed before the unlink, and a refused close keeps the file instead of deleting under the tab. saveChanges() captured editedContent up front but then read this.newContent, this.relPath and this.preDiagnostics after awaiting provider state twice, the tab closes and the diagnostics window. reset() lands inside those awaits from Task.ts (it resets the provider at the top of every new API attempt) and from this tool own teardown paths. Interleaving reset() into the state await threw Cannot read properties of undefined (reading the includes method) with document.save() already called once and the commit point already passed, so a write the user approved was reported as a failure; getNewDiagnostics then compared against the empty list reset() installs, which makes every current problem look new. Those three fields are now captured with editedContent. Same interleaving after the change: still lands mid-save, still clears the fields, and the call returns the saved content instead of throwing. Test-only rows answered in the same commit: the success path now observes writeCommitted inside closeAllDiffViews and asserts onCommit precedes it; the two real restores assert the target uri and the positionAt offsets that make the range full-buffer (content alone passes on a misdirected or partial restore, and the Range double cannot express the extent, so the assertion goes through the offsets the impl actually hands it); the editorless rollback gains the occupied-directory case (retained non-empty file inside the created dir, rmdir rejecting ENOTEMPTY, which removeCreatedDir tolerates only for ENOENT) and the stat-cannot-answer case (skip the unlink, still clean the dirs this edit created). clearTaskState() is now identity-checked like the teardown release beside it, so the guarantee does not rest on instanceId being unique per Task object. The tab double gained modified.scheme because the implementation guard reads modified.scheme; the double was the only thing that did not carry it. Gates run on this tree before commit: vitest over DiffViewProvider.spec, writeToFileTool.spec and writeToFileTool-partial-state-cleanup.spec - 176 passed, 5 skipped (181); tsc --noEmit exit 0; and the package lint script (eslint . --ext=ts --max-warnings=0 --cache ...) exit 0 with the eslint cache deleted first, because per-file eslint over an explicit file list is a quick check and is not the gate. Co-Authored-Changed-By: bseries-merge (review-row answers, controls and measurements for PR #1931).
1 parent 2fa500a commit 7699e36

3 files changed

Lines changed: 216 additions & 12 deletions

File tree

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,17 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
126126
}
127127

128128
public clearTaskState(task: Task): void {
129+
// Identity-checked, like the teardown release above: the entry is dropped only when the map
130+
// still holds THIS task's state object. The key is taskId + instanceId and instanceId is
131+
// minted by crypto.randomUUID() in the Task constructor, so a second instance of the same
132+
// history item does not inherit it - but this caller disposes the task it is clearing for,
133+
// and a clear that matched only the key could still drop an entry a live stream had just
134+
// re-created under the same taskId. Checking identity keeps that guarantee independent of
135+
// how instanceId is minted.
136+
const state = this.taskPartialStreamState.get(this.getPartialStreamFailureKey(task))
137+
if (state && state.task !== task) {
138+
return
139+
}
129140
this.resetTaskPartialState(task)
130141
}
131142

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,20 @@ export class DiffViewProvider {
388388
const absolutePath = path.resolve(this.cwd, this.relPath)
389389
const updatedDocument = this.activeDiffEditor.document
390390
const editedContent = updatedDocument.getText()
391+
// Capture the fields the continuation below reads, as editedContent is already captured. saveChanges
392+
// awaits provider state twice, the tab closes, and the diagnostics window before it
393+
// normalizes EOLs and builds the user-edits patch, and reset() can land inside any of
394+
// those awaits: Task.ts resets the provider at the top of every new API attempt, and
395+
// this tool resets it on its own teardown paths. Reading this.newContent or this.relPath
396+
// after those awaits threw a TypeError for a write that had already saved and had
397+
// already passed the commit point, and getNewDiagnostics compared against the empty
398+
// list reset() installs, so every current problem looked new. Measured: interleaving
399+
// reset() into the provider-state await throws
400+
// "Cannot read properties of undefined (reading 'includes')" at the EOL line with
401+
// document.save() already called once.
402+
const newContentForEol = this.newContent
403+
const relPathForPatch = this.relPath
404+
const preDiagnosticsForCompare = this.preDiagnostics
391405

392406
if (updatedDocument.isDirty) {
393407
const saved = await updatedDocument.save()
@@ -471,7 +485,7 @@ export class DiffViewProvider {
471485
const maxDiagnosticMessages = state?.maxDiagnosticMessages ?? 50
472486

473487
const newProblems = await diagnosticsToProblemsString(
474-
getNewDiagnostics(this.preDiagnostics, postDiagnostics),
488+
getNewDiagnostics(preDiagnosticsForCompare, postDiagnostics),
475489
[
476490
vscode.DiagnosticSeverity.Error, // only including errors since warnings can be distracting (if user wants to fix warnings they can use the @problems mention)
477491
],
@@ -486,18 +500,18 @@ export class DiffViewProvider {
486500

487501
// If the edited content has different EOL characters, we don't want to
488502
// show a diff with all the EOL differences.
489-
const newContentEOL = this.newContent.includes("\r\n") ? "\r\n" : "\n"
503+
const newContentEOL = newContentForEol.includes("\r\n") ? "\r\n" : "\n"
490504

491505
// Normalize EOL characters without trimming content
492506
const normalizedEditedContent = editedContent.replace(/\r\n|\n/g, newContentEOL)
493507

494508
// Just in case the new content has a mix of varying EOL characters.
495-
const normalizedNewContent = this.newContent.replace(/\r\n|\n/g, newContentEOL)
509+
const normalizedNewContent = newContentForEol.replace(/\r\n|\n/g, newContentEOL)
496510

497511
if (normalizedEditedContent !== normalizedNewContent) {
498512
// User made changes before approving edit.
499513
const userEdits = formatResponse.createPrettyPatch(
500-
this.relPath.toPosix(),
514+
relPathForPatch!.toPosix(),
501515
normalizedNewContent,
502516
normalizedEditedContent,
503517
)
@@ -1022,12 +1036,22 @@ export class DiffViewProvider {
10221036
private async discardFileTab(absolutePath: string): Promise<void> {
10231037
const tabs = vscode.window.tabGroups.all
10241038
.flatMap((group) => group.tabs)
1025-
.filter(
1026-
(tab) =>
1027-
tab.input instanceof vscode.TabInputText &&
1028-
tab.input.uri.scheme === "file" &&
1029-
arePathsEqual(tab.input.uri.fsPath, absolutePath),
1030-
)
1039+
.filter((tab) => {
1040+
const input = tab.input
1041+
if (input instanceof vscode.TabInputText) {
1042+
return input.uri.scheme === "file" && arePathsEqual(input.uri.fsPath, absolutePath)
1043+
}
1044+
// A composite diff tab for the same file counts too. The plain tab can be closed while
1045+
// the diff tab survives - the user closes it, or it was never opened separately -
1046+
// and TabInputTextDiff is not a TabInputText, so a text-only filter left the tab
1047+
// holding the unapproved content open while the rollback unlinked the file under it.
1048+
// closeAllDiffViews() will not take it either: it skips dirty tabs. This is the only
1049+
// place that can restore and close it before the unlink.
1050+
if (input instanceof vscode.TabInputTextDiff) {
1051+
return input.modified.scheme === "file" && arePathsEqual(input.modified.fsPath, absolutePath)
1052+
}
1053+
return false
1054+
})
10311055

10321056
for (const tab of tabs) {
10331057
// tabGroups.close()'s second argument is preserveFocus, not a force-discard flag: a

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

Lines changed: 171 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ describe("DiffViewProvider", () => {
169169
const makeDiffTabInput = (originalScheme: string, modifiedFsPath: string): vscode.TabInputTextDiff =>
170170
Object.assign(new vscode.TabInputTextDiff(makeUri(modifiedFsPath), makeUri(modifiedFsPath)), {
171171
original: { scheme: originalScheme },
172-
modified: { fsPath: modifiedFsPath },
172+
modified: makeUri(modifiedFsPath),
173173
})
174174

175175
const makeTab = (input: vscode.Tab["input"], label: string, overrides: Partial<vscode.Tab> = {}): vscode.Tab => ({
@@ -1047,7 +1047,10 @@ describe("DiffViewProvider", () => {
10471047
diffViewProvider["activeDiffEditor"] = {
10481048
document: { getText: vi.fn().mockReturnValue("new content"), isDirty: true, save },
10491049
} as unknown as vscode.TextEditor
1050-
const closeAllDiffViews = vi.fn().mockResolvedValue(undefined)
1050+
let commitSeenByCleanup: boolean | undefined
1051+
const closeAllDiffViews = vi.fn().mockImplementation(async () => {
1052+
commitSeenByCleanup = diffViewProvider["writeCommitted"]
1053+
})
10511054
diffViewProvider["closeAllDiffViews"] = closeAllDiffViews
10521055
const onCommit = vi.fn()
10531056

@@ -1056,6 +1059,11 @@ describe("DiffViewProvider", () => {
10561059
expect(save).toHaveBeenCalledTimes(1)
10571060
expect(onCommit).toHaveBeenCalledTimes(1)
10581061
expect(closeAllDiffViews).toHaveBeenCalledTimes(1)
1062+
// Ordering, not just presence: a regression that set the flag and fired the callback after
1063+
// cleanup would still satisfy the three counts above and would leave an approved write
1064+
// eligible for rollback in the window between the save and the tab close.
1065+
expect(commitSeenByCleanup).toBe(true)
1066+
expect(onCommit.mock.invocationCallOrder[0]).toBeLessThan(closeAllDiffViews.mock.invocationCallOrder[0])
10591067
expect(result.finalContent).toBe("new content")
10601068
})
10611069
})
@@ -1755,11 +1763,168 @@ describe("DiffViewProvider", () => {
17551763
// The restore edit carried the pre-stream content, and the full flow ran exactly once.
17561764
expect(mockWorkspaceEdit.replace).toHaveBeenCalledTimes(1)
17571765
expect(mockWorkspaceEdit.replace.mock.calls[0]?.[2]).toBe("pre-stream content")
1766+
// The replacement text alone does not say where the text went: a restore aimed at another
1767+
// document, or at only part of this one, passes on content alone. The uri is the target
1768+
// the rollback located through textDocuments, and the extent is whatever positionAt
1769+
// answered with 0 and the full text length - the two offsets the impl hands to Range -
1770+
// so both halves of the claim are asserted through members the doubles actually carry.
1771+
expect((mockWorkspaceEdit.replace.mock.calls[0]?.[0] as { fsPath?: string }).fsPath).toBe(mockTargetPath)
1772+
expect(editor.document.positionAt).toHaveBeenCalledWith(0)
1773+
expect(editor.document.positionAt).toHaveBeenLastCalledWith(editor.document.getText().length)
17581774
expect(editor.document.save).toHaveBeenCalledTimes(1)
17591775
expect(close).toHaveBeenCalledTimes(1)
17601776
expect(fs.unlink).toHaveBeenCalledTimes(1)
17611777
})
17621778

1779+
it("revertChanges() leaves a retained file and surfaces the occupied directory it cannot remove", async () => {
1780+
// The geometry the rollback is actually in: a non-empty file inside a directory this edit
1781+
// created. The retained file must survive, and the directory cannot go - a real rmdir on
1782+
// a non-empty directory fails with ENOTEMPTY, which removeCreatedDir tolerates only for
1783+
// ENOENT. Asserting the rejection is what stops the rollback from reporting a completed
1784+
// cleanup while a directory the user can still see is left behind.
1785+
const createdDirs = [`${mockCwd}/new-parent`, `${mockCwd}/new-parent/nested`]
1786+
Object.assign(diffViewProvider, {
1787+
isEditing: true,
1788+
relPath: "nested/mock-target-file.ts",
1789+
activeDiffEditor: undefined,
1790+
editType: "create",
1791+
createdDirs,
1792+
})
1793+
vi.mocked(fs.stat).mockResolvedValueOnce({ size: 12 } as Awaited<ReturnType<typeof fs.stat>>)
1794+
vi.mocked(fs.rmdir).mockRejectedValueOnce(
1795+
Object.assign(new Error("ENOTEMPTY: directory not empty, rmdir"), { code: "ENOTEMPTY" }),
1796+
)
1797+
1798+
await expect(diffViewProvider.revertChanges()).rejects.toThrow("ENOTEMPTY")
1799+
1800+
expect(fs.unlink).not.toHaveBeenCalledWith(`${mockCwd}/nested/mock-target-file.ts`)
1801+
expect(fs.rmdir).toHaveBeenCalledTimes(1)
1802+
expect(fs.rmdir).toHaveBeenCalledWith(createdDirs[1])
1803+
})
1804+
1805+
it("revertChanges() skips the unlink when stat cannot answer about the placeholder", async () => {
1806+
// stat is the only evidence the editorless rollback has that the path is still the empty
1807+
// placeholder this edit created. A stat that cannot answer is read as do-not-delete, and
1808+
// the directory cleanup this edit owns still runs.
1809+
const createdDirs = [`${mockCwd}/new-parent`]
1810+
Object.assign(diffViewProvider, {
1811+
isEditing: true,
1812+
relPath: "mock-target-file.ts",
1813+
activeDiffEditor: undefined,
1814+
editType: "create",
1815+
createdDirs,
1816+
})
1817+
vi.mocked(fs.stat).mockRejectedValueOnce(
1818+
Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }),
1819+
)
1820+
1821+
await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined()
1822+
1823+
expect(fs.stat).toHaveBeenCalledWith(`${mockCwd}/mock-target-file.ts`)
1824+
expect(fs.unlink).not.toHaveBeenCalledWith(`${mockCwd}/mock-target-file.ts`)
1825+
expect(fs.rmdir).toHaveBeenCalledWith(createdDirs[0])
1826+
})
1827+
1828+
it("revertChanges() restores and closes a dirty diff tab before unlinking the created file", async () => {
1829+
// The shape the text-only filter used to miss: the plain tab is gone and only the
1830+
// composite diff tab is left, holding the unapproved streamed content. TabInputTextDiff
1831+
// is not a TabInputText, and closeAllDiffViews() skips dirty tabs, so nothing used to
1832+
// close it and the unlink ran underneath it.
1833+
const editor = buildActiveDiffEditor({ isDirty: true })
1834+
const originalTabs = Object.getOwnPropertyDescriptor(vscode.window.tabGroups, "all")
1835+
const originalDocs = Object.getOwnPropertyDescriptor(vscode.workspace, "textDocuments")
1836+
const closeSpy = vi.spyOn(vscode.window.tabGroups, "close").mockResolvedValue(true)
1837+
const diffTab = {
1838+
input: makeDiffTabInput(DIFF_VIEW_URI_SCHEME, mockTargetPath),
1839+
isDirty: true,
1840+
label: "mock-target-file.ts (Changes)",
1841+
}
1842+
Object.defineProperty(vscode.window.tabGroups, "all", {
1843+
get: () => [{ tabs: [diffTab] }],
1844+
configurable: true,
1845+
})
1846+
Object.defineProperty(vscode.workspace, "textDocuments", {
1847+
get: () => [editor.document],
1848+
configurable: true,
1849+
})
1850+
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true)
1851+
Object.assign(diffViewProvider, {
1852+
isEditing: true,
1853+
relPath: "mock-target-file.ts",
1854+
activeDiffEditor: editor,
1855+
editType: "create",
1856+
createdDirs: [],
1857+
originalContent: "",
1858+
writeCommitted: false,
1859+
})
1860+
try {
1861+
await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined()
1862+
} finally {
1863+
if (originalTabs) {
1864+
Object.defineProperty(vscode.window.tabGroups, "all", originalTabs)
1865+
}
1866+
if (originalDocs) {
1867+
Object.defineProperty(vscode.workspace, "textDocuments", originalDocs)
1868+
}
1869+
}
1870+
expect(vscode.workspace.applyEdit).toHaveBeenCalledTimes(1)
1871+
expect(editor.document.save).toHaveBeenCalledTimes(1)
1872+
expect(closeSpy).toHaveBeenCalledTimes(1)
1873+
expect(fs.unlink).toHaveBeenCalledTimes(1)
1874+
expect(closeSpy.mock.invocationCallOrder[0]).toBeLessThan(
1875+
(fs.unlink as unknown as Mock).mock.invocationCallOrder[0],
1876+
)
1877+
})
1878+
1879+
it("revertChanges() keeps the created file when the dirty diff tab refuses to close", async () => {
1880+
// Fail closed: a refused close means unapproved content is still on screen, so the
1881+
// unlink must not run. Deleting the file under a tab the user has not dismissed loses
1882+
// the content this rollback exists to preserve.
1883+
const editor = buildActiveDiffEditor({ isDirty: true })
1884+
const originalTabs = Object.getOwnPropertyDescriptor(vscode.window.tabGroups, "all")
1885+
const originalDocs = Object.getOwnPropertyDescriptor(vscode.workspace, "textDocuments")
1886+
vi.spyOn(vscode.window.tabGroups, "close").mockResolvedValue(false)
1887+
const diffTab = {
1888+
input: makeDiffTabInput(DIFF_VIEW_URI_SCHEME, mockTargetPath),
1889+
isDirty: true,
1890+
label: "mock-target-file.ts (Changes)",
1891+
}
1892+
Object.defineProperty(vscode.window.tabGroups, "all", {
1893+
get: () => [{ tabs: [diffTab] }],
1894+
configurable: true,
1895+
})
1896+
Object.defineProperty(vscode.workspace, "textDocuments", {
1897+
get: () => [editor.document],
1898+
configurable: true,
1899+
})
1900+
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true)
1901+
Object.assign(diffViewProvider, {
1902+
isEditing: true,
1903+
relPath: "mock-target-file.ts",
1904+
activeDiffEditor: editor,
1905+
editType: "create",
1906+
createdDirs: [],
1907+
originalContent: "",
1908+
writeCommitted: false,
1909+
})
1910+
let failure: unknown
1911+
try {
1912+
await diffViewProvider.revertChanges()
1913+
} catch (error: unknown) {
1914+
failure = error
1915+
} finally {
1916+
if (originalTabs) {
1917+
Object.defineProperty(vscode.window.tabGroups, "all", originalTabs)
1918+
}
1919+
if (originalDocs) {
1920+
Object.defineProperty(vscode.workspace, "textDocuments", originalDocs)
1921+
}
1922+
}
1923+
expect(failure).toBeInstanceOf(Error)
1924+
expect((failure as Error).message).toContain("could not close the restored buffer")
1925+
expect(fs.unlink).not.toHaveBeenCalledWith(mockTargetPath)
1926+
})
1927+
17631928
it("revertChanges() closes the file tab when the file was not open and untouched", async () => {
17641929
const closeFileTab = vi.fn().mockResolvedValue(undefined)
17651930
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true)
@@ -1974,6 +2139,10 @@ describe("DiffViewProvider", () => {
19742139
// tab decision", not an exact count.
19752140
expect(mockWorkspaceEdit.replace).toHaveBeenCalledTimes(1)
19762141
expect(mockWorkspaceEdit.replace.mock.calls[0]?.[2]).toBe("original")
2142+
// Same reasoning as the pre-stream restore above: content is not evidence about the target.
2143+
expect((mockWorkspaceEdit.replace.mock.calls[0]?.[0] as { fsPath?: string }).fsPath).toBe(mockTargetPath)
2144+
expect(editor.document.positionAt).toHaveBeenCalledWith(0)
2145+
expect(editor.document.positionAt).toHaveBeenLastCalledWith(editor.document.getText().length)
19772146
expect(editor.document.save).toHaveBeenCalledTimes(1)
19782147
expect(closeAllDiffViews.mock.calls.length).toBeGreaterThanOrEqual(1)
19792148
expect(closeAllDiffViews.mock.invocationCallOrder[0]).toBeLessThan(closeFileTab.mock.invocationCallOrder[0])

0 commit comments

Comments
 (0)