From fca690c82eb6cee0db9cecb246965dd73943e5c5 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Thu, 27 Aug 2026 17:42:34 +0800 Subject: [PATCH 01/13] feat(editor): async post-save diagnostics on chat-diff save path (L1, #1375) (cherry picked from commit 991ab693526f1d9527fe8278a2e06f68b6575508) --- src/core/task/Task.ts | 9 ++ .../webview/__tests__/ClineProvider.spec.ts | 20 +-- src/integrations/editor/DiffViewProvider.ts | 124 ++++++++++++++---- .../editor/__tests__/DiffViewProvider.spec.ts | 25 +++- 4 files changed, 143 insertions(+), 35 deletions(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index e2e25ef93da..11b89007724 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -3763,6 +3763,15 @@ export class Task extends EventEmitter implements TaskLike { // could still build tools and call `createMessage()`. this.requestDispose() + // Stop post-save diagnostics tails that are still waiting on their delay. A + // disposed task cannot receive their say() emit, and without this the timer (and + // the provider + diagnostics snapshot it holds) survives the teardown. + try { + this.diffViewProvider.cancelPostSaveDiagnosticsTails() + } catch (error) { + console.error("Error cancelling post-save diagnostics tails:", error) + } + // Cancel any in-progress HTTP request try { this.cancelCurrentRequest() diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index b364b5baa79..0b154472537 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6875,12 +6875,17 @@ describe("Project MCP Settings", () => { const expectedRooDir = path.join("/test/workspace", ".roo") const expectedMcpPath = path.join(expectedRooDir, "mcp.json") - // Check that fs.mkdir was called with the correct path - expect(mockedFs.mkdir).toHaveBeenCalledWith(expectedRooDir, { recursive: true }) + // The handler must not create .roo itself: a dangling symlink there resolves + // outside the workspace, and creating that parent is exactly what confinement is + // supposed to prevent. safeWriteJson creates it, but only after its scope check. + expect(mockedFs.mkdir).not.toHaveBeenCalledWith(expectedRooDir, { recursive: true }) expect(pathUtils.getWorkspacePath).toHaveBeenCalled() - // Verify file was created with default content - expect(safeWriteJson).toHaveBeenCalledWith(expectedMcpPath, { mcpServers: {} }, { prettyPrint: true }) + // The project-scoped write carries the workspace root as its confinement scope. + expect(safeWriteJson).toHaveBeenCalledWith(expectedMcpPath, { mcpServers: {} }, { + prettyPrint: true, + confineTo: "/test/workspace", + }) // Check that openFile was called expect(openFileSpy).toHaveBeenCalledWith(expectedMcpPath) @@ -6909,10 +6914,9 @@ describe("Project MCP Settings", () => { const pathUtils = await import("../../../utils/path") vi.mocked(pathUtils.getWorkspacePath).mockReturnValue("/test/workspace") - // Mock fs functions to fail - const fs = await import("fs/promises") - const mockedFs = vi.mocked(fs) - mockedFs.mkdir.mockRejectedValue(new Error("Failed to create directory")) + // The handler no longer creates the directory itself, so the failure has to come + // from the confined write. + vi.mocked(safeWriteJson).mockRejectedValueOnce(new Error("Failed to create directory")) // Trigger openProjectMcpSettings await messageHandler({ diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 3c1d33ae283..90340d89c1f 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -46,6 +46,10 @@ export class DiffViewProvider { private streamedLines: string[] = [] private preDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [] private preEditScrollLine: number | undefined + // One controller per post-save diagnostics tail that is still waiting, so task + // disposal can cancel the wait instead of leaving a timer (and this provider and + // the pre-save diagnostics snapshot it closes over) running past the teardown. + private readonly postSaveTails = new Set() // Tracks whether the user activated the target file's editor tab during the // diff session. When the file was not already open before the edit, we only // keep it open afterward if the user explicitly interacted with it. @@ -1152,8 +1156,11 @@ export class DiffViewProvider { }> { const absolutePath = path.resolve(this.cwd, relPath) - // Get diagnostics before editing the file - this.preDiagnostics = vscode.languages.getDiagnostics() + // Get diagnostics before editing the file. Capture the snapshot locally: + // overlapping saveDirectly calls (multi-file edits) must not let a later + // call overwrite this one's baseline before its diagnostics tail runs. + const preDiagnostics = vscode.languages.getDiagnostics() + this.preDiagnostics = preDiagnostics // Write the content directly to the file await createDirectoriesForFile(absolutePath) @@ -1176,23 +1183,83 @@ export class DiffViewProvider { await doc.save() } - // Force a small delay to ensure diagnostics are triggered - await new Promise((resolve) => setTimeout(resolve, 100)) + // The 100 ms diagnostics-settle wait is carried by the + // emitPostSaveDiagnostics tail (inMemoryDocument) instead of here: + // blocking the save path delayed every openFile=false save even when + // diagnostics were disabled or the write delay was 0. } - let newProblemsMessage = "" - + // L1 (A2): resolve without awaiting the LSP diagnostics settle. The + // diagnostics check becomes a fire-and-forget tail that emits any new + // problems via the existing "error" ClineSay type; the returned + // newProblemsMessage is therefore always undefined. if (diagnosticsEnabled) { - // Add configurable delay to allow linters time to process - const safeDelayMs = Math.max(0, writeDelayMs) + // The method's outer try/catch guarantees it never rejects, so the + // fire-and-forget call needs no .catch wrapper. + void this.emitPostSaveDiagnostics(relPath, writeDelayMs, preDiagnostics, !openFile) + } + + // Store the results for formatFileWriteResponse + this.newProblemsMessage = undefined + this.userEdits = undefined + this.relPath = relPath + this.newContent = content + return { + newProblemsMessage: undefined, + userEdits: undefined, + finalContent: content, + } + } + + // L1 (A2): fire-and-forget post-save diagnostics. After the write delay, + // collects new Error-severity problems and emits them via the existing + // "error" ClineSay type (only Error-severity diagnostics reach this branch; + // "error" carries no task-failure semantics in core). Abort-safe: say() + // rejects when the task is aborted, so the whole body sits inside a + // try/catch that degrades to a console.warn — the tail can never reject. + // The wait itself is registered in postSaveTails so Task disposal can cancel + // it: an unregistered delay keeps the timer, this provider and the pre-save + // diagnostics snapshot alive past disposal, and the tail then does stale + // diagnostics work against a task that is already gone. + private async emitPostSaveDiagnostics( + relPath: string, + writeDelayMs: number, + preDiagnostics: [vscode.Uri, vscode.Diagnostic[]][], + inMemoryDocument = false, + ): Promise { + const controller = new AbortController() + this.postSaveTails.add(controller) + try { + // Add configurable delay to allow linters time to process. When the + // document was opened in memory (openFile=false), the tail also + // carries the 100 ms diagnostics-settle wait that used to block + // saveDirectly. The signal is the disposal hook: delay() rejects with + // AbortError once the task is gone, which is the tail's expected end. + const safeDelayMs = Math.max(0, writeDelayMs) + (inMemoryDocument ? 100 : 0) try { - await delay(safeDelayMs) + await delay(safeDelayMs, { signal: controller.signal }) } catch (error) { - console.warn(`Failed to apply write delay: ${error}`) + if (controller.signal.aborted) { + return + } + throw error + } + // A cancellation can also land between the wait resolving and the work + // starting; either way nothing is queried or emitted after it. + if (controller.signal.aborted) { + return } - const postDiagnostics = vscode.languages.getDiagnostics() + // Filter to the saved file: saveDirectly resolves before this tail + // completes, so in a multi-file write sequence (e.g. apply_patch) + // a later file's problems must not be attributed to this relPath. + const savedFilePath = path.resolve(this.cwd, relPath) + // arePathsEqual: case-insensitive on Windows, where a relPath whose + // casing differs from the diagnostic URI is still the same file. + const postDiagnostics = vscode.languages + .getDiagnostics() + .filter(([uri]) => arePathsEqual(uri.fsPath, savedFilePath)) // Get diagnostic settings from state const task = this.taskRef.deref() @@ -1201,27 +1268,36 @@ export class DiffViewProvider { const maxDiagnosticMessages = state?.maxDiagnosticMessages ?? 50 const newProblems = await diagnosticsToProblemsString( - getNewDiagnostics(this.preDiagnostics, postDiagnostics), + getNewDiagnostics(preDiagnostics, postDiagnostics), [vscode.DiagnosticSeverity.Error], this.cwd, includeDiagnosticMessages, maxDiagnosticMessages, ) - newProblemsMessage = - newProblems.length > 0 ? `\n\nNew problems detected after saving the file:\n${newProblems}` : "" + if (newProblems.length > 0) { + await task?.say("error", `New problems detected after saving file: ${relPath}\n\n${newProblems}`) + } + } catch (error) { + // Abort-safe: never let a post-save diagnostic emit become an + // unhandled rejection (say() rejects when the task is aborted). + console.warn(`Post-save diagnostics emit failed: ${error}`) } + finally { + this.postSaveTails.delete(controller) + } + } - // Store the results for formatFileWriteResponse - this.newProblemsMessage = newProblemsMessage - this.userEdits = undefined - this.relPath = relPath - this.newContent = content - - return { - newProblemsMessage, - userEdits: undefined, - finalContent: content, + /** + * Cancel post-save diagnostics tails that are still waiting. Called when the + * owning task is disposed. Deliberately NOT called from reset(): reset follows a + * successful write, and the tail that write started still has to report the + * problems it is waiting for. + */ + public cancelPostSaveDiagnosticsTails(): void { + for (const controller of this.postSaveTails) { + controller.abort() } + this.postSaveTails.clear() } } diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index e94a66e1db2..5250dece4df 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -28,7 +28,14 @@ vi.mock("../../../utils/fs", () => ({ // Mock path vi.mock("path", () => ({ resolve: vi.fn((cwd, relPath) => `${cwd}/${relPath}`), + normalize: vi.fn((p: string) => p), basename: vi.fn((path) => path.split("/").pop()), + dirname: vi.fn((path) => path.split("/").slice(0, -1).join("/") || "/"), + join: (...args: string[]) => args.join("/"), + // diagnosticsToProblemsString formats its output header via + // path.relative(cwd, uri.fsPath).toPosix(); the object-with-toPosix shape + // mirrors the repo's own diagnostics.spec.ts mock. + relative: vi.fn((cwd: string, p: string) => ({ toPosix: () => p.replace(`${cwd}/`, "") })), })) // Mock vscode @@ -792,12 +799,17 @@ describe("DiffViewProvider", () => { { preview: false, preserveFocus: true }, ) - // Verify diagnostics were checked after delay + // L1: saveDirectly resolves before the fire-and-forget diagnostics + // tail runs; flush one macrotask tick so the mocked delay (and the + // post-write getDiagnostics) have been reached before asserting. + await new Promise((resolve) => setTimeout(resolve, 0)) + + // Verify the tail applied the configured write delay expect(mockDelay).toHaveBeenCalledWith(2000) expect(vscode.languages.getDiagnostics).toHaveBeenCalled() - // Verify result - expect(result.newProblemsMessage).toBe("") + // Verify result: L1 no longer returns a problems message + expect(result.newProblemsMessage).toBeUndefined() expect(result.userEdits).toBeUndefined() expect(result.finalContent).toBe("new content") }) @@ -828,6 +840,10 @@ describe("DiffViewProvider", () => { expect(mockDelay).not.toHaveBeenCalled() // getDiagnostics is called once for pre-diagnostics, but not for post-diagnostics expect(vscode.languages.getDiagnostics).toHaveBeenCalledTimes(1) + + // L1: no diagnostics tail is launched, so nothing is ever emitted + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(mockTask.say).not.toHaveBeenCalled() }) it("should handle negative delay values", async () => { @@ -836,6 +852,9 @@ describe("DiffViewProvider", () => { await diffViewProvider.saveDirectly("test.ts", "new content", true, true, -500) + // L1: the tail runs after resolve; flush one macrotask tick first. + await new Promise((resolve) => setTimeout(resolve, 0)) + // Verify delay was called with 0 (safe minimum) expect(mockDelay).toHaveBeenCalledWith(0) }) From 31e6ae4e535e6795765e668f2daa74d72cfc02bd Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Thu, 8 Oct 2026 23:28:05 +0800 Subject: [PATCH 02/13] fix(editor): re-check cancellation before persisting a post-save diagnostic row The post-save tail awaits the diagnostic settings and then the problem formatting. Both awaits can outlive the task: the emit below calls task.say("error", ...), which PERSISTS an error row, so it must not start once the caller has been disposed. The re-check after the settings read already existed; the one after the formatting call was missing. Test: 'stops a post-save tail that is cancelled while the diagnostic settings are read' - a real pending problem is staged, the settings read resolves AFTER the cancellation, and the tail must not emit. Disclosure: this test pins the observable contract; it is not a per-line negative control - neutering each of the four abort checks in the tail individually still passes, because the emit is also blocked further down the path. Reported as such rather than claimed as a pin. Local: DiffViewProvider.spec + mcpWriteScope.spec + McpHub.spec = 157 passed / 0 failed; tsc --noEmit 0; eslint 0 err / 0 warn on both touched files. (cherry picked from commit 678bce8a82ab9f8b9798e5b9cf0d3386162eb610) --- src/integrations/editor/DiffViewProvider.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 90340d89c1f..0805f410b9e 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -1275,6 +1275,13 @@ export class DiffViewProvider { maxDiagnosticMessages, ) + // Formatting is awaited too, so a cancellation can land inside it. The emit below + // persists an error row into the task, so it must not start once the caller is gone: + // say() would otherwise be dropped or land in a task the user already left. + if (controller.signal.aborted) { + return + } + if (newProblems.length > 0) { await task?.say("error", `New problems detected after saving file: ${relPath}\n\n${newProblems}`) } From 38856499bedf000f3f58abc067acc71aead245bb Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Fri, 9 Oct 2026 01:50:04 +0800 Subject: [PATCH 03/13] test(editor): teach the write-delay assertions about the tail's abort signal The L1 tail passes { signal } to delay() so task disposal can cancel a wait that is still pending. Four existing assertions pinned delay(ms) with one argument and therefore failed once the tail registered its controller. Updated to expect the signal object. Local: DiffViewProvider.spec 79 passed / 0 failed (71 at the base + 8 from this unit); src-level tsc --noEmit 62 = the worktree baseline; eslint 0 err / 0 warn on all four files. --- src/integrations/editor/__tests__/DiffViewProvider.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 5250dece4df..786e229d8bf 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -805,7 +805,7 @@ describe("DiffViewProvider", () => { await new Promise((resolve) => setTimeout(resolve, 0)) // Verify the tail applied the configured write delay - expect(mockDelay).toHaveBeenCalledWith(2000) + expect(mockDelay).toHaveBeenCalledWith(2000, expect.objectContaining({ signal: expect.any(AbortSignal) })) expect(vscode.languages.getDiagnostics).toHaveBeenCalled() // Verify result: L1 no longer returns a problems message @@ -856,7 +856,7 @@ describe("DiffViewProvider", () => { await new Promise((resolve) => setTimeout(resolve, 0)) // Verify delay was called with 0 (safe minimum) - expect(mockDelay).toHaveBeenCalledWith(0) + expect(mockDelay).toHaveBeenCalledWith(0, expect.objectContaining({ signal: expect.any(AbortSignal) })) }) it("should store results for formatFileWriteResponse", async () => { From 40d9fa55cc696da9cf2a0a1f779aa8d2e1856c5d Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Fri, 9 Oct 2026 01:59:51 +0800 Subject: [PATCH 04/13] test(webview): drop the MCP-confinement assertions from this unit Those two hunks came in with the 7996380c0 patch, but they assert the .roo/mcp.json confinement that lives in #1405 (webviewMessageHandler + safeWriteJson confineTo), not in this branch. Without that production change the assertions are false: on Windows platform-unit-test failed at 'expect(mockedFs.mkdir).not.toHaveBeenCalledWith(...)' because this branch's handler still creates .roo itself. Reverted to the base version of the file; the confinement coverage stays where the production change is - #1405. Local: src-level tsc --noEmit 62 = baseline; ClineProvider.spec 'Project MCP Settings' green again. --- .../webview/__tests__/ClineProvider.spec.ts | 20 ++++++++----------- 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 0b154472537..b364b5baa79 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6875,17 +6875,12 @@ describe("Project MCP Settings", () => { const expectedRooDir = path.join("/test/workspace", ".roo") const expectedMcpPath = path.join(expectedRooDir, "mcp.json") - // The handler must not create .roo itself: a dangling symlink there resolves - // outside the workspace, and creating that parent is exactly what confinement is - // supposed to prevent. safeWriteJson creates it, but only after its scope check. - expect(mockedFs.mkdir).not.toHaveBeenCalledWith(expectedRooDir, { recursive: true }) + // Check that fs.mkdir was called with the correct path + expect(mockedFs.mkdir).toHaveBeenCalledWith(expectedRooDir, { recursive: true }) expect(pathUtils.getWorkspacePath).toHaveBeenCalled() - // The project-scoped write carries the workspace root as its confinement scope. - expect(safeWriteJson).toHaveBeenCalledWith(expectedMcpPath, { mcpServers: {} }, { - prettyPrint: true, - confineTo: "/test/workspace", - }) + // Verify file was created with default content + expect(safeWriteJson).toHaveBeenCalledWith(expectedMcpPath, { mcpServers: {} }, { prettyPrint: true }) // Check that openFile was called expect(openFileSpy).toHaveBeenCalledWith(expectedMcpPath) @@ -6914,9 +6909,10 @@ describe("Project MCP Settings", () => { const pathUtils = await import("../../../utils/path") vi.mocked(pathUtils.getWorkspacePath).mockReturnValue("/test/workspace") - // The handler no longer creates the directory itself, so the failure has to come - // from the confined write. - vi.mocked(safeWriteJson).mockRejectedValueOnce(new Error("Failed to create directory")) + // Mock fs functions to fail + const fs = await import("fs/promises") + const mockedFs = vi.mocked(fs) + mockedFs.mkdir.mockRejectedValue(new Error("Failed to create directory")) // Trigger openProjectMcpSettings await messageHandler({ From 62acc2bd43d204d2554916d484cef88dc9d070bd Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Fri, 9 Oct 2026 02:38:02 +0800 Subject: [PATCH 05/13] fix(editor): latch post-save diagnostics tails against a tail started after disposal Lifecycle: cancelPostSaveDiagnosticsTails() only aborted the controllers that existed at that moment. saveDirectly awaits createDirectoriesForFile, writeFile and the document open/show before it starts the tail, so a save that was already in flight could register a NEW tail after Task disposal had cancelled everything - the tail then called say() on a disposed task and kept the provider and diagnostics snapshot it captured alive. cancelPostSaveDiagnosticsTails() now sets a tailsDisposed latch and emitPostSaveDiagnostics returns before registering a controller once it is set. The latch is set before the aborts so no window exists between the two. Tests: DiffViewProvider 'does not start a post-save diagnostics tail once the tails have been cancelled' (cancel first, then saveDirectly with diagnostics enabled -> delay never called, say never called); Task 'cancels post-save diagnostics tails when the task is disposed' and 'continues disposal when cancelling the post-save diagnostics tails throws' (the step after the cancel in the same teardown still runs, and the failure is logged). Negative controls: drop the latch check -> 1 failed; drop the latch assignment -> 1 failed; remove the try/catch in disposeOnce -> 1 failed. Restored -> 80 passed and 2 passed. Local: DiffViewProvider.spec 80 passed / 0 failed; Task.spec tails tests 2 passed; src-level tsc --noEmit 62 = the worktree baseline; eslint 0 err / 0 warn on all four files. --- src/core/task/__tests__/Task.spec.ts | 26 +++++++++++++++++++++ src/integrations/editor/DiffViewProvider.ts | 10 ++++++++ 2 files changed, 36 insertions(+) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 5438453c2cf..146de512632 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7338,6 +7338,32 @@ describe("Cline", () => { expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Timed out")) }) + it("cancels post-save diagnostics tails when the task is disposed", async () => { + const task = new Task({ provider: mockProvider, apiConfiguration: mockApiConfig, task: "test task", startTask: false }) + const cancelSpy = vi + .spyOn(task.diffViewProvider, "cancelPostSaveDiagnosticsTails") + .mockImplementation(() => {}) + await task.disposeOnce() + expect(cancelSpy).toHaveBeenCalledTimes(1) + }) + + it("continues disposal when cancelling the post-save diagnostics tails throws", async () => { + const task = new Task({ provider: mockProvider, apiConfiguration: mockApiConfig, task: "test task", startTask: false }) + vi.spyOn(task.diffViewProvider, "cancelPostSaveDiagnosticsTails").mockImplementation(() => { + throw new Error("cancel boom") + }) + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + // The step after the cancel in the same teardown: if the throw escaped, this would + // never run and the HTTP request would keep streaming into a dead task. + const cancelRequestSpy = vi.spyOn(task, "cancelCurrentRequest").mockImplementation(() => {}) + await task.disposeOnce() + expect(cancelRequestSpy).toHaveBeenCalled() + expect(errorSpy).toHaveBeenCalledWith( + expect.stringContaining("Error cancelling post-save diagnostics tails:"), + expect.any(Error), + ) + }) + it("refuses to send a request when the task is disposed during the bounded metadata wait", async () => { // Disposal alone — no cancel button, no abortTask — must make the // task observe cancellation: disposeOnce sets the abort state diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 0805f410b9e..7eb24410d1c 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -50,6 +50,10 @@ export class DiffViewProvider { // disposal can cancel the wait instead of leaving a timer (and this provider and // the pre-save diagnostics snapshot it closes over) running past the teardown. private readonly postSaveTails = new Set() + // Latched once Task disposal has cancelled the tails. A save that was already awaiting + // its file operations can still reach the tail start after that point, and a tail that + // begins after disposal would emit into a dead task and keep its providers alive. + private tailsDisposed = false // Tracks whether the user activated the target file's editor tab during the // diff session. When the file was not already open before the edit, we only // keep it open afterward if the user explicitly interacted with it. @@ -1228,6 +1232,11 @@ export class DiffViewProvider { preDiagnostics: [vscode.Uri, vscode.Diagnostic[]][], inMemoryDocument = false, ): Promise { + if (this.tailsDisposed) { + // Disposal already ran: emitting now would call say() on a disposed task. + return + } + const controller = new AbortController() this.postSaveTails.add(controller) try { @@ -1302,6 +1311,7 @@ export class DiffViewProvider { * problems it is waiting for. */ public cancelPostSaveDiagnosticsTails(): void { + this.tailsDisposed = true for (const controller of this.postSaveTails) { controller.abort() } From e14f3fd3c6badf3282f33e6b43e10b0b79ad282b Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Fri, 9 Oct 2026 02:39:21 +0800 Subject: [PATCH 06/13] fix(test): reach the private disposeOnce with bracket notation task.disposeOnce() is private, so the two new tests failed src-level tsc with TS2341. Bracket notation is the convention this repo uses for private members in tests. Local: src-level tsc --noEmit back to 62 = the worktree baseline; tails tests 2 passed. --- src/core/task/__tests__/Task.spec.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 146de512632..7cc9d6dab73 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7343,7 +7343,8 @@ describe("Cline", () => { const cancelSpy = vi .spyOn(task.diffViewProvider, "cancelPostSaveDiagnosticsTails") .mockImplementation(() => {}) - await task.disposeOnce() + // disposeOnce is private; bracket notation is the repo's convention for it. + await task["disposeOnce"]() expect(cancelSpy).toHaveBeenCalledTimes(1) }) @@ -7356,7 +7357,8 @@ describe("Cline", () => { // The step after the cancel in the same teardown: if the throw escaped, this would // never run and the HTTP request would keep streaming into a dead task. const cancelRequestSpy = vi.spyOn(task, "cancelCurrentRequest").mockImplementation(() => {}) - await task.disposeOnce() + // disposeOnce is private; bracket notation is the repo's convention for it. + await task["disposeOnce"]() expect(cancelRequestSpy).toHaveBeenCalled() expect(errorSpy).toHaveBeenCalledWith( expect.stringContaining("Error cancelling post-save diagnostics tails:"), From 6fbd26a52a506cd49f9fb0295abe6c6f0ee747ed Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 10 Oct 2026 19:02:11 +0800 Subject: [PATCH 07/13] fix(editor): emit post-save diagnostics as a non-interactive say The diagnostics tail runs writeDelayMs after saveDirectly resolved, so by the time it emits, the task has usually moved on and may be sitting in ask() waiting for the user - approval of the next tool, completion_result. say() bumps lastMessageTs unless the message is marked non-interactive, and ask()'s pWaitFor reads a moved lastMessageTs as "superseded": the pending ask throws AskIgnoredError even though the user never answered. An informational message about a problem the user cannot act on yet was therefore able to cancel the decision they were making. The trigger is ordinary - a save that introduces an Error-severity diagnostic, followed by any ask left unanswered past the write delay. The tail now passes isNonInteractive, the same way every other asynchronous say in Task does. The "error" channel and the message text are unchanged, so nothing the webview or the conversation history sees is different; only the lastMessageTs side effect is gone. The existing emit test asserted the call with two arguments, which couples it to the signature; it now checks the channel and the text by position. A new test pins the flag itself, so removing it fails exactly that test. --- src/integrations/editor/DiffViewProvider.ts | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 7eb24410d1c..f87f0ebb1f0 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -1292,14 +1292,28 @@ export class DiffViewProvider { } if (newProblems.length > 0) { - await task?.say("error", `New problems detected after saving file: ${relPath}\n\n${newProblems}`) + // This tail runs writeDelayMs after saveDirectly resolved, so the task has usually + // moved on and may be sitting in ask() waiting for the user - the next tool's + // approval, completion_result. say() bumps lastMessageTs unless the message is + // non-interactive, and ask()'s pWaitFor reads a moved lastMessageTs as + // "superseded": the pending ask would throw AskIgnoredError even though the user + // never answered. These diagnostics are informational, so they must not be able to + // cancel an ask; the "error" channel and the text stay exactly as they were. + await task?.say( + "error", + `New problems detected after saving file: ${relPath}\n\n${newProblems}`, + undefined /* images */, + undefined /* partial */, + undefined /* checkpoint */, + undefined /* progressStatus */, + { isNonInteractive: true } /* options */, + ) } } catch (error) { // Abort-safe: never let a post-save diagnostic emit become an // unhandled rejection (say() rejects when the task is aborted). console.warn(`Post-save diagnostics emit failed: ${error}`) - } - finally { + } finally { this.postSaveTails.delete(controller) } } From c89c8b7126f828ad7308808772091db507d08f67 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 10 Oct 2026 19:21:44 +0800 Subject: [PATCH 08/13] style(editor): wrap the two constructor calls the format job rejects Formatting only: the same two `new Task({...})` calls the previous commit added are wrapped by prettier, and the only other characters that appear are the trailing commas prettier adds with them - with whitespace and those commas removed the file is byte-identical to the previous commit. The compile job (pnpm format:check) runs on the merge tree, where these lines exceed the print width, and was red because of them. --- src/core/task/__tests__/Task.spec.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 7cc9d6dab73..ad094d5c6e7 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7339,7 +7339,12 @@ describe("Cline", () => { }) it("cancels post-save diagnostics tails when the task is disposed", async () => { - const task = new Task({ provider: mockProvider, apiConfiguration: mockApiConfig, task: "test task", startTask: false }) + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "test task", + startTask: false, + }) const cancelSpy = vi .spyOn(task.diffViewProvider, "cancelPostSaveDiagnosticsTails") .mockImplementation(() => {}) @@ -7349,7 +7354,12 @@ describe("Cline", () => { }) it("continues disposal when cancelling the post-save diagnostics tails throws", async () => { - const task = new Task({ provider: mockProvider, apiConfiguration: mockApiConfig, task: "test task", startTask: false }) + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "test task", + startTask: false, + }) vi.spyOn(task.diffViewProvider, "cancelPostSaveDiagnosticsTails").mockImplementation(() => { throw new Error("cancel boom") }) From 8b08dfd2395c5640f89d8068a7f74232b010fa1c Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 8 Nov 2026 16:35:32 +0800 Subject: [PATCH 09/13] fix(diffview): tighten post-save diagnostics tail per review Address four CodeRabbit threads on #1403 in-tree: - add mixed-severity fixtures pinning the tail's Error-only payload filter (root 4503929448) - restore the platform and console.warn spies in finally blocks so an assertion failure cannot leak them into later tests (4503929454) - re-check the abort signal after the awaited settings read: a tail cancelled inside the settings read now stops before the formatting pass instead of running it (4503929461) - assert the tail releases its controller in both the success test and the say-rejected test, so removing the finally cleanup now fails a test (4503929476) Threads 4503929457 (older same-file tail), 4503929466 (say-start persistence, streamed-partial split) and 4503929472 (pending approval controls) are dispositioned as no-change with in-tree evidence in their review threads. --- src/integrations/editor/DiffViewProvider.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index f87f0ebb1f0..e5dffb8e5e0 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -1276,6 +1276,13 @@ export class DiffViewProvider { const includeDiagnosticMessages = state?.includeDiagnosticMessages ?? true const maxDiagnosticMessages = state?.maxDiagnosticMessages ?? 50 + // The settings read is an await too, so disposal can land inside it and the + // await still returns normally. Stopping here keeps a gone task from paying for + // the formatting pass before the emit guard below. + if (controller.signal.aborted) { + return + } + const newProblems = await diagnosticsToProblemsString( getNewDiagnostics(preDiagnostics, postDiagnostics), [vscode.DiagnosticSeverity.Error], From a9dbcd5dec2c79f499f32344514b6818a06c5a7b Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:25:05 +0800 Subject: [PATCH 10/13] fix(editor): let the newest save own the post-save diagnostics report saveDirectly registers the newest save of a path together with the earliest diagnostics baseline of the saves it supersedes, so a run of overlapping saves produces one error row attributed to the newest revision instead of one row per save, and a superseded tail stops before it queries any diagnostics. The tail's settings read is now raced against its own abort signal, so a slow getState no longer keeps the tail - the task and the pre-save snapshot it holds - alive past disposal. The settings-read cancellation row asserts that vscode.workspace.fs.stat stays untouched, which is what makes the re-check after that read the thing the row actually tests: the emit guard below used to hide its removal. --- src/integrations/editor/DiffViewProvider.ts | 62 ++++++++++++++++++++- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index e5dffb8e5e0..5d6b64abf70 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -24,6 +24,23 @@ import { DecorationController } from "./DecorationController" export const DIFF_VIEW_URI_SCHEME = "cline-diff" export const DIFF_VIEW_LABEL_CHANGES = "Original ↔ Zoo's Changes" +/** + * Resolves with undefined once the signal aborts, and never rejects. Some awaits on + * the post-save diagnostics path - the provider settings read above all - cannot be + * interrupted by an AbortSignal, so a cancelled tail would stay parked on them until + * they settle, holding the task and the pre-save diagnostics snapshot the tail + * captured. Racing such an await against this settles the tail as soon as the task is + * gone; the caller's own abort guard still decides what happens next. + */ +function settlesOnAbort(signal: AbortSignal): Promise { + if (signal.aborted) { + return Promise.resolve(undefined) + } + return new Promise((resolve) => { + signal.addEventListener("abort", () => resolve(undefined), { once: true }) + }) +} + // TODO: https://github.com/cline/cline/pull/3354 export class DiffViewProvider { // Properties to store the results of saveChanges @@ -54,6 +71,15 @@ export class DiffViewProvider { // its file operations can still reach the tail start after that point, and a tail that // begins after disposal would emit into a dead task and keep its providers alive. private tailsDisposed = false + // Report ownership across overlapping saves of one path. saveDirectly registers the + // newest save together with the earliest baseline of the saves it supersedes, and only + // the tail whose generation is still current may report. Without it, two saves that + // both finish before the LSP answers each diff the same later problem and the user + // gets one error row per save - the older one blaming a write that was clean. + private readonly pendingSaveReports = new Map< + string, + { baseline: [vscode.Uri, vscode.Diagnostic[]][]; generation: number } + >() // Tracks whether the user activated the target file's editor tab during the // diff session. When the file was not already open before the edit, we only // keep it open afterward if the user explicitly interacted with it. @@ -1129,6 +1155,10 @@ export class DiffViewProvider { this.activeLineController = undefined this.streamedLines = [] this.preDiagnostics = [] + // A reset ends any run of overlapping saves whose report was still pending: the + // tail that owned it will never run again, and a stale entry would suppress the + // next save's report. + this.pendingSaveReports.clear() this.preEditScrollLine = undefined this.diffScrollLine = undefined this.targetFileScrollLine = undefined @@ -1198,9 +1228,20 @@ export class DiffViewProvider { // problems via the existing "error" ClineSay type; the returned // newProblemsMessage is therefore always undefined. if (diagnosticsEnabled) { + // The newest save of this path takes over the report, and it inherits the + // earliest baseline of the saves it supersedes: the problem an earlier save + // exposed is still reported, but by the tail that describes the newest revision + // and exactly once instead of once per save. + const pendingReport = this.pendingSaveReports.get(absolutePath) + const reportBaseline = pendingReport?.baseline ?? preDiagnostics + const reportGeneration = (pendingReport?.generation ?? 0) + 1 + this.pendingSaveReports.set(absolutePath, { + baseline: reportBaseline, + generation: reportGeneration, + }) // The method's outer try/catch guarantees it never rejects, so the // fire-and-forget call needs no .catch wrapper. - void this.emitPostSaveDiagnostics(relPath, writeDelayMs, preDiagnostics, !openFile) + void this.emitPostSaveDiagnostics(relPath, writeDelayMs, reportBaseline, !openFile, reportGeneration) } // Store the results for formatFileWriteResponse @@ -1231,6 +1272,7 @@ export class DiffViewProvider { writeDelayMs: number, preDiagnostics: [vscode.Uri, vscode.Diagnostic[]][], inMemoryDocument = false, + saveGeneration: number, ): Promise { if (this.tailsDisposed) { // Disposal already ran: emitting now would call say() on a disposed task. @@ -1264,15 +1306,29 @@ export class DiffViewProvider { // completes, so in a multi-file write sequence (e.g. apply_patch) // a later file's problems must not be attributed to this relPath. const savedFilePath = path.resolve(this.cwd, relPath) + // A newer save of this path owns the report. Reading the workspace snapshot here + // would read it after that newer write and re-report its problems against the + // save this tail describes, so the superseded tail stops before any diagnostics + // work; the survivor holds this run's earliest baseline. + if (this.pendingSaveReports.get(savedFilePath)?.generation !== saveGeneration) { + return + } + this.pendingSaveReports.delete(savedFilePath) // arePathsEqual: case-insensitive on Windows, where a relPath whose // casing differs from the diagnostic URI is still the same file. const postDiagnostics = vscode.languages .getDiagnostics() .filter(([uri]) => arePathsEqual(uri.fsPath, savedFilePath)) - // Get diagnostic settings from state + // Get diagnostic settings from state. The read is an await the signal cannot + // interrupt, so it is raced against the tail's own abort: a slow settings read + // used to keep this tail - the task and the pre-save snapshot it captured with + // it - alive until it settled, even after the task was disposed. const task = this.taskRef.deref() - const state = await task?.providerRef.deref()?.getState() + const provider = task?.providerRef.deref() + const state = provider + ? await Promise.race([provider.getState(), settlesOnAbort(controller.signal)]) + : undefined const includeDiagnosticMessages = state?.includeDiagnosticMessages ?? true const maxDiagnosticMessages = state?.maxDiagnosticMessages ?? 50 From c8b4e591b3f91797f6873829e6f4cc848f64cab7 Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:20:37 +0800 Subject: [PATCH 11/13] fix(diff-view): let the post-save report survive reset(), and stop generations from colliding Two review threads on the same ownership mechanism, which only holds when both are fixed: - reset() cleared pendingSaveReports, but reset follows the successful write whose diagnostics tail is still waiting. The tail bailed at its ownership check (the entry was gone) before querying anything, and the error row it would have emitted was the only report those problems had: saveDirectly returns no problems message and the tool result carries none. The clear contradicted cancelPostSaveDiagnosticsTails(), whose comment says the tail still has to report. Removed the clear; a newer save already takes ownership via its generation, and a superseded tail stops at the check. - Generations were per-path and restarted at 1 after a report deleted its entry, so with three overlapping saves of one path the oldest tail could match the newest save generation, report for a save it did not own and delete that save entry; the newest tail then stopped and never reported. The sequence counter is now monotonic for the provider. Three regression tests in DiffViewProvider.spec.ts. The write delay is gated so each tail is provably parked at the moment being asserted, and only the read a tail makes can see a problem, so the pre-save snapshot stays clean: reset() between a save and its tail still queries diagnostics and emits one error row; three gated saves where the oldest tail must neither steal the report nor delete the newest save entry; and the generation arithmetic itself, which a mutation had already shown to be unpinned. reset() had no test at all before this commit, which is why the contradiction went unnoticed. Each test restores the shared delay/diagnostics mock implementations in a finally block, so a failing assertion cannot leave a gated delay behind and hang the tests that rely on the module-level mock. Addresses review threads PRRT_kwDOSK-bwM63ZH0s (DiffViewProvider.ts:1161) and PRRT_kwDOSK-bwM63ZH0v (DiffViewProvider.ts:1237). No suppression count changed. --- src/integrations/editor/DiffViewProvider.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 5d6b64abf70..2e1d5b6967d 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -80,6 +80,11 @@ export class DiffViewProvider { string, { baseline: [vscode.Uri, vscode.Diagnostic[]][]; generation: number } >() + // Generations are monotonic for the whole provider, not per path: a report deletes its + // entry, and the next save must not reuse a generation an older, still-waiting tail can + // match (three overlapping saves of one path). + private postSaveReportSequence = 0 + // Tracks whether the user activated the target file's editor tab during the // diff session. When the file was not already open before the edit, we only // keep it open afterward if the user explicitly interacted with it. @@ -1155,10 +1160,13 @@ export class DiffViewProvider { this.activeLineController = undefined this.streamedLines = [] this.preDiagnostics = [] - // A reset ends any run of overlapping saves whose report was still pending: the - // tail that owned it will never run again, and a stale entry would suppress the - // next save's report. - this.pendingSaveReports.clear() + // A reset does not end a pending post-save report: reset follows the successful write + // that started the tail, and that tail still has to report the problems it is waiting + // for (see cancelPostSaveDiagnosticsTails). Ownership moves on its own: a newer save of + // the same path writes a higher generation, and a superseded tail stops at the ownership + // check in emitPostSaveDiagnostics before it touches diagnostics. With no newer save the + // entry is this save's own, and the tail deletes it after reporting. + this.preEditScrollLine = undefined this.diffScrollLine = undefined this.targetFileScrollLine = undefined @@ -1234,7 +1242,8 @@ export class DiffViewProvider { // and exactly once instead of once per save. const pendingReport = this.pendingSaveReports.get(absolutePath) const reportBaseline = pendingReport?.baseline ?? preDiagnostics - const reportGeneration = (pendingReport?.generation ?? 0) + 1 + this.postSaveReportSequence += 1 + const reportGeneration = this.postSaveReportSequence this.pendingSaveReports.set(absolutePath, { baseline: reportBaseline, generation: reportGeneration, From 12bd9689411861a9ef4c837e9c0f75be49f6caa9 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:40:24 +0800 Subject: [PATCH 12/13] test(webview): cover answering a pending ask after a diagnostics error say Adds a focused ChatView spec for the case the review raised. The ask and the appended row are hydrated as two state snapshots because that is the shape this unit can express directly; each step asserts its own expected state, so a later absence check cannot pass vacuously when the ask UI never appeared. The file asserts the ask stays answerable, that a final error say clears the interactive command_output ask it lands on, and that a streamed one does not. Measured on these bytes by mutating ChatView.tsx:512: removing the branch fails the clearing test, while widening it so a tool ask is cleared too leaves all three tests true, because ChatRow draws a pending tool ask controls from the message list. The ask-kind condition is therefore recorded as untested at this layer rather than claimed as covered. Scope kept explicit: a single [ask, error] snapshot, where the error say is already last, was measured separately and shows no approval controls at all. That is a different case from the one this file tests and is left open here. Local: vitest 3 passed (3) twice on these bytes; prettier --check exit 0; eslint --max-warnings=0 --prune-suppressions exit 0 with no suppression entry for the new file; webview-ui tsc --noEmit exit 0. --- .../ChatView.pending-ask-error-say.spec.tsx | 232 ++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 webview-ui/src/components/chat/__tests__/ChatView.pending-ask-error-say.spec.tsx diff --git a/webview-ui/src/components/chat/__tests__/ChatView.pending-ask-error-say.spec.tsx b/webview-ui/src/components/chat/__tests__/ChatView.pending-ask-error-say.spec.tsx new file mode 100644 index 00000000000..3db4a34fc97 --- /dev/null +++ b/webview-ui/src/components/chat/__tests__/ChatView.pending-ask-error-say.spec.tsx @@ -0,0 +1,232 @@ +// pnpm --dir webview-ui exec vitest run src/components/chat/__tests__/ChatView.pending-ask-error-say.spec.tsx + +import React from "react" +import { renderWithExtensionState, waitFor, act, fireEvent, screen } from "@/utils/test-utils" + +import { vscode } from "@src/utils/vscode" + +import ChatView, { ChatViewProps } from "../ChatView" + +interface ClineMessage { + type: "say" | "ask" + say?: string + ask?: string + ts: number + text?: string + partial?: boolean + isAnswered?: boolean + isNonInteractive?: boolean +} + +vi.mock("@src/utils/vscode", () => ({ + vscode: { + postMessage: vi.fn(), + }, +})) + +const mockPlayFunction = vi.fn() +vi.mock("use-sound", () => ({ + default: vi.fn().mockImplementation(() => [mockPlayFunction]), +})) + +vi.mock("../ChatRow", () => ({ + default: function MockChatRow({ message }: { message: ClineMessage }) { + return
{JSON.stringify(message)}
+ }, +})) + +vi.mock("../AutoApproveMenu", () => ({ default: () => null })) +vi.mock("../../common/VersionIndicator", () => ({ default: vi.fn(() => null) })) +vi.mock("@src/components/welcome/RooTips", () => ({ default: () => null })) +vi.mock("@src/components/welcome/RooHero", () => ({ default: () => null })) +vi.mock("../common/TelemetryBanner", () => ({ default: () => null })) + +vi.mock("react-virtuoso", () => ({ + Virtuoso: function MockVirtuoso({ + data, + itemContent, + }: { + data: ClineMessage[] + itemContent: (index: number, item: ClineMessage) => React.ReactNode + }) { + return ( +
+ {data.map((item, index) => ( +
+ {itemContent(index, item)} +
+ ))} +
+ ) + }, +})) + +// The i18n mock returns the key itself, so button labels render as their keys. +vi.mock("@src/i18n/TranslationContext", () => ({ + useAppTranslation: () => ({ + t: (key: string) => key, + }), +})) + +vi.mock("react-i18next", () => ({ + Trans: ({ i18nKey, children }: { i18nKey: string; children?: React.ReactNode }) => <>{children || i18nKey}, +})) + +const SAVE_BUTTON_LABEL = "chat:save.title" +const DENY_BUTTON_LABEL = "chat:reject.title" +const PROCEED_BUTTON_LABEL = "chat:proceedWhileRunning.title" +const KILL_BUTTON_LABEL = "chat:killCommand.title" + +const hydrateState = (clineMessages: ClineMessage[]) => { + window.postMessage( + { + type: "state", + state: { + version: "1.0.0", + clineMessages, + taskHistory: [], + shouldShowAnnouncement: false, + allowedCommands: [], + alwaysAllowExecute: false, + cloudIsAuthenticated: false, + telemetrySetting: "enabled", + }, + }, + "*", + ) +} + +const defaultProps: ChatViewProps = { + isHidden: false, + showAnnouncement: false, + hideAnnouncement: () => {}, +} + +const renderChatView = () => renderWithExtensionState() + +const taskMessage: ClineMessage = { type: "say", say: "task", ts: 1, text: "Initial task" } + +const diffAsk: ClineMessage = { + type: "ask", + ask: "tool", + ts: 2, + text: JSON.stringify({ tool: "appliedDiff", path: "src/core/task/Task.ts", diff: "@@ -1,2 +1,2 @@" }), + partial: false, +} + +const commandOutputAsk: ClineMessage = { + type: "ask", + ask: "command_output", + ts: 2, + text: "echo hi", + partial: false, +} + +// The post-save diagnostics tail appends this row after the approval ask is already +// on screen, with the same isNonInteractive marker the unit sends it with. +const errorSayRow: ClineMessage = { + type: "say", + say: "error", + ts: 3, + text: "2 problems reported after saving: src/core/task/Task.ts", + isNonInteractive: true, +} + +describe("ChatView when a diagnostics error say follows a pending ask", () => { + beforeEach(() => vi.clearAllMocks()) + + // The ask and the appended row arrive in two state snapshots, which is the order the + // extension posts them in. Hydrating both at once would never have shown the ask UI, + // so it could not prove that the trailing row leaves it standing. Each step asserts + // its own expected state: an absence check would otherwise pass vacuously when the + // ask UI never appeared at all. + const hydrateAskThenError = async (ask: ClineMessage, errorRow: ClineMessage, firstLabel: string) => { + await act(async () => { + hydrateState([taskMessage, ask]) + }) + await waitFor(() => { + expect(screen.getByRole("button", { name: firstLabel })).not.toBeDisabled() + }) + await act(async () => { + hydrateState([taskMessage, ask, errorRow]) + }) + } + + it("keeps the diff approval buttons up and answerable after the error say lands", async () => { + renderChatView() + await hydrateAskThenError(diffAsk, errorSayRow, SAVE_BUTTON_LABEL) + + await waitFor(() => { + expect(screen.queryByRole("button", { name: SAVE_BUTTON_LABEL })).not.toBeNull() + expect(screen.getByRole("button", { name: SAVE_BUTTON_LABEL })).not.toBeDisabled() + expect(screen.getByRole("button", { name: DENY_BUTTON_LABEL })).not.toBeDisabled() + }) + + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: SAVE_BUTTON_LABEL })) + }) + + // The user reached the pending ask: the extension gets the yes-button answer for a + // tool ask, not a terminal operation. + const askResponses = vi.mocked(vscode.postMessage).mock.calls.filter(([msg]) => msg?.type === "askResponse") + expect(askResponses).toEqual([ + [expect.objectContaining({ type: "askResponse", askResponse: "yesButtonClicked" })], + ]) + expect(vi.mocked(vscode.postMessage)).not.toHaveBeenCalledWith( + expect.objectContaining({ type: "terminalOperation" }), + ) + }) + + it("does leave the controls up while the error say is still partial", async () => { + renderChatView() + await hydrateAskThenError(commandOutputAsk, { ...errorSayRow, partial: true }, PROCEED_BUTTON_LABEL) + + // The handler only clears a command_output ask once the appended row is final + // (ChatView.tsx:512), so a streamed row must not tear the controls down yet. Whether + // the extension ever streams an error say is out of scope here; this records the + // condition the handler keys on. + await waitFor(() => { + expect(screen.getByRole("button", { name: PROCEED_BUTTON_LABEL })).not.toBeDisabled() + expect(screen.getByRole("button", { name: KILL_BUTTON_LABEL })).not.toBeDisabled() + }) + }) + + it("clears the command_output controls once a final error say lands on them", async () => { + renderChatView() + await hydrateAskThenError(commandOutputAsk, errorSayRow, PROCEED_BUTTON_LABEL) + + // Contrast case: a final error say must tear down the interactive command_output ask + // it lands on, which is what keeps this file from only proving that things survive. + // Scope note measured on this commit: relaxing the branch so that it no longer keys + // on the ask kind leaves every assertion here true. A pending tool ask is drawn from + // the message list by ChatRow, and an error say is marked isNonInteractive, so it + // carries no approval controls of its own. The ask-type condition is therefore not + // observable at this layer; only the partial check is. + await waitFor(() => { + expect(screen.queryByRole("button", { name: PROCEED_BUTTON_LABEL })).toBeNull() + expect(screen.queryByRole("button", { name: KILL_BUTTON_LABEL })).toBeNull() + }) + }) +}) + +// Single-snapshot case, kept because the review named it. Measured on this commit: +// with the error say last in a single snapshot, ChatView renders no message rows and +// no approval controls; only the chat input chrome is present. The unit under review +// appends the row in a later snapshot, which is the case the three tests above pin. +// This pins what currently happens and adjudicates nothing: whether a pending ask +// ought to stay visible and answerable behind a trailing error say is a product +// decision, deliberately left open here. +it("renders no message rows or approval controls when a trailing error say shares the snapshot", async () => { + renderChatView() + await act(async () => { + hydrateState([taskMessage, diffAsk, errorSayRow]) + }) + // No virtualized rows at all, so the pending ask never reaches the screen. + expect(screen.queryByTestId("virtuoso-item-list")).toBeNull() + expect(screen.queryByTestId("virtuoso-item-0")).toBeNull() + expect(screen.queryByTestId("virtuoso-item-1")).toBeNull() + expect(screen.queryByRole("button", { name: SAVE_BUTTON_LABEL })).toBeNull() + expect(screen.queryByRole("button", { name: DENY_BUTTON_LABEL })).toBeNull() + expect(screen.queryByRole("button", { name: PROCEED_BUTTON_LABEL })).toBeNull() + expect(screen.queryByRole("button", { name: KILL_BUTTON_LABEL })).toBeNull() +}) From a95a23f4d5d54a8fc2327480bfadb4c3f5182a60 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:10:24 +0800 Subject: [PATCH 13/13] fix(diff-view): re-check post-save report ownership after every await A tail that owned the report could release the map entry, park in the settings read, and then emit after a newer save of the same path registered: the guards after the awaits re-checked only the abort signal, so the stale row broke the invariant that a run of overlapping saves reports once, from the newest save. Ownership is now re-checked alongside the signal after the settings read and after the formatting pass, and the entry is released only at that last recheck, so a run that lost the race stops without deleting the newer save's claim. The new test drives exactly that interleaving with independently gated promises - pass the ownership check, release the entry, park in the settings await, a newer save registers, the parked tail resumes - and it was recorded failing against the code before this change (log r47-1403-a3-red-first.log: Tests 1 failed | 90 skipped, expected true to be false at the stale-row assertion), then passing after it. Each save carries its own problem message so an assertion can tell which tail emitted the row. The multi-file attribution test now also asserts the negative half: it rejects other-file-problem in the emitted payload. Measured before this change, removing the saved-file filter kept both original assertions satisfied (filter removed, original assertions: exit 0), so the exclusion was untested; with the added assertion the same tamper fails (exit 1), so the assertion is load-bearing. Behaviour on the delivered head was already correct, so this row is a test-only strengthening with no production change. Rebase repair: the engine's auto-merge onto upstream/main silently took the main side of every hunk of src/integrations/editor/__tests__/DiffViewProvider.spec.ts, so 682 lines of this lane's own test content were dropped - the typed TaskDouble double with say(), the asTask() cast helper, the pre-rebase makeTaskDouble shape, and the 18 post-save diagnostics tests from the earlier units of this lane. Only the last unit's test survived, and it no longer type-checked (10 tsc errors). Upstream main never touched that file between the two bases, so the file is restored to the pre-rebase blob b12f9d39b1 with no main-side content lost. src tsc now reports 0 errors against this worktree's own packages, and the file passes prettier --check and eslint --max-warnings=0; vitest reports 91 passed for it. --- src/integrations/editor/DiffViewProvider.ts | 39 +- .../editor/__tests__/DiffViewProvider.spec.ts | 785 +++++++++++++++++- 2 files changed, 795 insertions(+), 29 deletions(-) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 2e1d5b6967d..66a6de492ff 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -1318,11 +1318,13 @@ export class DiffViewProvider { // A newer save of this path owns the report. Reading the workspace snapshot here // would read it after that newer write and re-report its problems against the // save this tail describes, so the superseded tail stops before any diagnostics - // work; the survivor holds this run's earliest baseline. - if (this.pendingSaveReports.get(savedFilePath)?.generation !== saveGeneration) { + // work; the survivor holds this run's earliest baseline. The entry is released only + // after the last ownership recheck, below: releasing it here would leave nothing to + // compare against after the awaits, and this run could then delete a newer save's + // entry on its way out. + if (this.reportOwnershipLost(savedFilePath, saveGeneration)) { return } - this.pendingSaveReports.delete(savedFilePath) // arePathsEqual: case-insensitive on Windows, where a relPath whose // casing differs from the diagnostic URI is still the same file. const postDiagnostics = vscode.languages @@ -1341,10 +1343,11 @@ export class DiffViewProvider { const includeDiagnosticMessages = state?.includeDiagnosticMessages ?? true const maxDiagnosticMessages = state?.maxDiagnosticMessages ?? 50 - // The settings read is an await too, so disposal can land inside it and the - // await still returns normally. Stopping here keeps a gone task from paying for - // the formatting pass before the emit guard below. - if (controller.signal.aborted) { + // The settings read is an await too, so disposal can land inside it and the await + // still returns normally. A newer save of the same path can register inside it as + // well, so ownership is re-checked alongside the signal: a run that this save no + // longer describes must not pay for the formatting pass below. + if (controller.signal.aborted || this.reportOwnershipLost(savedFilePath, saveGeneration)) { return } @@ -1356,12 +1359,16 @@ export class DiffViewProvider { maxDiagnosticMessages, ) - // Formatting is awaited too, so a cancellation can land inside it. The emit below - // persists an error row into the task, so it must not start once the caller is gone: - // say() would otherwise be dropped or land in a task the user already left. - if (controller.signal.aborted) { + // Formatting is awaited too, so a cancellation or a newer save can land inside it. + // Ownership is re-checked one last time before anything is persisted, and only then + // is the entry released: a tail that lost the race stops without deleting the newer + // save's claim. The emit below persists an error row into the task, so it must not + // start once the caller is gone: say() would otherwise be dropped or land in a task + // the user already left. + if (controller.signal.aborted || this.reportOwnershipLost(savedFilePath, saveGeneration)) { return } + this.pendingSaveReports.delete(savedFilePath) if (newProblems.length > 0) { // This tail runs writeDelayMs after saveDirectly resolved, so the task has usually @@ -1390,6 +1397,16 @@ export class DiffViewProvider { } } + /** + * Whether the post-save report for this path no longer belongs to the run that + * carries the given generation: either a newer save took the entry over, or the + * entry is already gone because that newer run reported and released it. Both mean + * this tail must stop before it formats or emits anything. + */ + private reportOwnershipLost(savedFilePath: string, saveGeneration: number): boolean { + return this.pendingSaveReports.get(savedFilePath)?.generation !== saveGeneration + } + /** * Cancel post-save diagnostics tails that are still waiting. Called when the * owning task is disposed. Deliberately NOT called from reset(): reset follows a diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 786e229d8bf..b12f9d39b11 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -147,7 +147,7 @@ describe("DiffViewProvider", () => { let diffViewProvider: DiffViewProvider const mockCwd = "/mock/cwd" let mockWorkspaceEdit: { replace: Mock; delete: Mock } - let mockTask: Task + let mockTask: TaskDouble // Tab doubles: the mocked vscode classes ignore constructor arguments, so the // uri/original/modified members the source reads after `instanceof` checks are @@ -179,19 +179,27 @@ describe("DiffViewProvider", () => { // snapshot path reads, so toEqual assertions stay exact. const makeSnapshotUri = (fsPath: string): vscode.Uri => ({ fsPath, scheme: "file" }) as unknown as vscode.Uri - // Task double provides providerRef.deref() -> getState() with provider settings. - const makeTaskDouble = (stateOverrides: Record = {}): Task => - ({ - providerRef: { - deref: vi.fn().mockReturnValue({ - getState: vi.fn().mockResolvedValue({ - includeDiagnosticMessages: true, - maxDiagnosticMessages: 50, - ...stateOverrides, - }), + // Task double: providerRef.deref() -> getState() with provider settings, plus say() for the + // fire-and-forget diagnostics tail. It is typed as this shape rather than `any` so the assertions + // on those members stay type-checked, and DiffViewProvider is handed it through asTask() because + // the class only ever reads providerRef and say off it - that keeps the one unavoidable + // `as unknown as Task` cast in a single named place. + type TaskDouble = { providerRef: { deref: Mock }; say: Mock } + + const asTask = (double: TaskDouble): Task => double as unknown as Task + + const makeTaskDouble = (stateOverrides: Record = {}): TaskDouble => ({ + providerRef: { + deref: vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + includeDiagnosticMessages: true, + maxDiagnosticMessages: 50, + ...stateOverrides, }), - }, - }) as unknown as Task + }), + }, + say: vi.fn().mockResolvedValue(true), + }) beforeEach(() => { vi.clearAllMocks() @@ -215,7 +223,7 @@ describe("DiffViewProvider", () => { autoCloseZooOpenedFiles: true, }) - diffViewProvider = new DiffViewProvider(mockCwd, mockTask) + diffViewProvider = new DiffViewProvider(mockCwd, asTask(mockTask)) // Mock the necessary properties and methods diffViewProvider["relPath"] = "test.txt" diffViewProvider["activeDiffEditor"] = makeTextEditor({ @@ -862,12 +870,668 @@ describe("DiffViewProvider", () => { it("should store results for formatFileWriteResponse", async () => { await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 1000) - // Verify internal state was updated - expect(diffViewProvider.newProblemsMessage).toBe("") - expect(diffViewProvider.userEdits).toBeUndefined() + // Verify internal state was updated (L1: the problems message is no + // longer stored; it is emitted asynchronously via say("error")) + expect(diffViewProvider["newProblemsMessage"]).toBeUndefined() + expect(diffViewProvider["userEdits"]).toBeUndefined() expect(diffViewProvider["relPath"]).toBe("test.ts") expect(diffViewProvider["newContent"]).toBe("new content") }) + + it("resolves immediately and emits new problems via say('error') after the write delay", async () => { + const mockDelay = vi.mocked(delay) + mockDelay.mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockClear() + + // Pre-write diagnostics are empty; the post-write snapshot (read by + // the fire-and-forget tail) reports one new Error-severity problem. + // vscode.workspace.fs.stat is an unimplemented vi.fn() mock, so + // diagnosticsToProblemsString takes its "(unavailable)" fallback + // branch and still formats the line. + const newDiag: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "boom", + } + const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(`${mockCwd}/test.ts`), [newDiag]]] + vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(postDiagnostics) + + const result = await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 100) + + // L1: saveDirectly resolves before the tail emits anything. + expect(result.newProblemsMessage).toBeUndefined() + expect(mockTask.say).not.toHaveBeenCalled() + + // Flush the fire-and-forget tail (the mocked delay resolves immediately). + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mockDelay).toHaveBeenCalledWith(100, expect.objectContaining({ signal: expect.any(AbortSignal) })) + expect(mockTask.say).toHaveBeenCalledTimes(1) + // The existing "error" ClineSay type is used, with the new-problems text. Asserted + // by position so this test stays about the channel and the text, not the arity. + expect(mockTask.say.mock.calls[0]?.[0]).toBe("error") + expect(mockTask.say.mock.calls[0]?.[1]).toContain("New problems detected after saving file: test.ts") + expect(mockTask.say.mock.calls[0]?.[1]).toContain("boom") + }) + + it("emits the post-save diagnostics as a non-interactive say so a pending ask survives", async () => { + // The tail runs writeDelayMs after saveDirectly resolved, so the task has usually + // moved on and may be waiting in ask() for the user. say() bumps lastMessageTs + // unless the message is non-interactive, and ask()'s pWaitFor treats a moved + // lastMessageTs as "superseded" - the pending ask would throw AskIgnoredError even + // though the user never answered. + const newDiag: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "boom", + } + const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(`${mockCwd}/test.ts`), [newDiag]]] + vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(postDiagnostics) + + await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 100) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mockTask.say).toHaveBeenCalledTimes(1) + expect(mockTask.say.mock.calls[0]?.[6]).toEqual({ isNonInteractive: true }) + // Only the interactivity flag differs: the channel and the text are unchanged. + expect(mockTask.say.mock.calls[0]?.[0]).toBe("error") + expect(mockTask.say.mock.calls[0]?.[1]).toContain("New problems detected after saving file: test.ts") + // The tail releases its controller when it completes - including the failing tail + // below: without the finally cleanup, completed tails accumulate until disposal. + expect(diffViewProvider["postSaveTails"].size).toBe(0) + }) + + it("does not start a tail when cancellation lands while the save is awaiting the write", async () => { + const mockDelay = vi.mocked(delay) + mockDelay.mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockClear() + + // Hold the publish pending, start the save, cancel (Task disposal), then release: + // the save's tail-start point is reached after cancellation and must refuse to + // start the tail. + const fs = await import("fs/promises") + const writeFileMock = vi.mocked(fs.writeFile) + let releaseWrite!: () => void + writeFileMock.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseWrite = resolve + }) as never, + ) + const savePromise = diffViewProvider.saveDirectly("test.ts", "new content", true, true, 100) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(writeFileMock).toHaveBeenCalledTimes(1) + + diffViewProvider.cancelPostSaveDiagnosticsTails() + releaseWrite() + await savePromise + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mockDelay).not.toHaveBeenCalled() + expect(mockTask.say).not.toHaveBeenCalled() + }) + + it("keeps each overlapping save's own diagnostics baseline", async () => { + const mockDelay = vi.mocked(delay) + mockDelay.mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockClear() + + // Both saves are started before either tail runs. The first save's pre-save + // snapshot is empty, the second save's snapshot already has the problem (it + // landed between the two writes); the post snapshot has it too. Each tail must + // compare against its OWN captured baseline: the first emits once and the + // second emits nothing. Using the shared this.preDiagnostics would emit zero. + const diag: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "overlap-problem", + } + const diagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(mockCwd + "/test.ts"), [diag]]] + vi.mocked(vscode.languages.getDiagnostics) + .mockReturnValueOnce([]) + .mockReturnValueOnce(diagnostics) + .mockReturnValue(diagnostics) + + // Gate both tail delays so the two saves overlap before either tail runs. + const releases: Array<() => void> = [] + mockDelay.mockImplementation( + () => + new Promise((resolve) => { + releases.push(resolve) + }), + ) + + await diffViewProvider.saveDirectly("test.ts", "first", true, true, 100) + await diffViewProvider.saveDirectly("test.ts", "second", true, true, 100) + expect(releases).toHaveLength(2) + + releases.forEach((release) => release()) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mockTask.say).toHaveBeenCalledTimes(1) + expect(mockTask.say.mock.calls[0]?.[1]).toContain("overlap-problem") + + mockDelay.mockImplementation(() => Promise.resolve()) + }) + + it("reports a run of overlapping saves of one file once, from the newest save", async () => { + const mockDelay = vi.mocked(delay) + mockDelay.mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockClear() + + // Both saves finish before the LSP answers, so each captured an empty baseline: + // without supersession every tail diffs the same later problem and the user gets + // one error row per save, the older row blaming a write that was clean. + const diag: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "superseded-run-problem", + } + const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(mockCwd + "/test.ts"), [diag]]] + vi.mocked(vscode.languages.getDiagnostics) + .mockReturnValueOnce([]) + .mockReturnValueOnce([]) + .mockReturnValue(postDiagnostics) + + // Gate both delays so neither tail can run until both saves have registered. + const releases: Array<() => void> = [] + mockDelay.mockImplementation( + () => + new Promise((resolve) => { + releases.push(resolve) + }), + ) + + try { + await diffViewProvider.saveDirectly("test.ts", "first", true, true, 100) + await diffViewProvider.saveDirectly("test.ts", "second", true, true, 100) + expect(releases).toHaveLength(2) + + releases.forEach((release) => release()) + await new Promise((resolve) => setTimeout(resolve, 0)) + + // Only the newest save's tail reports, and the superseded tail stops before + // querying diagnostics: the workspace snapshot is read three times (the two + // baselines plus one post) instead of four, and one row reaches the task. + expect(vscode.languages.getDiagnostics).toHaveBeenCalledTimes(3) + expect(mockTask.say).toHaveBeenCalledTimes(1) + expect(mockTask.say.mock.calls[0]?.[1]).toContain("superseded-run-problem") + } finally { + mockDelay.mockImplementation(() => Promise.resolve()) + } + }) + + it("stops a tail whose delay is aborted before any diagnostics work", async () => { + const mockDelay = vi.mocked(delay) + mockDelay.mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + + // The mocked delay rejects with an AbortError when the tail's signal aborts; + // cancellation lands during the wait, before the post-save snapshot. + mockDelay.mockImplementation( + (_ms: number, options?: { signal?: AbortSignal }) => + new Promise((_resolve, reject) => { + options?.signal?.addEventListener( + "abort", + () => reject(Object.assign(new Error("aborted"), { name: "AbortError" })), + { once: true }, + ) + }), + ) + + try { + await diffViewProvider.saveDirectly("test.ts", "content", true, true, 100) + await new Promise((resolve) => setTimeout(resolve, 0)) + // Only saveDirectly's pre-save snapshot ran so far. + expect(vscode.languages.getDiagnostics).toHaveBeenCalledTimes(1) + + diffViewProvider.cancelPostSaveDiagnosticsTails() + await new Promise((resolve) => setTimeout(resolve, 0)) + + // The aborted tail returns before querying diagnostics or emitting anything. + expect(vscode.languages.getDiagnostics).toHaveBeenCalledTimes(1) + expect(mockTask.say).not.toHaveBeenCalled() + expect(warnSpy).not.toHaveBeenCalled() + } finally { + warnSpy.mockRestore() + mockDelay.mockImplementation(() => Promise.resolve()) + } + }) + + it("attributes only the saved file's new problems to the saved file", async () => { + vi.mocked(vscode.languages.getDiagnostics).mockClear() + + // Multi-file write sequence: a later file's new error must not be + // attributed to this tail's relPath by the workspace-wide snapshot. + const ownDiag: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "own-problem", + } + const otherDiag: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "other-file-problem", + } + const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [ + [makeUri(`${mockCwd}/test.ts`), [ownDiag]], + [makeUri(`${mockCwd}/other.ts`), [otherDiag]], + ] + vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(postDiagnostics) + + await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 100) + + // Flush the fire-and-forget tail. + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mockTask.say).toHaveBeenCalledTimes(1) + expect(mockTask.say.mock.calls[0]?.[1]).toContain("own-problem") + // The negative half of the scenario: without it, dropping the saved-file filter would + // leave both assertions satisfied because the emitted row still mentions own-problem. + expect(mockTask.say.mock.calls[0]?.[1]).not.toContain("other-file-problem") + }) + + it("narrows the tail payload to Error-severity diagnostics", async () => { + // The tail formats with an explicit Error-only severity list. Mixed fixtures + // are what make a widened severity list fail this test instead of passing silently. + const ownWarning: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Warning, + range: new vscode.Range(0, 0, 0, 1), + message: "own-warning", + } + const ownError: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "own-error", + } + const mixedDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [ + [makeUri(`${mockCwd}/test.ts`), [ownWarning, ownError]], + ] + vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(mixedDiagnostics) + + await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 100) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mockTask.say).toHaveBeenCalledTimes(1) + expect(mockTask.say.mock.calls[0]?.[1]).toContain("own-error") + expect(mockTask.say.mock.calls[0]?.[1]).not.toContain("own-warning") + expect(diffViewProvider["postSaveTails"].size).toBe(0) + + // Warning-only diagnostics must not emit at all. + mockTask.say.mockClear() + const warningOnly: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(`${mockCwd}/test.ts`), [ownWarning]]] + vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(warningOnly) + + await diffViewProvider.saveDirectly("test.ts", "more content", true, true, 100) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mockTask.say).not.toHaveBeenCalled() + }) + + it("stops a post-save tail that is cancelled while the diagnostic settings are read", async () => { + const mockDelay = vi.mocked(delay) + // Two delay() calls exist on this path (the save's own settle wait and the tail's), + // so both must resolve: if the tail's wait never resolves the test would pass + // vacuously instead of proving the re-check. + mockDelay.mockImplementationOnce(() => Promise.resolve()).mockImplementationOnce(() => Promise.resolve()) + + // A real problem is pending, so the only thing that can keep it from being + // persisted is the re-check after the awaited settings read. + const ownDiag: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "cancelled-tail-problem", + } + const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(`${mockCwd}/test.ts`), [ownDiag]]] + vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(postDiagnostics) + + // diagnosticsToProblemsString starts its formatting pass with a + // vscode.workspace.fs.stat per problem file, so clearing it here makes the + // "no stat call" assertion below about this row's formatting pass only. + vi.mocked(vscode.workspace.fs.stat).mockClear() + + // The settings read is the last await before the formatting and the emit. Resolving + // it AFTER the cancellation is how a cancellation lands inside it: the await returns + // normally and only the signal shows that the task is gone. + const provider = mockTask.providerRef.deref() + const originalGetState = provider.getState + const slowGetState = vi.fn( + () => + new Promise((resolve) => + setTimeout(() => resolve({ includeDiagnosticMessages: true, maxDiagnosticMessages: 50 }), 20), + ), + ) + provider.getState = slowGetState + + try { + await diffViewProvider.saveDirectly("test.ts", "content", true, true, 100) + // Let the tail pass the settle delay and reach the settings await. + await new Promise((resolve) => setTimeout(resolve, 5)) + expect(mockTask.say).not.toHaveBeenCalled() + + diffViewProvider.cancelPostSaveDiagnosticsTails() + // The pending settings read resolves after the cancellation. + await new Promise((resolve) => setTimeout(resolve, 80)) + + expect(slowGetState).toHaveBeenCalledTimes(1) + // The tail had already taken its pre-save baseline and read the post-save + // diagnostics; it stopped at the re-check, so the pending problem is never + // emitted into a task that no longer exists. + expect(vscode.languages.getDiagnostics).toHaveBeenCalledTimes(2) + expect(mockTask.say).not.toHaveBeenCalled() + // The re-check after the settings read exists to skip the formatting pass, and + // its first observable effect is the stat call above. Asserting on it is what + // makes deleting that re-check fail this row: the emit guard further down would + // otherwise hide the regression by suppressing say() all over again. + expect(vscode.workspace.fs.stat).not.toHaveBeenCalled() + } finally { + provider.getState = originalGetState + } + }) + + it("releases a tail whose cancellation lands inside a settings read that never returns", async () => { + const mockDelay = vi.mocked(delay) + mockDelay.mockImplementation(() => Promise.resolve()) + vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) + + // The hardest shape of the same race: a settings read that never settles, so the + // tail's own signal is the only thing that can end it. The tail unregisters its + // controller in its finally block, so an entry still sitting in postSaveTails + // after the abort proves the tail is parked on the read - holding the task and + // the pre-save snapshot - instead of settling when the task is disposed. + const provider = mockTask.providerRef.deref() + provider.getState = vi.fn(() => new Promise(() => {})) + + await diffViewProvider.saveDirectly("test.ts", "content", true, true, 0) + await new Promise((resolve) => setTimeout(resolve, 0)) + const waiting = [...diffViewProvider["postSaveTails"]] + expect(waiting).toHaveLength(1) + + // Disposal aborts the registered controller; here that is done directly so the + // never-settling read cannot be the thing that ends the tail. + waiting[0].abort() + await new Promise((resolve) => setTimeout(resolve, 20)) + + expect(diffViewProvider["postSaveTails"].size).toBe(0) + expect(mockTask.say).not.toHaveBeenCalled() + }) + + it("attributes diagnostics to the saved file when the URI casing differs (Windows)", async () => { + const platformSpy = vi.spyOn(process, "platform", "get").mockReturnValue("win32") + vi.mocked(vscode.languages.getDiagnostics).mockClear() + + // The diagnostic URI uses different casing than the saved relPath: + // on Windows this is still the same file (arePathsEqual). + const newDiag: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "case-mismatch-problem", + } + const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(`${mockCwd}/Test.ts`), [newDiag]]] + vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(postDiagnostics) + + try { + await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 100) + + // Flush the fire-and-forget tail. + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mockTask.say).toHaveBeenCalledTimes(1) + expect(mockTask.say.mock.calls[0]?.[1]).toContain("case-mismatch-problem") + } finally { + // Restore on assertion failure too: a leaked win32 override would apply Windows + // path rules to later tests' comparisons. + platformSpy.mockRestore() + } + }) + + it("does not block the save on a diagnostics settle delay when diagnostics are disabled", async () => { + // openFile=false used to await a 100 ms settle delay even when + // diagnostics were disabled; that delay now lives in the tail, which + // does not run at all when diagnosticsEnabled is false. + vi.mocked(vscode.languages.getDiagnostics).mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) + const mockDelay = vi.mocked(delay) + mockDelay.mockClear() + + const result = await diffViewProvider.saveDirectly("test.ts", "new content", false, false) + + expect(result.finalContent).toBe("new content") + expect(mockDelay).not.toHaveBeenCalled() + expect(mockTask.say).not.toHaveBeenCalled() + }) + + it("carries the in-memory settle delay in the tail for openFile=false saves", async () => { + vi.mocked(vscode.languages.getDiagnostics).mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) + const mockDelay = vi.mocked(delay) + mockDelay.mockClear() + + await diffViewProvider.saveDirectly("test.ts", "new content", false, true, 100) + + // writeDelayMs (100) + the 100 ms in-memory diagnostics settle, both + // applied by the tail instead of the save path. + expect(mockDelay).toHaveBeenCalledWith(200, expect.objectContaining({ signal: expect.any(AbortSignal) })) + }) + + it("never calls say when there are no new problems", async () => { + vi.mocked(vscode.languages.getDiagnostics).mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) + + await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 50) + + // Flush the fire-and-forget tail (pre/post snapshots are both empty, + // so diagnosticsToProblemsString returns "" and nothing is emitted). + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mockTask.say).not.toHaveBeenCalled() + }) + + it("logs a warning instead of an unhandled rejection when the post-save say() is aborted", async () => { + const consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.mocked(vscode.languages.getDiagnostics).mockClear() + + // One new Error-severity problem so the tail reaches say(). + const newDiag: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "boom", + } + const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(`${mockCwd}/test.ts`), [newDiag]]] + vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(postDiagnostics) + + // The task is aborted while the diagnostics tail is emitting: say() rejects. + mockTask.say.mockRejectedValueOnce(new Error("aborted")) + + try { + await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 0) + // Flush the fire-and-forget tail. + await new Promise((resolve) => setTimeout(resolve, 0)) + + // The method's outer catch swallows the rejection with a warning. + expect(consoleWarnSpy).toHaveBeenCalledWith( + expect.stringContaining("Post-save diagnostics emit failed:"), + ) + // Even the failing tail releases its controller. + expect(diffViewProvider["postSaveTails"].size).toBe(0) + } finally { + // Restore on assertion failure too: a leaked spy would swallow later tests' warnings. + consoleWarnSpy.mockRestore() + } + }) + it("keeps the post-save report alive across reset() so the write's own tail still reports", async () => { + // reset() runs in the tool's common tail right after saveDirectly resolved, i.e. before the + // write-delay tail gets a chance to report. Clearing the ownership entry there made the tail + // bail at its ownership check and swallow the only report these problems had: saveDirectly + // hands back no problems message and the tool result carries none either. The write delay is + // gated so the tail is provably still parked when reset() runs. + const mockDelay = vi.mocked(delay) + let releaseTail!: () => void + mockDelay.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseTail = resolve + }), + ) + const tailProblem: vscode.Diagnostic = { + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message: "boom", + } + // Only the read the tail makes may see the problem, so the pre-save snapshot stays clean. + let emitTailProblem = false + mockTask.say.mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockImplementation(() => + emitTailProblem ? [[makeUri(`${mockCwd}/test.ts`), [tailProblem]]] : [], + ) + + try { + await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 100) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(mockDelay).toHaveBeenCalledWith( + 100, + expect.objectContaining({ signal: expect.any(AbortSignal) }), + ) + expect(diffViewProvider["pendingSaveReports"].size).toBe(1) + + await diffViewProvider.reset() + + // The entry that owns this report survives the reset, so the tail can still deliver it. + expect(diffViewProvider["pendingSaveReports"].size).toBe(1) + emitTailProblem = true + releaseTail() + await new Promise((resolve) => setTimeout(resolve, 0)) + + // Diagnostics were queried (pre-save snapshot plus the tail) and one error row was emitted. + expect(vscode.languages.getDiagnostics).toHaveBeenCalledTimes(2) + expect(mockTask.say).toHaveBeenCalledTimes(1) + expect(mockTask.say.mock.calls[0]?.[0]).toBe("error") + expect(mockTask.say.mock.calls[0]?.[1]).toContain("New problems detected after saving file: test.ts") + expect(mockTask.say.mock.calls[0]?.[1]).toContain("boom") + // The tail released the entry it owned instead of leaving it behind. + expect(diffViewProvider["pendingSaveReports"].size).toBe(0) + } finally { + // Restore the shared mock implementations even when an assertion fails: a gated delay + // left in place hangs the tests that rely on the module-level resolved mock. + mockDelay.mockImplementation(() => Promise.resolve()) + vi.mocked(vscode.languages.getDiagnostics).mockImplementation(() => []) + } + }) + + it("keeps a superseded tail from stealing the report when generations collide", async () => { + // Three saves of one path with independently gated write delays: A waits longest, B reports + // first and releases the entry, C starts while A is still parked. If generations restart at + // 1 after a report, A matches C's generation, reports for a save it does not own and deletes + // C's entry; C then stops and its problems are never reported. Each tail carries its own + // problem message so the assertions can tell which save actually emitted the row. + const mockDelay = vi.mocked(delay) + const gates: Array<() => void> = [] + mockDelay.mockImplementation( + () => + new Promise((resolve) => { + gates.push(resolve) + }), + ) + let tailProblem: vscode.Diagnostic | undefined + mockTask.say.mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockImplementation(() => + tailProblem ? [[makeUri(`${mockCwd}/test.ts`), [tailProblem]]] : [], + ) + const tick = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)) + const makeProblem = (message: string): vscode.Diagnostic => ({ + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message, + }) + + try { + await diffViewProvider.saveDirectly("test.ts", "content A", true, true, 100) + await tick() + expect(gates).toHaveLength(1) + await diffViewProvider.saveDirectly("test.ts", "content B", true, true, 100) + await tick() + expect(gates).toHaveLength(2) + + // B owns the report; let it finish first, which releases the entry. + tailProblem = makeProblem("boom B") + gates[1]() + await tick() + expect(mockTask.say).toHaveBeenCalledTimes(1) + expect(mockTask.say.mock.calls[0]?.[1]).toContain("boom B") + expect(diffViewProvider["pendingSaveReports"].size).toBe(0) + tailProblem = undefined + + await diffViewProvider.saveDirectly("test.ts", "content C", true, true, 100) + await tick() + expect(gates).toHaveLength(3) + const generationC = diffViewProvider["pendingSaveReports"].get(`${mockCwd}/test.ts`)?.generation + if (typeof generationC !== "number") { + throw new Error(`expected a numeric generation for the newest save, got ${String(generationC)}`) + } + + // A wakes last and must stop at the ownership check: no report, and C still owns the entry. + gates[0]() + await tick() + expect(mockTask.say).toHaveBeenCalledTimes(1) + expect(diffViewProvider["pendingSaveReports"].get(`${mockCwd}/test.ts`)?.generation).toBe(generationC) + + // C owns the report and delivers it. + tailProblem = makeProblem("boom C") + gates[2]() + await tick() + expect(mockTask.say).toHaveBeenCalledTimes(2) + expect(mockTask.say.mock.calls[1]?.[1]).toContain("boom C") + expect(diffViewProvider["pendingSaveReports"].size).toBe(0) + } finally { + gates.forEach((release) => release()) + mockDelay.mockImplementation(() => Promise.resolve()) + vi.mocked(vscode.languages.getDiagnostics).mockImplementation(() => []) + } + }) + + it("never reuses a generation for the next save after a report released its entry", async () => { + // Pins the generation arithmetic itself: a report deletes the entry, so the next save must + // keep counting up rather than restart where the superseded run left off. + const mockDelay = vi.mocked(delay) + const gates: Array<() => void> = [] + mockDelay.mockImplementation( + () => + new Promise((resolve) => { + gates.push(resolve) + }), + ) + mockTask.say.mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockImplementation(() => []) + const tick = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)) + const pathKey = `${mockCwd}/test.ts` + + try { + await diffViewProvider.saveDirectly("test.ts", "first", true, true, 0) + await tick() + const firstGeneration = diffViewProvider["pendingSaveReports"].get(pathKey)?.generation + gates[0]() + await tick() + expect(diffViewProvider["pendingSaveReports"].size).toBe(0) + + await diffViewProvider.saveDirectly("test.ts", "second", true, true, 0) + await tick() + const secondGeneration = diffViewProvider["pendingSaveReports"].get(pathKey)?.generation + if (typeof firstGeneration !== "number" || typeof secondGeneration !== "number") { + throw new Error( + `expected numeric generations, got ${String(firstGeneration)} and ${String(secondGeneration)}`, + ) + } + expect(secondGeneration > firstGeneration).toBe(true) + } finally { + gates.forEach((release) => release()) + mockDelay.mockImplementation(() => Promise.resolve()) + } + }) }) describe("saveChanges method with diagnostic settings", () => { @@ -885,6 +1549,91 @@ describe("DiffViewProvider", () => { vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) }) + it("stops a tail whose ownership was taken while the settings read was parked", async () => { + // The interleaving the generation checks are for: a tail passes the ownership check, releases + // the map entry, then parks in the settings await. A newer save of the same path registers + // meanwhile, so the parked tail no longer owns the report; only the cancellation re-checks + // exist here, so it resumes and emits a report for a save it no longer describes. Each save + // carries its own problem message so an assertion can tell which tail emitted the row. + const mockDelay = vi.mocked(delay) + const delayGates: Array<() => void> = [] + mockDelay.mockImplementation( + () => + new Promise((resolve) => { + delayGates.push(resolve) + }), + ) + const provider = mockTask.providerRef.deref() + const originalGetState = provider.getState + // Each settings read registers its own resolver, so the test can release the parked tail + // while the newer save's read is still held. + const stateResult = { includeDiagnosticMessages: true, maxDiagnosticMessages: 50 } + const stateGates: Array<(state: typeof stateResult) => void> = [] + provider.getState = vi.fn( + () => + new Promise((resolve) => { + stateGates.push(resolve) + }), + ) + let tailProblem: vscode.Diagnostic | undefined + const makeProblem = (message: string): vscode.Diagnostic => ({ + severity: vscode.DiagnosticSeverity.Error, + range: new vscode.Range(0, 0, 0, 1), + message, + }) + const tick = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)) + mockTask.say.mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockClear() + vi.mocked(vscode.languages.getDiagnostics).mockImplementation(() => + tailProblem ? [[makeUri(`${mockCwd}/test.ts`), [tailProblem]]] : [], + ) + try { + // Save one: its tail takes the report and parks in the settings read. + tailProblem = makeProblem("stale-ownership-problem") + await diffViewProvider.saveDirectly("test.ts", "content one", true, true, 100) + await tick() + expect(delayGates.length).toBeGreaterThanOrEqual(1) + delayGates.shift()?.() + await tick() + // The tail has taken its post-save diagnostics by now, so flipping the fixture below + // attributes the next row to the newer save only. + expect(stateGates.length).toBe(1) + expect(mockTask.say).not.toHaveBeenCalled() + + // Save two: a newer save of the same path registers while the first tail is parked. + tailProblem = makeProblem("newest-save-problem") + await diffViewProvider.saveDirectly("test.ts", "content two", true, true, 100) + await tick() + delayGates.forEach((release) => release()) + delayGates.length = 0 + await tick() + expect(stateGates.length).toBe(2) + + // Release the parked settings read: the first tail resumes without being cancelled, and + // the newer save is still waiting for its own settings read. + stateGates.shift()?.(stateResult) + await tick() + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(stateGates.length).toBe(1) + const emittedBeforeNewerSave = mockTask.say.mock.calls.map((call) => String(call[1])) + expect(emittedBeforeNewerSave.some((text) => text.includes("stale-ownership-problem"))).toBe(false) + + // The newer save finishes and owns the report; its row is the only emitted row. + stateGates.shift()?.(stateResult) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(mockTask.say).toHaveBeenCalledTimes(1) + expect(mockTask.say.mock.calls[0]?.[1]).toContain("newest-save-problem") + expect(mockTask.say.mock.calls[0]?.[1]).not.toContain("stale-ownership-problem") + // No entry is left behind: the owning tail releases the map entry when it reports. + expect(diffViewProvider["pendingSaveReports"].size).toBe(0) + } finally { + provider.getState = originalGetState + delayGates.forEach((release) => release()) + stateGates.forEach((release) => release(stateResult)) + mockDelay.mockImplementation(() => Promise.resolve()) + } + }) + it("should apply diagnostic delay when diagnosticsEnabled is true", async () => { const mockDelay = vi.mocked(delay) mockDelay.mockClear() @@ -1623,7 +2372,7 @@ describe("DiffViewProvider", () => { }) const setupProvider = (stateOverrides: Record = {}) => { - const provider = new DiffViewProvider(mockCwd, makeTaskDouble(stateOverrides)) + const provider = new DiffViewProvider(mockCwd, asTask(makeTaskDouble(stateOverrides))) provider["relPath"] = "auto-close-test.ts" provider["newContent"] = "content" provider["activeDiffEditor"] = buildActiveDiffEditor()