diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 3c1d33ae28..53f6f306e7 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -15,12 +15,18 @@ import { import { createDirectoriesForFile } from "../../utils/fs" import { arePathsEqual, getReadablePath } from "../../utils/path" +import { getErrorCode } from "../../utils/errorCode" import { formatResponse } from "../../core/prompts/responses" import { diagnosticsToProblemsString, getNewDiagnostics } from "../diagnostics" import { Task } from "../../core/task/Task" import { DecorationController } from "./DecorationController" +/** Narrow ENOENT test so a rollback can tolerate a file or dir that never landed. */ +function isEnoent(error: unknown): boolean { + return getErrorCode(error) === "ENOENT" +} + export const DIFF_VIEW_URI_SCHEME = "cline-diff" export const DIFF_VIEW_LABEL_CHANGES = "Original ↔ Zoo's Changes" @@ -33,6 +39,14 @@ export class DiffViewProvider { isEditing = false originalContent: string | undefined private createdDirs: string[] = [] + /** + * Absolute path of the empty placeholder open() created for a new-file edit, or undefined + * when no placeholder is outstanding. reset() does NOT clear relPath, and saveDirectly() + * sets relPath for a file that was written with approval, so relPath alone cannot tell a + * caller that a file on disk belongs to the abandoned edit. Only this field justifies an + * unlink. + */ + private placeholderPath: string | undefined private documentWasOpen = false // Tracks whether the target file's tab was pinned before the diff session. // Closing the tab to open the diff drops VS Code's pin state, so we restore @@ -132,6 +146,10 @@ export class DiffViewProvider { // Make sure the file exists before we open it. if (!fileExists) { await fs.writeFile(absolutePath, "") + // From here until the placeholder is removed, THIS edit owns that path. Set after + // the write succeeds, so a failed write does not claim ownership of a file we did + // not create. + this.placeholderPath = absolutePath } // If the file was already open, close it (must happen after showing the @@ -326,6 +344,7 @@ export class DiffViewProvider { async saveChanges( diagnosticsEnabled: boolean = true, writeDelayMs: number = DEFAULT_WRITE_DELAY_MS, + onCommit?: () => void, ): Promise<{ newProblemsMessage: string | undefined userEdits: string | undefined @@ -339,10 +358,27 @@ export class DiffViewProvider { const updatedDocument = this.activeDiffEditor.document const editedContent = updatedDocument.getText() - if (updatedDocument.isDirty) { - await updatedDocument.save() + if (updatedDocument.isDirty && !(await updatedDocument.save())) { + // save() resolving false (without throwing) means the write did not persist. Stop + // BEFORE the commit point: onCommit has not run and placeholderPath stays owned, so + // the caller still holds an uncommitted cleanup state and the teardown removes what + // open() created. Reporting this write as durable would strand an unpersisted file + // whose ownership had already been released. + throw new Error(`Saving ${absolutePath} was not confirmed; the write was not committed.`) } + // The write is irreversible from here: a clean document already matches disk, and a saved + // one has landed. Everything below (closing the diff views, tab bookkeeping, diagnostics) + // can still reject, and a caller that rolls the tool call back after this point would undo + // a write the user approved - so it is told, at the commit point rather than on return. + onCommit?.() + + // Ownership is released only once the approved write has landed. A save that rejects leaves + // the placeholder as open() created it, and the caller's teardown still has to remove it: + // clearing it here would tell discardUnapprovedStream() that nothing this edit created is + // left to clean, and an empty or half-written new file would survive the failed write. + this.placeholderPath = undefined + // Stop tracking touches and cancel any pending scroll-to-diff before any // programmatic editor activation below. this.disposeActiveEditorListener() @@ -513,14 +549,276 @@ export class DiffViewProvider { return JSON.stringify(result) } + /** + * Remove a file this edit created. Tolerates ENOENT: when open() failed before the + * placeholder was written (or the write itself failed) there is nothing to delete, and + * that must not abort the rollback. + */ + private async removeCreatedFile(absolutePath: string): Promise { + try { + await fs.unlink(absolutePath) + } catch (error: unknown) { + if (!isEnoent(error)) { + throw error + } + } + } + + /** Same tolerance for a directory this edit created that never made it to disk. */ + private async removeCreatedDir(dirPath: string): Promise { + try { + await fs.rmdir(dirPath) + } catch (error: unknown) { + if (!isEnoent(error)) { + throw error + } + } + } + + /** + * Whether this edit still owns a placeholder file that cleanup must remove. + * True from the moment open() creates the file until a rollback or commit removes + * it; a failed removal leaves it true so the caller can keep the session (and the + * retry path) instead of resetting the ownership away. + */ + get ownsPlaceholder(): boolean { + return this.placeholderPath !== undefined + } + + /** + * Whether an active edit session belongs to a different path than the one a + * call is about to write. A session is retained when its rollback could not + * complete (a refused save keeps \`isEditing\` and the dirty buffer so the + * user's content survives); a later write for ANOTHER path must not reuse + * that session: it would update and save the old document while requesting + * approval for the new path. + */ + isEditingDifferentPath(relPath: string): boolean { + if (!this.isEditing || this.relPath === undefined) { + return false + } + return this.relPath !== relPath + } + + /** + * The path of the retained edit session, when one is active. Used to tell the + * caller which write must be resolved before another path can be written. + */ + get editingRelPath(): string | undefined { + return this.isEditing ? this.relPath : undefined + } + + /** + * Release the placeholder this edit owns when the approved write never committed: + * saveChanges() threw before its commit point, so the file on disk is still the empty + * placeholder open() created. Leaving it behind unowned would make a later attempt + * treat it as the pre-existing target and strand an empty file no rollback recognizes + * anymore. The dirty editor (it holds the approved content for a manual save or retry) + * and the created directories are deliberately untouched: that save needs both the + * buffer and its parent directories. + */ + async discardOwnedPlaceholder(): Promise { + const placeholderPath = this.placeholderPath + if (!placeholderPath) { + return + } + await this.removeCreatedFile(placeholderPath) + this.placeholderPath = undefined + } + + /** + * Release a diff view whose content was never approved: an abandoned partial stream, + * a failed stream, or a write the user was never asked to approve (rooignore denial, + * validation failure). Deliberately NOT the same as revertChanges(), because + * revertChanges() SAVES and neither abandoned case may write to disk: + * + * - create: its new-file branch saves a dirty buffer as-is before deleting the file, + * which writes partial model output the task never approved - and leaves it on disk + * if the delete then fails. + * - modify: its branch restores the original content and saves it. That is a write to + * a file the user never approved, and for a rooignore-denial path a write the + * policy forbids outright. + * + * Here the target file is never written. A create buffer is emptied FIRST, so the + * only bytes that can ever reach the placeholder are none and the tab is clean enough + * to close without a prompt; a modify buffer is restored to the content already on + * disk in memory only, so the file itself is untouched and the tab (now showing the + * original content, still marked dirty) is left for the user rather than force-closed + * over any edits they may have typed into the preview. The placeholder plus the directories this edit + * created are removed once the buffer outcome is confirmed - a restore applyEdit accepted and, for a + * create, a save it confirmed. While that outcome is unconfirmed the artifacts stay owned and on disk: + * deleting them under a buffer that still holds unapproved content leaves that buffer one save away + * from recreating a file nobody approved. + */ + async discardUnapprovedStream(): Promise { + if (!this.relPath) { + return + } + + const absolutePath = path.resolve(this.cwd, this.relPath) + // Snapshot the directories this edit created BEFORE the editor work below, and clear the field so + // nothing else can act on them twice. The sweep below runs when the buffer outcome is confirmed; + // when it is not, the catch hands this snapshot back, so the retained session's next cleanup still + // knows what this edit put on disk. + const createdDirs = this.createdDirs + this.createdDirs = [] + // Same snapshot for the placeholder, but the ownership stays set until the unlink + // actually succeeds: a failed removal (EPERM) must leave the file owned so the + // caller can keep the session and a retry path instead of stranding it unowned. + const placeholderPath = this.placeholderPath + + let editorFailure: unknown + + // Lifecycle teardown first: ahead of the editor branch below and therefore ahead of the awaited + // buffer restore. open() installs onDidChangeActiveTextEditor, onDidChangeTextEditorSelection + // and onDidChangeTextEditorVisibleRanges, and close() clears activeDiffEditor without + // disposing them, so a discard reached after the view was closed used to sweep the artifacts + // and leave three window-level handlers plus any pending deferred reveal installed on a + // session the caller keeps when this method returns with ownership retained. + this.disposeActiveEditorListener() + this.cancelDeferredScroll() + + // open() creates the directories and the empty placeholder BEFORE it assigns + // activeDiffEditor (openDiffEditor() can reject on its 10s timeout or a failed + // vscode.diff call), so an abandoned create can leave artifacts on disk with no + // editor at all. Only the buffer and tab work needs the editor; the artifact + // cleanup below runs either way. + if (this.activeDiffEditor) { + const document = this.activeDiffEditor.document + // Held until the buffer outcome below confirms itself. A restore applyEdit declined, a save that + // did not confirm, or a rejection anywhere before that confirmation leaves unapproved content in + // a buffer whose tab is still open, and unlinking the file underneath it would let a later save + // of that buffer recreate the file with content nobody ever approved. + let bufferUnconfirmed = true + try { + if (document.isDirty) { + // Restore the buffer to what this edit started from - the empty placeholder for a create, + // the content already on disk for a modify. A refused applyEdit leaves the unapproved streamed + // content in the buffer, and saving then would persist exactly what this method exists to + // discard, so the save is conditional and a refused restore stops the rollback outright below. + const edit = new vscode.WorkspaceEdit() + const fullRange = new vscode.Range( + document.positionAt(0), + document.positionAt(document.getText().length), + ) + const restoredContent = + this.editType === "modify" ? this.stripAllBOMs(this.originalContent ?? "") : "" + edit.replace(document.uri, fullRange, restoredContent) + const applied = await vscode.workspace.applyEdit(edit) + if (!applied) { + // A refused restore leaves the unapproved content in the buffer: closing the tabs and sweeping + // the artifacts underneath it would strand that content with nothing left that can recover it, + // so this stops the rollback outright, exactly as an unconfirmed save of the restored buffer + // does below. The catch restores the createdDirs snapshot and the placeholder stays owned, + // which is what tells the caller to skip reset() and keep the session for a retry. + throw new Error( + `Could not restore the diff editor buffer for ${this.relPath}; it may still hold unapproved content.`, + ) + } else if (this.editType !== "modify") { + // Only the emptied placeholder is ever saved: this edit created that file, and + // closing a dirty tab would prompt. A modify is never saved here - a modify's + // restore is an in-memory revert, and saving it would write to a file the user + // never approved (see the method comment). A false save leaves the buffer dirty + // over the placeholder: closeAllDiffViews() would skip the dirty tab and the + // unlink would delete the file underneath it, leaving the buffer one save away + // from recreating it - the same hazard revertChanges() refuses, so the rollback + // stops here with the placeholder still owned and the session still retryable. + if (!(await document.save())) { + throw new Error( + `Rollback could not save the restored buffer for ${this.relPath}; its clean state is unconfirmed, so the cleanup stopped before closing tabs or deleting the placeholder.`, + ) + } + } + } + // Close the diff tabs only now: a vscode.diff tab is dirty while its modified side + // holds the streamed content, and closeAllDiffViews() deliberately skips dirty tabs to + // avoid a save prompt. Closing before the restore above left that tab open over a file + // this method is about to unlink. + // Confirmed: the buffer holds nothing this edit streamed - restored, and for a create saved, or + // already clean. A rejection from the closes below can leave a tab open over a clean buffer, a + // lesser hazard than an artifact nothing can remove once the caller resets the session, so + // those rejections still fall through to the sweep. + bufferUnconfirmed = false + await this.closeAllDiffViews() + await this.closeFileTab(absolutePath) + } catch (error) { + // An unconfirmed buffer outcome keeps the placeholder and the created directories exactly as + // they are - owned, on disk - because the retained session is what a retry works from. + if (bufferUnconfirmed) { + // The rollback stopped before the artifact sweep: hand the directory snapshot back with + // the still-owned placeholder, so the next cleanup of this session knows what this edit + // created. The retained ownership is what tells the caller to skip reset(). + this.createdDirs = createdDirs + throw error + } + // Only the tab closes failed, on a buffer whose outcome is confirmed: the placeholder and the + // created directories still have to go, because the caller resets the session afterwards and + // nothing else can remove them. The original failure is re-thrown once they are dealt with. + editorFailure = error + } + } + + let cleanupFailure: unknown + try { + // Only a placeholder THIS edit created may be removed. relPath survives reset(), and + // saveDirectly() sets it for a file that was written with approval, so unlinking + // absolutePath unconditionally can delete content the user approved. + if (placeholderPath) { + // The helpers carry the ENOENT tolerance: open() creates the placeholder, + // and if it is already gone there is nothing left to remove. + await this.removeCreatedFile(placeholderPath) + this.placeholderPath = undefined + } + + // Remove only the directories this edit created, in reverse order. + for (let i = createdDirs.length - 1; i >= 0; i--) { + await this.removeCreatedDir(createdDirs[i]) + } + } catch (error) { + // A sweep that stopped partway leaves whatever it did not reach on disk and untracked, + // because this field was cleared up front. Hand the snapshot back: when the unlink is the + // step that failed the placeholder is still owned, the session is retained, and the next + // discard finishes the sweep in reverse order - the helpers tolerate whatever a partial sweep + // already removed. When only a directory removal failed, ownership is already released and + // the caller-side reset clears this field again, so nothing changes on that path. + this.createdDirs = createdDirs + cleanupFailure = error + console.error("Error removing abandoned write_to_file artifacts:", error) + } + + // Restore any preview tabs the diff evicted, reconstructing the user's prior + // not-yet-edited tab state, the way saveChanges() and revertChanges() do at their own ends. + // The discard path never reached this: reset() clears snapshotPreviewTabs right after, so a + // denied stream left every tab VS Code evicted to open the diff gone for the session. + // Skipped when the sweep failed - the placeholder is then still on disk and still owned, the + // snapshot is the only record the retry path has of what is left to remove, and reopening + // tabs on top of a half-removed artifact would report a workspace that is not restored. + // restorePreviewTabs() reports its own per-tab failures, so it cannot mask editorFailure. + if (!cleanupFailure) { + await this.restorePreviewTabs() + } + if (editorFailure) { + throw editorFailure instanceof Error ? editorFailure : new Error(String(editorFailure)) + } + if (cleanupFailure) { + throw cleanupFailure instanceof Error ? cleanupFailure : new Error(String(cleanupFailure)) + } + } + async revertChanges(): Promise { - if (!this.relPath || !this.activeDiffEditor) { + if (!this.relPath) { return } const fileExists = this.editType === "modify" - const updatedDocument = this.activeDiffEditor.document const absolutePath = path.resolve(this.cwd, this.relPath) + // Only the placeholder THIS edit owns may be deleted. A stale session (a prior reset() + // whose close failed) can carry relPath onto the next call, and the path derived from + // it may name a file this edit never created - e.g. the previously approved write. + // Ownership is released only once the unlink succeeds: a rollback that fails partway + // (refused restore, EPERM unlink) must leave the placeholder OWNED so the caller can + // skip reset() and keep a retry path, instead of stranding the empty file unowned. + // A double unlink from a later discard is safe - removeCreatedFile tolerates ENOENT. // Stop tracking touches and cancel any pending scroll-to-diff before any // programmatic editor activation below. @@ -528,52 +826,101 @@ export class DiffViewProvider { this.cancelDeferredScroll() if (!fileExists) { - if (updatedDocument.isDirty) { - await updatedDocument.save() + // open() creates the parent directories and an empty placeholder file BEFORE it + // awaits openDiffEditor(). If that await rejects there is no activeDiffEditor, and + // the previous early return here left the placeholder and the new directories on + // disk: the next execute() then saw an empty file and treated the requested new file + // as an existing one, so a denial preserved the debris. The filesystem rollback runs + // either way; only the document work needs an editor. + if (this.activeDiffEditor) { + const updatedDocument = this.activeDiffEditor.document + if (updatedDocument.isDirty) { + // The diff tab's modified side holds the streamed content, and the tab is dirty + // while it does: closeAllDiffViews() skips dirty tabs (closing one would prompt), + // so the rollback must put the pre-stream content back and confirm a clean save + // BEFORE any tab or file goes. Unlinking the placeholder underneath an open dirty + // diff tab left the unapproved content one save away from recreating the deleted + // file. A refused restore or an unconfirmed save stops the rollback here - before + // the close and the delete - and propagates as the rollback hazard it is. + const edit = new vscode.WorkspaceEdit() + const fullRange = new vscode.Range( + updatedDocument.positionAt(0), + updatedDocument.positionAt(updatedDocument.getText().length), + ) + edit.replace(updatedDocument.uri, fullRange, this.originalContent ?? "") + if (!(await vscode.workspace.applyEdit(edit))) { + throw new Error( + `Rollback could not restore the buffer for ${absolutePath}; it may still hold unapproved content, so the rollback stopped before closing tabs or deleting the file.`, + ) + } + if (!(await updatedDocument.save())) { + throw new Error( + `Rollback could not save the restored buffer for ${absolutePath}; its clean state is unconfirmed, so the rollback stopped before closing tabs or deleting the file.`, + ) + } + // A file-scheme buffer for the same path, if one is open, holds the same + // unapproved content: discard it with the same restore-save-close discipline. + await this.discardFileTab(absolutePath) + await this.closeAllDiffViews() + } else { + await this.closeAllDiffViews() + // The file was newly created for this edit; close its transiently + // opened tab before deleting it from disk. + await this.closeFileTab(absolutePath) + } } - await this.closeAllDiffViews() - // The file was newly created for this edit; close its transiently - // opened tab before deleting it from disk. - await this.closeFileTab(absolutePath) - await fs.unlink(absolutePath) + if (this.placeholderPath) { + await this.removeCreatedFile(this.placeholderPath) + // The file is gone: release ownership before the directory loop, so a later + // failure there cannot strand an ownership that no longer has a file. + this.placeholderPath = undefined + } // Remove only the directories we created, in reverse order. for (let i = this.createdDirs.length - 1; i >= 0; i--) { - await fs.rmdir(this.createdDirs[i]) + await this.removeCreatedDir(this.createdDirs[i]) } } else { - // Revert document. - const edit = new vscode.WorkspaceEdit() + // The document revert needs the editor. A failed open() (openDiffEditor rejects + // after open() already set relPath/isEditing) leaves none: skip only the document + // work then, and let execution reach the shared teardown below - returning early + // would leave relPath, editType, isEditing and the preview-tab snapshot behind, + // the exact stale-session state this method's rollback guarantees rule out. + const updatedDocument = this.activeDiffEditor?.document + if (updatedDocument) { + // Revert document. + const edit = new vscode.WorkspaceEdit() - const fullRange = new vscode.Range( - updatedDocument.positionAt(0), - updatedDocument.positionAt(updatedDocument.getText().length), - ) + const fullRange = new vscode.Range( + updatedDocument.positionAt(0), + updatedDocument.positionAt(updatedDocument.getText().length), + ) - edit.replace(updatedDocument.uri, fullRange, this.stripAllBOMs(this.originalContent ?? "")) + edit.replace(updatedDocument.uri, fullRange, this.stripAllBOMs(this.originalContent ?? "")) + + // Apply the edit and save, since contents shouldn't have changed + // this won't show in local history unless of course the user made + // changes and saved during the edit. + await vscode.workspace.applyEdit(edit) + await updatedDocument.save() - // Apply the edit and save, since contents shouldn't have changed - // this won't show in local history unless of course the user made - // changes and saved during the edit. - await vscode.workspace.applyEdit(edit) - await updatedDocument.save() + await this.closeAllDiffViews() - await this.closeAllDiffViews() + // Read auto-close preferences from state; fall back to defaults that + // preserve the existing behavior when unset. + const revertTask = this.taskRef.deref() + const revertState = await revertTask?.providerRef.deref()?.getState() - // Read auto-close preferences from state; fall back to defaults that - // preserve the existing behavior when unset. - const revertTask = this.taskRef.deref() - const revertState = await revertTask?.providerRef.deref()?.getState() - - await this.keepOrCloseEditedFile( - absolutePath, - false, - revertState?.autoCloseZooOpenedFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES, - revertState?.autoCloseZooOpenedFilesAfterUserEdited ?? - DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED, - revertState?.autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES, - ) + await this.keepOrCloseEditedFile( + absolutePath, + false, + revertState?.autoCloseZooOpenedFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES, + revertState?.autoCloseZooOpenedFilesAfterUserEdited ?? + DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED, + revertState?.autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES, + ) + } } // Restore any preview tabs the diff evicted, reconstructing the user's @@ -847,6 +1194,104 @@ export class DiffViewProvider { // Close the plain (non-diff) editor tab for the target file. Used when the // file was opened transiently for the diff and the user never interacted // with it, so it should not linger after accept/deny. + /** + * Close the tab for this path WITHOUT saving. Used by the new-file rollback, where the + * buffer holds unapproved streamed content that must never reach disk; closeFileTab() + * deliberately skips dirty tabs, so a dirty buffer needs the forced close. + * + * A close that fails or is refused is a rollback failure: the buffer would still hold the + * content the user never approved, one save away from disk. Put the pre-stream content back + * so nothing saveable survives, and propagate - the caller must not keep deleting around a + * buffer it could not discard. + */ + private async discardFileTab(absolutePath: string): Promise { + const tabs = vscode.window.tabGroups.all + .flatMap((group) => group.tabs) + .filter( + (tab) => + tab.input instanceof vscode.TabInputText && + tab.input.uri.scheme === "file" && + arePathsEqual(tab.input.uri.fsPath, absolutePath), + ) + + for (const tab of tabs) { + // tabGroups.close()'s second argument is preserveFocus, not a force-discard flag: a + // dirty tab prompts or is refused, which is how unapproved streamed content survived a + // "forced" close. Restore the buffer to its pre-stream content and save it clean first, + // so close() never sees a dirty tab and nothing unapproved reaches disk. A refused + // restore or an unconfirmed clean save stops the rollback HERE: closing anyway would + // hand the user a save-confirmation prompt over a buffer still holding unapproved + // content (or an unconfirmed state), and answering it yes writes exactly what this + // rollback exists to discard. + if (!(await this.restorePreStreamBuffer(absolutePath))) { + throw new Error( + `Rollback could not restore the buffer for ${absolutePath}; it may still hold unapproved content, so the tab was left open rather than closed.`, + ) + } + if (!(await this.saveBufferClean(absolutePath))) { + throw new Error( + `Rollback could not save the restored buffer for ${absolutePath}; its clean state is unconfirmed, so the tab was left open rather than closed.`, + ) + } + + let closed: boolean + let closeError: Error | undefined + try { + closed = await vscode.window.tabGroups.close(tab) + } catch (error) { + closed = false + closeError = error instanceof Error ? error : new Error(String(error)) + } + if (!closed) { + throw new Error( + `Rollback could not close the restored buffer for ${absolutePath}; its content was put back to the pre-stream state but the tab is still open.`, + { cause: closeError }, + ) + } + } + } + + /** + * Replace an open buffer's content with what it held before streaming started, so a buffer + * that could not be closed never keeps unapproved content available to save. + * + * Returns false when VS Code refuses the edit: the buffer still holds the streamed content, + * and discardFileTab() stops the rollback rather than closing or saving over it. Returns + * true when no open buffer needed restoring or the restore applied. + */ + private async restorePreStreamBuffer(absolutePath: string): Promise { + const document = vscode.workspace.textDocuments.find( + (document) => document.uri.scheme === "file" && arePathsEqual(document.uri.fsPath, absolutePath), + ) + if (!document) { + return true + } + const edit = new vscode.WorkspaceEdit() + const range = new vscode.Range(document.positionAt(0), document.positionAt(document.getText().length)) + edit.replace(document.uri, range, this.originalContent ?? "") + return vscode.workspace.applyEdit(edit) + } + + /** + * Persist a restored buffer so the tab is clean before it is closed: close() refuses or prompts + * on a dirty tab, and a refused close is how unapproved content outlived a "forced" rollback. + * Only reached after discardFileTab()'s restore applied, so what lands here is the pre-stream + * content, never the streamed partial. + * + * Returns false when document.save() does not confirm the save: the buffer may still be dirty, + * so closing would prompt over an unconfirmed state and discardFileTab() stops the rollback + * instead. Returns true when the save completed or there was nothing to save. + */ + private async saveBufferClean(absolutePath: string): Promise { + const document = vscode.workspace.textDocuments.find( + (document) => document.uri.scheme === "file" && arePathsEqual(document.uri.fsPath, absolutePath), + ) + if (!document?.isDirty) { + return true + } + return document.save() + } + private async closeFileTab(absolutePath: string): Promise { const tabs = vscode.window.tabGroups.all .flatMap((group) => group.tabs) @@ -1109,25 +1554,39 @@ export class DiffViewProvider { this.disposeActiveEditorListener() this.cancelDeferredScroll() - await this.closeAllDiffViews() - this.editType = undefined - this.isEditing = false - this.originalContent = undefined - this.createdDirs = [] - this.documentWasOpen = false - this.documentWasPinned = false - this.activeDiffEditor = undefined - this.fadedOverlayController = undefined - this.activeLineController = undefined - this.streamedLines = [] - this.preDiagnostics = [] - this.preEditScrollLine = undefined - this.diffScrollLine = undefined - this.targetFileScrollLine = undefined - this.lastScrolledSource = undefined - this.userTouchedDocument = false - this.userTouchedDiffEditor = false - this.snapshotPreviewTabs = [] + try { + await this.closeAllDiffViews() + } finally { + // Clear the session even when the close rejected: a stale relPath/editType/isEditing + // surviving a failed reset is what turned one bad tab-close into loss of approved + // content - the next execution skips open(), reuses the stale create session, and a + // later denial's rollback deletes the file the previous write approved. The close + // failure still propagates to the caller. + this.editType = undefined + this.isEditing = false + // A session's path must not outlive the session: revertChanges() reads relPath to decide + // what to roll back, and a stale relPath with editType cleared points the next rollback at + // whatever file this provider last touched - a file the current edit never created. + this.relPath = undefined + this.newContent = undefined + this.originalContent = undefined + this.createdDirs = [] + this.placeholderPath = undefined + this.documentWasOpen = false + this.documentWasPinned = false + this.activeDiffEditor = undefined + this.fadedOverlayController = undefined + this.activeLineController = undefined + this.streamedLines = [] + this.preDiagnostics = [] + this.preEditScrollLine = undefined + this.diffScrollLine = undefined + this.targetFileScrollLine = undefined + this.lastScrolledSource = undefined + this.userTouchedDocument = false + this.userTouchedDiffEditor = false + this.snapshotPreviewTabs = [] + } } /** @@ -1149,6 +1608,7 @@ export class DiffViewProvider { newProblemsMessage: string | undefined userEdits: string | undefined finalContent: string | undefined + openFailure: string | undefined }> { const absolutePath = path.resolve(this.cwd, relPath) @@ -1159,27 +1619,38 @@ export class DiffViewProvider { await createDirectoriesForFile(absolutePath) await fs.writeFile(absolutePath, content, "utf-8") + // The write above is the commit point: an opening failure that follows it is not a + // publish failure, so the committed outcome and its bookkeeping are kept and the + // opening failure is reported alongside them instead of replacing them. + let openFailure: string | undefined + const noteOpenFailure = (error: unknown): void => { + openFailure = error instanceof Error ? error.message : String(error) + console.warn(`Opening ${absolutePath} failed after its content was committed: ${openFailure}`) + } // Open the document to ensure diagnostics are loaded // When openFile is false (PREVENT_FOCUS_DISRUPTION enabled), we only open in memory - if (openFile) { - // Show the document in the editor - await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), { - preview: false, - preserveFocus: true, - }) - } else { - // Just open the document in memory to trigger diagnostics without showing it - const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(absolutePath)) + try { + if (openFile) { + // Show the document in the editor + await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), { + preview: false, + preserveFocus: true, + }) + } else { + // Just open the document in memory to trigger diagnostics without showing it + const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(absolutePath)) - // Save the document to ensure VSCode recognizes it as saved and triggers diagnostics - if (doc.isDirty) { - await doc.save() - } + // Save the document to ensure VSCode recognizes it as saved and triggers diagnostics + if (doc.isDirty) { + await doc.save() + } - // Force a small delay to ensure diagnostics are triggered - await new Promise((resolve) => setTimeout(resolve, 100)) + // Force a small delay to ensure diagnostics are triggered + await new Promise((resolve) => setTimeout(resolve, 100)) + } + } catch (error) { + noteOpenFailure(error) } - let newProblemsMessage = "" if (diagnosticsEnabled) { @@ -1222,6 +1693,7 @@ export class DiffViewProvider { newProblemsMessage, userEdits: undefined, finalContent: content, + openFailure, } } } diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index e94a66e1db..de609e27df 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -1,12 +1,25 @@ +import * as fs from "fs/promises" import { DiffViewProvider, DIFF_VIEW_URI_SCHEME, DIFF_VIEW_LABEL_CHANGES } from "../DiffViewProvider" import { DecorationController } from "../DecorationController" import type { Task } from "../../../core/task/Task" import type { Mock } from "vitest" import * as vscode from "vscode" import delay from "delay" -import { DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" - -import { makePosition, makeRange, makeTextDocument, makeTextEditor, makeUri } from "../../../test-utils/vscode" +import { + DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES, + DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED, + DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES, + DEFAULT_WRITE_DELAY_MS, +} from "@roo-code/types" + +import { + makeDisposable, + makePosition, + makeRange, + makeTextDocument, + makeTextEditor, + makeUri, +} from "../../../test-utils/vscode" // Mock delay vi.mock("delay", () => ({ @@ -18,6 +31,10 @@ vi.mock("fs/promises", () => ({ readFile: vi.fn().mockResolvedValue("file content"), writeFile: vi.fn().mockResolvedValue(undefined), access: vi.fn().mockResolvedValue(undefined), + // revertChanges() rolls a new-file edit back by deleting the placeholder and the + // directories the edit created. + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), })) // Mock utils @@ -54,7 +71,7 @@ vi.mock("vscode", () => ({ onDidChangeTextEditorVisibleRanges: vi.fn(() => ({ dispose: vi.fn() })), tabGroups: { all: [], - close: vi.fn(), + close: vi.fn().mockResolvedValue(true), activeTabGroup: { activeTab: undefined }, }, visibleTextEditors: [], @@ -375,6 +392,33 @@ describe("DiffViewProvider", () => { expect(diffViewProvider["documentWasPinned"]).toBe(true) expect(diffViewProvider["documentWasOpen"]).toBe(true) }) + + it("leaves the placeholder unowned when opening a file the user already had on disk", async () => { + // editType modify means the file already exists, so open() writes no placeholder and must + // not claim ownership of one: a modify discard that believed the claim would unlink the + // user's real file. The ownership assignment sits inside the if (!fileExists) block, and + // this is the row that fails if it moves out of it. + const existingUri = makeUri(`${mockCwd}/existing.ts`) + const mockEditor = makeTextEditor({ document: makeTextDocument({ uri: existingUri }) }) + 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: existingUri })) + }, 0) + return { dispose: vi.fn() } + }) + vi.mocked(vscode.window).visibleTextEditors = [mockEditor] + diffViewProvider.editType = "modify" + + await diffViewProvider.open("existing.ts") + + // No placeholder was written, so nothing is owned. The getter is asserted alongside the + // field it reads, because no other row drives it through an open() of an existing file. + expect(fs.writeFile).not.toHaveBeenCalled() + expect(diffViewProvider["placeholderPath"]).toBeUndefined() + expect(diffViewProvider.ownsPlaceholder).toBe(false) + }) }) describe("scrollToFirstDiff method", () => { @@ -840,12 +884,67 @@ describe("DiffViewProvider", () => { expect(mockDelay).toHaveBeenCalledWith(0) }) + it("keeps the committed outcome and reports the opening failure separately when the open rejects after publication", async () => { + const fsMock = await import("fs/promises") + const reason = new Error("TextEditorService refused to show the document") + vi.mocked(vscode.window.showTextDocument).mockRejectedValueOnce(reason) + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}) + + const result = await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) + + // The write landed before the open failed, so the committed result is still returned + // and the opening failure travels as its own field rather than as a failed publish. + expect(fsMock.writeFile).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", "utf-8") + expect(result.finalContent).toBe("new content") + expect(result.userEdits).toBeUndefined() + expect(result.openFailure).toContain("TextEditorService refused to show the document") + expect(warn).toHaveBeenCalledWith(expect.stringContaining("failed after its content was committed")) + warn.mockRestore() + }) + + it("reports an in-memory open failure as its own field when openTextDocument rejects and the file is not shown", async () => { + const reason = new Error("TextDocumentService refused to open the document") + vi.mocked(vscode.workspace.openTextDocument).mockRejectedValueOnce(reason) + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}) + + const result = await diffViewProvider.saveDirectly("test.ts", "new content", false, false, 0) + + // With openFile false the document is opened in memory only, and the write above is still + // the commit point: a rejection in the in-memory branch reports itself alongside the + // committed outcome instead of replacing it. + expect(result.finalContent).toBe("new content") + expect(result.openFailure).toContain("TextDocumentService refused to open the document") + expect(vscode.window.showTextDocument).not.toHaveBeenCalled() + warn.mockRestore() + }) + + it("reports the failure of the in-memory save as its own field when doc.save rejects", async () => { + const reason = new Error("file service refused to save the opened document") + const dirtyDoc = makeTextDocument({ uri: makeUri(`${mockCwd}/test.ts`) }) + Object.assign(dirtyDoc, { isDirty: true, save: vi.fn().mockRejectedValue(reason) }) + vi.mocked(vscode.workspace.openTextDocument).mockResolvedValueOnce(dirtyDoc) + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}) + + const result = await diffViewProvider.saveDirectly("test.ts", "new content", false, false, 0) + + // doc.save() sits inside the same try as openTextDocument(), so its rejection is reported + // the same way instead of escaping saveDirectly as a publish failure. + expect(result.finalContent).toBe("new content") + expect(result.openFailure).toContain("file service refused to save the opened document") + expect(dirtyDoc.save).toHaveBeenCalledTimes(1) + warn.mockRestore() + }) + it("should store results for formatFileWriteResponse", async () => { - await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 1000) + const result = await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 1000) // Verify internal state was updated expect(diffViewProvider.newProblemsMessage).toBe("") expect(diffViewProvider.userEdits).toBeUndefined() + + // The success path: an open that completed leaves no opening failure behind, so a change that + // reported one unconditionally would fail here. + expect(result.openFailure).toBeUndefined() expect(diffViewProvider["relPath"]).toBe("test.ts") expect(diffViewProvider["newContent"]).toBe("new content") }) @@ -1086,7 +1185,16 @@ describe("DiffViewProvider", () => { describe("userTouchedDocument close/keep behavior", () => { const mockTargetPath = `${mockCwd}/mock-target-file.ts` - const buildActiveDiffEditor = () => + // vscode types `TextDocument.isDirty` as read-only, but the doubles in this block are plain + // objects that a test has to dirty on purpose before `saveChanges()` runs. Widening the + // document view of this one builder keeps every `editor.document.isDirty = ...` below a + // plain assignment: the mutable structural type is what `makeTextDocument` actually hands + // back at runtime, so no assertion and no `any` is needed. + type ActiveDiffEditor = Omit & { + document: Omit & { isDirty: boolean } + } + + const buildActiveDiffEditor = (): ActiveDiffEditor => makeTextEditor({ document: makeTextDocument({ uri: makeUri(mockTargetPath), @@ -1130,6 +1238,778 @@ describe("DiffViewProvider", () => { expect(vscode.window.showTextDocument).toHaveBeenCalled() }) + it("revertChanges() removes the placeholder and created dirs when open() failed before the editor existed", async () => { + // open() creates the parent dirs and an empty placeholder BEFORE it awaits + // openDiffEditor(). If that await rejects there is no activeDiffEditor, and the + // rollback used to bail out - leaving an empty file that the next execute() mistook + // for an existing file, which a denial then preserved. + const createdDirs = [`${mockCwd}/new-parent`, `${mockCwd}/new-parent/nested`] + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs, + // open() claimed the placeholder before its editor open rejected. + placeholderPath: `${mockCwd}/mock-target-file.ts`, + }) + + await diffViewProvider.revertChanges() + + expect(fs.unlink).toHaveBeenCalledWith(`${mockCwd}/mock-target-file.ts`) + expect(fs.rmdir).toHaveBeenNthCalledWith(1, createdDirs[1]) + expect(fs.rmdir).toHaveBeenNthCalledWith(2, createdDirs[0]) + }) + + it("revertChanges() tolerates a placeholder that was never written", async () => { + // The failed open may have died before fs.writeFile ran; ENOENT during the + // rollback is success, not a new failure that would abort the cleanup. + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [], + // Ownership was claimed (open()'s write succeeded); the file vanished externally + // before the rollback ran. + placeholderPath: `${mockCwd}/mock-target-file.ts`, + }) + vi.mocked(fs.unlink).mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + + await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined() + + // The rollback still attempted the delete - the tolerance is about not + // aborting the rest of the cleanup, not about skipping it. + expect(fs.unlink).toHaveBeenCalledWith(`${mockCwd}/mock-target-file.ts`) + }) + + it("open() does not claim placeholder ownership when the placeholder write fails", async () => { + // The failed open may have died inside fs.writeFile(); placeholderPath is set only + // after the write succeeds, so a failed write must not mark a file this edit never + // created as owned, and the rollback must still remove the directories it did + // create without unlinking the unowned path. + const { createDirectoriesForFile } = await import("../../../utils/fs") + vi.mocked(createDirectoriesForFile).mockResolvedValueOnce([`${mockCwd}/new-parent`]) + vi.mocked(fs.writeFile).mockRejectedValueOnce(new Error("EACCES: permission denied")) + + await expect(diffViewProvider.open("mock-target-file.ts")).rejects.toThrow("EACCES: permission denied") + + expect(diffViewProvider["placeholderPath"]).toBeUndefined() + expect(diffViewProvider["createdDirs"]).toEqual([`${mockCwd}/new-parent`]) + + await diffViewProvider.revertChanges() + + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).toHaveBeenCalledWith(`${mockCwd}/new-parent`) + }) + + it("discardOwnedPlaceholder() unlinks the owned placeholder and releases ownership", async () => { + // The approved-but-uncommitted state: the file on disk is still the empty + // placeholder this edit created, so removing it is safe and releasing ownership + // after the removal keeps reset() from stranding it unowned. + diffViewProvider["placeholderPath"] = mockTargetPath + + await diffViewProvider.discardOwnedPlaceholder() + + expect(fs.unlink).toHaveBeenCalledWith(mockTargetPath) + expect(diffViewProvider["placeholderPath"]).toBeUndefined() + // The public getter, not only the field it reads: nothing else in this spec asserts the released + // state, so a getter that always reported true would pass the suite. + expect(diffViewProvider.ownsPlaceholder).toBe(false) + }) + + it("discardOwnedPlaceholder() keeps ownership when the removal fails", async () => { + // An EPERM unlink must not release ownership: the placeholder is still on disk, + // and the caller needs the intact state to retry or to report the hazard. + diffViewProvider["placeholderPath"] = mockTargetPath + vi.mocked(fs.unlink).mockRejectedValueOnce( + Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" }), + ) + + await expect(diffViewProvider.discardOwnedPlaceholder()).rejects.toThrow("EPERM: operation not permitted") + expect(diffViewProvider["placeholderPath"]).toBe(mockTargetPath) + }) + + it("discardOwnedPlaceholder() is a no-op without ownership and tolerates a vanished file", async () => { + // An edit that never created a file must not unlink anything, and a placeholder + // that vanished externally is still a released ownership, not a new failure. + await diffViewProvider.discardOwnedPlaceholder() + expect(fs.unlink).not.toHaveBeenCalled() + + diffViewProvider["placeholderPath"] = mockTargetPath + vi.mocked(fs.unlink).mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + + await expect(diffViewProvider.discardOwnedPlaceholder()).resolves.toBeUndefined() + expect(diffViewProvider["placeholderPath"]).toBeUndefined() + }) + + it("revertChanges() stops before the document work for an existing file when no editor exists", async () => { + // The modify branch used to dereference activeDiffEditor unconditionally. When open() + // never produced an editor there is no document to restore, and the old code threw a + // TypeError out of the denial path instead of finishing the teardown. + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "modify", + createdDirs: [], + }) + + await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined() + + expect(vscode.workspace.applyEdit).not.toHaveBeenCalled() + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).not.toHaveBeenCalled() + // Only the document work is skipped: the shared teardown still runs, so no + // stale session survives the rollback. + expect(diffViewProvider["relPath"]).toBeUndefined() + expect(diffViewProvider["isEditing"]).toBe(false) + expect(diffViewProvider["editType"]).toBeUndefined() + }) + + it("revertChanges() keeps rolling back the remaining directories when one rmdir hits ENOENT", async () => { + // Same tolerance as the placeholder, for the created dirs: a directory that never + // landed must not abort the rest of the rollback and must not surface as a new failure. + const createdDirs = [`${mockCwd}/new-parent`, `${mockCwd}/new-parent/nested`] + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs, + }) + vi.mocked(fs.rmdir).mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + + await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined() + + expect(fs.rmdir).toHaveBeenCalledTimes(2) + expect(fs.rmdir).toHaveBeenNthCalledWith(1, createdDirs[1]) + expect(fs.rmdir).toHaveBeenNthCalledWith(2, createdDirs[0]) + }) + + it("revertChanges() surfaces a non-ENOENT directory failure instead of swallowing it", async () => { + // The tolerance is scoped to ENOENT: a directory that exists but could not be removed + // is a real rollback failure and must reach the caller rather than be hidden. + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [`${mockCwd}/new-parent`], + }) + vi.mocked(fs.rmdir).mockRejectedValueOnce(Object.assign(new Error("EBUSY"), { code: "EBUSY" })) + + await expect(diffViewProvider.revertChanges()).rejects.toThrow("EBUSY") + }) + + it("revertChanges() keeps placeholder ownership when the unlink fails", async () => { + // A rollback that cannot remove the placeholder must leave it OWNED: the caller + // skips reset() on that signal and keeps a retry path, instead of the empty file + // being stranded unowned for the next attempt to mistake for an existing file. + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [], + placeholderPath: mockTargetPath, + }) + vi.mocked(fs.unlink).mockRejectedValueOnce( + Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" }), + ) + + await expect(diffViewProvider.revertChanges()).rejects.toThrow("EPERM: operation not permitted") + expect(diffViewProvider["placeholderPath"]).toBe(mockTargetPath) + expect(diffViewProvider.ownsPlaceholder).toBe(true) + }) + + it("revertChanges() releases placeholder ownership once the unlink succeeded even if a directory removal fails", async () => { + // Ownership tracks the file, not the whole rollback: after the unlink lands, the + // ownership is released before the directory loop, so a later EBUSY cannot strand + // an ownership whose file no longer exists. + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [`${mockCwd}/new-parent`], + placeholderPath: mockTargetPath, + }) + vi.mocked(fs.rmdir).mockRejectedValueOnce(Object.assign(new Error("EBUSY"), { code: "EBUSY" })) + + await expect(diffViewProvider.revertChanges()).rejects.toThrow("EBUSY") + expect(fs.unlink).toHaveBeenCalledWith(mockTargetPath) + expect(diffViewProvider["placeholderPath"]).toBeUndefined() + }) + + it("discardUnapprovedStream() keeps placeholder ownership when the unlink fails", async () => { + // Same discipline as revertChanges(): the abandoned-stream cleanup runs even with + // no editor, and a failed unlink must leave the placeholder owned so the caller + // can skip reset() and keep a retry path instead of stranding it unowned. + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [], + placeholderPath: mockTargetPath, + }) + vi.mocked(fs.unlink).mockRejectedValueOnce( + Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" }), + ) + + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow("EPERM: operation not permitted") + expect(diffViewProvider["placeholderPath"]).toBe(mockTargetPath) + }) + + it("revertChanges() after reset() does not unlink a file this edit never created", async () => { + // reset() used to leave relPath behind with editType cleared, which is exactly the state + // that sends the NEXT rollback down the new-file branch: fs.unlink on whatever file this + // provider last touched. A truncated tool call or an EACCES in a later write then deleted + // a file the user had already saved. + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [], + placeholderPath: mockTargetPath, + }) + + await diffViewProvider.reset() + await diffViewProvider.revertChanges() + + expect(diffViewProvider["relPath"]).toBeUndefined() + expect(fs.unlink).not.toHaveBeenCalled() + }) + it("revertChanges() after a FAILED reset does not delete the previously approved file", async () => { + // An approved new-file write landed and reset() then rejected on the tab close. + // Without the finally, relPath/editType/isEditing and the placeholder ownership + // survived the failure: the next execution skipped open(), reused the stale create + // session, and a later denial's rollback unlinked the file the user had approved. + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + isEditing: true, + createdDirs: [], + placeholderPath: mockTargetPath, + }) + diffViewProvider["closeAllDiffViews"] = vi.fn().mockRejectedValue(new Error("close failed")) + + await expect(diffViewProvider.reset()).rejects.toThrow("close failed") + + // The failed reset still released the session and the placeholder ownership. + expect(diffViewProvider["relPath"]).toBeUndefined() + expect(diffViewProvider["editType"]).toBeUndefined() + expect(diffViewProvider["isEditing"]).toBe(false) + expect(diffViewProvider["placeholderPath"]).toBeUndefined() + + // The next edit's denial rolls back owning no placeholder: the previously approved + // file must survive even though a relPath is set again. The tab close succeeds this + // time - only the rollback's delete authority is under test. + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + Object.assign(diffViewProvider, { + relPath: "follow-up-denied.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [], + }) + await diffViewProvider.revertChanges() + expect(fs.unlink).not.toHaveBeenCalled() + }) + + it("saveChanges() signals its commit point at the document save, not on return", async () => { + // Everything after the save - closing the diff views, tab bookkeeping, diagnostics - can + // still reject. A caller that rolls the tool call back on that rejection would undo a + // write that already landed, so it has to be told at the save rather than when the + // method returns. + const order: string[] = [] + const editor = buildActiveDiffEditor() + editor.document.isDirty = true + editor.document.save = vi.fn(async () => { + order.push("save") + return true + }) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + newContent: "content", + activeDiffEditor: editor, + placeholderPath: mockTargetPath, + closeFileTab: vi.fn().mockResolvedValue(undefined), + restorePreviewTabs: vi.fn().mockResolvedValue(undefined), + }) + diffViewProvider["closeAllDiffViews"] = vi.fn(async () => { + order.push("closeDiffViews") + }) + + await diffViewProvider.saveChanges(false, 0, () => { + order.push("commit") + }) + + expect(order).toEqual(["save", "commit", "closeDiffViews"]) + // Ownership follows the same line: the placeholder open() created is only released once + // the approved content is on disk. + expect(diffViewProvider["placeholderPath"]).toBeUndefined() + }) + + it("saveChanges() withholds the commit point and the placeholder when the save rejects", async () => { + // A rejected save means nothing landed. Signalling the commit point anyway would tell + // the caller the rollback has to stand down, and clearing placeholderPath would tell + // discardUnapprovedStream() that nothing this edit created is left to remove - the empty + // or half-written new file would survive the failed write. + const order: string[] = [] + const editor = buildActiveDiffEditor() + editor.document.isDirty = true + editor.document.save = vi.fn(async () => { + order.push("save") + throw new Error("save rejected") + }) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + newContent: "content", + activeDiffEditor: editor, + placeholderPath: mockTargetPath, + closeFileTab: vi.fn().mockResolvedValue(undefined), + }) + + await expect(diffViewProvider.saveChanges(false, 0, () => order.push("commit"))).rejects.toThrow( + "save rejected", + ) + + expect(order).toEqual(["save"]) + expect(diffViewProvider["placeholderPath"]).toBe(mockTargetPath) + }) + + it("saveChanges() does not commit when the save resolves false", async () => { + // save() can resolve false without throwing: the write did not persist. The commit + // point was never reached, so onCommit must not run and the placeholder must stay + // owned - reporting the write as durable would strand an unpersisted file whose + // cleanup ownership had already been released. + const order: string[] = [] + const editor = buildActiveDiffEditor() + editor.document.isDirty = true + editor.document.save = vi.fn(async () => { + order.push("save") + return false + }) + + const closeAllDiffViews = vi.fn().mockResolvedValue(undefined) + const disposeActiveEditorListener = vi.fn() + diffViewProvider["closeAllDiffViews"] = closeAllDiffViews + diffViewProvider["disposeActiveEditorListener"] = disposeActiveEditorListener + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + newContent: "content", + activeDiffEditor: editor, + placeholderPath: mockTargetPath, + }) + + await expect(diffViewProvider.saveChanges(false, 0, () => order.push("commit"))).rejects.toThrow( + "was not confirmed; the write was not committed", + ) + + expect(order).toEqual(["save"]) + expect(diffViewProvider["placeholderPath"]).toBe(mockTargetPath) + + // And nothing past the commit point ran: a false save stopped saveChanges before it closed the + // diff views and before it stopped tracking the active editor, so moving either of those above + // the save guard fails this row. + expect(closeAllDiffViews).not.toHaveBeenCalled() + expect(disposeActiveEditorListener).not.toHaveBeenCalled() + }) + + it("saveChanges() commits an already-clean document and releases placeholder ownership", async () => { + // A clean document already matches disk and never saves, but it crosses the same + // commit point: the callback must run and the placeholder ownership must be + // released even though no save happened. + const editor = buildActiveDiffEditor() + editor.document.isDirty = false + const onCommit = vi.fn() + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + newContent: "content", + activeDiffEditor: editor, + placeholderPath: mockTargetPath, + documentWasOpen: false, + userTouchedDocument: false, + preEditScrollLine: undefined, + editType: "modify", + originalContent: "original", + }) + + await diffViewProvider.saveChanges(false, 0, onCommit) + + expect(editor.document.save).not.toHaveBeenCalled() + expect(onCommit).toHaveBeenCalledTimes(1) + expect(diffViewProvider["placeholderPath"]).toBeUndefined() + }) + + it("revertChanges() surfaces a placeholder delete that failed for a non-ENOENT reason", async () => { + // The ENOENT tolerance is scoped: an unlink that fails for another reason means the + // unapproved placeholder is still on disk, and the caller must not be told the + // rollback succeeded. + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [], + placeholderPath: mockTargetPath, + }) + vi.mocked(fs.unlink).mockRejectedValueOnce( + Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }), + ) + + await expect(diffViewProvider.revertChanges()).rejects.toThrow("EACCES: permission denied") + }) + + it("revertChanges() restores the streamed buffer to its pre-stream content before closing and unlinking a new file", async () => { + // The diff buffer holds the streamed content of a write that was never approved. + // Saving it as-is persisted exactly what this rollback is undoing - local history, file + // watchers, and, if the delete below fails, the content itself. The rollback restores the + // pre-stream content first and only then saves, so the only content ever written is the + // empty pre-stream buffer. + const editor = buildActiveDiffEditor() + editor.document.isDirty = true + editor.document.save = vi.fn().mockResolvedValue(true) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + const dirtyTab = { + input: Object.assign(new vscode.TabInputText(makeUri(mockTargetPath)), { + uri: makeUri(mockTargetPath), + }), + isDirty: true, + label: "mock-target-file.ts", + } + const originalTabs = Object.getOwnPropertyDescriptor(vscode.window.tabGroups, "all") + Object.defineProperty(vscode.window.tabGroups, "all", { + get: () => [{ tabs: [dirtyTab] }], + configurable: true, + }) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: editor, + editType: "create", + createdDirs: [], + originalContent: "", + placeholderPath: mockTargetPath, + }) + + try { + await diffViewProvider.revertChanges() + } finally { + // Do not leak the tab fixture: later tests read the module-level tabGroups.all. + if (originalTabs) { + Object.defineProperty(vscode.window.tabGroups, "all", originalTabs) + } + } + + expect(editor.document.save).toHaveBeenCalledTimes(1) + const [, , replacedText] = mockWorkspaceEdit.replace.mock.calls[0] + expect(replacedText).toBe("") + // No force argument: tabGroups.close()'s second parameter is preserveFocus, not a + // discard flag, so passing true never discarded anything - it only suppressed the + // prompt while the dirty tab was silently refused. + expect(vscode.window.tabGroups.close).toHaveBeenCalledWith(dirtyTab) + expect(fs.unlink).toHaveBeenCalledWith(mockTargetPath) + }) + + it("revertChanges() cleans and closes the dirty vscode.diff tab before unlinking the new file", async () => { + // The denial-path hazard named on the pre-merge check: openDiffEditor() opens a + // vscode.diff tab whose input is a TabInputTextDiff, closeAllDiffViews() skips that tab + // while its modified side is dirty, and unlinking the placeholder underneath the open + // dirty tab left unapproved content one save away from recreating the deleted file. + // The provider's own tab helpers are deliberately NOT stubbed: the tab cleanup order + // through the real helpers is what is under test. + const callOrder: string[] = [] + const document = { + isDirty: true, + getText: () => "partial model output", + positionAt: (offset: number) => ({ line: 0, character: offset }), + uri: makeUri(mockTargetPath), + save: vi.fn(async () => { + callOrder.push("save") + document.isDirty = false + return true + }), + } + const diffTab = { + label: `mock-target-file.ts ${DIFF_VIEW_LABEL_CHANGES}`, + input: Object.assign(new vscode.TabInputTextDiff(makeUri("diff-original"), makeUri(mockTargetPath)), { + original: { scheme: DIFF_VIEW_URI_SCHEME, fsPath: "mock-target-file.ts" }, + modified: { scheme: "file", fsPath: mockTargetPath }, + }), + // The tab is dirty exactly while the modified-side buffer is: the rollback has to + // make the buffer clean for the tab to become closeable at all. + get isDirty() { + return document.isDirty + }, + } + const originalTabs = Object.getOwnPropertyDescriptor(vscode.window.tabGroups, "all") + Object.defineProperty(vscode.window.tabGroups, "all", { + get: () => [{ tabs: [diffTab] }], + configurable: true, + }) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: { document }, + editType: "create", + createdDirs: [], + originalContent: "", + placeholderPath: mockTargetPath, + }) + vi.mocked(vscode.workspace.applyEdit).mockImplementation(async () => { + callOrder.push("applyEdit") + return true + }) + vi.mocked(vscode.window.tabGroups.close).mockImplementation(async () => { + callOrder.push("closeTab") + return true + }) + vi.mocked(fs.unlink).mockImplementation(async () => { + callOrder.push("unlink") + return undefined + }) + + try { + await diffViewProvider.revertChanges() + } finally { + // Do not leak the tab fixture: later tests read the module-level tabGroups.all. + if (originalTabs) { + Object.defineProperty(vscode.window.tabGroups, "all", originalTabs) + } + } + + // The buffer is put back to its pre-stream (empty) content and saved clean before + // anything closes, and the tab is gone before the file is deleted: no save can + // recreate the abandoned file from a buffer the user never approved. + expect(callOrder.slice(0, 2)).toEqual(["applyEdit", "save"]) + const [, , replacedText] = mockWorkspaceEdit.replace.mock.calls[0] + expect(replacedText).toBe("") + expect(callOrder.indexOf("closeTab")).toBeGreaterThan(-1) + expect(callOrder.indexOf("closeTab")).toBeLessThan(callOrder.indexOf("unlink")) + expect(fs.unlink).toHaveBeenCalledWith(mockTargetPath) + }) + + it("revertChanges() reports a discard the editor refused instead of leaving the buffer open", async () => { + // A forced close can still fail (a vetoing editor). Swallowing that left the unapproved + // streamed content in an open, saveable buffer while the rollback kept deleting the + // file underneath it. The failure must propagate, and the buffer must be put back to + // its pre-stream state so nothing saveable survives. + const editor = buildActiveDiffEditor() + editor.document.isDirty = true + // The diff-side restore/save confirms; the file-scheme buffer below is the one + // whose close gets vetoed. + editor.document.save = vi.fn().mockResolvedValue(true) + const streamedBuffer = { + uri: makeUri(mockTargetPath), + getText: vi.fn().mockReturnValue("streamed content"), + isDirty: true, + positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), + save: vi.fn().mockResolvedValue(true), + } + const dirtyTab = { + input: Object.assign(new vscode.TabInputText(makeUri(mockTargetPath)), { + uri: makeUri(mockTargetPath), + }), + isDirty: true, + label: "mock-target-file.ts", + } + const originalTabs = Object.getOwnPropertyDescriptor(vscode.window.tabGroups, "all") + const originalDocuments = Object.getOwnPropertyDescriptor(vscode.workspace, "textDocuments") + Object.defineProperty(vscode.window.tabGroups, "all", { + get: () => [{ tabs: [dirtyTab] }], + configurable: true, + }) + Object.defineProperty(vscode.workspace, "textDocuments", { + value: [streamedBuffer], + configurable: true, + }) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: editor, + editType: "create", + createdDirs: [`${mockCwd}/mock-parent`, `${mockCwd}/mock-parent/mock-nested`], + originalContent: "", + placeholderPath: mockTargetPath, + }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + vi.mocked(vscode.window.tabGroups.close).mockRejectedValueOnce(new Error("close vetoed")) + + try { + await expect(diffViewProvider.revertChanges()).rejects.toThrow("could not close the restored buffer") + } finally { + if (originalTabs) { + Object.defineProperty(vscode.window.tabGroups, "all", originalTabs) + } + if (originalDocuments) { + Object.defineProperty(vscode.workspace, "textDocuments", originalDocuments) + } + } + + // The buffer went back to its pre-stream state and was saved clean BEFORE the close, + // so the close never saw a dirty tab; the rollback then stopped rather than deleting the + // file out from under a buffer it could not discard. + expect(vscode.workspace.applyEdit).toHaveBeenCalled() + expect(streamedBuffer.save).toHaveBeenCalledTimes(1) + expect(vscode.window.tabGroups.close).toHaveBeenCalledWith(dirtyTab) + // The buffer was put back to its pre-stream state (empty for a new file): the edit that + // was applied replaces the streamed text with originalContent. + const appliedEdit = vi.mocked(vscode.WorkspaceEdit).mock.results[0].value + expect(appliedEdit.replace).toHaveBeenCalledWith( + expect.objectContaining({ fsPath: mockTargetPath }), + expect.anything(), + "", + ) + + // The sweep never started: the placeholder this edit owned is still owned, the directory + // snapshot is untouched, and neither unlink nor rmdir ran, because the rollback stopped at the + // refused close before the sweep instead of deleting underneath a buffer it could not discard. + expect(diffViewProvider.ownsPlaceholder).toBe(true) + expect(diffViewProvider["createdDirs"]).toEqual([ + `${mockCwd}/mock-parent`, + `${mockCwd}/mock-parent/mock-nested`, + ]) + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).not.toHaveBeenCalled() + }) + + it("revertChanges() stops the rollback without closing when the buffer restore is refused", async () => { + // applyEdit resolving false leaves the streamed content in the buffer. Saving it would + // persist exactly what this rollback exists to discard, and closing the dirty tab would + // trade the rollback report for a save-confirmation prompt over unapproved content, so + // the rollback stops and reports instead. + const editor = buildActiveDiffEditor() + editor.document.isDirty = true + const streamedBuffer = { + uri: makeUri(mockTargetPath), + getText: vi.fn().mockReturnValue("streamed content"), + isDirty: true, + positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), + save: vi.fn().mockResolvedValue(undefined), + } + const dirtyTab = { + input: Object.assign(new vscode.TabInputText(makeUri(mockTargetPath)), { + uri: makeUri(mockTargetPath), + }), + isDirty: true, + label: "mock-target-file.ts", + } + const originalTabs = Object.getOwnPropertyDescriptor(vscode.window.tabGroups, "all") + const originalDocuments = Object.getOwnPropertyDescriptor(vscode.workspace, "textDocuments") + Object.defineProperty(vscode.window.tabGroups, "all", { + get: () => [{ tabs: [dirtyTab] }], + configurable: true, + }) + Object.defineProperty(vscode.workspace, "textDocuments", { + value: [streamedBuffer], + configurable: true, + }) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: editor, + editType: "create", + createdDirs: [`${mockCwd}/mock-parent`, `${mockCwd}/mock-parent/mock-nested`], + originalContent: "", + placeholderPath: mockTargetPath, + }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValueOnce(false) + + try { + await expect(diffViewProvider.revertChanges()).rejects.toThrow(/could not restore the buffer/i) + } finally { + if (originalTabs) { + Object.defineProperty(vscode.window.tabGroups, "all", originalTabs) + } + if (originalDocuments) { + Object.defineProperty(vscode.workspace, "textDocuments", originalDocuments) + } + } + + // The restore was attempted and refused; the save that would have written the unapproved + // streamed content to disk never ran, and the dirty tab was NOT closed - closing it + // would trade a safe rollback report for a save-confirmation prompt over unapproved + // content. The rollback stops here and reports. + expect(vscode.workspace.applyEdit).toHaveBeenCalled() + expect(streamedBuffer.save).not.toHaveBeenCalled() + expect(vscode.window.tabGroups.close).not.toHaveBeenCalled() + + // The sweep never started: the placeholder this edit owned is still owned, the directory + // snapshot is untouched, and neither unlink nor rmdir ran. The rollback stopped at the refused + // restore, before it deleted anything this edit created. + expect(diffViewProvider.ownsPlaceholder).toBe(true) + expect(diffViewProvider["createdDirs"]).toEqual([ + `${mockCwd}/mock-parent`, + `${mockCwd}/mock-parent/mock-nested`, + ]) + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).not.toHaveBeenCalled() + }) + + it("revertChanges() stops the rollback without closing when the clean save is not confirmed", async () => { + // document.save() resolving false leaves the buffer's clean state unconfirmed. Closing + // then would prompt the user over a possibly-dirty tab, and answering yes can write + // content the rollback never confirmed clean, so the close is skipped and the failure + // is reported. + const editor = buildActiveDiffEditor() + editor.document.isDirty = true + // The diff-side restore/save confirms; the file-scheme buffer below is the one whose + // save stays unconfirmed. + editor.document.save = vi.fn().mockResolvedValue(true) + const streamedBuffer = { + uri: makeUri(mockTargetPath), + getText: vi.fn().mockReturnValue("streamed content"), + isDirty: true, + positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), + save: vi.fn().mockResolvedValue(false), + } + const dirtyTab = { + input: Object.assign(new vscode.TabInputText(makeUri(mockTargetPath)), { + uri: makeUri(mockTargetPath), + }), + isDirty: true, + label: "mock-target-file.ts", + } + const originalTabs = Object.getOwnPropertyDescriptor(vscode.window.tabGroups, "all") + const originalDocuments = Object.getOwnPropertyDescriptor(vscode.workspace, "textDocuments") + Object.defineProperty(vscode.window.tabGroups, "all", { + get: () => [{ tabs: [dirtyTab] }], + configurable: true, + }) + Object.defineProperty(vscode.workspace, "textDocuments", { + value: [streamedBuffer], + configurable: true, + }) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: editor, + editType: "create", + createdDirs: [`${mockCwd}/mock-parent`, `${mockCwd}/mock-parent/mock-nested`], + originalContent: "", + placeholderPath: mockTargetPath, + }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + + try { + await expect(diffViewProvider.revertChanges()).rejects.toThrow(/could not save the restored buffer/i) + } finally { + if (originalTabs) { + Object.defineProperty(vscode.window.tabGroups, "all", originalTabs) + } + if (originalDocuments) { + Object.defineProperty(vscode.workspace, "textDocuments", originalDocuments) + } + } + + // The restore applied and the save was attempted, but the unconfirmed save stops the + // rollback before the close. + expect(streamedBuffer.save).toHaveBeenCalledTimes(1) + expect(vscode.window.tabGroups.close).not.toHaveBeenCalled() + + // The sweep never started: the placeholder this edit owned is still owned, the directory + // snapshot is untouched, and neither unlink nor rmdir ran. An unconfirmed save stops the + // rollback before the artifact sweep, which is what keeps a half-confirmed file owned. + expect(diffViewProvider.ownsPlaceholder).toBe(true) + expect(diffViewProvider["createdDirs"]).toEqual([ + `${mockCwd}/mock-parent`, + `${mockCwd}/mock-parent/mock-nested`, + ]) + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).not.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) @@ -1776,4 +2656,1288 @@ describe("DiffViewProvider", () => { expect(vscode.window.showTextDocument).toHaveBeenCalled() }) }) + describe("discardUnapprovedStream method", () => { + const mockTargetPath = `${mockCwd}/mock-target-file.ts` + + const makeAbandonedDocument = (callOrder: string[], isDirty = true) => ({ + isDirty, + getText: () => "partial model output", + positionAt: (offset: number) => ({ line: 0, character: offset }), + uri: { fsPath: mockTargetPath, path: mockTargetPath }, + save: vi.fn(async () => { + callOrder.push("save") + // A confirmed save: the discard treats an unconfirmed one as a rollback failure. + return true + }), + }) + + const openAbandonedView = (document: unknown, createdDirs: string[], callOrder: string[]) => + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: { document }, + editType: "create", + createdDirs, + // open() records the placeholder it wrote; the discard may only delete what it owns. + placeholderPath: `${mockCwd}/mock-target-file.ts`, + closeAllDiffViews: vi.fn(async () => { + callOrder.push("closeDiffViews") + }), + closeFileTab: vi.fn(async () => { + callOrder.push("closeFileTab") + }), + }) + + it("never persists the unapproved buffer: blanks it with an empty replacement, then deletes the placeholder", async () => { + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + openAbandonedView(document, [], callOrder) + vi.mocked(vscode.workspace.applyEdit).mockImplementation(async () => { + callOrder.push("applyEdit") + return true + }) + + await diffViewProvider.discardUnapprovedStream() + + expect(callOrder).toEqual(["applyEdit", "save", "closeDiffViews", "closeFileTab"]) + // The only content the discard may write is an empty buffer, and it must be + // written to THIS document before the save that would otherwise persist the + // partial model output. + expect(mockWorkspaceEdit.replace).toHaveBeenCalledTimes(1) + const [replacedUri, , replacedText] = mockWorkspaceEdit.replace.mock.calls[0] + expect(replacedUri).toEqual(document.uri) + // The replacement covers the whole buffer: the range is built from + // positionAt(0) to positionAt(getText().length), so nothing can survive it. + expect(vi.mocked(vscode.Range)).toHaveBeenCalledWith( + { line: 0, character: 0 }, + { line: 0, character: "partial model output".length }, + ) + expect(replacedText).toBe("") + expect(mockWorkspaceEdit.delete).not.toHaveBeenCalled() + // The placeholder for THIS relPath is what gets removed. + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("mock-target-file.ts")) + }) + + it("restores a modify buffer in memory and never saves the target file", async () => { + // revertChanges() restores a modify by applyEdit + document.save(). For a stream the + // user never approved that save is a write they never asked for, and for a + // .rooignore-denied path a write the policy forbids outright, so the discard restores + // the buffer and leaves the file on disk untouched. + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + openAbandonedView(document, [], callOrder) + Object.assign(diffViewProvider, { + editType: "modify", + originalContent: "original content", + // A modify owns no placeholder: only open() of a create writes one. + placeholderPath: undefined, + }) + vi.mocked(vscode.workspace.applyEdit).mockImplementation(async () => { + callOrder.push("applyEdit") + return true + }) + + await diffViewProvider.discardUnapprovedStream() + + expect(callOrder).toEqual(["applyEdit", "closeDiffViews", "closeFileTab"]) + const [replacedUri, , replacedText] = mockWorkspaceEdit.replace.mock.calls[0] + expect(replacedUri).toEqual(document.uri) + expect(replacedText).toBe("original content") + // The replacement covers the whole buffer, so no streamed content survives it. + expect(vi.mocked(vscode.Range)).toHaveBeenCalledWith( + { line: 0, character: 0 }, + { line: 0, character: "partial model output".length }, + ) + expect(document.save).not.toHaveBeenCalled() + // Nothing is unlinked for a modify: saveChanges() may have written this very file with + // the user's approval, and this edit created no directories. + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).not.toHaveBeenCalled() + }) + + it("stops the cleanup and keeps the placeholder when the buffer restore is refused", async () => { + // applyEdit resolving false leaves the unapproved partial content in the buffer. Saving then + // would persist exactly what this method exists to discard, and closing the tabs or unlinking + // the placeholder underneath that buffer would leave content the user never approved with + // nothing left that can still recover it - so the rollback stops before the close and the + // delete, the same way an unconfirmed save of the restored buffer does. + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + openAbandonedView(document, [`${mockCwd}/new-dir`], callOrder) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(false) + + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow( + /could not restore the diff editor buffer/i, + ) + + expect(document.save).not.toHaveBeenCalled() + // Nothing after the refused restore ran: no close and no unlink. + expect(callOrder).toEqual([]) + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).not.toHaveBeenCalled() + // Ownership and the directory snapshot survive the refused restore. The caller skips reset() + // while the placeholder is still owned, so the retry keeps a session and a discard that still + // knows what it may delete. + expect(diffViewProvider["placeholderPath"] as string | undefined).toBe(mockTargetPath) + expect(diffViewProvider["createdDirs"]).toEqual([`${mockCwd}/new-dir`]) + }) + + it("stops the cleanup and keeps placeholder ownership when the save is not confirmed", async () => { + // document.save() resolving false leaves the emptied buffer dirty over the + // placeholder: closeAllDiffViews() would skip the dirty tab and the unlink would + // delete the file underneath it, leaving the buffer one save away from recreating + // the file from a denied write. The discard stops before the close and the delete, + // keeping ownership so the caller skips reset() and the session stays retryable. + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + document.save = vi.fn(async () => { + callOrder.push("save") + return false + }) + const closeAllDiffViews = vi.fn(async () => { + callOrder.push("closeDiffViews") + }) + const closeFileTab = vi.fn(async () => { + callOrder.push("closeFileTab") + }) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: { document }, + editType: "create", + createdDirs: [`${mockCwd}/new-dir`], + placeholderPath: `${mockCwd}/mock-target-file.ts`, + closeAllDiffViews, + closeFileTab, + }) + vi.mocked(vscode.workspace.applyEdit).mockImplementation(async () => { + callOrder.push("applyEdit") + return true + }) + + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow( + /could not save the restored buffer/i, + ) + + // The restore was attempted and the save refused; nothing closes and nothing deletes. + expect(callOrder).toEqual(["applyEdit", "save"]) + expect(closeAllDiffViews).not.toHaveBeenCalled() + expect(closeFileTab).not.toHaveBeenCalled() + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).not.toHaveBeenCalled() + // Ownership is preserved: the placeholder is still on disk and still ours. + expect(diffViewProvider["placeholderPath"] as string | undefined).toBe(`${mockCwd}/mock-target-file.ts`) + }) + + it("removes the directories this edit created in reverse order, after the placeholder unlink", async () => { + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + const createdDirs = [`${mockCwd}/mock-dir`, `${mockCwd}/mock-dir/nested`] + openAbandonedView(document, createdDirs, callOrder) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + + await diffViewProvider.discardUnapprovedStream() + + expect(fs.unlink).toHaveBeenCalledTimes(1) + expect(fs.rmdir).toHaveBeenCalledTimes(createdDirs.length) + // Reverse order, so a parent is never removed before the child inside it, and + // only the directories this edit created - never a pre-existing one. + expect(vi.mocked(fs.rmdir).mock.calls.map((c) => c[0])).toEqual([...createdDirs].reverse()) + const unlinkOrder = vi.mocked(fs.unlink).mock.invocationCallOrder[0] + for (const order of vi.mocked(fs.rmdir).mock.invocationCallOrder) { + expect(order).toBeGreaterThan(unlinkOrder) + } + }) + + it("does not save when the abandoned buffer is already clean", async () => { + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder, false) + openAbandonedView(document, [], callOrder) + + await diffViewProvider.discardUnapprovedStream() + + expect(vscode.workspace.applyEdit).not.toHaveBeenCalled() + expect(document.save).not.toHaveBeenCalled() + expect(mockWorkspaceEdit.replace).not.toHaveBeenCalled() + expect(fs.unlink).toHaveBeenCalledTimes(1) + }) + + it("keeps the placeholder and the directories when the buffer restore rejects", async () => { + // A rejected applyEdit leaves the restore unconfirmed, exactly like one that resolves false: the + // buffer still holds the unapproved content and its tab is still open, so unlinking the placeholder + // underneath it would leave that buffer one save away from recreating the file with content nobody + // approved. The artifacts stay owned and the directory snapshot goes back to the session, which is + // what tells the caller to skip reset() and keep the retry path open. + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + const createdDirs = [`${mockCwd}/mock-dir`] + openAbandonedView(document, createdDirs, callOrder) + vi.mocked(vscode.workspace.applyEdit).mockRejectedValue(new Error("applyEdit rejected")) + + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow("applyEdit rejected") + + expect(callOrder).toEqual([]) + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).not.toHaveBeenCalled() + expect(diffViewProvider["placeholderPath"] as string | undefined).toBe(mockTargetPath) + expect(diffViewProvider["createdDirs"]).toEqual(createdDirs) + }) + + it("keeps the placeholder and the directories when the restored buffer save rejects", async () => { + // A rejected save is as unconfirmed as one resolving false: the buffer is still dirty over the + // placeholder this edit created, so the sweep must not delete the file underneath it. + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + const createdDirs = [`${mockCwd}/mock-dir`] + openAbandonedView(document, createdDirs, callOrder) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + document.save.mockRejectedValueOnce(new Error("save rejected")) + + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow("save rejected") + + // The mock rejects without running its recording body, so the call is counted, not ordered. + expect(document.save).toHaveBeenCalledTimes(1) + expect(callOrder).toEqual([]) + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).not.toHaveBeenCalled() + expect(diffViewProvider["placeholderPath"] as string | undefined).toBe(mockTargetPath) + expect(diffViewProvider["createdDirs"]).toEqual(createdDirs) + }) + + it("sweeps the artifacts when only the tab closes reject on a confirmed buffer", async () => { + // The half of the contract the two tests above must not swallow: once the buffer outcome is + // confirmed, a close failure still has to leave the artifacts gone, because the caller resets the + // session after a throw and nothing else can remove them. The failure still surfaces. + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + openAbandonedView(document, [`${mockCwd}/mock-dir`], callOrder) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + vi.mocked(fs.access).mockResolvedValue(undefined) + // One preview tab the diff evicted when it opened, whose file is still on disk: the discard + // path has to put it back even though the tab close is what failed. + const evictedPreview = makeUri(`${mockCwd}/evicted-preview.ts`) + const showCallsBeforeDiscard = vi.mocked(vscode.window.showTextDocument).mock.calls.length + Object.assign(diffViewProvider, { + closeAllDiffViews: vi.fn().mockRejectedValue(new Error("close rejected")), + snapshotPreviewTabs: [ + { uri: evictedPreview, scrollLine: undefined, viewColumn: vscode.ViewColumn.One }, + ], + }) + vi.mocked(fs.unlink).mockResolvedValue(undefined) + + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow("close rejected") + + expect(fs.unlink).toHaveBeenCalledWith(mockTargetPath) + expect(fs.rmdir).toHaveBeenCalledWith(`${mockCwd}/mock-dir`) + expect(diffViewProvider["placeholderPath"] as string | undefined).toBeUndefined() + + // The sweep completed, so the preview-tab restore ran even though the close failed: the + // evicted preview tab is re-shown exactly once, and the editorFailure throw at the end of the + // method cannot skip it - moving restorePreviewTabs() after that throw fails this row. + expect(vi.mocked(vscode.window.showTextDocument).mock.calls.length).toBe(showCallsBeforeDiscard + 1) + expect(vi.mocked(vscode.window.showTextDocument).mock.lastCall?.[0]).toBe(evictedPreview) + }) + + it("disposes the touch listeners and cancels the deferred scroll while the buffer restore is still pending", async () => { + // Review row wM62emT0. The window a late deferred reveal can fire in is exactly the window the + // buffer restore is awaited in, so this test holds applyEdit() open, starts the discard, and + // asks whether the teardown already happened before the restoration is settled. Fake timers keep + // that window open instead of leaning on wall-clock scheduling, and the restoration is resolved in + // a finally block so the pending promise cannot outlive the test. The handle is declared out + // of the try on purpose: a failure inside the try must report itself instead of being replaced + // by the reference error a finally-block read of an uninitialised let would raise. + let settleRestore: (applied: boolean) => void = () => {} + vi.useFakeTimers() + try { + const callOrder: string[] = [] + const revealRange = vi.fn() + const document = makeTextDocument({ + uri: makeUri(mockTargetPath), + getText: vi.fn().mockReturnValue("a\nCHANGED\nc\nd\n"), + positionAt: vi.fn((offset: number) => makePosition(0, offset)), + }) + Object.assign(document, { isDirty: true }) + const editor = makeTextEditor({ document, visibleRanges: [makeRange()], revealRange }) + const disposeActive = vi.fn() + const disposeSelection = vi.fn() + const disposeScroll = vi.fn() + openAbandonedView(document, [], callOrder) + Object.assign(diffViewProvider, { + activeDiffEditor: editor, + editType: "modify", + originalContent: "a\nb\nc\nd\n", + placeholderPath: undefined, + diffScrollLine: 1, + activeEditorListener: makeDisposable({ dispose: disposeActive }), + diffEditorSelectionListener: makeDisposable({ dispose: disposeSelection }), + diffScrollListener: makeDisposable({ dispose: disposeScroll }), + }) + vi.mocked(vscode.window).visibleTextEditors = [editor] + // The keep path re-shows the edited file; give that re-show an editor double so the + // assertions below are the only thing this test can fail on. + vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) + // Schedule the deferred re-reveal the way a tool does, then deny the stream while it is + // still pending. The first reveal is the immediate one; only a surviving timer would add a + // second one after the buffer was already restored. + diffViewProvider.scrollToFirstDiff() + expect(revealRange).toHaveBeenCalledTimes(1) + vi.mocked(vscode.workspace.applyEdit).mockImplementation( + () => + new Promise((resolve) => { + settleRestore = resolve + }), + ) + const discarding = diffViewProvider.discardUnapprovedStream() + await Promise.resolve() + await Promise.resolve() + expect(disposeActive).toHaveBeenCalledOnce() + expect(disposeSelection).toHaveBeenCalledOnce() + expect(disposeScroll).toHaveBeenCalledOnce() + expect(diffViewProvider["deferredScrollTimer"]).toBeUndefined() + // Advancing past the deferred reveal must not put the viewport anywhere: the timer was + // cancelled before the restore was awaited, so there is no late reveal left to fire. + vi.advanceTimersByTime(2000) + expect(revealRange).toHaveBeenCalledTimes(1) + settleRestore(true) + await discarding + expect(callOrder).toEqual(["closeDiffViews", "closeFileTab"]) + } finally { + settleRestore(true) + vi.useRealTimers() + } + }) + + it("disposes the touch listeners on the path where the abandoned view is already closed", async () => { + // Review row wM62emT0, the half the sweep-only test below does not cover. open() installs + // onDidChangeActiveTextEditor, onDidChangeTextEditorSelection and + // onDidChangeTextEditorVisibleRanges, and close() clears activeDiffEditor without touching + // them. A discard reached from that state used to run the sweep and nothing else: the three + // window-level handlers and any pending deferred reveal stayed installed on a session the + // caller may keep for a retry, and reset() is not called when ownership is retained. + vi.useFakeTimers() + try { + const disposeActive = vi.fn() + const disposeSelection = vi.fn() + const disposeScroll = vi.fn() + const lateReveal = vi.fn() + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [], + placeholderPath: mockTargetPath, + activeEditorListener: makeDisposable({ dispose: disposeActive }), + diffEditorSelectionListener: makeDisposable({ dispose: disposeSelection }), + diffScrollListener: makeDisposable({ dispose: disposeScroll }), + // The pending reveal is seeded here, next to the listeners, because the field is declared + // ReturnType on the provider while this file resolves the global timer call + // to the other declaration; assigning the same handle through bracket notation would need an + // assertion. Same handle, same fake clock, same late-reveal guard. + deferredScrollTimer: setTimeout(lateReveal, 300), + }) + vi.mocked(fs.unlink).mockResolvedValue(undefined) + await diffViewProvider.discardUnapprovedStream() + expect(disposeActive).toHaveBeenCalledOnce() + expect(disposeSelection).toHaveBeenCalledOnce() + expect(disposeScroll).toHaveBeenCalledOnce() + expect(diffViewProvider["deferredScrollTimer"]).toBeUndefined() + vi.advanceTimersByTime(1000) + expect(lateReveal).not.toHaveBeenCalled() + expect(fs.unlink).toHaveBeenCalledWith(mockTargetPath) + } finally { + vi.useRealTimers() + } + }) + it("reopens a preview tab the diff evicted before reset() drops the snapshot", async () => { + // Review row wM62emT7. restorePreviewTabs() is defined at DiffViewProvider.ts:1135 and + // called from saveChanges() and revertChanges(), but the discard path never reached it, so a + // denied stream left every preview tab VS Code evicted to open the diff gone: reset() clears + // snapshotPreviewTabs and nothing reopens what it held. + const revealRange = vi.fn() + vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor({ revealRange })) + // No tab in any group: the captured file is one the diff evicted. + Object.defineProperty(vscode.window.tabGroups, "all", { + get: (): vscode.TabGroup[] => [], + configurable: true, + }) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "modify", + createdDirs: [], + placeholderPath: undefined, + snapshotPreviewTabs: [ + { + uri: makeSnapshotUri(`${mockCwd}/mock-preview-tab.ts`), + scrollLine: 7, + viewColumn: vscode.ViewColumn.One, + }, + ], + }) + await diffViewProvider.discardUnapprovedStream() + await diffViewProvider.reset() + expect(vscode.window.showTextDocument).toHaveBeenCalledWith( + { fsPath: `${mockCwd}/mock-preview-tab.ts`, scheme: "file" }, + { preview: true, preserveFocus: true, viewColumn: vscode.ViewColumn.One }, + ) + expect(revealRange).toHaveBeenCalledTimes(1) + expect(revealRange).toHaveBeenCalledWith( + expect.objectContaining({ start: { line: 7, character: 0 } }), + vscode.TextEditorRevealType.AtTop, + ) + expect(diffViewProvider["snapshotPreviewTabs"]).toEqual([]) + }) + + it("leaves the snapshot in place when the artifact sweep fails so the retry can finish it", async () => { + // The restoration is skipped, not merely ordered late, when the sweep failed: the placeholder + // is still on disk and owned, and reopening the evicted tabs would report a restored + // workspace on top of a half-removed artifact while the snapshot is the only record the + // retry path has of what is left to remove. + Object.defineProperty(vscode.window.tabGroups, "all", { + get: (): vscode.TabGroup[] => [], + configurable: true, + }) + vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [], + placeholderPath: mockTargetPath, + snapshotPreviewTabs: [ + { + uri: makeSnapshotUri(`${mockCwd}/mock-preview-tab.ts`), + scrollLine: 7, + viewColumn: vscode.ViewColumn.One, + }, + ], + }) + vi.mocked(fs.unlink).mockRejectedValueOnce(new Error("EPERM: operation not permitted")) + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow("EPERM") + expect(vscode.window.showTextDocument).not.toHaveBeenCalled() + expect(diffViewProvider["snapshotPreviewTabs"]).toHaveLength(1) + }) + it("removes the placeholder and created directories even when open() failed before activeDiffEditor was assigned", async () => { + // open() creates the directories (line 130) and the empty placeholder (line 134) + // BEFORE openDiffEditor() assigns activeDiffEditor (line 173). If that call rejects + // - the 10s timeout or a failed vscode.diff - an abandoned create therefore has + // artifacts on disk and no editor, and the early return must not skip the cleanup. + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: undefined, + editType: "create", + createdDirs: [`${mockCwd}/mock-dir`], + // open() had already written the placeholder before openDiffEditor() rejected, + // so this edit owns the path. + placeholderPath: `${mockCwd}/mock-target-file.ts`, + }) + + await diffViewProvider.discardUnapprovedStream() + + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("mock-target-file.ts")) + expect(fs.rmdir).toHaveBeenCalledWith(`${mockCwd}/mock-dir`) + // Nothing editor-side ran, and nothing threw: the artifacts are the whole job here. + expect(vscode.workspace.applyEdit).not.toHaveBeenCalled() + // Bracket access for the private field: the snapshot must be consumed, so a second + // discard cannot try to remove the same directories again. + expect(diffViewProvider["createdDirs"]).toEqual([]) + }) + + it("logs and rejects when the placeholder unlink fails for a reason other than ENOENT", async () => { + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + openAbandonedView(document, [], callOrder) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + const permissionError = Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" }) + vi.mocked(fs.unlink).mockRejectedValueOnce(permissionError) + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow("EPERM: operation not permitted") + + expect(errorSpy).toHaveBeenCalledWith("Error removing abandoned write_to_file artifacts:", permissionError) + }) + + it("hands the created directories back when the unlink fails, so the retained session can finish the sweep", async () => { + // The unlink is the first step of the sweep, so an EPERM there leaves the placeholder owned - + // which is what keeps the session - and the directories this edit created still on disk. + // If the snapshot is not handed back the retained session forgets them and the retry can + // only remove the file. Two directories, so the retry has to show the reverse order again. + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + const dirA = `${mockCwd}/mock-dir-a` + const dirB = `${mockCwd}/nested/mock-dir-b` + openAbandonedView(document, [dirA, dirB], callOrder) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + vi.mocked(fs.unlink).mockRejectedValueOnce( + Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" }), + ) + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow("EPERM: operation not permitted") + + // Owned, on disk and still tracked: that trio is what makes a retry able to finish the job. + expect(diffViewProvider["placeholderPath"] as string | undefined).toBe(mockTargetPath) + expect(diffViewProvider["createdDirs"]).toEqual([dirA, dirB]) + expect(fs.rmdir).not.toHaveBeenCalled() + + await diffViewProvider.discardUnapprovedStream() + + expect(fs.unlink).toHaveBeenCalledTimes(2) + expect(diffViewProvider["placeholderPath"] as string | undefined).toBeUndefined() + expect(diffViewProvider["createdDirs"]).toEqual([]) + expect(vi.mocked(fs.rmdir).mock.calls.map((c) => c[0])).toEqual([dirB, dirA]) + expect(errorSpy).toHaveBeenCalledTimes(1) + errorSpy.mockRestore() + }) + + it("logs and rejects when removing a created directory fails for a reason other than ENOENT", async () => { + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + openAbandonedView(document, [`${mockCwd}/mock-dir`], callOrder) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + vi.mocked(fs.unlink).mockResolvedValue(undefined) + const notEmpty = Object.assign(new Error("ENOTEMPTY: directory not empty"), { code: "ENOTEMPTY" }) + vi.mocked(fs.rmdir).mockRejectedValueOnce(notEmpty) + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow("ENOTEMPTY: directory not empty") + + expect(errorSpy).toHaveBeenCalledWith("Error removing abandoned write_to_file artifacts:", notEmpty) + }) + + it("tolerates an already-deleted placeholder and directories (ENOENT) without throwing", async () => { + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + // Two created directories: the tolerance has to hold for every one of them, so the + // rejection is keyed on the path rather than on which call comes first. + const dirA = `${mockCwd}/mock-dir-a` + const dirB = `${mockCwd}/nested/mock-dir-b` + openAbandonedView(document, [dirA, dirB], callOrder) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + const enoent = Object.assign(new Error("ENOENT"), { code: "ENOENT" }) + // A single unlink call in this flow, so the placeholder stays Once-based. + vi.mocked(fs.unlink).mockRejectedValueOnce(enoent) + vi.mocked(fs.rmdir).mockImplementation(async (dir) => { + if (dir === dirA || dir === dirB) { + throw enoent + } + }) + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + await expect(diffViewProvider.discardUnapprovedStream()).resolves.toBeUndefined() + + // Both directories were attempted; the assertion is on the paths, not the order. + expect(fs.rmdir).toHaveBeenCalledWith(dirA) + expect(fs.rmdir).toHaveBeenCalledWith(dirB) + expect(errorSpy).not.toHaveBeenCalledWith( + "Error removing abandoned write_to_file artifacts:", + expect.anything(), + ) + + // beforeEach only clears call data, not implementations, so put the default back. + vi.mocked(fs.rmdir).mockResolvedValue(undefined) + }) + + it("reports the editor failure rather than the cleanup failure when both happen", async () => { + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + openAbandonedView(document, [`${mockCwd}/mock-dir`], callOrder) + // The buffer outcome has to be confirmed for the sweep to run at all, which is what makes both + // failures possible in the same call: applyEdit accepted the restore, a tab close then rejects and + // the placeholder unlink that follows it rejects too. + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + Object.assign(diffViewProvider, { + closeAllDiffViews: vi.fn().mockRejectedValue(new Error("close rejected")), + }) + vi.mocked(fs.unlink).mockRejectedValueOnce(Object.assign(new Error("EPERM"), { code: "EPERM" })) + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + // The caller reports a rollback hazard from the thrown error, so the ORIGINAL failure is what must + // surface; the cleanup failure is still logged for the operator. + await expect(diffViewProvider.discardUnapprovedStream()).rejects.toThrow("close rejected") + expect(errorSpy).toHaveBeenCalledWith( + "Error removing abandoned write_to_file artifacts:", + expect.objectContaining({ code: "EPERM" }), + ) + }) + + it("leaves a file this edit never created a placeholder for on disk", async () => { + // reset() does not clear relPath, and saveDirectly() sets it for an approved write. + // Without ownership tracking the discard would unlink that approved file: an approved + // write_to_file to A, then a new write_to_file whose block exits through a rollback + // path before open() ever ran, still sees relPath === A. + const callOrder: string[] = [] + const document = makeAbandonedDocument(callOrder) + Object.assign(diffViewProvider, { + relPath: "previously-approved-file.ts", + activeDiffEditor: { document }, + editType: undefined, + createdDirs: [], + placeholderPath: undefined, + }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + + await expect(diffViewProvider.discardUnapprovedStream()).resolves.toBeUndefined() + + expect(fs.unlink).not.toHaveBeenCalled() + expect(fs.rmdir).not.toHaveBeenCalled() + // The buffer is still blanked and the tab closed: the unapproved content is gone + // without touching a file the user approved. + expect(mockWorkspaceEdit.replace).toHaveBeenCalledTimes(1) + expect(mockWorkspaceEdit.replace.mock.calls[0][2]).toBe("") + }) + + it("removes the placeholder that a new-file open() wrote, driven through the public methods", async () => { + // The ownership lifecycle lives at the public-method layer, so exercise it there: + // open() writes the empty placeholder and records it, and the discard of an abandoned + // create removes exactly that path. + const relPath = "owned-placeholder.ts" + const fsPath = `${mockCwd}/${relPath}` + const mockEditor = { + document: { + uri: { fsPath, scheme: "file" }, + getText: vi.fn().mockReturnValue(""), + isDirty: false, + save: vi.fn().mockResolvedValue(undefined), + lineCount: 0, + }, + selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, + edit: vi.fn().mockResolvedValue(true), + revealRange: vi.fn(), + } + // Structural double for the mocked editor: the mock only implements the members + // open() touches, so it is routed through unknown rather than any. + const editor = mockEditor as unknown as vscode.TextEditor + vi.mocked(vscode.window).visibleTextEditors = [editor] + vi.mocked(vscode.window.showTextDocument).mockResolvedValue(editor) + vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { + setTimeout(() => callback({ uri: { fsPath, scheme: "file" } } as vscode.TextDocument), 0) + return { dispose: vi.fn() } + }) + vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) + vi.mocked(vscode.window.onDidChangeTextEditorVisibleRanges).mockReturnValue({ dispose: vi.fn() }) + vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) + diffViewProvider.editType = "create" + + await diffViewProvider.open(relPath) + + // open() created the placeholder, and this edit now owns it. + expect(fs.writeFile).toHaveBeenCalledWith(fsPath, "") + + await diffViewProvider.discardUnapprovedStream() + + expect(fs.unlink).toHaveBeenCalledWith(fsPath) + }) + + it("does not remove the file once saveChanges() has approved the content", async () => { + // saveChanges() turns the placeholder into approved content and drops this edit's + // claim on it, so a later abandoned cleanup must leave the approved file on disk. + const relPath = "approved-by-save.ts" + const fsPath = `${mockCwd}/${relPath}` + Object.assign(diffViewProvider, { + relPath, + newContent: "approved content", + editType: "create", + createdDirs: [], + placeholderPath: fsPath, + preDiagnostics: [], + activeDiffEditor: { + document: { + uri: { fsPath, scheme: "file" }, + getText: vi.fn().mockReturnValue("approved content"), + isDirty: false, + save: vi.fn().mockResolvedValue(undefined), + }, + }, + closeAllDiffViews: vi.fn().mockResolvedValue(undefined), + closeFileTab: vi.fn().mockResolvedValue(undefined), + }) + vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) + vi.mocked(vscode.window.showTextDocument).mockResolvedValue(undefined as never) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + + await diffViewProvider.saveChanges(false, 0) + + await diffViewProvider.discardUnapprovedStream() + + expect(fs.unlink).not.toHaveBeenCalled() + }) + + it("closes the dirty vscode.diff tab that only TabInputTextDiff matches, before the unlink", async () => { + // The hazard named on #1932: openDiffEditor() opens a vscode.diff tab whose input is a + // TabInputTextDiff, so a rollback helper that looks for TabInputText tabs finds nothing, + // closeAllDiffViews() then skips the tab while it is dirty, and the streamed content + // survives in a buffer one save away from recreating a file the user never approved. + // The provider's own tab helpers are deliberately NOT stubbed here: the tab-input matching + // is what is under test. + const callOrder: string[] = [] + const document = { + isDirty: true, + getText: () => "partial model output", + positionAt: (offset: number) => ({ line: 0, character: offset }), + uri: makeUri(mockTargetPath), + save: vi.fn(async () => { + callOrder.push("save") + document.isDirty = false + return true + }), + } + const diffTab = { + label: `mock-target-file.ts ${DIFF_VIEW_LABEL_CHANGES}`, + input: Object.assign(new vscode.TabInputTextDiff(makeUri("diff-original"), makeUri(mockTargetPath)), { + original: { scheme: DIFF_VIEW_URI_SCHEME, fsPath: "mock-target-file.ts" }, + modified: { scheme: "file", fsPath: mockTargetPath }, + }), + // The tab is dirty exactly while the modified-side buffer is: the discard has to make + // the buffer clean for the tab to become closeable at all. + get isDirty() { + return document.isDirty + }, + } + const originalTabs = Object.getOwnPropertyDescriptor(vscode.window.tabGroups, "all") + Object.defineProperty(vscode.window.tabGroups, "all", { + get: () => [{ tabs: [diffTab] }], + configurable: true, + }) + Object.assign(diffViewProvider, { + relPath: "mock-target-file.ts", + activeDiffEditor: { document }, + editType: "create", + createdDirs: [], + placeholderPath: mockTargetPath, + }) + vi.mocked(vscode.workspace.applyEdit).mockImplementation(async () => { + callOrder.push("applyEdit") + return true + }) + vi.mocked(vscode.window.tabGroups.close).mockImplementation(async () => { + callOrder.push("closeTab") + return true + }) + vi.mocked(fs.unlink).mockImplementation(async () => { + callOrder.push("unlink") + return undefined + }) + + try { + await diffViewProvider.discardUnapprovedStream() + } finally { + // Do not leak the tab fixture: later tests read the module-level tabGroups.all. + if (originalTabs) { + Object.defineProperty(vscode.window.tabGroups, "all", originalTabs) + } + } + + // The buffer is emptied before anything is closed, and the only content the discard + // writes is an empty buffer: a later save has nothing left to persist. + expect(callOrder.slice(0, 2)).toEqual(["applyEdit", "save"]) + const [, , replacedText] = mockWorkspaceEdit.replace.mock.calls[0] + expect(replacedText).toBe("") + // The tab is gone before the file is, so no save can recreate the abandoned file from a + // buffer the user never approved. + expect(callOrder.indexOf("closeTab")).toBeGreaterThan(-1) + expect(callOrder.indexOf("closeTab")).toBeLessThan(callOrder.indexOf("unlink")) + expect(fs.unlink).toHaveBeenCalledWith(mockTargetPath) + }) + + it("does nothing when no abandoned view is open", async () => { + Object.assign(diffViewProvider, { relPath: undefined, activeDiffEditor: undefined }) + + await diffViewProvider.discardUnapprovedStream() + + expect(fs.unlink).not.toHaveBeenCalled() + }) + }) + describe("isEditingDifferentPath and editingRelPath", () => { + // The production predicate the streaming guard and the different-path rejection both call. + // Everywhere else a test double stands in for it, so only these assertions can fail when the + // predicate itself regresses - for example to always reporting "not a different path". + it("reports no different path while no edit session is active", () => { + Object.assign(diffViewProvider, { isEditing: false, relPath: "leftover/path.ts" }) + + expect(diffViewProvider.isEditingDifferentPath("any/path.ts")).toBe(false) + expect(diffViewProvider.editingRelPath).toBeUndefined() + }) + + it("accepts the retained path and rejects another one", () => { + Object.assign(diffViewProvider, { isEditing: true, relPath: "retained/path.ts" }) + + expect(diffViewProvider.isEditingDifferentPath("retained/path.ts")).toBe(false) + expect(diffViewProvider.isEditingDifferentPath("other/path.ts")).toBe(true) + expect(diffViewProvider.editingRelPath).toBe("retained/path.ts") + }) + + it("compares the paths exactly as the caller spelled them", () => { + // Deliberately no normalisation: the predicate is a plain inequality, so a caller that hands + // over a differently spelled form of the retained path is treated as a second write. Pinning + // it here is what stops a later normalisation from silently widening the guard with nobody + // deciding that. + Object.assign(diffViewProvider, { isEditing: true, relPath: "dir/path.ts" }) + + expect(diffViewProvider.isEditingDifferentPath("./dir/path.ts")).toBe(true) + expect(diffViewProvider.isEditingDifferentPath("dir/path.ts")).toBe(false) + }) + }) + + describe("rollback and reset behavior this unit settles without a directive", () => { + // Each it below closes a line of the 50 blocking rows the mutation-diff leg published at + // p1066/u6-execute-error-path-cleanup d52c1614f6e4. The lines named here are the ones this + // unit's own diff defines: for each of them no earlier-merging unit in the chain + // (U3 #1931, U4 #1929, U5a #1930, U5b #2435) adds the same line against its own merge base, + // so the construct is this unit's to settle and no suppression directive is used anywhere. + // The names below describe behavior rather than quoting line numbers, because a name that + // quotes a line number goes stale against the next head. The mapping to the published blocking + // rows stays in this comment and travels with the PR body rather than with the names: nothing + // in this repository reads a test name to find a mutation row - scripts/stryker-diff.mjs matches + // test file names against source file names (its lines 337 to 341) and the PR comment workflow + // reads the Stryker report JSON - so renaming cannot orphan a row. + const settleRelPath = "settled-target-file.ts" + const settleTargetPath = `${mockCwd}/settled-target-file.ts` + + // The rollback reads only deref() off the task reference, and deref() off that task's + // providerRef, so these fixtures carry nothing else and are not assignable to Task. + // One cast inside this helper replaces the six `as unknown as WeakRef` casts these + // rows used to repeat: AGENTS.md asks for a single cast, made where the value is built, + // with the faked members named - deref on the reference, providerRef.deref on the task. + // The literal also carries [Symbol.toStringTag] because this project's Node typings + // declare that property on WeakRef, so a plain object literal is not assignable to the field. + const makeTaskRef = (task?: unknown): WeakRef => ({ + [Symbol.toStringTag]: "WeakRef", + deref: () => task as Task | undefined, + }) + + // revertChanges() reads only uri/getText/positionAt/isDirty/save off the diff document, + // so the double stays that narrow and every input the rollback decides on is an argument. + const makeRollbackDocument = (content: string, isDirty: boolean, saved: boolean) => ({ + uri: makeUri(settleTargetPath), + getText: vi.fn().mockReturnValue(content), + // Distinct answers per offset: a fixture that returned (0,0) for every offset could not tell a + // full-buffer range from an empty one. The Range double wraps whatever positions it is given. + positionAt: vi.fn((offset: number) => + offset === 0 ? { line: 0, character: 0 } : { line: 1, character: offset }, + ), + isDirty, + save: vi.fn().mockResolvedValue(saved), + }) + + const makeDirtyFileTab = () => ({ + input: Object.assign(new vscode.TabInputText(makeUri(settleTargetPath)), { + uri: makeUri(settleTargetPath), + }), + isDirty: true, + label: settleRelPath, + }) + + // Both fixtures below sit on module-level VS Code properties the provider reads live, so each + // run installs its own value and hands the original descriptor back rather than leaking state. + const withTabGroupsAll = (tabs: unknown[], run: () => Promise) => { + const original = Object.getOwnPropertyDescriptor(vscode.window.tabGroups, "all") + Object.defineProperty(vscode.window.tabGroups, "all", { get: () => [{ tabs }], configurable: true }) + return run().finally(() => { + if (original) { + Object.defineProperty(vscode.window.tabGroups, "all", original) + } + }) + } + + const withTextDocuments = (documents: unknown[], run: () => Promise) => { + const original = Object.getOwnPropertyDescriptor(vscode.workspace, "textDocuments") + Object.defineProperty(vscode.workspace, "textDocuments", { value: documents, configurable: true }) + return run().finally(() => { + if (original) { + Object.defineProperty(vscode.workspace, "textDocuments", original) + } + }) + } + + it("reports no different path when the session flag is up but its retained path is gone", () => { + // The guard's other exit. isEditing can stay true with relPath already cleared by a reset + // whose tab close rejected, and falling through to the comparison would then call every + // later write a second write, because undefined differs from every path. + Object.assign(diffViewProvider, { isEditing: true, relPath: undefined }) + + expect(diffViewProvider.isEditingDifferentPath("any/path.ts")).toBe(false) + }) + + it("restores the recorded content rather than an empty buffer when a new-file rollback meets a dirty diff buffer", async () => { + const document = makeRollbackDocument("partial model output", true, true) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "create", + createdDirs: [], + placeholderPath: undefined, + originalContent: "the content the file held before this write", + }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + + await withTabGroupsAll([makeDirtyFileTab()], () => diffViewProvider.revertChanges()) + + // Distinct positions prove the range spans the buffer: an empty or reversed range would hand + // the Range double the same position twice, and the uri is the document being rolled back. + const [replacedUri, , replacedText] = mockWorkspaceEdit.replace.mock.calls[0] + expect(replacedUri).toBe(document.uri) + expect(document.positionAt).toHaveBeenNthCalledWith(1, 0) + expect(document.positionAt).toHaveBeenNthCalledWith(2, "partial model output".length) + expect(replacedText).toBe("the content the file held before this write") + }) + + it("falls back to an empty buffer text, not a placeholder string, when a new-file rollback has no recorded original", async () => { + const document = makeRollbackDocument("partial model output", true, true) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "create", + createdDirs: [], + placeholderPath: undefined, + originalContent: undefined, + }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + + await withTabGroupsAll([makeDirtyFileTab()], () => diffViewProvider.revertChanges()) + + // Distinct positions prove the range spans the buffer: an empty or reversed range would hand + // the Range double the same position twice, and the uri is the document being rolled back. + const [replacedUri, , replacedText] = mockWorkspaceEdit.replace.mock.calls[0] + expect(replacedUri).toBe(document.uri) + expect(document.positionAt).toHaveBeenNthCalledWith(1, 0) + expect(document.positionAt).toHaveBeenNthCalledWith(2, "partial model output".length) + expect(replacedText).toBe("") + }) + + it("reports the unconfirmed save of the diff buffer it just restored, naming the path and the stopped work", async () => { + // applyEdit confirmed, document.save() did not: the rollback stops before any close or + // unlink, and the report is the only thing the caller gets, so it has to carry the reason. + const document = makeRollbackDocument("partial model output", true, false) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "create", + createdDirs: [], + placeholderPath: settleTargetPath, + originalContent: "", + }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + + await withTabGroupsAll([makeDirtyFileTab()], async () => { + await expect(diffViewProvider.revertChanges()).rejects.toThrowError( + new Error( + `Rollback could not save the restored buffer for ${settleTargetPath}; its clean state is unconfirmed, so the rollback stopped before closing tabs or deleting the file.`, + ), + ) + }) + + expect(vscode.window.tabGroups.close).not.toHaveBeenCalled() + expect(fs.unlink).not.toHaveBeenCalled() + }) + + it("restores the recorded content rather than an empty buffer when an existing file is rolled back", async () => { + const document = makeRollbackDocument("streamed content", false, true) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "modify", + createdDirs: [], + originalContent: "the content the file held before this write", + }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["keepOrCloseEditedFile"] = vi.fn().mockResolvedValue(undefined) + + await diffViewProvider.revertChanges() + + const [, , replacedText] = mockWorkspaceEdit.replace.mock.calls[0] + expect(replacedText).toBe("the content the file held before this write") + }) + + it("strips an empty buffer text rather than a stand-in when a modify rollback has no recorded original", async () => { + const document = makeRollbackDocument("streamed content", false, true) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "modify", + createdDirs: [], + originalContent: undefined, + }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["keepOrCloseEditedFile"] = vi.fn().mockResolvedValue(undefined) + + await diffViewProvider.revertChanges() + + const [, , replacedText] = mockWorkspaceEdit.replace.mock.calls[0] + expect(replacedText).toBe("") + }) + + it("rolls back to the centralized defaults when the task behind the rollback is gone", async () => { + // revertChanges() reads its auto-close settings through taskRef -> providerRef -> getState(). + // Any link of that chain can already be gone by the time a denial lands, and a rollback that + // throws while reading them would take the session teardown with it. It must instead fall + // back to the same defaults saveChanges() uses. + const document = makeRollbackDocument("streamed content", false, true) + const keepOrClose = vi.fn().mockResolvedValue(undefined) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "modify", + createdDirs: [], + originalContent: "original", + }) + diffViewProvider["taskRef"] = makeTaskRef() + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["keepOrCloseEditedFile"] = keepOrClose + + await diffViewProvider.revertChanges() + + const args = keepOrClose.mock.calls[0] + expect(args[0]).toBe(settleTargetPath) + expect(args[1]).toBe(false) + expect(args[2]).toBe(DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES) + expect(args[3]).toBe(DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED) + expect(args[4]).toBe(DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES) + }) + + it("rolls back to the centralized defaults when the task no longer holds a provider", async () => { + const document = makeRollbackDocument("streamed content", false, true) + const keepOrClose = vi.fn().mockResolvedValue(undefined) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "modify", + createdDirs: [], + originalContent: "original", + }) + diffViewProvider["taskRef"] = makeTaskRef({ providerRef: { deref: () => undefined } }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["keepOrCloseEditedFile"] = keepOrClose + + await diffViewProvider.revertChanges() + + const args = keepOrClose.mock.calls[0] + expect(args[2]).toBe(DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES) + expect(args[3]).toBe(DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED) + expect(args[4]).toBe(DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES) + }) + + it("carries the settings the state holds through the rollback path", async () => { + // The rollback path is the one the auto-close decision table never exercised: every row of + // that table drives saveChanges(). Opting in on the rollback path has to close the tab, or + // the settings would mean one thing on accept and another on deny. + const document = makeRollbackDocument("streamed content", false, true) + const closeFileTab = vi.fn().mockResolvedValue(undefined) + const showEditedFile = vi.fn().mockResolvedValue(undefined) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "modify", + createdDirs: [], + originalContent: "original", + documentWasOpen: false, + userTouchedDocument: false, + userTouchedDiffEditor: false, + }) + diffViewProvider["taskRef"] = makeTaskRef( + makeTaskDouble({ + autoCloseZooOpenedFiles: true, + autoCloseZooOpenedFilesAfterUserEdited: true, + autoCloseZooOpenedNewFiles: true, + }), + ) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["closeFileTab"] = closeFileTab + diffViewProvider["showEditedFileWithoutDisruptingFocus"] = showEditedFile + + await diffViewProvider.revertChanges() + + expect(closeFileTab).toHaveBeenCalledWith(settleTargetPath) + expect(showEditedFile).not.toHaveBeenCalled() + }) + + it("forwards the three settings in the slots the decision reads them from", async () => { + // The outcome of this footing cannot tell the two unreadable settings apart: with the base + // auto-close off and a modify rollback, the tab is kept whichever value the after-user-edited + // and new-files arguments hold. Only the arguments themselves can show that the values state + // holds reach keepOrCloseEditedFile in their own slots rather than as centralized defaults - + // and the two assertions below fail when a forwarded value is replaced by its default, + // while a swap of the two settings that share a value here would still pass. + const document = makeRollbackDocument("streamed content", false, true) + const keepOrClose = vi.fn().mockResolvedValue(undefined) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "modify", + createdDirs: [], + originalContent: "original", + documentWasOpen: false, + userTouchedDocument: false, + userTouchedDiffEditor: false, + }) + diffViewProvider["taskRef"] = makeTaskRef( + makeTaskDouble({ + autoCloseZooOpenedFiles: false, + autoCloseZooOpenedFilesAfterUserEdited: true, + autoCloseZooOpenedNewFiles: false, + }), + ) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["keepOrCloseEditedFile"] = keepOrClose + + await diffViewProvider.revertChanges() + + const args = keepOrClose.mock.calls[0] + expect(args[2]).toBe(false) + expect(args[3]).toBe(true) + expect(args[4]).toBe(false) + }) + it("pins the new-files argument in its own slot on the same unreadable footing", async () => { + // The row above sets the two settings the decision cannot read to distinct values only for the + // after-user-edited slot; autoCloseZooOpenedNewFiles shares its value with the base setting + // there, so dropping its forward would pass. Flipping only that flag here makes the same + // assertion catch it, and the two rows together pin all three arguments against being + // replaced by their centralized defaults on a path where the outcome cannot tell them apart. + const document = makeRollbackDocument("streamed content", false, true) + const keepOrClose = vi.fn().mockResolvedValue(undefined) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "modify", + createdDirs: [], + originalContent: "original", + documentWasOpen: false, + userTouchedDocument: false, + userTouchedDiffEditor: false, + }) + diffViewProvider["taskRef"] = makeTaskRef( + makeTaskDouble({ + autoCloseZooOpenedFiles: false, + autoCloseZooOpenedFilesAfterUserEdited: false, + autoCloseZooOpenedNewFiles: true, + }), + ) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["keepOrCloseEditedFile"] = keepOrClose + + await diffViewProvider.revertChanges() + + const args = keepOrClose.mock.calls[0] + expect(args[2]).toBe(false) + expect(args[3]).toBe(false) + expect(args[4]).toBe(true) + }) + + it("keeps the tab on the rollback path when the user touched the document and the after-user-edited setting is off", async () => { + // The touched-document branch is the only one where autoCloseZooOpenedFilesAfterUserEdited decides + // the outcome on a modify rollback, and it is the only branch where autoCloseZooOpenedNewFiles is + // unreadable. Setting the three flags to distinct values here means a wrong forwarded value moves + // the outcome: base on + after-user-edited on would close, new-files on alone would close. + const document = makeRollbackDocument("streamed content", false, true) + const closeFileTab = vi.fn().mockResolvedValue(undefined) + const showEditedFile = vi.fn().mockResolvedValue(undefined) + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "modify", + createdDirs: [], + originalContent: "original", + documentWasOpen: false, + userTouchedDocument: true, + userTouchedDiffEditor: false, + }) + diffViewProvider["taskRef"] = makeTaskRef( + makeTaskDouble({ + autoCloseZooOpenedFiles: true, + autoCloseZooOpenedFilesAfterUserEdited: false, + autoCloseZooOpenedNewFiles: false, + }), + ) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true) + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["closeFileTab"] = closeFileTab + diffViewProvider["showEditedFileWithoutDisruptingFocus"] = showEditedFile + + await diffViewProvider.revertChanges() + + expect(closeFileTab).not.toHaveBeenCalled() + expect(showEditedFile).toHaveBeenCalledWith(settleTargetPath) + }) + + it("stops the rollback and reports the refused restore of the file-scheme buffer by name", async () => { + // The diff-side restore confirms; the plain file-scheme buffer holding the same unapproved + // content is the one VS Code refuses to put back. Closing it anyway would hand the user a + // save prompt over exactly the content this rollback discards. + const document = makeRollbackDocument("partial model output", true, true) + const streamedBuffer = { + uri: makeUri(settleTargetPath), + scheme: "file", + getText: vi.fn().mockReturnValue("partial model output"), + positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }), + isDirty: true, + save: vi.fn().mockResolvedValue(true), + } + Object.assign(diffViewProvider, { + relPath: settleRelPath, + activeDiffEditor: { document }, + editType: "create", + createdDirs: [], + placeholderPath: settleTargetPath, + originalContent: "", + }) + vi.mocked(vscode.workspace.applyEdit).mockResolvedValueOnce(true).mockResolvedValueOnce(false) + + await withTextDocuments([streamedBuffer], () => + withTabGroupsAll([makeDirtyFileTab()], async () => { + await expect(diffViewProvider.revertChanges()).rejects.toThrowError( + new Error( + `Rollback could not restore the buffer for ${settleTargetPath}; it may still hold unapproved content, so the tab was left open rather than closed.`, + ), + ) + }), + ) + + expect(streamedBuffer.save).not.toHaveBeenCalled() + expect(vscode.window.tabGroups.close).not.toHaveBeenCalled() + expect(fs.unlink).not.toHaveBeenCalled() + }) + + it("clears every session field the reset owns, not only the ones with a visible effect", async () => { + // A flag that survives reset() is read by the NEXT edit as if it described that edit: + // documentWasOpen decides whether the tab is restored instead of closed, the two touched + // flags decide auto-close, and streamedLines/preDiagnostics/snapshotPreviewTabs carry one + // edit's stream, diagnostics and tab snapshot into the next one. + Object.assign(diffViewProvider, { + documentWasOpen: true, + documentWasPinned: true, + streamedLines: ["leftover streamed line"], + preDiagnostics: [{ message: "leftover diagnostic" }], + userTouchedDocument: true, + userTouchedDiffEditor: true, + snapshotPreviewTabs: [makePreviewTab(`${mockCwd}/leftover-preview.ts`)], + // The three fields below have no visible effect, which is why this case used to + // stop at the flags above: createdDirs lists the directories this edit created + // and would roll back, newContent is the content the edit accumulated for its + // write, and originalContent is the file's content on disk before the edit, + // which revertChanges() needs to put back. reset() clears all three, and a + // stale one would be read by the next edit exactly like the flags above. + createdDirs: [`${mockCwd}/new-parent`, `${mockCwd}/new-parent/nested`], + newContent: "new content", + originalContent: "Original content\n", + }) + + await diffViewProvider.reset() + + expect(diffViewProvider["documentWasOpen"]).toBe(false) + expect(diffViewProvider["documentWasPinned"]).toBe(false) + expect(diffViewProvider["userTouchedDocument"]).toBe(false) + expect(diffViewProvider["userTouchedDiffEditor"]).toBe(false) + expect(diffViewProvider["streamedLines"]).toEqual([]) + expect(diffViewProvider["preDiagnostics"]).toEqual([]) + expect(diffViewProvider["snapshotPreviewTabs"]).toEqual([]) + expect(diffViewProvider["createdDirs"]).toEqual([]) + expect(diffViewProvider["newContent"]).toBeUndefined() + expect(diffViewProvider["originalContent"]).toBeUndefined() + }) + }) })