From 253a7b09ad47e2fc5ea157daed843246db3200f6 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 06:41:49 +0800 Subject: [PATCH 01/34] chore(webview): rebase the view identity unit onto main 6df256602d Semantic merge of pull 1552 head f5c8a2fe8203208307bb09c3c4a256362e0c6790 onto main head 6df256602d19502028ce9a2f744555b53973cf90, landed as one commit. Replaying the 100 branch commits against a main that already carries the earlier merged content of this branch yields replay artifacts rather than semantic conflicts, so the merge result is taken directly. Conflict surface: one file, src/core/webview/__tests__/ClineProvider.spec.ts, two regions, each with an empty merge base section, so both sides are kept in full. Main keeps the mention segment helpers plus the launch listener test; this branch keeps the stalled profile helper plus the re-pin test. Production files carry zero conflicts: global-settings.ts, vscode-extension-host.ts, ClineProvider.ts, webviewMessageHandler.ts, src/package.json and src/eslint-suppressions.json auto-merged at disjoint sites. One duplicate that the textual merge accepted was removed: both sides added the byte identical line importing t from ../../../i18n, main after the resolveChatProvider import and this branch after the safeWriteJson import, so the merged file held it twice and tsc reported TS2300 duplicate identifier on two lines. One copy stays, in the placement main uses; both sides stay satisfied because the two copies were identical. Region audit: the only base regions touched by both sides are three spots inside this one test file, the two conflict regions above and this import group. Both rules survive, audited per file. Method: from merge base 5e32badca3, take the added lines of main and of the pull head for each of the 27 files and count them line by line against the committed file. Result: main adds 515 added lines and this branch adds 12021 from that same base, and every one of them is present in the committed file at least as often as that side added it, while the removed lines of both sides stay removed. Suppressions relative to main head only fall, 2844 to 2841, with the two moves being core/webview/__tests__/ClineProvider.spec.ts 195 to 193 and core/webview/__tests__/ClineProvider.sticky-mode.spec.ts 27 to 26. No count rose and no new entry appears. --- .../src/__tests__/global-settings.test.ts | 29 + packages/types/src/__tests__/index.test.ts | 5 + packages/types/src/global-settings.ts | 12 + packages/types/src/vscode-extension-host.ts | 1 + packages/types/src/vscode.ts | 8 + .../__tests__/registerCommands.spec.ts | 1146 +++- src/activate/registerCommands.ts | 334 +- src/core/config/ContextProxy.ts | 3 + src/core/config/ProviderSettingsManager.ts | 66 +- .../config/__tests__/ContextProxy.spec.ts | 16 + .../__tests__/ProviderSettingsManager.spec.ts | 51 +- .../config/__tests__/importExport.spec.ts | 91 + src/core/config/importExport.ts | 8 + src/core/webview/ClineProvider.ts | 2366 ++++++- .../ClineProvider.apiHandlerRebuild.spec.ts | 119 +- .../ClineProvider.lockApiConfig.spec.ts | 70 + .../webview/__tests__/ClineProvider.spec.ts | 5563 ++++++++++++++++- .../ClineProvider.sticky-mode.spec.ts | 533 +- .../ClineProvider.sticky-profile.spec.ts | 122 + .../__tests__/webviewMessageHandler.spec.ts | 1099 +++- src/core/webview/webviewMessageHandler.ts | 287 +- src/eslint-suppressions.json | 4 +- src/package.json | 46 +- .../src/context/ExtensionStateContext.tsx | 5 +- .../__tests__/ExtensionStateContext.spec.tsx | 97 + webview-ui/src/utils/__tests__/vscode.spec.ts | 384 ++ webview-ui/src/utils/vscode.ts | 90 +- 27 files changed, 12020 insertions(+), 535 deletions(-) create mode 100644 webview-ui/src/utils/__tests__/vscode.spec.ts diff --git a/packages/types/src/__tests__/global-settings.test.ts b/packages/types/src/__tests__/global-settings.test.ts index f2b2e7e8e5b..7f3166989e7 100644 --- a/packages/types/src/__tests__/global-settings.test.ts +++ b/packages/types/src/__tests__/global-settings.test.ts @@ -39,6 +39,35 @@ describe("alwaysDenyUnapprovedCommands global setting", () => { }) }) +describe("viewStates global setting", () => { + it("parses a valid per-view record", () => { + const parsed = globalSettingsSchema.parse({ + viewStates: { + "stable-view-1": { mode: "code", currentApiConfigName: "profile-a", updatedAt: 1730000000000 }, + "stable-view-2": {}, + }, + }) + expect(parsed.viewStates?.["stable-view-1"]).toEqual({ + mode: "code", + currentApiConfigName: "profile-a", + updatedAt: 1730000000000, + }) + expect(parsed.viewStates?.["stable-view-2"]).toEqual({}) + expect(GLOBAL_SETTINGS_KEYS).toContain("viewStates") + }) + + it("rejects invalid field values inside a view entry", () => { + expect(() => globalSettingsSchema.parse({ viewStates: { v: { mode: 42 } } })).toThrow() + expect(() => globalSettingsSchema.parse({ viewStates: { v: { currentApiConfigName: 42 } } })).toThrow() + expect(() => globalSettingsSchema.parse({ viewStates: { v: { updatedAt: "soon" } } })).toThrow() + }) + + it("rejects non-object viewStates values", () => { + expect(() => globalSettingsSchema.parse({ viewStates: "not-a-record" })).toThrow() + expect(() => globalSettingsSchema.parse({ viewStates: { v: "not-an-entry" } })).toThrow() + }) +}) + describe("collapseCommandOutputByDefault global setting", () => { it.each([true, false, undefined])("round-trips %s through the export/import schema", (value) => { const settings = globalSettingsSchema.parse({ collapseCommandOutputByDefault: value }) diff --git a/packages/types/src/__tests__/index.test.ts b/packages/types/src/__tests__/index.test.ts index 15441d48fd2..b4cee22f8c9 100644 --- a/packages/types/src/__tests__/index.test.ts +++ b/packages/types/src/__tests__/index.test.ts @@ -3,6 +3,10 @@ import { GLOBAL_STATE_KEYS } from "../index.js" describe("GLOBAL_STATE_KEYS", () => { + it("should contain registered durable per-view state", () => { + expect(GLOBAL_STATE_KEYS).toContain("viewStates") + }) + it("should contain provider settings keys", () => { expect(GLOBAL_STATE_KEYS).toContain("autoApprovalEnabled") }) @@ -13,6 +17,7 @@ describe("GLOBAL_STATE_KEYS", () => { it("should not contain secret state keys", () => { expect(GLOBAL_STATE_KEYS).not.toContain("openRouterApiKey") + expect(GLOBAL_STATE_KEYS).not.toContain("apiKey") }) it("should contain OpenAI Compatible base URL setting", () => { diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index ef812b01bbd..c8036e36799 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -117,6 +117,17 @@ export const MAX_CHECKPOINT_TIMEOUT_SECONDS = 60 */ export const DEFAULT_CHECKPOINT_TIMEOUT_SECONDS = 15 +/** + * Persisted non-secret selections for a stable webview instance. + */ +export const viewStateSchema = z.object({ + mode: z.string().optional(), + currentApiConfigName: z.string().optional(), + updatedAt: z.number().optional(), + /** Host-minted token binding this entry to the webview that wrote it. */ + claimToken: z.string().optional(), +}) + /** * GlobalSettings */ @@ -125,6 +136,7 @@ export const globalSettingsSchema = z.object({ currentApiConfigName: z.string().optional(), listApiConfigMeta: z.array(providerSettingsEntrySchema).optional(), pinnedApiConfigs: z.record(z.string(), z.boolean()).optional(), + viewStates: z.record(z.string(), viewStateSchema).optional(), lastShownAnnouncementId: z.string().optional(), customInstructions: z.string().optional(), diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 4e7efff57fc..b6dbaffd57d 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -759,6 +759,7 @@ export interface WebviewMessage { | "themeFixtureProbeResponse" | "diagnosticsResponse" text?: string + viewStateId?: string taskId?: string editedMessageContent?: string tab?: "settings" | "history" | "mcp" | "modes" | "chat" | "marketplace" | "cloud" diff --git a/packages/types/src/vscode.ts b/packages/types/src/vscode.ts index 811ceda165f..ab13f48dfe4 100644 --- a/packages/types/src/vscode.ts +++ b/packages/types/src/vscode.ts @@ -35,6 +35,14 @@ export const commandIds = [ "popoutButtonClicked", "settingsButtonClicked", + // Editor-tab (popped-out) surface variants of the title-bar buttons. The + // shared ids above target the sidebar click origin, so the tab surface + // needs its own ids (see registerCommands.ts getTabProvider). + "plusButtonClickedInTab", + "settingsButtonClickedInTab", + "marketplaceButtonClickedInTab", + "historyButtonClickedInTab", + "openInNewTab", "newTask", diff --git a/src/activate/__tests__/registerCommands.spec.ts b/src/activate/__tests__/registerCommands.spec.ts index c59933a7c15..81e1fc93a6b 100644 --- a/src/activate/__tests__/registerCommands.spec.ts +++ b/src/activate/__tests__/registerCommands.spec.ts @@ -1,11 +1,22 @@ import type { Mock } from "vitest" import * as vscode from "vscode" -import { ClineProvider } from "../../core/webview/ClineProvider" +import { TelemetryService } from "@roo-code/telemetry" import { WebviewFocusTracker } from "../../core/webview/WebviewFocusTracker" -import { ContextProxy } from "../../core/config/ContextProxy" import { makeExtensionContext } from "../../test-utils/vscode" -import { getPanel, getVisibleProviderOrLog, openClineInNewTab, registerCommands, setPanel } from "../registerCommands" +import { ContextProxy } from "../../core/config/ContextProxy" +import { ClineProvider } from "../../core/webview/ClineProvider" +import { MdmService } from "../../services/mdm/MdmService" + +import { + __getLiveTabPanelCountForTests, + __resetLiveTabPanelsForTests, + getPanel, + getVisibleProviderOrLog, + openClineInNewTab, + registerCommands, + setPanel, +} from "../registerCommands" vi.mock("execa", () => ({ execa: vi.fn(), @@ -143,11 +154,11 @@ describe("registerCommands handlers", () => { let mockVisibleProvider: { postMessageToWebview: Mock retryWebviewRecovery: Mock<() => Promise> - evictCurrentTask?: Mock - refreshWorkspace?: Mock } let mockProvider: { postMessageToWebview: Mock + evictCurrentTask: Mock + refreshWorkspace: Mock webviewFocusTracker: WebviewFocusTracker retryWebviewRecovery: Mock<() => Promise> } @@ -181,6 +192,8 @@ describe("registerCommands handlers", () => { mockProvider = { retryWebviewRecovery: vi.fn().mockResolvedValue(undefined), postMessageToWebview: vi.fn().mockResolvedValue(undefined), + evictCurrentTask: vi.fn().mockResolvedValue(undefined), + refreshWorkspace: vi.fn().mockResolvedValue(undefined), webviewFocusTracker: new WebviewFocusTracker(), } ;(ClineProvider.getVisibleInstance as Mock).mockReturnValue(mockVisibleProvider) @@ -209,6 +222,7 @@ describe("registerCommands handlers", () => { // Reset module-level panel state to prevent leakage between tests. setPanel(undefined, "sidebar") setPanel(undefined, "tab") + __resetLiveTabPanelsForTests() }) it("registers the ripgrep diagnostic command and stores its disposable in context.subscriptions", async () => { @@ -267,6 +281,8 @@ describe("registerCommands handlers", () => { }, ) + // The sidebar title-bar handlers target the registered provider (the + // sidebar click origin) directly, not the visible-instance heuristic. it("creates diagnostics from all provider instances without requiring a visible provider", async () => { const { createDiagnosticsReport } = await import("../../services/diagnostics") const providers = [{}, {}] @@ -282,44 +298,112 @@ describe("registerCommands handlers", () => { }) }) - it("settingsButtonClicked posts both settingsButtonClicked and didBecomeVisible actions", () => { + it("settingsButtonClicked posts both settingsButtonClicked and didBecomeVisible actions on the registered provider", () => { handlers["zoo-code.settingsButtonClicked"]() - expect(mockVisibleProvider.postMessageToWebview).toHaveBeenCalledWith({ + expect(TelemetryService.instance.captureTitleButtonClicked).toHaveBeenCalledWith("settings") + expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "settingsButtonClicked", }) - expect(mockVisibleProvider.postMessageToWebview).toHaveBeenCalledWith({ + expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "didBecomeVisible", }) - expect(mockVisibleProvider.postMessageToWebview).toHaveBeenCalledTimes(2) - }) - - it("settingsButtonClicked is a no-op when no visible provider", () => { - ;(ClineProvider.getVisibleInstance as Mock).mockReturnValue(undefined) - - handlers["zoo-code.settingsButtonClicked"]() - + expect(mockProvider.postMessageToWebview).toHaveBeenCalledTimes(2) expect(mockVisibleProvider.postMessageToWebview).not.toHaveBeenCalled() }) - it("historyButtonClicked posts historyButtonClicked action", () => { + it("historyButtonClicked posts historyButtonClicked action on the registered provider", () => { handlers["zoo-code.historyButtonClicked"]() - expect(mockVisibleProvider.postMessageToWebview).toHaveBeenCalledWith({ + expect(TelemetryService.instance.captureTitleButtonClicked).toHaveBeenCalledWith("history") + expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "historyButtonClicked", }) + expect(mockVisibleProvider.postMessageToWebview).not.toHaveBeenCalled() }) - it("marketplaceButtonClicked posts marketplaceButtonClicked action", () => { + it("marketplaceButtonClicked posts marketplaceButtonClicked action on the registered provider", () => { handlers["zoo-code.marketplaceButtonClicked"]() - expect(mockVisibleProvider.postMessageToWebview).toHaveBeenCalledWith({ + expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "marketplaceButtonClicked", }) + expect(mockVisibleProvider.postMessageToWebview).not.toHaveBeenCalled() + }) + + // The `*InTab` handlers serve the `editor/title` menu: they target the + // instance that owns the tracked tab panel, resolved via + // ClineProvider.getInstanceForView. + const tabHandlerCases: { command: string; actions: string[]; telemetry?: string }[] = [ + { + command: "zoo-code.settingsButtonClickedInTab", + actions: ["settingsButtonClicked", "didBecomeVisible"], + telemetry: "settings", + }, + { command: "zoo-code.historyButtonClickedInTab", actions: ["historyButtonClicked"], telemetry: "history" }, + { command: "zoo-code.marketplaceButtonClickedInTab", actions: ["marketplaceButtonClicked"] }, + ] + it.each(tabHandlerCases)( + "$command targets the tab instance for the tracked tab panel", + ({ command, actions, telemetry }) => { + const mockTabProvider = { postMessageToWebview: vi.fn().mockResolvedValue(undefined) } + // Retain the tracked tab panel and pin the instance lookup + // against its identity: a handler that resolved the sidebar view + // or any other view must fail instead of passing on the stubbed + // provider result alone. + const tabPanel = {} as vscode.WebviewPanel + setPanel(tabPanel, "tab") + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(mockTabProvider) + + handlers[command]() + + // Identity pin: the lookup must receive the exact tracked panel + // object, not a different object that merely compares equal. + expect((ClineProvider.getInstanceForView as Mock).mock.calls[0]![0]).toBe(tabPanel) + for (const action of actions) { + expect(mockTabProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action }) + } + expect(mockTabProvider.postMessageToWebview).toHaveBeenCalledTimes(actions.length) + if (telemetry) { + expect(TelemetryService.instance.captureTitleButtonClicked).toHaveBeenCalledWith(telemetry) + } + expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled() + }, + ) + + // The `*InTab` handlers must no-op when there is no live tab instance: a + // missing or disposed tab must not crash the handler or fall back to + // another instance. Every handler is awaited, so an async handler that + // slipped past its guard (rejecting on the missing instance) fails the + // test instead of settling as an unhandled rejection. + const inTabNoOpCommands = [ + "zoo-code.plusButtonClickedInTab", + "zoo-code.settingsButtonClickedInTab", + "zoo-code.historyButtonClickedInTab", + "zoo-code.marketplaceButtonClickedInTab", + ] + it.each(inTabNoOpCommands)("%s is a no-op when no tab panel is tracked", async (command) => { + await handlers[command]() + + expect(ClineProvider.getInstanceForView as Mock).not.toHaveBeenCalled() + expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled() + expect(mockVisibleProvider.postMessageToWebview).not.toHaveBeenCalled() + }) + + it.each(inTabNoOpCommands)("%s is a no-op when the tab instance is disposed", async (command) => { + const disposedPanel = {} as vscode.WebviewPanel + setPanel(disposedPanel, "tab") + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(undefined) + + await handlers[command]() + + expect(ClineProvider.getInstanceForView as Mock).toHaveBeenCalledWith(disposedPanel) + expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled() + expect(mockVisibleProvider.postMessageToWebview).not.toHaveBeenCalled() }) it("acceptInput posts acceptInput message", () => { @@ -392,44 +476,158 @@ describe("registerCommands handlers", () => { }) }) - it("focusInput does not post when no sidebar panel is active", async () => { + it("focusInput does not post when no sidebar panel is tracked", async () => { + await handlers["zoo-code.focusInput"]() + + expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled() + }) + + it("focusInput does not post when a tab panel is tracked without a live tab instance", async () => { + setPanel({} as vscode.WebviewView, "sidebar") + setPanel({} as vscode.WebviewPanel, "tab") + + await handlers["zoo-code.focusInput"]() + + // The tab takes selection priority, so the sidebar must not receive + // the message; with no live tab instance there is no other target. + expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled() + }) + + it("focusInput posts the focus message on the tab instance when a tab panel is tracked", async () => { + const mockTabProvider = { postMessageToWebview: vi.fn().mockResolvedValue(undefined) } + setPanel({} as vscode.WebviewView, "sidebar") + const tabPanel = {} as vscode.WebviewPanel + setPanel(tabPanel, "tab") + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(mockTabProvider) + await handlers["zoo-code.focusInput"]() + // The tab takes selection priority: assert it was selected by identity + // (reference, not structural equality). + expect((ClineProvider.getInstanceForView as Mock).mock.calls[0]![0]).toBe(tabPanel) + // No error was logged on the success path. + expect(mockOutputChannel.appendLine).not.toHaveBeenCalled() + expect(mockTabProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "focusInput" }) expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled() }) - // Representative coverage for the .catch arm on all five void-prefixed - // postMessageToWebview sites in registerCommands.ts (settingsButtonClicked - // posts twice, plus historyButtonClicked, marketplaceButtonClicked, and - // acceptInput). Each handler is synchronous, so the .catch arm runs on a - // microtask; setImmediate ensures all microtasks are flushed before we assert. The + it("setPanel keeps independent refs: clearing only the tab ref re-enables the sidebar post", async () => { + setPanel({} as vscode.WebviewView, "sidebar") + setPanel({} as vscode.WebviewPanel, "tab") + + // The tab ref does not wipe the sidebar ref... + await handlers["zoo-code.focusInput"]() + expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled() + + // ...and clearing only the tab ref re-enables the sidebar post. + setPanel(undefined, "tab") + await handlers["zoo-code.focusInput"]() + expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "focusInput" }) + }) + + // Coverage for the .catch arm on the sidebar title-bar post sites + // (settingsButtonClicked posts twice, plus historyButtonClicked and + // marketplaceButtonClicked) and acceptInput (the visible-provider path). + // Each handler is synchronous, so the .catch arm runs on a microtask; + // setImmediate ensures all microtasks are flushed before we assert. The // log messages carry a `[]` prefix so multi-failure logs // remain unambiguous; the prefix is per-handler, not per-call (both of - // settingsButtonClicked's posts share the same prefix). + // settingsButtonClicked's posts share the same prefix). Each post rejects + // with its own error and call N is pinned to post N, so a mutant that + // alters one catch's message cannot hide behind the other post's + // identical log. it.each([ - { command: "zoo-code.settingsButtonClicked", prefix: "settingsButtonClicked", expectedCalls: 2 }, - { command: "zoo-code.historyButtonClicked", prefix: "historyButtonClicked", expectedCalls: 1 }, - { command: "zoo-code.marketplaceButtonClicked", prefix: "marketplaceButtonClicked", expectedCalls: 1 }, - { command: "zoo-code.acceptInput", prefix: "acceptInput", expectedCalls: 1 }, + { + command: "zoo-code.settingsButtonClicked", + prefix: "settingsButtonClicked", + errorLabels: ["first post", "second post"], + target: "sidebar" as const, + }, + { + command: "zoo-code.historyButtonClicked", + prefix: "historyButtonClicked", + errorLabels: ["post"], + target: "sidebar" as const, + }, + { + command: "zoo-code.marketplaceButtonClicked", + prefix: "marketplaceButtonClicked", + errorLabels: ["post"], + target: "sidebar" as const, + }, + { command: "zoo-code.acceptInput", prefix: "acceptInput", errorLabels: ["post"], target: "visible" as const }, ])( "$command logs to outputChannel when postMessageToWebview rejects", - async ({ command, prefix, expectedCalls }) => { - const boom = new Error("boom") - mockVisibleProvider.postMessageToWebview.mockReset() - mockVisibleProvider.postMessageToWebview.mockRejectedValue(boom) + async ({ command, prefix, errorLabels, target }) => { + const post = + target === "sidebar" ? mockProvider.postMessageToWebview : mockVisibleProvider.postMessageToWebview + post.mockReset() + const booms = errorLabels.map((label) => new Error(label)) + booms.forEach((boom) => post.mockRejectedValueOnce(boom)) handlers[command]() - // Flush microtasks so the chained .catch arm runs. + // Flush microtasks so the chained .catch arms run. await new Promise((resolve) => setImmediate(resolve)) - expect(mockOutputChannel.appendLine).toHaveBeenCalledTimes(expectedCalls) - expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( - `[${prefix}] postMessageToWebview failed: ${boom}`, - ) + expect(mockOutputChannel.appendLine).toHaveBeenCalledTimes(booms.length) + booms.forEach((boom, index) => { + expect(mockOutputChannel.appendLine).toHaveBeenNthCalledWith( + index + 1, + `[${prefix}] postMessageToWebview failed: ${boom}`, + ) + }) }, ) + // The two posts reject with distinct errors and the nth-call assertions + // pin each catch's message, so neither template literal can survive + // behind the other post's identical log. + it("settingsButtonClickedInTab logs to outputChannel when postMessageToWebview rejects", async () => { + const booms = [new Error("first post"), new Error("second post")] + const mockTabProvider = { + postMessageToWebview: vi.fn().mockRejectedValueOnce(booms[0]).mockRejectedValueOnce(booms[1]), + } + setPanel({} as vscode.WebviewPanel, "tab") + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(mockTabProvider) + + handlers["zoo-code.settingsButtonClickedInTab"]() + + // Flush microtasks so the chained .catch arms run. + await new Promise((resolve) => setImmediate(resolve)) + + expect(mockOutputChannel.appendLine).toHaveBeenCalledTimes(2) + expect(mockOutputChannel.appendLine).toHaveBeenNthCalledWith( + 1, + `[settingsButtonClickedInTab] postMessageToWebview failed: ${booms[0]}`, + ) + expect(mockOutputChannel.appendLine).toHaveBeenNthCalledWith( + 2, + `[settingsButtonClickedInTab] postMessageToWebview failed: ${booms[1]}`, + ) + }) + + // The history and marketplace InTab catch sites share the identical + // single-post pattern (their sidebar equivalents are covered by the + // it.each above); pin their exact messages too. + it.each([ + { command: "zoo-code.historyButtonClickedInTab", prefix: "historyButtonClickedInTab" }, + { command: "zoo-code.marketplaceButtonClickedInTab", prefix: "marketplaceButtonClickedInTab" }, + ])("$command logs to outputChannel when the tab postMessageToWebview rejects", async ({ command, prefix }) => { + const boom = new Error("post") + const mockTabProvider = { postMessageToWebview: vi.fn().mockRejectedValue(boom) } + setPanel({} as vscode.WebviewPanel, "tab") + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(mockTabProvider) + + handlers[command]() + + // Flush microtasks so the chained .catch arm runs. + await new Promise((resolve) => setImmediate(resolve)) + + expect(mockOutputChannel.appendLine).toHaveBeenCalledTimes(1) + expect(mockOutputChannel.appendLine).toHaveBeenCalledWith(`[${prefix}] postMessageToWebview failed: ${boom}`) + }) + it("toggleAutoApprove logs to outputChannel when postMessageToWebview rejects", async () => { // toggleAutoApprove is `async` and awaits postMessageToWebview inside a // try/catch (rather than relying on a `.catch` microtask like the @@ -447,22 +645,41 @@ describe("registerCommands handlers", () => { ) }) - it("plusButtonClicked calls evictCurrentTask on the visible provider", async () => { - const evictCurrentTask = vi.fn().mockResolvedValue(undefined) - const refreshWorkspace = vi.fn().mockResolvedValue(undefined) - mockVisibleProvider.evictCurrentTask = evictCurrentTask - mockVisibleProvider.refreshWorkspace = refreshWorkspace - + it("plusButtonClicked calls evictCurrentTask on the registered sidebar provider", async () => { await handlers["zoo-code.plusButtonClicked"]() - expect(evictCurrentTask).toHaveBeenCalledTimes(1) + expect(TelemetryService.instance.captureTitleButtonClicked).toHaveBeenCalledWith("plus") + expect(mockProvider.evictCurrentTask).toHaveBeenCalledTimes(1) + expect(mockProvider.refreshWorkspace).toHaveBeenCalledTimes(1) + expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "chatButtonClicked" }) + expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "focusInput" }) }) - it("plusButtonClicked is a no-op when no visible provider", async () => { - ;(ClineProvider.getVisibleInstance as Mock).mockReturnValue(undefined) - - // Should not throw even with no visible provider - await handlers["zoo-code.plusButtonClicked"]() + it("plusButtonClickedInTab evicts and posts on the tab instance for the tracked tab panel", async () => { + const mockTabProvider = { + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + evictCurrentTask: vi.fn().mockResolvedValue(undefined), + refreshWorkspace: vi.fn().mockResolvedValue(undefined), + } + // Same identity pin as the other InTab cases: the eviction must run + // against the provider resolved from the exact tracked tab panel. + const tabPanel = {} as vscode.WebviewPanel + setPanel(tabPanel, "tab") + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(mockTabProvider) + + await handlers["zoo-code.plusButtonClickedInTab"]() + + // Identity pin: the eviction must run against the provider resolved + // from the exact tracked panel object, not a merely-equal stub. + expect((ClineProvider.getInstanceForView as Mock).mock.calls[0]![0]).toBe(tabPanel) + expect(TelemetryService.instance.captureTitleButtonClicked).toHaveBeenCalledWith("plus") + expect(mockTabProvider.evictCurrentTask).toHaveBeenCalledTimes(1) + expect(mockTabProvider.refreshWorkspace).toHaveBeenCalledTimes(1) + expect(mockTabProvider.postMessageToWebview).toHaveBeenCalledWith({ + type: "action", + action: "chatButtonClicked", + }) + expect(mockTabProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "focusInput" }) }) }) @@ -499,6 +716,7 @@ describe("openClineInNewTab", () => { // Reset module-level panel state. setPanel(undefined, "sidebar") setPanel(undefined, "tab") + __resetLiveTabPanelsForTests() }) it.each([false, true])( @@ -532,6 +750,9 @@ describe("openClineInNewTab", () => { undefined, ) + // No tab was tracked, so the reuse path (and its instance lookup) + // must not run. + expect(ClineProvider.getInstanceForView as Mock).not.toHaveBeenCalled() expect(vscode.window.createWebviewPanel).toHaveBeenCalledWith( "zoo-code.TabPanelProvider", "Zoo Code", @@ -542,4 +763,825 @@ describe("openClineInNewTab", () => { }), ) }) + + it("reveals the existing tab instead of creating a second panel", async () => { + const mockExistingProvider = { postMessageToWebview: vi.fn().mockResolvedValue(undefined) } + const mockPanel = Object.assign({} as vscode.WebviewPanel, { + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + reveal: vi.fn().mockResolvedValue(undefined), + }) + setPanel(mockPanel, "tab") + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(mockExistingProvider) + + const result = await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + expect(result).toBe(mockExistingProvider) + expect(mockPanel.reveal).toHaveBeenCalledTimes(1) + expect(vscode.window.createWebviewPanel).not.toHaveBeenCalled() + expect(mockExistingProvider.postMessageToWebview).toHaveBeenCalledWith({ + type: "action", + action: "didBecomeVisible", + }) + }) + + it("re-runs the editor group lock when the first attempt failed", async () => { + const mockExistingProvider = { postMessageToWebview: vi.fn().mockResolvedValue(undefined) } + const panel = Object.assign({} as vscode.WebviewPanel, { + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + reveal: vi.fn().mockResolvedValue(undefined), + }) + ;(vscode.window.createWebviewPanel as Mock).mockReturnValue(panel) + // The lock rejects after the panel was created and tracked: the panel and its + // provider stay registered, so the next open takes the reuse path and has to + // re-issue the lock it never got. + const executeCommand = vi.mocked(vscode.commands.executeCommand) + executeCommand.mockImplementation(async (command: string) => { + if (command === "workbench.action.lockEditorGroup") { + throw new Error("lock failed") + } + return undefined + }) + + await expect( + openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }), + ).rejects.toThrow("lock failed") + expect(getPanel()).toBe(panel) + + executeCommand.mockImplementation(async () => undefined) + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(mockExistingProvider) + const result = await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + expect(result).toBe(mockExistingProvider) + expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(1) + expect( + executeCommand.mock.calls.filter(([command]) => command === "workbench.action.lockEditorGroup"), + ).toHaveLength(2) + + executeCommand.mockReset() + }) + + it("fails the open when the panel closes while the provider is initializing", async () => { + let disposeHandler: (() => void) | undefined + const panel = Object.assign({} as vscode.WebviewPanel, { + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn((handler: () => void) => { + disposeHandler = handler + }), + dispose: vi.fn(() => disposeHandler?.()), + }) + ;(vscode.window.createWebviewPanel as Mock).mockReturnValue(panel) + // A close that lands while the provider is generating HTML makes its + // resolveWebviewView return without an error (a disposed view is a stale + // resolve), so the open must detect the close itself instead of handing the + // disposed provider back to API.startNewTask. + const resolveSpy = vi.spyOn(ClineProvider.prototype, "resolveWebviewView").mockImplementation(async () => { + disposeHandler?.() + }) + const disposeSpy = vi.spyOn(ClineProvider.prototype, "dispose").mockResolvedValue(undefined) + + await expect( + openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }), + ).rejects.toThrow("The Zoo Code editor tab was closed while it was initializing.") + expect(disposeSpy).toHaveBeenCalledTimes(1) + + resolveSpy.mockRestore() + disposeSpy.mockRestore() + }) + + it("creates a new tab panel when the tracked tab's provider has been disposed", async () => { + const mockPanel = Object.assign({} as vscode.WebviewPanel, { + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + reveal: vi.fn().mockResolvedValue(undefined), + }) + setPanel(mockPanel, "tab") + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(undefined) + + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + expect(mockPanel.reveal).not.toHaveBeenCalled() + expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(1) + }) + + it("re-points the tracked tab ref at the panel that becomes active", async () => { + // Panel A is created first and tracked... + const panelA = Object.assign({} as vscode.WebviewPanel, { + marker: "panel-A", + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + }) + ;(vscode.window.createWebviewPanel as Mock).mockReturnValueOnce(panelA) + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + // ...then panel B is created, which re-points the tracked tab ref. + const panelB = Object.assign({} as vscode.WebviewPanel, { + marker: "panel-B", + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + }) + ;(vscode.window.createWebviewPanel as Mock).mockReturnValueOnce(panelB) + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + // Activating A must reassign the tracked tab ref to A's panel... + const stateChange = (panelA.onDidChangeViewState as Mock).mock.calls[0]![0] as (e: { + webviewPanel: vscode.WebviewPanel + }) => void + stateChange({ webviewPanel: { ...panelA, active: true, visible: true } }) + + // ...so plusButtonClickedInTab targets A's provider, not B's. + const mockProviderA = { + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + evictCurrentTask: vi.fn().mockResolvedValue(undefined), + refreshWorkspace: vi.fn().mockResolvedValue(undefined), + } + ;(ClineProvider.getInstanceForView as Mock).mockImplementation((view: unknown) => + (view as { marker?: string }).marker === "panel-A" ? mockProviderA : undefined, + ) + const handlers = new Map unknown>() + ;(vscode.commands.registerCommand as Mock).mockImplementation( + (id: string, cb: (...args: unknown[]) => unknown) => { + handlers.set(id, cb) + return { dispose: vi.fn() } + }, + ) + const mockSidebarProvider = Object.assign({} as ClineProvider, { + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + }) + registerCommands({ + context: mockContext, + outputChannel: mockOutputChannel, + provider: mockSidebarProvider, + }) + + await handlers.get("zoo-code.plusButtonClickedInTab")!() + + expect(mockProviderA.evictCurrentTask).toHaveBeenCalledTimes(1) + expect(mockProviderA.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "chatButtonClicked" }) + expect(mockProviderA.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "focusInput" }) + }) + + it("re-points the tracked tab ref at the remaining live panel when the tracked panel closes", async () => { + // A preceding test's instance-lookup double must not leak into the reuse + // path: both opens here must create fresh panels. + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(undefined) + + // Panel A is created and tracked first... + const panelA = Object.assign({} as vscode.WebviewPanel, { + marker: "panel-A", + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + }) + ;(vscode.window.createWebviewPanel as Mock).mockReturnValueOnce(panelA) + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + // ...then panel B opens in a different group: B becomes active, so the + // state-change handler re-points the tracked ref at B. + const panelB = Object.assign({} as vscode.WebviewPanel, { + marker: "panel-B", + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + }) + ;(vscode.window.createWebviewPanel as Mock).mockReturnValueOnce(panelB) + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + Object.assign(panelB, { active: true, visible: true }) + ;(panelB.onDidChangeViewState as Mock).mock.calls[0]![0]!({ webviewPanel: panelB }) + expect(getPanel()).toBe(panelB) + + // Closing the tracked panel (B) emits no state change for A, so the dispose + // handler alone must re-point the tracked ref at the remaining live panel. + Object.assign(panelA, { visible: true }) + const disposeB = (panelB.onDidDispose as Mock).mock.calls[0]![0] as () => void + disposeB() + expect(getPanel()).toBe(panelA) + + // The re-pointed panel must actually serve the tab-scoped commands: the + // command handler resolves the provider from the tracked panel, so panel + // A's provider receives the message even though B was created last. + const replacementProvider = { postMessageToWebview: vi.fn().mockResolvedValue(undefined) } + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(replacementProvider) + const commandHandlers: Record unknown> = {} + ;(vscode.commands.registerCommand as Mock).mockImplementation( + (id: string, cb: (...args: unknown[]) => unknown) => { + commandHandlers[id] = cb + return { dispose: vi.fn() } + }, + ) + registerCommands({ + context: mockContext, + outputChannel: mockOutputChannel, + provider: {} as ClineProvider, + }) + await commandHandlers["zoo-code.historyButtonClickedInTab"]() + expect(replacementProvider.postMessageToWebview).toHaveBeenCalledWith({ + type: "action", + action: "historyButtonClicked", + }) + + // Closing the last live tab clears the ref again. + const disposeA = (panelA.onDidDispose as Mock).mock.calls[0]![0] as () => void + disposeA() + expect(getPanel()).toBeUndefined() + }) + + it("re-points the tracked tab at the best remaining live panel on close", async () => { + const makePanel = (marker: string) => + Object.assign({} as vscode.WebviewPanel, { + marker, + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + }) + const openThree = async (p1: vscode.WebviewPanel, p2: vscode.WebviewPanel, p3: vscode.WebviewPanel) => { + ;(vscode.window.createWebviewPanel as Mock) + .mockReturnValueOnce(p1) + .mockReturnValueOnce(p2) + .mockReturnValueOnce(p3) + // A preceding test's instance-lookup double must not leak into the reuse + // path: each open here creates a fresh panel. + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(undefined) + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + // The last created panel becomes the tracked tab. + ;(p3.onDidChangeViewState as Mock).mock.calls[0]![0]!({ webviewPanel: p3 }) + expect(getPanel()).toBe(p3) + return p3 + } + const disposeTracked = (p: vscode.WebviewPanel) => { + const handler = (p.onDidDispose as Mock).mock.calls[0]![0] as () => void + handler() + } + + // Phase 1 — an active remaining panel wins over a visible one, even + // while the active panel itself is not visible: during a view-state + // transition active and visible can diverge, and the active panel is + // the one the user was last looking at, so it must win the re-pointing. + const panelA = makePanel("phase-1-A") + const panelD = makePanel("phase-1-D") + const panelC = makePanel("phase-1-C") + await openThree(panelA, panelD, panelC) + Object.assign(panelA, { active: true, visible: false }) + Object.assign(panelD, { active: false, visible: true }) + disposeTracked(panelC) + expect(getPanel()).toBe(panelA) + + // Phase 2 — a visible remaining panel wins over a hidden one. + __resetLiveTabPanelsForTests() + setPanel(undefined, "tab") + const panelE = makePanel("phase-2-E") + const panelV = makePanel("phase-2-V") + const panelC2 = makePanel("phase-2-C") + await openThree(panelE, panelV, panelC2) + Object.assign(panelE, { active: false, visible: false }) + Object.assign(panelV, { active: false, visible: true }) + disposeTracked(panelC2) + expect(getPanel()).toBe(panelV) + + // Phase 3 — with no active or visible remaining panel, the first remaining + // panel keeps the tracked ref: a panel can be open but hidden behind another + // editor group (neither active nor visible), and dropping the ref here would + // let the next open create a second panel instead of revealing it. + __resetLiveTabPanelsForTests() + setPanel(undefined, "tab") + const panelH1 = makePanel("phase-3-H1") + const panelH2 = makePanel("phase-3-H2") + const panelC3 = makePanel("phase-3-C") + await openThree(panelH1, panelH2, panelC3) + Object.assign(panelH1, { active: false, visible: false }) + Object.assign(panelH2, { active: false, visible: false }) + disposeTracked(panelC3) + expect(getPanel()).toBe(panelH1) + }) + + it("cleans up the tracked refs and disposes the provider when initialization fails", async () => { + const resolveSpy = vi + .spyOn(ClineProvider.prototype, "resolveWebviewView") + .mockRejectedValue(new Error("init failed")) + // The real provider dispose disposes the panel, which fires the disposal + // handler installed by createClineTabPanel; the double mirrors that + // contract so the tracked-ref cleanup runs the production path. + let disposeHandler: (() => void) | undefined + const failingPanel = Object.assign({} as vscode.WebviewPanel, { + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn((handler: () => void) => { + disposeHandler = handler + }), + dispose: vi.fn(() => disposeHandler?.()), + }) + ;(vscode.window.createWebviewPanel as Mock).mockReturnValue(failingPanel) + const disposeSpy = vi.spyOn(ClineProvider.prototype, "dispose").mockImplementation(async () => { + failingPanel.dispose() + }) + + await expect( + openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }), + ).rejects.toThrow("init failed") + + // The half-registered panel must not stay tracked: the live registry + // drops it and the provider is disposed - disposing the provider + // disposes the panel, whose disposal handler then clears the tracked + // ref (no other live panel remains here). + expect(__getLiveTabPanelCountForTests()).toBe(0) + expect(getPanel()).toBeUndefined() + expect(disposeSpy).toHaveBeenCalledTimes(1) + + resolveSpy.mockRestore() + disposeSpy.mockRestore() + }) + + it("re-points the tracked tab at the surviving panel when a new panel's initialization fails", async () => { + // clearAllMocks() keeps mock implementations: reset the instance-lookup + // return value so a preceding test's tab double cannot leak into the + // creation path below. + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(undefined) + // Panel A opens fully and becomes the tracked tab. + const panelA = Object.assign({} as vscode.WebviewPanel, { + marker: "panel-A", + active: true, + visible: true, + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + }) + ;(vscode.window.createWebviewPanel as Mock).mockReturnValueOnce(panelA) + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + expect(getPanel()).toBe(panelA) + + // Panel B's initialization fails. Its provider dispose mirrors the real + // contract: disposing the provider disposes the panel, which fires the + // disposal handler installed by createClineTabPanel. + let disposeHandlerB: (() => void) | undefined + const panelB = Object.assign({} as vscode.WebviewPanel, { + marker: "panel-B", + active: true, + visible: true, + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn((handler: () => void) => { + disposeHandlerB = handler + }), + dispose: vi.fn(() => disposeHandlerB?.()), + }) + ;(vscode.window.createWebviewPanel as Mock).mockReturnValueOnce(panelB) + const resolveSpy = vi + .spyOn(ClineProvider.prototype, "resolveWebviewView") + .mockRejectedValueOnce(new Error("init failed")) + const disposeSpy = vi.spyOn(ClineProvider.prototype, "dispose").mockImplementation(async () => { + panelB.dispose() + }) + + await expect( + openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }), + ).rejects.toThrow("init failed") + + // The failed panel leaves the live registry, and the tracked ref follows + // the disposal handler to the surviving panel A instead of being cleared + // up front - clearing it first would make the handler skip the re-point + // and leave the tab surface without a provider. + expect(__getLiveTabPanelCountForTests()).toBe(1) + expect(getPanel()).toBe(panelA) + expect(disposeSpy).toHaveBeenCalledTimes(1) + + resolveSpy.mockRestore() + disposeSpy.mockRestore() + }) + + it("preserves the initialization error when provider cleanup also fails", async () => { + const resolveSpy = vi + .spyOn(ClineProvider.prototype, "resolveWebviewView") + .mockRejectedValue(new Error("init failed")) + // A throwing MCP disposable inside dispose() rejects the cleanup await; + // that rejection must not replace the initialization error the caller + // sees (deregistration itself already ran in dispose()'s finally path). + const disposeSpy = vi.spyOn(ClineProvider.prototype, "dispose").mockRejectedValue(new Error("cleanup boom")) + ;(vscode.window.createWebviewPanel as Mock).mockReturnValue( + Object.assign({} as vscode.WebviewPanel, { + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + }), + ) + + await expect( + openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }), + ).rejects.toThrow("init failed") + + resolveSpy.mockRestore() + disposeSpy.mockRestore() + }) + + it("falls back to an undefined MdmService when MdmService.getInstance throws", async () => { + ;(MdmService.getInstance as Mock).mockImplementation(() => { + throw new Error("MDM service not initialized") + }) + + const provider = await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + // The creation must survive the MDM lookup failure: the provider is + // constructed with an undefined MDM service and the tab panel is + // still created. + const ctor = vi.mocked(ClineProvider) + expect(ctor.mock.instances[0]).toBeDefined() + expect(ctor).toHaveBeenCalledWith( + mockContext, + mockOutputChannel, + "editor", + undefined, + expect.any(WebviewFocusTracker), + undefined, + ) + expect(provider).toBe(ctor.mock.instances[0]) + expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(1) + + // The fallback is observable in the output channel. + expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( + "[openClineInNewTab] MDM service unavailable, continuing without it: Error: MDM service not initialized", + ) + }) + + it("opens a new group to the right and targets ViewColumn.Two when no editors are visible", async () => { + // The vscode mock factory declares a mutable visibleTextEditors slot that the + // readonly public API type hides, so seed it through Object.assign. + Object.assign(vscode.window, { visibleTextEditors: [] }) + + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.newGroupRight") + expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.lockEditorGroup") + expect(vscode.window.createWebviewPanel).toHaveBeenCalledWith( + "zoo-code.TabPanelProvider", + "Zoo Code", + vscode.ViewColumn.Two, + { + enableScripts: true, + retainContextWhenHidden: true, + localResourceRoots: [mockContext.extensionUri], + }, + ) + + // The panel icon points at the extension's asset files. + const panel = (vscode.window.createWebviewPanel as Mock).mock.results[0].value as { + iconPath?: { light: { path: string }; dark: { path: string } } + } + expect(panel.iconPath).toEqual({ + light: { path: "assets/icons/panel_light.png" }, + dark: { path: "assets/icons/panel_dark.png" }, + }) + }) + + it("treats editors without a viewColumn as column 0 when computing the target column", async () => { + // openClineInNewTab only reads viewColumn from each editor, so the + // fixture keeps that single field. + const editorWithoutColumn = Object.assign({} as vscode.TextEditor, { viewColumn: undefined }) + Object.assign(vscode.window, { + visibleTextEditors: [editorWithoutColumn], + }) + + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + // lastCol falls back to 0, so the panel lands on column 1 instead of + // opening a new editor group. + expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith("workbench.action.newGroupRight") + expect(vscode.window.createWebviewPanel).toHaveBeenCalledWith( + "zoo-code.TabPanelProvider", + "Zoo Code", + 1, + expect.objectContaining({ enableScripts: true }), + ) + }) + + it("places the tab panel one column right of the rightmost visible editor", async () => { + // openClineInNewTab only reads viewColumn from each editor, so the + // fixtures keep that single field. + Object.assign(vscode.window, { + visibleTextEditors: [ + Object.assign({} as vscode.TextEditor, { viewColumn: 1 }), + Object.assign({} as vscode.TextEditor, { viewColumn: 3 }), + ], + }) + + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + // lastCol is 3, so the panel lands on column 4 without opening a new + // editor group. + expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith("workbench.action.newGroupRight") + expect(vscode.window.createWebviewPanel).toHaveBeenCalledWith( + "zoo-code.TabPanelProvider", + "Zoo Code", + 4, + expect.objectContaining({ enableScripts: true }), + ) + }) + + it("constructs the tab provider with the 'editor' context and the live MdmService instance", async () => { + // MdmService has a private constructor, so pin a sentinel stand-in. + const mockMdm = Object.assign({} as MdmService, { name: "mock-mdm" }) + ;(MdmService.getInstance as Mock).mockReturnValue(mockMdm) + + const provider = await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + const ctor = vi.mocked(ClineProvider) + expect(ctor).toHaveBeenCalledTimes(1) + expect(ctor).toHaveBeenCalledWith( + mockContext, + mockOutputChannel, + "editor", + undefined, + expect.any(WebviewFocusTracker), + mockMdm, + ) + expect(provider).toBe(ctor.mock.instances[0]) + }) + + it("posts didBecomeVisible only for visible state changes and clears the tracked tab on dispose", async () => { + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + // Retain the panel returned during creation and pin the tracked tab + // against it with identity (not a weak defined check), so a wrong or + // duplicated tracked panel fails before the dispose assertions. + const panel = (vscode.window.createWebviewPanel as Mock).mock.results[0].value as { + onDidChangeViewState: Mock + onDidDispose: Mock + } + expect(getPanel()).toBe(panel) + + const stateHandler = panel.onDidChangeViewState.mock.calls[0][0] as (event: { + webviewPanel: { visible: boolean; webview: { postMessage: (message: unknown) => void } } + }) => void + const visibleEvent = { webviewPanel: { visible: true, webview: { postMessage: vi.fn() } } } + stateHandler(visibleEvent) + expect(visibleEvent.webviewPanel.webview.postMessage).toHaveBeenCalledWith({ + type: "action", + action: "didBecomeVisible", + }) + + const hiddenEvent = { webviewPanel: { visible: false, webview: { postMessage: vi.fn() } } } + stateHandler(hiddenEvent) + expect(hiddenEvent.webviewPanel.webview.postMessage).not.toHaveBeenCalled() + + const disposeHandler = panel.onDidDispose.mock.calls[0][0] as () => void + disposeHandler() + expect(getPanel()).toBeUndefined() + }) + + it("serializes concurrent opens so overlapping calls create one panel and share one provider", async () => { + const [first, second] = await Promise.all([ + openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }), + openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }), + ]) + + // Overlapping "Open in editor" calls must share the in-flight + // creation: exactly one tab panel is created and both callers receive + // the same constructed provider. Pinning both results against the + // mocked constructor (not just against each other) keeps the test + // failing if the shared result is undefined. + const ctor = vi.mocked(ClineProvider) + const constructed = ctor.mock.instances[0] + expect(constructed).toBeDefined() + expect(first).toBe(constructed) + expect(second).toBe(constructed) + expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(1) + }) + + it("shares one in-flight creation when openInNewTab and popoutButtonClicked start before it resolves", async () => { + // Defer the first creation at ContextProxy.getInstance so both command + // handlers can start while the creation is still in flight. + let resolveContextProxy!: () => void + ;(ContextProxy.getInstance as Mock).mockReturnValue( + new Promise((resolve) => { + resolveContextProxy = resolve + }), + ) + + const commandHandlers: Record unknown> = {} + ;(vscode.commands.registerCommand as Mock).mockImplementation( + (id: string, cb: (...args: unknown[]) => unknown) => { + commandHandlers[id] = cb + return { dispose: vi.fn() } + }, + ) + const sidebarProvider = Object.assign({} as ClineProvider, { + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + }) + registerCommands({ + context: mockContext, + outputChannel: mockOutputChannel, + provider: sidebarProvider, + }) + + const started = [commandHandlers["zoo-code.openInNewTab"](), commandHandlers["zoo-code.popoutButtonClicked"]()] + + // While the shared creation is suspended at ContextProxy.getInstance, + // neither caller has created a panel yet. + expect(vscode.window.createWebviewPanel).not.toHaveBeenCalled() + + resolveContextProxy() + const [first, second] = await Promise.all(started) + + // Both command entry points await the shared in-flight creation: + // exactly one tab panel is created and both results are the same + // constructed provider. + const ctor = vi.mocked(ClineProvider) + const constructed = ctor.mock.instances[0] + expect(constructed).toBeDefined() + expect(first).toBe(constructed) + expect(second).toBe(constructed) + expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(1) + }) + + it("creates a fresh panel for a new call once the previous creation settled and its provider disposed", async () => { + // The first open settles and tracks its panel. + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(1) + + // The tracked provider is disposed, so the next open cannot reuse the + // existing tab: the settled (and cleared) in-flight promise must not + // be returned, and a fresh panel is created. + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(undefined) + + const secondProvider = await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + + const ctor = vi.mocked(ClineProvider) + const second = ctor.mock.instances[1] + expect(second).toBeDefined() + expect(secondProvider).toBe(second) + expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(2) + }) + + it("keeps the replacement panel tracked when a stale panel's disposal fires late", async () => { + // Capture each created panel so the first panel's (stale) dispose + // handler can fire after the replacement is already tracked. + const createdPanels: { onDidDispose: Mock }[] = [] + ;(vscode.window.createWebviewPanel as Mock).mockImplementation(() => { + const panel = { + webview: { postMessage: vi.fn() }, + onDidChangeViewState: vi.fn(), + onDidDispose: vi.fn(), + } + createdPanels.push(panel) + return panel + }) + + // First open creates and tracks panel A. + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + expect(getPanel()).toBe(createdPanels[0]) + + // Panel A's provider is disposed before the second open, so the + // second open creates the replacement panel B. + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(undefined) + await openClineInNewTab({ + context: mockContext, + outputChannel: mockOutputChannel, + webviewFocusTracker: new WebviewFocusTracker(), + }) + expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(2) + expect(getPanel()).toBe(createdPanels[1]) + + // Panel A's stale dispose handler fires after the replacement is + // tracked; it must not clobber the replacement's ref. + createdPanels[0].onDidDispose.mock.calls[0][0]() + + expect(getPanel()).toBe(createdPanels[1]) + + // Tab-surface commands still reach the provider that owns the + // replacement panel after the stale disposal. + const replacementProvider = { postMessageToWebview: vi.fn().mockResolvedValue(undefined) } + ;(ClineProvider.getInstanceForView as Mock).mockReturnValue(replacementProvider) + const commandHandlers: Record unknown> = {} + ;(vscode.commands.registerCommand as Mock).mockImplementation( + (id: string, cb: (...args: unknown[]) => unknown) => { + commandHandlers[id] = cb + return { dispose: vi.fn() } + }, + ) + registerCommands({ + context: mockContext, + outputChannel: mockOutputChannel, + provider: {} as ClineProvider, + }) + await commandHandlers["zoo-code.historyButtonClickedInTab"]() + expect(replacementProvider.postMessageToWebview).toHaveBeenCalledWith({ + type: "action", + action: "historyButtonClicked", + }) + }) }) diff --git a/src/activate/registerCommands.ts b/src/activate/registerCommands.ts index f0f4747eeef..ba7cbdfbaeb 100644 --- a/src/activate/registerCommands.ts +++ b/src/activate/registerCommands.ts @@ -1,7 +1,8 @@ import * as vscode from "vscode" import delay from "delay" +import { createDiagnosticsReport } from "../services/diagnostics" -import type { CommandId } from "@roo-code/types" +import type { CommandId, ExtensionMessage } from "@roo-code/types" import { TelemetryService } from "@roo-code/telemetry" import { getCommand } from "../utils/commands" @@ -13,7 +14,6 @@ import { handleNewTask } from "./handleTask" import { importSettingsWithFeedback } from "../core/config/importExport" import { MdmService } from "../services/mdm/MdmService" import { registerRipgrepDiagnosticCommand } from "../services/ripgrep/diagnostic" -import { createDiagnosticsReport } from "../services/diagnostics" /** * Helper to get the visible ClineProvider instance or log if not found. @@ -31,8 +31,60 @@ export function getVisibleProviderOrLog(outputChannel: vscode.OutputChannel): Cl let sidebarPanel: vscode.WebviewView | undefined = undefined let tabPanel: vscode.WebviewPanel | undefined = undefined +// Tab panels that are still open. When the tracked panel closes, its dispose +// handler re-points the tracked ref at one of these: the remaining panel may +// not emit onDidChangeViewState (its own visibility did not change), so +// without this the tab-scoped title-bar commands and focusInput would be left +// without a target. +const liveTabPanels = new Set() + +/** + * Test-only: clears the module-level registry so tab panels created by one + * spec cannot leak into another's tracked-panel re-pointing. + * @internal Exported for focused implementation tests. + */ +export function __resetLiveTabPanelsForTests(): void { + liveTabPanels.clear() +} + /** - * Get the currently active panel + * Test-only: the number of tab panels currently in the live registry, so a + * spec can assert the cleanup of a failed or closed panel without probing + * through a close of a live panel. + * @internal Exported for focused implementation tests. + */ +export function __getLiveTabPanelCountForTests(): number { + return liveTabPanels.size +} + +// In-flight "open in editor" creation shared by overlapping calls: a +// double-click starts before the first call tracks its new panel, so +// concurrent callers must share one creation instead of racing to create +// two tab panels. +let pendingTabPanelCreation: Promise | undefined + +// Tab panels whose editor group is known to be locked. A first lock can +// reject (the command is not guaranteed to run) while the panel and its +// provider stay registered, and a retry then takes the reuse branch below - +// so the reuse path has to re-issue the lock it never got. +const lockedTabGroups = new WeakSet() + +/** + * Lock the editor group hosting `panel` so clicking on files does not open + * them over the panel, and remember that the lock landed. A freshly created + * group has to settle first: locking in the same tick as the panel creation + * targets the group the panel is leaving. + */ +const lockTabEditorGroup = async (panel: vscode.WebviewPanel): Promise => { + await delay(100) + await vscode.commands.executeCommand("workbench.action.lockEditorGroup") + lockedTabGroups.add(panel) +} + +/** + * Get the currently active panel. + * + * @internal Exported for focused implementation tests. * @returns WebviewPanel或WebviewView */ export function getPanel(): vscode.WebviewPanel | vscode.WebviewView | undefined { @@ -40,7 +92,12 @@ export function getPanel(): vscode.WebviewPanel | vscode.WebviewView | undefined } /** - * Set panel references + * Set panel references. + * + * The two refs are independent: each surface keeps its own ref for its whole + * lifetime, so resolving the sidebar view never wipes a live tab panel (and + * vice versa). Callers pass `undefined` only when the surface itself is + * disposed (see the `onDidDispose` wiring in `openClineInNewTab`). */ export function setPanel( newPanel: vscode.WebviewPanel | vscode.WebviewView | undefined, @@ -48,13 +105,22 @@ export function setPanel( ): void { if (type === "sidebar") { sidebarPanel = newPanel as vscode.WebviewView - tabPanel = undefined } else { tabPanel = newPanel as vscode.WebviewPanel - sidebarPanel = undefined } } +/** + * The instance that owns the tracked tab panel, if it is still alive. + * + * Title-bar commands on the editor-tab surface use this instead of the + * visible-instance heuristic, so a click on the tab's title bar always + * targets that tab even when the sidebar is visible side-by-side. + */ +function getTabProvider(): ClineProvider | undefined { + return tabPanel ? ClineProvider.getInstanceForView(tabPanel) : undefined +} + export type RegisterCommandOptions = { context: vscode.ExtensionContext outputChannel: vscode.OutputChannel @@ -81,27 +147,64 @@ export const registerCommands = (options: RegisterCommandOptions) => { // type while rejecting direct calls with arguments. VS Code dispatches positional // arguments dynamically; `unknown` requires callers to inspect returned values. type CommandCallback = (...args: never[]) => unknown + +// Posts each action in order to the target instance. Failures are logged +// (not thrown) with the handler-specific prefix so a failed post stays +// attributable in the output channel. +const postActions = ( + outputChannel: vscode.OutputChannel, + target: ClineProvider, + actions: readonly NonNullable[], + logPrefix: string, +) => { + for (const action of actions) { + void target + .postMessageToWebview({ type: "action", action }) + .catch((error) => outputChannel.appendLine(`[${logPrefix}] postMessageToWebview failed: ${error}`)) + } +} + const getCommandsMap = ({ context, outputChannel, provider, }: RegisterCommandOptions): Record, CommandCallback> => ({ activationCompleted: () => {}, + createDiagnosticsReport: () => + createDiagnosticsReport({ + context, + outputChannel, + providers: ClineProvider.getAllInstances(), + }), + // The `view/title` menu is scoped to the sidebar view, so the click + // origin of these handlers is the sidebar provider wired in at + // activation (`provider`). Target it directly instead of the + // visible-instance heuristic, which would follow the user's focus to a + // tab instance when both surfaces are open side-by-side. The `*InTab` + // variants serve the `editor/title` menu and target the tab instance + // through `getTabProvider()` instead. plusButtonClicked: async () => { - const visibleProvider = getVisibleProviderOrLog(outputChannel) + TelemetryService.instance.captureTitleButtonClicked("plus") - if (!visibleProvider) { + await provider.evictCurrentTask() + await provider.refreshWorkspace() + await provider.postMessageToWebview({ type: "action", action: "chatButtonClicked" }) + // Send focusInput action immediately after chatButtonClicked + // This ensures the focus happens after the view has switched + await provider.postMessageToWebview({ type: "action", action: "focusInput" }) + }, + plusButtonClickedInTab: async () => { + const tabProvider = getTabProvider() + if (!tabProvider) { return } TelemetryService.instance.captureTitleButtonClicked("plus") - await visibleProvider.evictCurrentTask() - await visibleProvider.refreshWorkspace() - await visibleProvider.postMessageToWebview({ type: "action", action: "chatButtonClicked" }) - // Send focusInput action immediately after chatButtonClicked - // This ensures the focus happens after the view has switched - await visibleProvider.postMessageToWebview({ type: "action", action: "focusInput" }) + await tabProvider.evictCurrentTask() + await tabProvider.refreshWorkspace() + await tabProvider.postMessageToWebview({ type: "action", action: "chatButtonClicked" }) + await tabProvider.postMessageToWebview({ type: "action", action: "focusInput" }) }, popoutButtonClicked: () => { TelemetryService.instance.captureTitleButtonClicked("popout") @@ -111,43 +214,50 @@ const getCommandsMap = ({ openInNewTab: () => openClineInNewTab({ context, outputChannel, webviewFocusTracker: provider.webviewFocusTracker }), settingsButtonClicked: () => { - const visibleProvider = getVisibleProviderOrLog(outputChannel) + TelemetryService.instance.captureTitleButtonClicked("settings") - if (!visibleProvider) { + // Also explicitly post the visibility message to trigger scroll reliably. + postActions(outputChannel, provider, ["settingsButtonClicked", "didBecomeVisible"], "settingsButtonClicked") + }, + settingsButtonClickedInTab: () => { + const tabProvider = getTabProvider() + if (!tabProvider) { return } TelemetryService.instance.captureTitleButtonClicked("settings") - void visibleProvider - .postMessageToWebview({ type: "action", action: "settingsButtonClicked" }) - .catch((error) => outputChannel.appendLine(`[settingsButtonClicked] postMessageToWebview failed: ${error}`)) - // Also explicitly post the visibility message to trigger scroll reliably - void visibleProvider - .postMessageToWebview({ type: "action", action: "didBecomeVisible" }) - .catch((error) => outputChannel.appendLine(`[settingsButtonClicked] postMessageToWebview failed: ${error}`)) + postActions( + outputChannel, + tabProvider, + ["settingsButtonClicked", "didBecomeVisible"], + "settingsButtonClickedInTab", + ) }, historyButtonClicked: () => { - const visibleProvider = getVisibleProviderOrLog(outputChannel) + TelemetryService.instance.captureTitleButtonClicked("history") - if (!visibleProvider) { + postActions(outputChannel, provider, ["historyButtonClicked"], "historyButtonClicked") + }, + historyButtonClickedInTab: () => { + const tabProvider = getTabProvider() + if (!tabProvider) { return } TelemetryService.instance.captureTitleButtonClicked("history") - void visibleProvider - .postMessageToWebview({ type: "action", action: "historyButtonClicked" }) - .catch((error) => outputChannel.appendLine(`[historyButtonClicked] postMessageToWebview failed: ${error}`)) + postActions(outputChannel, tabProvider, ["historyButtonClicked"], "historyButtonClickedInTab") }, marketplaceButtonClicked: () => { - const visibleProvider = getVisibleProviderOrLog(outputChannel) - if (!visibleProvider) return - void visibleProvider - .postMessageToWebview({ type: "action", action: "marketplaceButtonClicked" }) - .catch((error) => - outputChannel.appendLine(`[marketplaceButtonClicked] postMessageToWebview failed: ${error}`), - ) + postActions(outputChannel, provider, ["marketplaceButtonClicked"], "marketplaceButtonClicked") + }, + marketplaceButtonClickedInTab: () => { + const tabProvider = getTabProvider() + if (!tabProvider) { + return + } + postActions(outputChannel, tabProvider, ["marketplaceButtonClicked"], "marketplaceButtonClickedInTab") }, newTask: (params: { prompt?: string } | null | undefined) => handleNewTask(params, provider.webviewFocusTracker), setCustomStoragePath: async () => { @@ -170,18 +280,19 @@ const getCommandsMap = ({ filePath, ) }, - createDiagnosticsReport: () => - createDiagnosticsReport({ - context, - outputChannel, - providers: ClineProvider.getAllInstances(), - }), focusInput: async () => { try { await focusPanel(tabPanel, sidebarPanel) - // Send focus input message only for sidebar panels - if (sidebarPanel && getPanel() === sidebarPanel) { + // Post to the surface focusPanel selected: the tab takes + // selection priority, so the sidebar is targeted only when no + // tab panel is tracked. + if (tabPanel) { + const tabProvider = getTabProvider() + if (tabProvider) { + await tabProvider.postMessageToWebview({ type: "action", action: "focusInput" }) + } + } else if (sidebarPanel) { await provider.postMessageToWebview({ type: "action", action: "focusInput" }) } } catch (error) { @@ -233,7 +344,59 @@ type OpenClineInNewTabOptions = { webviewFocusTracker: WebviewFocusTracker } -export const openClineInNewTab = async ({ context, outputChannel, webviewFocusTracker }: OpenClineInNewTabOptions) => { +export const openClineInNewTab = async (options: OpenClineInNewTabOptions) => { + // Serialize overlapping "Open in editor" calls: a double-click starts + // before the first call tracks its new panel, so without a shared + // in-flight creation both calls would race to create two tab panels. + // The shared promise is stored before the creation body awaits + // ContextProxy.getInstance, so every caller started while the creation + // is in flight — openInNewTab and popoutButtonClicked both dispatch + // through here — awaits it instead of creating a second panel: exactly + // one panel is created and every caller receives the same provider. + if (pendingTabPanelCreation) { + return pendingTabPanelCreation + } + + const creation = createTabPanelUnlocked(options) + pendingTabPanelCreation = creation + + try { + return await creation + } finally { + // Clear once settled (success or failure) so the next call starts + // fresh: the reuse path in createTabPanelUnlocked then takes over + // for the tracked panel. Guard the clear so this settlement cannot + // clobber a replacement already stored in the slot. That clobber is + // unreachable in single-threaded settlement order: while the slot + // holds this in-flight creation, every other caller receives that + // same promise (guard above), so no replacement can be stored before + // this finally block runs — the equality check pins the invariant. + if (pendingTabPanelCreation === creation) { + pendingTabPanelCreation = undefined + } + } +} + +// The unserialized tab-creation body. Only openClineInNewTab may call it, +// after it has stored the shared in-flight promise. +const createTabPanelUnlocked = async ({ context, outputChannel, webviewFocusTracker }: OpenClineInNewTabOptions) => { + // Reuse the tracked tab instead of opening a second one: a repeated + // "Open in editor" click reveals the existing tab's panel. + if (tabPanel) { + const existingProvider = ClineProvider.getInstanceForView(tabPanel) + if (existingProvider) { + await tabPanel.reveal() + // A first lock that rejected left this panel tracked with its editor + // group unlocked; returning here without retrying it would leave files + // opening over the panel for the rest of the session. + if (!lockedTabGroups.has(tabPanel)) { + await lockTabEditorGroup(tabPanel) + } + await existingProvider.postMessageToWebview({ type: "action", action: "didBecomeVisible" }) + return existingProvider + } + } + // (This example uses webviewProvider activation event which is necessary to // deserialize cached webview, but since we use retainContextWhenHidden, we // don't need to use that event). @@ -244,8 +407,9 @@ export const openClineInNewTab = async ({ context, outputChannel, webviewFocusTr let mdmService: MdmService | undefined try { mdmService = MdmService.getInstance() - } catch { - // MDM service not initialized, which is fine - extension can work without it + } catch (error) { + // MDM service unavailable: log the fallback and continue without it. + outputChannel.appendLine(`[openClineInNewTab] MDM service unavailable, continuing without it: ${error}`) mdmService = undefined } @@ -277,6 +441,12 @@ export const openClineInNewTab = async ({ context, outputChannel, webviewFocusTr // Save as tab type panel. setPanel(newPanel, "tab") + liveTabPanels.add(newPanel) + + // A close that lands while the provider is still initializing makes + // resolveWebviewView return without an error (the provider treats a disposed + // view as a stale resolve), so the open has to notice it on its own. + let closedBeforeInitialized = false // TODO: Use better svg icon with light and dark variants (see // https://stackoverflow.com/questions/58365687/vscode-extension-iconpath). @@ -285,12 +455,21 @@ export const openClineInNewTab = async ({ context, outputChannel, webviewFocusTr dark: vscode.Uri.joinPath(context.extensionUri, "assets", "icons", "panel_dark.png"), } - await tabProvider.resolveWebviewView(newPanel) - + // Register the cleanup listeners before the first initialization await: a + // close that lands while resolveWebviewView is still running must be able + // to find the tracked-ref re-pointing already installed, or the panel + // would stay tracked (and the provider registered) after disposal. // Add listener for visibility changes to notify webview newPanel.onDidChangeViewState( (e) => { const panel = e.webviewPanel + // Re-point the tracked tab ref at the panel the user is actually + // looking at: several tab panels can stay visible at once, but + // only the active one is the current tab, and the title-bar + // commands must resolve that instance, not the last created one. + if (panel.active) { + setPanel(panel, "tab") + } if (panel.visible) { panel.webview.postMessage({ type: "action", action: "didBecomeVisible" }) // Use the same message type as in SettingsView.tsx } @@ -299,19 +478,68 @@ export const openClineInNewTab = async ({ context, outputChannel, webviewFocusTr context.subscriptions, // Register listener for disposal ) - // Handle panel closing events. + // Handle panel closing events: clear the tracked ref only if this panel + // is still the tracked one, so a late disposal of an already-replaced + // panel cannot clobber the replacement's ref. newPanel.onDidDispose( () => { - // A recovery may already have installed a replacement panel. - if (tabPanel === newPanel) setPanel(undefined, "tab") + closedBeforeInitialized = true + liveTabPanels.delete(newPanel) + if (tabPanel === newPanel) { + // Re-point the tracked ref at the best remaining live tab: an active + // panel first, then a visible one, then any remaining panel — a panel + // can be open but hidden behind another editor group (neither active + // nor visible), and clearing the tracked ref here would let the next + // open create a second panel instead of revealing the one already + // serving a task. The identity guard above keeps a late disposal of an + // already-replaced panel from clobbering the replacement's ref. + const remaining = + [...liveTabPanels].find((panel) => panel.active) || + [...liveTabPanels].find((panel) => panel.visible) || + [...liveTabPanels][0] + setPanel(remaining, "tab") + } }, null, context.subscriptions, // Also register dispose listener ) + try { + await tabProvider.resolveWebviewView(newPanel) + + // The panel was closed while the provider initialized: resolveWebviewView + // returned without an error, and handing the disposed provider back would + // let the caller (API.startNewTask) build a task on a dead surface. + if (closedBeforeInitialized) { + throw new Error("The Zoo Code editor tab was closed while it was initializing.") + } + } catch (error) { + // Initialization failed: drop the half-registered panel from the live + // registry and dispose the provider so the failed surface leaves no + // listeners or state behind. Disposing the provider disposes the panel + // (resolveWebviewView assigns this.view before its first await), whose + // disposal listener (installed above) then re-points the tracked ref at + // the best remaining live panel - or clears it when none remains. + // Clearing the ref here first would make that handler skip the + // re-pointing and leave getTabProvider() undefined while another tab + // panel is still open. A user close that landed during initialization + // already ran that handler. + liveTabPanels.delete(newPanel) + try { + await tabProvider.dispose() + } catch (cleanupError) { + // A cleanup rejection (e.g. an MCP client whose disposal throws) must + // not replace the initialization error the caller is about to see; + // dispose()'s finally path has already deregistered the provider. + tabProvider.log( + `Tab provider cleanup after failed init also failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`, + ) + } + throw error + } + // Lock the editor group so clicking on files doesn't open them over the panel. - await delay(100) - await vscode.commands.executeCommand("workbench.action.lockEditorGroup") + await lockTabEditorGroup(newPanel) return tabProvider } diff --git a/src/core/config/ContextProxy.ts b/src/core/config/ContextProxy.ts index e53f60fb838..26a253057e2 100644 --- a/src/core/config/ContextProxy.ts +++ b/src/core/config/ContextProxy.ts @@ -67,6 +67,9 @@ const globalSettingsExportSchema = globalSettingsSchema.omit({ taskHistory: true, listApiConfigMeta: true, currentApiConfigName: true, + // Per-view selection state is machine-local: it keeps flowing through the + // normal runtime and pruning paths but must not transfer between settings. + viewStates: true, }) export class ContextProxy { diff --git a/src/core/config/ProviderSettingsManager.ts b/src/core/config/ProviderSettingsManager.ts index 79a9d67c794..a1b1859ee0d 100644 --- a/src/core/config/ProviderSettingsManager.ts +++ b/src/core/config/ProviderSettingsManager.ts @@ -55,6 +55,19 @@ export const providerProfilesSchema = z.object({ export type ProviderProfiles = z.infer +/** + * Signals that a profile's configuration no longer exists. Callers that treat an + * already-deleted profile as an idempotent no-op branch on this type instead of + * matching error message text, which a profile name containing the phrase could + * otherwise spoof. + */ +export class ProviderSettingsNotFoundError extends Error { + constructor(message: string) { + super(message) + this.name = "ProviderSettingsNotFoundError" + } +} + export class ProviderSettingsManager { private static readonly SCOPE_PREFIX = "roo_cline_config_" private readonly defaultConfigId = this.generateId() @@ -102,6 +115,36 @@ export class ProviderSettingsManager { return next } + // Lock shared by every manager bound to the same secrets key. The sidebar and + // each editor tab construct their own `ProviderSettingsManager` over the same + // `context.secrets`, so the per-instance `_lock` above cannot serialize a + // check-then-write pair issued through two instances: a same-name create from + // the other view fits between `hasConfig` and `saveConfig`. + private static sharedLocks = new Map>() + + /** + * Run `cb` inside the critical section shared by every manager using this + * instance's secrets key, so a check-then-write pair - and the compensation + * that undoes it - cannot interleave with another view's. The per-instance + * lock still guards each individual read/write; this outer lock is taken + * first and released last, so the two cannot deadlock. + */ + public runExclusiveAcrossInstances(cb: () => Promise): Promise { + const key = this.secretsKey + const previous = ProviderSettingsManager.sharedLocks.get(key) ?? Promise.resolve() + const run = previous.then(cb) + // Store a settled-clean owner so one failed critical section cannot poison + // the queue for the next caller. + ProviderSettingsManager.sharedLocks.set( + key, + run.then( + () => {}, + () => {}, + ), + ) + return run + } + /** * Initialize config if it doesn't exist and run migrations. */ @@ -485,6 +528,22 @@ export class ProviderSettingsManager { } } + /** + * Read the manager-owned current profile selection. Exposed for callers that + * snapshot the full activation state before a mutation group so a failure can + * compensate the manager store as well as its ContextProxy copies. + */ + public async getCurrentProfileName(): Promise { + try { + return await this.lock(async () => { + const providerProfiles = await this.load() + return providerProfiles.currentApiConfigName + }) + } catch (error) { + throw new Error(`Failed to read the active profile: ${error instanceof Error ? error.message : error}`) + } + } + /** * Activate a profile by name or ID. */ @@ -514,7 +573,7 @@ export class ProviderSettingsManager { const providerProfiles = await this.load() if (!providerProfiles.apiConfigs[name]) { - throw new Error(`Config '${name}' not found`) + throw new ProviderSettingsNotFoundError(`Config '${name}' not found`) } if (Object.keys(providerProfiles.apiConfigs).length === 1) { @@ -525,6 +584,11 @@ export class ProviderSettingsManager { await this.store(providerProfiles) }) } catch (error) { + // A missing config is a caller-meaningful signal, not a failure: rethrow it + // unwrapped so callers can branch on the type instead of message text. + if (error instanceof ProviderSettingsNotFoundError) { + throw error + } throw new Error(`Failed to delete config: ${error}`) } } diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index 4766f87112f..878938b8607 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -1151,4 +1151,20 @@ Output only the summary of the conversation so far, without any additional comme expect(customSupportPromptsUpdateCalls.length).toBe(0) }) }) + + describe("export", () => { + it("should exclude viewStates from the exported settings", async () => { + await proxy.setValue("viewStates", { + "stable-sidebar-view": { mode: "architect", currentApiConfigName: "profile-a", updatedAt: 1 }, + }) + await proxy.setValue("customInstructions", "global instructions") + + const exported = await proxy.export() + + // Per-view selection state is machine-local and must never transfer + // between settings, while ordinary global settings keep round-tripping. + expect(exported).not.toHaveProperty("viewStates") + expect(exported?.customInstructions).toBe("global instructions") + }) + }) }) diff --git a/src/core/config/__tests__/ProviderSettingsManager.spec.ts b/src/core/config/__tests__/ProviderSettingsManager.spec.ts index e179e22341d..0f8f8d9da1d 100644 --- a/src/core/config/__tests__/ProviderSettingsManager.spec.ts +++ b/src/core/config/__tests__/ProviderSettingsManager.spec.ts @@ -12,7 +12,7 @@ import { import { clearAllMocks } from "../../../test-utils/reset" import { makeExtensionContext } from "../../../test-utils/vscode" -import { ProviderSettingsManager, ProviderProfiles } from "../ProviderSettingsManager" +import { ProviderSettingsManager, ProviderSettingsNotFoundError, ProviderProfiles } from "../ProviderSettingsManager" // `export()` builds an API handler per profile to read model capabilities. Mock // buildApiHandler with the real @roo-code/types model definitions so the token-field @@ -90,6 +90,50 @@ describe("ProviderSettingsManager", () => { }) describe("initialize", () => { + it("serializes critical sections across managers bound to the same secrets key", async () => { + const first = new ProviderSettingsManager(mockContext) + const second = new ProviderSettingsManager(mockContext) + const events: string[] = [] + let releaseFirst: () => void = () => {} + const firstGate = new Promise((resolve) => { + releaseFirst = resolve + }) + + const firstRun = first.runExclusiveAcrossInstances(async () => { + events.push("first:enter") + await firstGate + events.push("first:exit") + }) + // Let the first critical section start before the second one is queued. + await new Promise((resolve) => setTimeout(resolve, 0)) + const secondRun = second.runExclusiveAcrossInstances(async () => { + events.push("second:enter") + }) + await new Promise((resolve) => setTimeout(resolve, 0)) + + // The sidebar and each editor tab own a manager over the same + // context.secrets: without a lock shared by those instances the second + // critical section starts while the first is still inside it. + expect(events).toEqual(["first:enter"]) + + releaseFirst() + await Promise.all([firstRun, secondRun]) + expect(events).toEqual(["first:enter", "first:exit", "second:enter"]) + }) + + it("keeps the shared critical section usable after a rejection", async () => { + const first = new ProviderSettingsManager(mockContext) + const second = new ProviderSettingsManager(mockContext) + + await expect( + first.runExclusiveAcrossInstances(async () => { + throw new Error("boom") + }), + ).rejects.toThrow("boom") + + await expect(second.runExclusiveAcrossInstances(async () => "ok")).resolves.toBe("ok") + }) + it("should not write to storage when secrets.get returns null", async () => { // Mock readConfig to return null mockSecrets.get.mockResolvedValueOnce(null) @@ -992,6 +1036,11 @@ describe("ProviderSettingsManager", () => { }), ) + // The typed not-found signal is the contract callers branch on: a profile + // name containing "not found" must not be matchable via message text. + await expect(providerSettingsManager.deleteConfig("nonexistent")).rejects.toBeInstanceOf( + ProviderSettingsNotFoundError, + ) await expect(providerSettingsManager.deleteConfig("nonexistent")).rejects.toThrow( "Config 'nonexistent' not found", ) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 6c66655325b..c83a8511356 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -331,6 +331,97 @@ describe("importExport", () => { ]) }) + it("should not apply imported viewStates to the context proxy", async () => { + const fileContent = JSON.stringify({ + providerProfiles: { + currentApiConfigName: "test", + apiConfigs: { + test: { apiProvider: providerIdentifiers.openai, apiKey: "test-key", id: "test-id" }, + }, + }, + globalSettings: { + mode: "code", + viewStates: { + "stable-sidebar-view": { + mode: "architect", + currentApiConfigName: "profile-a", + updatedAt: 1, + }, + }, + }, + }) + + ;(fs.readFile as Mock).mockResolvedValue(fileContent) + + mockProviderSettingsManager.export.mockResolvedValue({ + currentApiConfigName: "default", + apiConfigs: { default: { apiProvider: providerIdentifiers.anthropic, id: "default-id" } }, + }) + + mockProviderSettingsManager.listConfig.mockResolvedValue([ + { name: "test", id: "test-id", apiProvider: providerIdentifiers.openai }, + { name: "default", id: "default-id", apiProvider: providerIdentifiers.anthropic }, + ]) + + // Stateful write-tracking proxy: every write path (setValues, setValue, + // setProviderSettings) is merged into `state` and recorded in `writes`, + // so the assertions below cover every payload rather than one call. + // Plain-function doubles cast once, matching the file-level mock pattern. + const makeStatefulProxy = (seed: Record) => { + const state: Record = { ...seed } + const writes: Record[] = [] + const record = (values: Record) => { + writes.push(values) + Object.assign(state, values) + } + return { + state, + writes, + proxy: Object.assign({} as ContextProxy, { + setValues: vi.fn(async (values: Record) => record(values)), + setValue: vi.fn(async (key: string, value: unknown) => record({ [key]: value })), + setProviderSettings: vi.fn(async (settings: Record) => record(settings)), + }), + } + } + + // This machine already has view state: it must survive the import untouched. + const existingViewStates = { + "existing-view": { mode: "code", currentApiConfigName: "default", updatedAt: 0 }, + } + const seeded = makeStatefulProxy({ viewStates: existingViewStates }) + const result = await importSettingsFromPath("/mock/path/settings.json", { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: seeded.proxy, + customModesManager: mockCustomModesManager, + }) + + expect(result.success).toBe(true) + // Per-view selection state is machine-local: importing settings must not + // apply another machine's view pins, while other settings round-trip. + expect(seeded.state.viewStates).toEqual(existingViewStates) + expect(seeded.state.mode).toBe("code") + expect(result).not.toHaveProperty("globalSettings.viewStates") + + // A machine without view state must not gain any from the import. + const fresh = makeStatefulProxy({}) + const freshResult = await importSettingsFromPath("/mock/path/settings.json", { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: fresh.proxy, + customModesManager: mockCustomModesManager, + }) + + expect(freshResult.success).toBe(true) + expect(fresh.state).not.toHaveProperty("viewStates") + expect(fresh.state.mode).toBe("code") + expect(freshResult).not.toHaveProperty("globalSettings.viewStates") + + // No write path may carry the imported machine's view pins. + for (const payload of [...seeded.writes, ...fresh.writes]) { + expect(payload).not.toHaveProperty("viewStates") + } + }) + it("should return success: false when file content is invalid", async () => { ;(vscode.window.showOpenDialog as Mock).mockResolvedValue([{ fsPath: "/mock/path/settings.json" }]) diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 9882039ad38..29c94975526 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -98,6 +98,14 @@ function sanitizeGlobalSettings(rawGlobalSettings: unknown): { for (const [key, rawValue] of Object.entries(rawGlobalSettings)) { const path = `globalSettings.${key}` + + // Per-view selection state is machine-local: it round-trips through the + // normal runtime and pruning paths, but importing it would pin selections + // from another machine's views on this one. + if (key === "viewStates") { + continue + } + const schema = globalSettingsShape[key as keyof GlobalSettings] if (!schema) { diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 32714067fa2..0a5a853e662 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -26,6 +26,7 @@ import { } from "./webviewRecoveryPolicy" import { + PROVIDER_SETTINGS_KEYS, type TaskProviderLike, type TaskProviderEvents, type GlobalState, @@ -49,6 +50,7 @@ import { type CloudUserInfo, type CloudOrganizationMembership, type CreateTaskOptions, + type ProviderSettingsWithId, type TokenUsage, type ToolUsage, type ExtensionMessage, @@ -134,7 +136,7 @@ import { forceFullModelDetailsLoad, hasLoadedFullDetails } from "../../api/provi import { ContextProxy } from "../config/ContextProxy" import { withoutInvalidDisplaySettings } from "../config/displaySettings" -import { ProviderSettingsManager } from "../config/ProviderSettingsManager" +import { ProviderSettingsManager, ProviderSettingsNotFoundError } from "../config/ProviderSettingsManager" import { CustomModesManager } from "../config/CustomModesManager" import { PendingActionSettlementError, Task } from "../task/Task" @@ -163,6 +165,14 @@ import { REQUESTY_BASE_URL } from "../../shared/utils/requesty" import { validateAndFixToolResultIds } from "../task/validateToolResultIds" import { PendingEditOperationStore, type PendingEditOperationInput } from "./PendingEditOperationStore" +type PersistedViewState = NonNullable[string] + +/** + * Values that can be held in a view-local state buffer (in-memory) and, for the + * non-secret subset, persisted durably per stable view id. + */ +type ViewLocalStateValues = Partial & Partial + /** * https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts * https://github.com/KumarVariable/vscode-extension-sidebar-html/blob/master/src/customSidebarViewProvider.ts @@ -233,6 +243,60 @@ type GetStateOptions = { includeTaskHistory?: boolean } +/** + * In-flight profile-create claims shared by every provider instance in this + * extension host. A rollback may only delete a record whose creation it can + * prove it owns: when two views concurrently create the same new name, both + * observe `hasConfig === false`, yet the surviving record belongs to the + * create that completed. A failed create must therefore skip the deletion + * while another create for the same name is still in flight, and the last + * claimant to settle performs it. + */ +const profileCreateClaims = new Map() + +function claimProfileCreate(name: string): void { + profileCreateClaims.set(name, (profileCreateClaims.get(name) ?? 0) + 1) +} + +/** + * Names whose create claim has already landed: a failed create must not + * delete the record a successful sibling create saved, even when it settles + * last. + */ +const profileCreatesSucceeded = new Set() + +/** Records that a create for this name landed, so failed siblings spare the record. */ +function markProfileCreateSucceeded(name: string): void { + profileCreatesSucceeded.add(name) +} + +/** Drops one claim and reports whether the caller was the last claimant. */ +function releaseProfileCreate(name: string): boolean { + const remaining = (profileCreateClaims.get(name) ?? 1) - 1 + if (remaining <= 0) { + profileCreateClaims.delete(name) + return true + } + profileCreateClaims.set(name, remaining) + return false +} + +type ProfileActivationSnapshot = { + listApiConfigMeta: ProviderSettingsEntry[] | undefined + currentApiConfigName: string | undefined + viewCurrentApiConfigName: string | undefined + providerSettings: RooCodeSettings + viewApiConfiguration: ProviderSettings | undefined + viewStates: Record +} + +type ProviderManagerSnapshot = { + previousRecord: ProviderSettingsWithId | undefined + recordExisted: boolean | undefined + previousCurrentProfileName: string | undefined + claimedCreate: boolean +} + function removeTaskEventListeners(listeners: WeakMap void>>, task: Task): void { const cleanupFunctions = listeners.get(task) if (cleanupFunctions) { @@ -251,6 +315,19 @@ export class ClineProvider public static readonly sideBarId = `${Package.name}.SidebarProvider` public static readonly tabPanelId = `${Package.name}.TabPanelProvider` private static activeInstances: Set = new Set() + private static nextViewId = 0 + private static readonly MAX_PERSISTED_VIEW_STATES = 50 + private static readonly MAX_VIEW_STATE_ID_LENGTH = 64 + private static persistedViewStateWriteQueue: Promise = Promise.resolve() + + /** + * View ids whose durable entry a queued write intentionally removed + * (unpin, clear, or re-key move). Activation rollback treats these as + * tombstones and never resurrects a tracked eviction the clear has + * since deleted; a write that lands an entry lifts its tombstone. + */ + private static clearedViewStateIds = new Set() + private disposables: vscode.Disposable[] = [] private webviewDisposables: vscode.Disposable[] = [] private pendingThemeFixtureProbes = new Map< string, @@ -350,13 +427,21 @@ export class ClineProvider options: { runToCompletion?: boolean } = {}, ): Promise { const controller = new AbortController() + // Set when the caller's timeout fires while this mutation is still queued behind a + // longer-running one: the callback must not start after its caller already saw a + // timeout, or the mutation would change state while reporting failure. + let callerTimedOut = false // Run fn after either outcome so a rejected mutation never poisons the queue. - const run = this.providerProfileMutationQueue.then( - () => fn(controller.signal), - () => fn(controller.signal), - ) + const start = () => { + if (callerTimedOut) { + return Promise.reject(new Error("Provider profile mutation timed out while queued")) + } + return fn(controller.signal) + } + const run = this.providerProfileMutationQueue.then(start, start) const callerResult = this.withProviderProfileMutationTimeout(run, () => { if (options.runToCompletion) { + callerTimedOut = true this.log("Provider profile mutation timed out; waiting for it to finish before the next mutation") return } @@ -419,6 +504,58 @@ export class ClineProvider */ private clineMessagesSeq = 0 + /** + * Unique identifier for this provider instance's view. + * Based on renderContext and a monotonically increasing counter to ensure uniqueness across multiple instances. + */ + public readonly viewId: string + + /** + * Stable identifier for persisted per-view state keys. + * Defaults to viewId until the webview reports its VS Code-persisted id. + */ + private viewStateId: string + + /** + * Whether this instance wrote an entry under its own session-local temporary id. + * Temporary ids restart from 0 on every extension host start, so an entry under the + * same name can belong to a different session. Only re-key entries this instance wrote. + */ + private wroteUnderTemporaryViewStateId = false + + /** + * Local state buffer for this specific view instance. + * Used to isolate mode, apiConfiguration, and other fields from the shared ContextProxy singleton + * when running in parallel (multi-tab) mode. + */ + private viewLocalState: Partial = {} + + /** + * View ids evicted from the durable viewStates map by this instance's writes + * since the last activation snapshot: the rollback restores exactly these + * entries, so a sibling's intentional pin clear is never resurrected. + */ + private prunedViewIdsDuringActivation: string[] = [] + + /** + * This view's pinned profile name from the view-local buffer. Exposed for + * sibling-instance inspection (getAllInstances() filtering): `viewLocalState` + * is private and must not be reached through bracket access. + */ + get pinnedProfileName(): string | undefined { + return this.viewLocalState.currentApiConfigName + } + + /** + * This view's profile settings overlay from the view-local buffer. Exposed for the + * message handler, which must not reach viewLocalState through bracket access: review + * thread 4595383337 needs the handler to put this exact value back when a pin write + * fails after the overlay was seeded for the new name. + */ + get pinnedProfileOverlay(): ProviderSettings | undefined { + return this.viewLocalState.apiConfiguration + } + public isViewLaunched = false public settingsImportedAt?: number public readonly latestAnnouncementId = "nov-2026-v3.98.2-pass-gemini-responses-fixes" // v3.98.2 Zoo Pass, Gemini models, Responses API, and provider fixes @@ -448,6 +585,11 @@ export class ClineProvider mdmService?: MdmService, ) { super() + // Initialize viewId based on renderContext and monotonically increasing instance identifier for uniqueness. + // activeInstances is used for visibility/iteration checks, so we keep tracking instances separately. + this.viewId = `${renderContext}-${ClineProvider.nextViewId++}` + this.viewStateId = this.viewId + ClineProvider.activeInstances.add(this) this.currentWorkspacePath = getWorkspacePath() this.pendingEditOperations = new PendingEditOperationStore( ClineProvider.PENDING_OPERATION_TIMEOUT_MS, @@ -514,6 +656,9 @@ export class ClineProvider await this.postStateToWebviewWithoutClineMessages() }) + // Load initial state from global state into viewLocalState buffer after dependencies used by getState are ready. + void this.loadViewState() + // Initialize MCP Hub through the singleton manager McpServerManager.getInstance(this.context, this) .then((hub) => { @@ -659,6 +804,479 @@ export class ClineProvider } } + /** + * Reads the registered viewStates map, returning a defensive copy. + * When fresh is set, the map is read directly from globalState (bypassing the + * ContextProxy cache) so serialized writes never observe a stale in-memory value. + */ + private getPersistedViewStates(options: { fresh?: boolean } = {}): Record { + const viewStates = options.fresh + ? this.context.globalState.get("viewStates") + : this.contextProxy.getValue("viewStates") + + if (!viewStates || typeof viewStates !== "object" || Array.isArray(viewStates)) { + return Object.create(null) + } + + // Copy onto a null prototype. A view id that names an Object.prototype key + // ("constructor", "toString", "valueOf", ...) must not resolve through the + // prototype chain and be mistaken for a persisted entry. + return Object.assign(Object.create(null), viewStates) + } + + /** + * Persists this view's non-secret selections through the serialized write queue. + * The write re-reads the map fresh and merges into the existing entry, removing the + * entry entirely when nothing persistable remains, so concurrent views cannot clobber it. + * The entry is keyed by the view id active when the change was made. Writes captured + * while the provider still holds its temporary (pre-launch) id persist under that id + * and are re-keyed to the stable view id when the webview registers one, so a change + * that lands before the launch message stays durable instead of being lost. + */ + private async savePersistedViewState(values: Partial): Promise { + // Capture the id at change time: a write belongs to the view that was active + // when the change was made, even if a newer id is registered while it is queued. + const viewStateId = this.viewStateId + const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + const states = this.getPersistedViewStates({ fresh: true }) + // The first write to an unowned temporary id claims the slot instead of merging + // into it: temporary names restart from 0 on every host start, so an entry under + // this name can be a leftover from an earlier session, and merging would adopt its + // fields and later re-key them under the stable id. Entries under a stable id, or + // under the temporary id this instance already authored, keep the merge semantics. + const ownsTargetEntry = viewStateId !== this.viewId || this.wroteUnderTemporaryViewStateId + const current = ownsTargetEntry ? (states[viewStateId] ?? {}) : {} + const next: PersistedViewState = { ...current } + + if ("mode" in values) { + if (values.mode === undefined || values.mode === null) { + delete next.mode + } else { + next.mode = values.mode + } + } + + if ("currentApiConfigName" in values) { + if (values.currentApiConfigName === undefined || values.currentApiConfigName === null) { + delete next.currentApiConfigName + } else { + next.currentApiConfigName = values.currentApiConfigName + } + } + + let wroteEntry = false + if (!next.mode && !next.currentApiConfigName) { + delete states[viewStateId] + ClineProvider.clearedViewStateIds.add(viewStateId) + } else { + next.updatedAt = values.updatedAt ?? Date.now() + states[viewStateId] = next + ClineProvider.clearedViewStateIds.delete(viewStateId) + wroteEntry = true + } + + const pruned = this.prunePersistedViewStates(states) + const evicted = Object.keys(states).filter((viewId) => !Object.hasOwn(pruned, viewId)) + if (evicted.length > 0) { + this.prunedViewIdsDuringActivation.push(...evicted) + } + + try { + await this.contextProxy.setValue("viewStates", pruned) + } catch (error) { + // updateGlobalState applies the new map to the in-memory cache before + // the durable write, so a rejected write leaves the cache claiming an + // entry that never reached disk. Restore the cache to the value durable + // storage actually holds (undefined when the key was never written); the + // cache update lands even if this compensating write also fails, so + // readers cannot observe the lost entry either way. + try { + await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) + } catch { + // The cache is updated before the durable attempt: it matches the + // durable value regardless of whether this restore write landed. + } + throw error + } + // Authorship is recorded only after the durable write lands: a failed persistence + // must not mark the temporary id as owned, or a later load would adopt an entry + // that was never actually stored. + if (wroteEntry && viewStateId === this.viewId) { + this.wroteUnderTemporaryViewStateId = true + } + }) + + ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) + await write + } + + /** + * Removes the given view's entry from the registered viewStates map. + * Runs through the serialized write queue to avoid racing concurrent view-state writes. + */ + private async clearPersistedViewState(viewStateId = this.viewStateId): Promise { + const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + const states = this.getPersistedViewStates({ fresh: true }) + delete states[viewStateId] + // The tombstone claims the entry is gone, so only a landed clear may leave + // it set: a rejected durable write leaves the entry stored, and a later + // activation that prunes it would skip the rollback restore for a view ID + // this clear did not actually remove. Drop the claim this call added. + const wasCleared = ClineProvider.clearedViewStateIds.has(viewStateId) + ClineProvider.clearedViewStateIds.add(viewStateId) + try { + await this.contextProxy.setValue("viewStates", states) + } catch (error) { + // The entry is still durable after a failed clear, so drop the + // tombstone this call added (one an earlier clear set stays). + if (!wasCleared) { + ClineProvider.clearedViewStateIds.delete(viewStateId) + } + // updateGlobalState applies the new map to the in-memory cache before + // the durable write, so a rejected write leaves the cache missing an + // entry that durable storage still holds. Restore the cache to the + // value storage actually holds (undefined when the key was never + // written); the cache update lands even if this compensating write + // also fails, so readers cannot observe the loss either way. + try { + await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) + } catch { + // The cache is updated before the durable attempt: it matches the + // durable value regardless of whether this restore write landed. + } + throw error + } + }) + + ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) + await write + } + + /** + * Re-points persisted view pins that reference a removed profile so views do not + * rehydrate a missing profile name after a reload. Runs through the serialized + * write queue like every other viewStates mutation. + */ + private async repointPersistedViewStates( + removedProfileName: string, + replacementProfileName: string, + ): Promise { + const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + const states = this.getPersistedViewStates({ fresh: true }) + let changed = false + + for (const [viewId, entry] of Object.entries(states)) { + if (entry?.currentApiConfigName !== removedProfileName) { + continue + } + + changed = true + const { currentApiConfigName: _removed, ...rest } = entry + + if (rest.mode) { + states[viewId] = { ...rest, currentApiConfigName: replacementProfileName, updatedAt: Date.now() } + } else { + states[viewId] = { currentApiConfigName: replacementProfileName, updatedAt: Date.now() } + } + } + + if (changed) { + const pruned = this.prunePersistedViewStates(states) + const evicted = Object.keys(states).filter((viewId) => !Object.hasOwn(pruned, viewId)) + if (evicted.length > 0) { + this.prunedViewIdsDuringActivation.push(...evicted) + } + + try { + await this.contextProxy.setValue("viewStates", pruned) + } catch (error) { + // updateGlobalState applies the new map to the in-memory cache + // before the durable write: restore the cache to the value durable + // storage actually holds so closed-view pins cannot serve re-pointed + // names that never reached disk, then let the caller compensate. + try { + await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) + } catch { + // The cache is updated before the durable attempt: it matches the + // durable value regardless of whether this restore write landed. + } + throw error + } + } + }) + + ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) + await write + } + + /** + * Keeps only the most recently updated entries of the persisted view states map, + * bounded by MAX_PERSISTED_VIEW_STATES so the global key cannot grow unboundedly. + */ + private prunePersistedViewStates(states: Record): Record { + return Object.fromEntries( + Object.entries(states) + .sort(([, a], [, b]) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0)) + .slice(0, ClineProvider.MAX_PERSISTED_VIEW_STATES), + ) + } + + /** + * Re-keys this provider's temporary pre-launch viewStates entry to the newly + * registered stable id so pre-launch writes become durable under the stable key + * instead of orphaning under a session-local temporary id. Only the provider's own + * temporary id is eligible: an entry under a previously registered stable id belongs + * to that webview's storage and is left alone. When the stable entry already exists + * it wins and the temporary entry is dropped, because temporary ids are session + * counters that can collide across window reloads. Runs through the serialized write + * queue like every other viewStates mutation. + */ + private async rekeyPersistedViewStateEntry(nextViewStateId: string): Promise { + const previousViewStateId = this.viewId + + const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + // An entry under this name can belong to a different session, because temporary + // ids restart from 0 on every extension host start. Only re-key entries this + // instance wrote, otherwise a stale entry from another session is adopted. + if (!this.wroteUnderTemporaryViewStateId) { + return + } + + const states = this.getPersistedViewStates({ fresh: true }) + const previous = states[previousViewStateId] + + if (!previous) { + return + } + + delete states[previousViewStateId] + ClineProvider.clearedViewStateIds.add(previousViewStateId) + + if (!states[nextViewStateId]) { + states[nextViewStateId] = previous + ClineProvider.clearedViewStateIds.delete(nextViewStateId) + } + + const pruned = this.prunePersistedViewStates(states) + const evicted = Object.keys(states).filter((viewId) => !Object.hasOwn(pruned, viewId)) + if (evicted.length > 0) { + this.prunedViewIdsDuringActivation.push(...evicted) + } + + try { + await this.contextProxy.setValue("viewStates", pruned) + } catch (error) { + // updateGlobalState applies the new map to the in-memory cache before + // the durable write, so a rejected re-key would leave the cache serving + // the stable entry while durable storage still holds the temporary one. + // Restore the cache to the value durable storage actually holds (the same + // rollback savePersistedViewState applies), so a later load or a retry of + // the registration sees the pre-rekey entry. + try { + await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) + } catch { + // The cache is updated before the durable attempt: it matches the + // durable value regardless of whether this restore write landed. + } + throw error + } + + // Only a successful write clears authorship: a failed attempt leaves the entry + // under the temporary name, and a retry must still be able to re-key it. + this.wroteUnderTemporaryViewStateId = false + }) + + ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) + await write + } + + /** + * Registers this provider's stable view identifier and loads any persisted selections it owns. + * The identifier is sanitized so it remains a safe object key in the shared viewStates map. + */ + public async setViewStateId(viewStateId: string | undefined): Promise { + // The webview generates this id on purpose - it has to survive a webview reload, + // which recreates the view on both sides - so the host cannot mint it instead. + // What the host owns is which view may hold a given persisted key, so everything + // below validates the supplied value before it becomes one. + if (typeof viewStateId !== "string") { + // A crafted postMessage can carry any JSON value here even though the message + // type declares a string; the persisted key must stay a string. + this.log(`[setViewStateId] Ignoring a non-string viewStateId for view ${this.viewId}.`) + return + } + + const normalizedViewStateId = viewStateId.trim().replace(/[^A-Za-z0-9_-]/g, "_") + + if ( + !normalizedViewStateId || + normalizedViewStateId === this.viewStateId || + // Reject "__proto__": writing states["__proto__"] would go through the + // Object.prototype setter and be silently dropped by the later spread. + normalizedViewStateId === "__proto__" + ) { + return + } + + // Bound the key: the webview generates a UUID, so a much longer value is not a + // view id, and an unbounded key is unbounded growth in the shared viewStates map. + if (normalizedViewStateId.length > ClineProvider.MAX_VIEW_STATE_ID_LENGTH) { + this.log( + `[setViewStateId] Ignoring an oversized viewStateId (${normalizedViewStateId.length} chars) for view ${this.viewId}.`, + ) + return + } + + const claimant = ClineProvider.getAllInstances().find( + (instance) => instance !== this && instance.viewStateId === normalizedViewStateId, + ) + if (claimant) { + // Ownership check: a key another live view holds must not be adopted. Doing so + // would load that view's pinned profile, nested overlay, and mode into this + // provider, and this webview could then overwrite that view's persisted entry. + // Staying on the temporary id keeps this view working against the shared state. + this.log( + `[setViewStateId] Refusing viewStateId ${normalizedViewStateId} for view ${this.viewId}: already claimed by live view ${claimant.viewId}.`, + ) + return + } + + const previousViewStateId = this.viewStateId + + this.viewStateId = normalizedViewStateId + + try { + // Re-key any durable entry written under the temporary pre-launch id before + // loading, so the load sees the view's own pre-registration selections. + await this.rekeyPersistedViewStateEntry(this.viewStateId) + + await this.loadViewState() + } catch (error) { + // A persistence failure must not leave the provider holding an id that was + // never registered: restore the previous id so a later launch retries the + // registration and the load instead of the guard above early-returning for + // the failed id. + this.viewStateId = previousViewStateId + throw error + } + } + + /** + * Loads non-secret persisted selections from the registered viewStates map. + * Missing entries are intentionally left unset so getState() falls back to shared ContextProxy values. + * Fields mutated while the async profile lookup is in flight are reapplied on top of the + * loaded state, field by field, so in-flight user selections are not clobbered by the load. + */ + private async loadViewState(): Promise { + // Capture the id this load is for: a newer id registered while an async + // profile lookup is in flight must not be overwritten by this stale load. + const loadedForViewId = this.viewStateId + + // While the stable id has not been registered yet, the key is this instance's + // session-local name. Temporary names restart from 0 on every host start, so an + // entry under the same name can belong to a different session. Load only entries + // this instance authored. + if (loadedForViewId === this.viewId && !this.wroteUnderTemporaryViewStateId) { + return + } + try { + const persisted = this.getPersistedViewStates()[loadedForViewId] + const loadedState: Partial = {} + + // Snapshot the in-memory buffer before the async profile lookup. The + // mutation paths update viewLocalState in place, so a shallow copy is + // what makes fields mutated during the load window observable below. + const preLoadBuffer = { ...this.viewLocalState } + + if (persisted?.mode) { + // A persisted mode may reference a custom mode that was deleted after it was + // pinned: restore it only when the slug still resolves, so a stale slug cannot + // shadow the shared mode from getState(). + const customModes = await this.customModesManager.getCustomModes() + if (getModeBySlug(persisted.mode, customModes)) { + loadedState.mode = persisted.mode as Mode + } else { + this.log(`[loadViewState] Ignoring unknown persisted mode "${persisted.mode}"`) + } + } + + if (persisted?.currentApiConfigName) { + loadedState.currentApiConfigName = persisted.currentApiConfigName + + try { + const { name: _name, ...apiConfiguration } = await this.providerSettingsManager.getProfile({ + name: persisted.currentApiConfigName, + }) + loadedState.apiConfiguration = apiConfiguration as ProviderSettings + } catch (error) { + this.log( + `[loadViewState] Unable to resolve API profile '${persisted.currentApiConfigName}' for viewId ${this.viewId}: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } + + if (this.viewStateId !== loadedForViewId) { + this.log(`[loadViewState] Discarding stale state for superseded view id ${loadedForViewId}`) + return + } + + // Reapply the buffer fields that changed while the load was in flight, + // tracking the change instead of testing against undefined: a field cleared + // during the load window must stay cleared (the loaded value must not + // resurrect it), and a field written to a new value must win over it. + // Untouched fields keep the persisted values authoritative, and the + // pre-load buffer is never merged wholesale so stale temporary-id state + // cannot override the stable persisted state. + const postLoadBuffer = this.viewLocalState + const mergedState: Partial = { ...loadedState } + + if (!Object.is(preLoadBuffer.mode, postLoadBuffer.mode)) { + if (postLoadBuffer.mode === undefined) { + delete mergedState.mode + } else { + mergedState.mode = postLoadBuffer.mode + } + } + + if (!Object.is(preLoadBuffer.currentApiConfigName, postLoadBuffer.currentApiConfigName)) { + if (postLoadBuffer.currentApiConfigName === undefined) { + delete mergedState.currentApiConfigName + } else { + mergedState.currentApiConfigName = postLoadBuffer.currentApiConfigName + } + } + + if (!Object.is(preLoadBuffer.apiConfiguration, postLoadBuffer.apiConfiguration)) { + if (postLoadBuffer.apiConfiguration === undefined) { + delete mergedState.apiConfiguration + } else { + mergedState.apiConfiguration = postLoadBuffer.apiConfiguration + } + } + + this.viewLocalState = mergedState + this.log(`[loadViewState] Loaded state for viewId ${this.viewId}`) + } catch (error) { + this.log( + `[loadViewState] Error loading state for viewId ${this.viewId}: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } + + /** + * Saves a single view-local state value. The in-memory buffer is always updated; the + * non-secret subset (mode, currentApiConfigName) is persisted durably under the view + * id active when the change was made, re-keyed to the stable id on registration. + */ + public async saveViewState( + key: K, + value: ViewLocalStateValues[K] | undefined, + ): Promise { + await this._saveViewLocalStateFromMutation({ [key]: value } as ViewLocalStateValues) + + this.log(`[saveViewState] Saved ${String(key)} for viewId ${this.viewId}`) + } + /** * Override EventEmitter's on method to match TaskProviderLike interface */ @@ -1052,24 +1670,31 @@ export class ClineProvider CloudService.instance.off("settings-updated", this.handleCloudSettingsUpdate) } - this._workspaceTracker?.dispose() - this._workspaceTracker = undefined - await this.mcpHub?.unregisterClient() - this.mcpHub = undefined - await this.skillsManager?.dispose() - this.skillsManager = undefined - await this.marketplaceManager?.cleanup() - this.customModesManager?.dispose() - this.taskTitleService.dispose() - this.taskHistoryStore.dispose() - this.log("Disposed all disposables") - ClineProvider.activeInstances.delete(this) - this.diagnosticsRequestBroker.dispose() + try { + this._workspaceTracker?.dispose() + this._workspaceTracker = undefined + await this.mcpHub?.unregisterClient() + this.mcpHub = undefined + await this.skillsManager?.dispose() + this.skillsManager = undefined + await this.marketplaceManager?.cleanup() + this.customModesManager?.dispose() + this.taskTitleService.dispose() + this.taskHistoryStore.dispose() + this.diagnosticsRequestBroker.dispose() + this.log("Disposed all disposables") + } finally { + // Deregistration must not depend on the cleanup above completing: a + // throwing disposable (e.g. an MCP client whose disposal rejects) + // would otherwise leave this provider registered while _disposed is + // already set, so no later retry could repair the registration. + ClineProvider.activeInstances.delete(this) - // Clean up any event listeners attached to this provider - this.removeAllListeners() + // Clean up any event listeners attached to this provider + this.removeAllListeners() - McpServerManager.unregisterProvider(this) + McpServerManager.unregisterProvider(this) + } } public get isViewVisible(): boolean { @@ -1084,6 +1709,16 @@ export class ClineProvider return Array.from(this.activeInstances) } + /** + * Returns the live instance whose current view is the given view or panel, + * if any. Title-bar commands on a specific surface use this to target the + * instance that owns that surface rather than the visible-instance + * heuristic (which picks whichever surface the user last focused). + */ + public static getInstanceForView(view: vscode.WebviewView | vscode.WebviewPanel): ClineProvider | undefined { + return Array.from(this.activeInstances).find((instance) => instance.view === view) + } + public static async getInstance(): Promise { let visibleProvider = ClineProvider.getVisibleInstance() @@ -1553,7 +2188,10 @@ export class ClineProvider historyItem.mode = defaultModeSlug } - await this.updateGlobalState("mode", historyItem.mode) + // Persist the restored mode through this view's per-view pin rather than the + // shared global: a global write would leak the restored mode into other views + // in parallel mode, and a buffer-only write would be lost after a reload. + await this.saveViewState("mode", historyItem.mode) // Load the saved API config for the restored mode if it exists. // Skip mode-based profile activation if historyItem.apiConfigName exists, @@ -1790,28 +2428,25 @@ export class ClineProvider return } - try { - const delivered = await this.view?.webview.postMessage(omitOriginalContentFromExtensionMessage(message)) - this.diagnosticsRecorder.record({ - boundary: "webview-out", - phase: delivered ? "success" : "failure", - type: message.type, - action: message.action, - elapsedMs: Date.now() - startedAt, - stateSequence: message.type === "state" ? message.state?.clineMessagesSeq : undefined, - taskId, - }) - } catch { - this.diagnosticsRecorder.record({ - boundary: "webview-out", - phase: "failure", - type: message.type, - action: message.action, - elapsedMs: Date.now() - startedAt, - taskId, - }) - // View disposed, drop message silently + const webview = this.view?.webview + if (!webview) { + return } + + // Dispatch without awaiting the renderer ack: VS Code settles postMessage only when the + // webview page acknowledges the message, and a page reload or view dispose in flight + // orphans that promise forever. Awaiting it could wedge every caller on the task critical + // path (e.g. the trailing postStateToWebview in handleModeSwitchUnlocked gates the next + // turn after a mode switch). Message ordering is enforced by the message seq, not the ack. + // Promise.resolve() normalizes non-promise returns (e.g. test doubles) before the catch. + void Promise.resolve(webview.postMessage(omitOriginalContentFromExtensionMessage(message))).catch((error) => { + // Swallow: postMessage rejects when the webview is disposed in flight. + // Log the dropped message type so a wedged webview channel is diagnosable + // instead of silently losing state updates. + this.log( + `[postMessageToWebview] dropped message type=${message.type}: ${error instanceof Error ? error.message : String(error)}`, + ) + }) } public requestWebviewThemeFixture(timeoutMs = 5_000): Promise { @@ -2100,8 +2735,12 @@ export class ClineProvider * current task. Pass null to apply only global mode/profile effects for a pending child. */ public async handleModeSwitch(newMode: Mode, targetTask: Task | null | undefined = this.getCurrentTask()) { - return this.enqueueProviderProfileMutation((signal) => - this.handleModeSwitchUnlocked(newMode, targetTask, signal), + return this.enqueueProviderProfileMutation( + (signal) => this.handleModeSwitchUnlocked(newMode, targetTask, signal), + // The switch and its nested activation must own the queue until every + // write - including compensation - settles: a timeout must not let the + // next queued mutation overlap writes that are still in flight. + { runToCompletion: true }, ) } @@ -2112,18 +2751,55 @@ export class ClineProvider ): Promise { const task = targetTask + // A cancelled or timed-out switch must not be partially applied: bail out + // before the task history / _taskMode writes as well as the durable mode + // write below. Aborts that land while the history write is in flight are + // handled in flight (the landed write is rolled back); the pre-write check + // further down still covers the remaining gap before the durable write. + if (signal?.aborted) { + return + } + + // The task-level writes below land before the durable shared-mode write, so a + // rejected shared write has to undo them: capture the pre-switch mode here. + let previousTaskMode: Mode | undefined + if (task) { TelemetryService.instance.captureModeSwitch(task.taskId, newMode) - task.emit(RooCodeEventName.TaskModeSwitched, task.taskId, newMode) try { // Update the task history with the new mode first. const taskHistoryItem = this.getTaskHistoryItem(task.taskId) + // The history item holds the mode this switch is about to overwrite. + previousTaskMode = taskHistoryItem?.mode ?? task["_taskMode"] if (taskHistoryItem) { await this.updateTaskHistory({ ...taskHistoryItem, mode: newMode }) + + // An abort that lands while the history write is in flight has + // already persisted the new mode: restore the pre-switch item and + // bail before the in-memory task write and the emit, so task + // history, task state, and provider mode cannot diverge. A failed + // rollback must not surface as the persistence error of the + // cancelled switch: log it and keep the cancellation result. + if (signal?.aborted) { + try { + // Restore only the field this switch changed: re-read the item so + // fields the running task persisted during the pending window + // (tokens, cost, status, apiConfigName) survive the rollback. + const latest = this.getTaskHistoryItem(task.taskId) ?? taskHistoryItem + await this.updateTaskHistory({ ...latest, mode: taskHistoryItem.mode }) + } catch (rollbackError) { + this.log(`Failed to roll back mode switch ${task.taskId}: ${String(rollbackError)}`) + } + return + } + } else if (signal?.aborted) { + return } + task.emit(RooCodeEventName.TaskModeSwitched, task.taskId, newMode) + // Only update the task's mode after successful persistence. ;(task as any)._taskMode = newMode } catch (error) { @@ -2138,7 +2814,56 @@ export class ClineProvider } } - await this.updateGlobalState("mode", newMode) + // A cancelled or timed-out switch must not write the mode or emit + // ModeChanged: check the mutation signal right before the durable write. + if (signal?.aborted) { + return + } + + // setValue (not the deprecated updateGlobalState) so the in-memory viewLocalState + // buffer stays in sync with the durable global write: getValues() merges + // viewLocalState on top of the ContextProxy values, so an unsynced stale + // restored mode would otherwise shadow the fresh switch for consumers. + // If the durable write fails, roll the shared write back so getValues() + // cannot mix a fresh shared mode with the stale pre-switch buffer. + const previousMode = this.getValue("mode") + try { + await this.setValue("mode", newMode) + } catch (error) { + try { + await this.contextProxy.setValue("mode", previousMode) + } catch (rollbackError) { + this.log( + `[handleModeSwitch] Failed to roll back shared mode after persistence failure: ${ + rollbackError instanceof Error ? rollbackError.message : String(rollbackError) + }`, + ) + } + // The history write and `_taskMode` landed before this durable write: + // restore the pre-switch mode so a rejected switch cannot leave the task + // and its history entry on a mode that was never persisted. + if (task && previousTaskMode !== undefined) { + try { + // Re-read the item so fields the running task persisted while the + // switch was in flight survive; only the mode is restored. + const latest = this.getTaskHistoryItem(task.taskId) + if (latest) { + await this.updateTaskHistory({ ...latest, mode: previousTaskMode }) + } + } catch (rollbackError) { + this.log( + `[handleModeSwitch] Failed to roll back the task mode for ${task.taskId}: ${ + rollbackError instanceof Error ? rollbackError.message : String(rollbackError) + }`, + ) + } + task["_taskMode"] = previousTaskMode + } + this.log( + `[handleModeSwitch] Failed to persist mode "${newMode}": ${error instanceof Error ? error.message : String(error)}`, + ) + throw error + } this.emit(RooCodeEventName.ModeChanged, newMode) @@ -2190,7 +2915,14 @@ export class ClineProvider } } else { // Keep an unmapped mode's default local; another window may already have saved a shared choice. - const currentApiConfigNameAfter = this.getGlobalState("currentApiConfigName") + // The effective selection is asked for here, not the durable global one: thread + // PRRT_kwDOSK-bwM61BXE7, printed at line 5138 of the head e7038a8529 and + // unread as of the 2026-11-16 read, says a view that pins profile A must not + // have the shared selection B saved as an unmapped mode's default, because a + // later switch to that mode can activate B. pinnedProfileName is this view's + // own pin (line 544), so it wins wherever it is set; the global selection + // stays the fallback for a view that pins nothing. + const currentApiConfigNameAfter = this.pinnedProfileName ?? this.getGlobalState("currentApiConfigName") if (currentApiConfigNameAfter) { const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter) @@ -2281,6 +3013,207 @@ export class ClineProvider return !!this.getProviderProfileEntry(name) } + /** + * Prior state that the profile activation writes overwrite, captured before the + * concurrent write group so a failure can compensate the writes that landed. + */ + private _snapshotProfileActivationState(): ProfileActivationSnapshot { + // The rollback may only restore entries this activation's own writes evict. + this.prunedViewIdsDuringActivation = [] + // Capture only the provider-settings keys. getValues() returns the whole + // global state, and restoring that copy would write unrelated keys + // (viewStates, mode, taskHistory, ...) back over changes that legitimately + // landed while the activation group was in flight. + const allValues = this.contextProxy.getValues() + const providerSettings = Object.fromEntries( + PROVIDER_SETTINGS_KEYS.map((key) => [key, allValues[key]]), + ) as RooCodeSettings + return { + listApiConfigMeta: this.contextProxy.getValue("listApiConfigMeta"), + currentApiConfigName: this.contextProxy.getValue("currentApiConfigName"), + // This view's own pin: the rollback must restore it as-is instead of + // overwriting it with the shared selection. + viewCurrentApiConfigName: this.viewLocalState?.currentApiConfigName, + providerSettings, + viewApiConfiguration: this.viewLocalState?.apiConfiguration, + // The activation's pin write merges into and prunes the durable map: the + // rollback needs the exact pre-activation map to bring back any sibling the + // pruning evicted, entry metadata included. + viewStates: this.getPersistedViewStates({ fresh: true }), + } + } + + /** + * Compensate the profile activation writes after one of them failed. Every + * restore is awaited independently and logged: one failed restore must not + * strand the others. The caller rethrows the original failure. + */ + private async _restoreProfileActivationState(snapshot: ProfileActivationSnapshot): Promise { + try { + await this.updateGlobalState("listApiConfigMeta", snapshot.listApiConfigMeta) + } catch (error) { + this.log( + `[ClineProvider] profile-activation rollback failed for the profile list: ${error instanceof Error ? error.message : String(error)}`, + ) + } + try { + // Restore the shared selection through the ContextProxy directly: + // this.setValue would also write the shared value into this view's pin + // and its durable viewStates entry, replacing the view's own selection + // with another view's choice. + await this.contextProxy.setValue("currentApiConfigName", snapshot.currentApiConfigName) + } catch (error) { + this.log( + `[ClineProvider] profile-activation rollback failed for the current profile selection: ${error instanceof Error ? error.message : String(error)}`, + ) + } + try { + await this.contextProxy.setProviderSettings(snapshot.providerSettings) + } catch (error) { + this.log( + `[ClineProvider] profile-activation rollback failed for the shared provider settings: ${error instanceof Error ? error.message : String(error)}`, + ) + } + try { + // Restore this view's own pin and overlay together: an absent pin stays + // absent (undefined deletes the entry) instead of materializing a pin + // from the shared value. + await this._saveViewLocalStateFromMutation({ + currentApiConfigName: snapshot.viewCurrentApiConfigName, + apiConfiguration: snapshot.viewApiConfiguration, + }) + } catch (error) { + this.log( + `[ClineProvider] profile-activation rollback failed for the view-local overlay: ${error instanceof Error ? error.message : String(error)}`, + ) + } + try { + // Restore the siblings the activation's pruning evicted, last, so it + // lands after the overlay restore's own pin write, with their original + // entry metadata. Only tracked evictions are restored: an entry a + // sibling deleted on purpose after the snapshot is newer than the + // snapshot too, and resurrecting it would undo the sibling's clear on + // reload. The mutation queue is per-instance, so sibling views keep + // writing to the durable map while an activation group is in flight; + // merge, never replace, to leave those newer writes alone. + const restore = ClineProvider.persistedViewStateWriteQueue.then(async () => { + const current = this.getPersistedViewStates({ fresh: true }) + const merged = { ...current } + for (const viewId of this.prunedViewIdsDuringActivation) { + const entry = snapshot.viewStates[viewId] + if (entry && !Object.hasOwn(merged, viewId) && !ClineProvider.clearedViewStateIds.has(viewId)) { + merged[viewId] = entry + } + } + await this.contextProxy.setValue("viewStates", merged) + }) + ClineProvider.persistedViewStateWriteQueue = restore.catch(() => {}) + await restore + } catch (error) { + this.log( + `[ClineProvider] profile-activation rollback failed for the durable viewStates map: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } + + /** + * Prior provider-manager state that the profile mutation group overwrites: the + * manager's record for the profile being saved (or its confirmed absence) and + * the manager-owned current selection. The manager store is the source of truth + * that the profile list and the shared settings are derived from, so + * compensation has to restore it and not only its ContextProxy copies. + */ + private async _snapshotProviderManagerState(name: string): Promise { + let previousRecord: ProviderSettingsWithId | undefined + let recordExisted: boolean | undefined + let claimedCreate = false + try { + // hasConfig distinguishes a confirmed absence from a read failure; the + // generic wrapper getProfile throws for a missing record cannot, because + // the manager does not type its not-found rejections. + recordExisted = await this.providerSettingsManager.hasConfig(name) + if (recordExisted) { + const { name: _name, ...record } = await this.providerSettingsManager.getProfile({ name }) + previousRecord = record as ProviderSettingsWithId + } else { + // Confirmed absence: claim the create so a concurrent create of the + // same name by another view can make this rollback skip the deletion + // that would destroy the other view's successful save. + claimProfileCreate(name) + claimedCreate = true + } + } catch { + // Unreadable: the restore must not delete what it cannot see. + recordExisted = undefined + } + let previousCurrentProfileName: string | undefined + try { + previousCurrentProfileName = await this.providerSettingsManager.getCurrentProfileName() + } catch { + // Best-effort: the selection restore is skipped when unreadable. + } + return { previousRecord, recordExisted, previousCurrentProfileName, claimedCreate } + } + + /** + * Selection-only variant of the manager snapshot, for paths that overwrite the + * manager selection without touching any profile record. + */ + private async _snapshotProviderManagerSelection(): Promise { + let previousCurrentProfileName: string | undefined + try { + previousCurrentProfileName = await this.providerSettingsManager.getCurrentProfileName() + } catch { + // Best-effort: the selection restore is skipped when unreadable. + } + return { previousRecord: undefined, recordExisted: undefined, claimedCreate: false, previousCurrentProfileName } + } + + /** + * Restore the manager record for a mutation that failed after the record write + * landed. A record the mutation created is deleted; a deletion that refuses + * (last remaining configuration) is logged and leaves the record behind. + */ + private async _restoreProviderManagerRecord(name: string, snapshot: ProviderManagerSnapshot): Promise { + try { + if (snapshot.recordExisted === true && snapshot.previousRecord) { + await this.providerSettingsManager.saveConfig(name, snapshot.previousRecord) + } else if (snapshot.recordExisted === false) { + // Delete only when this mutation owns the last create claim for the + // name: another view may have created the same profile concurrently + // and succeeded, and the record belongs to that save. + const lastClaimant = snapshot.claimedCreate ? releaseProfileCreate(name) : true + if (lastClaimant) { + // A successful claimant owns the record: delete only when no claimant + // succeeded, and clear the bookkeeping either way. + const anySucceeded = profileCreatesSucceeded.delete(name) + if (!anySucceeded) { + await this.providerSettingsManager.deleteConfig(name) + } + } + } + } catch (error) { + this.log( + `[ClineProvider] profile-mutation rollback failed for the provider-manager record: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } + + /** + * Restore the manager-owned current selection captured by a prior snapshot. + */ + private async _restoreProviderManagerSelection(snapshot: ProviderManagerSnapshot): Promise { + try { + if (snapshot.previousCurrentProfileName) { + await this.providerSettingsManager.activateProfile({ name: snapshot.previousCurrentProfileName }) + } + } catch (error) { + this.log( + `[ClineProvider] profile-mutation rollback failed for the provider-manager selection: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } + async upsertProviderProfile( name: string, providerSettings: ProviderSettings, @@ -2412,54 +3345,241 @@ export class ClineProvider // we rely on the `ContextProxy`'s data store and in other cases // we rely on the `ProviderSettingsManager`'s data store. It might // be simpler to unify these two. - const id = await this.providerSettingsManager.saveConfig(name, providerSettings) - - if (signal.aborted) return id - - if (activate) { - const { mode } = await this.getState() - - if (signal.aborted) return id - - // These promises do the following: - // 1. Adds or updates the list of provider profiles. - // 2. Sets the current provider profile. - // 3. Sets the current mode's provider profile. - // 4. Copies the provider settings to the context. - // - // Note: 1, 2, and 4 can be done in one `ContextProxy` call: - // this.contextProxy.setValues({ ...providerSettings, listApiConfigMeta: ..., currentApiConfigName: ... }) - // We should probably switch to that and verify that it works. - // I left the original implementation in just to be safe. - // `allSettled` so a caller that rolls back after a failure never races a write still in flight. - const activationResults = await Promise.allSettled([ - this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()), - this.updateGlobalState("currentApiConfigName", name), - this.setModeConfig(mode, id), - this.contextProxy.setProviderSettings(providerSettings), - ]) - const failedActivation = activationResults.find( - (result): result is PromiseRejectedResult => result.status === "rejected", + // The manager record written below belongs to the same mutation group as + // the activation writes: snapshot the prior manager record and the + // manager's own selection BEFORE saveConfig so a failure anywhere in the + // group compensates the manager store too, not just its ContextProxy + // copies. The shared/per-view snapshot is taken at the same point. + const managerSnapshot = await this._snapshotProviderManagerState(name) + const preWriteSnapshot = this._snapshotProfileActivationState() + // Review thread 4594702295 (created 2026-11-17T02:56:13Z, printed at line 3471 of + // this head with original_line 3471) names the one restore this method catch was + // missing. Both rebuilds in the non-activating branch below land ahead of the state + // post at line 3475, and every restore in the catch covers the manager record, the + // manager selection, the mode mapping and the shared/per-view state, so a rejected + // post left the conversation this view runs sending the settings the failed save had + // written while the durable stores went back to what they were. Captured here and + // assigned only by that branch, then restored through the rebuild path the file + // already uses for the task, with the task identity as the guard so a task swapped + // or disposed while the compensation ran is left alone. + let priorTaskConfig: ProviderSettings | undefined + let priorTaskId: string | undefined + let id: string + try { + id = await this.providerSettingsManager.saveConfig(name, providerSettings) + } catch (error) { + // saveConfig assigns the record before awaiting the store write, so a + // rejection may still have landed the record: route through the + // manager-record rollback (which deletes a landed record and spends the + // create claim) instead of escaping the group with the claim leaked. + await this._restoreProviderManagerRecord(name, managerSnapshot) + throw error + } + + if (signal.aborted) { + // The record landed; the create is complete, so the claim is spent and + // the outcome recorded: a failed sibling create must spare the record. + if (managerSnapshot.claimedCreate) { + markProfileCreateSucceeded(name) + if (releaseProfileCreate(name)) { + profileCreatesSucceeded.delete(name) + } + } + return id + } + + // saveConfig normalizes the record (schema parse, legacy downgrades): + // read the stored copy back and use it for every activation write, + // sibling refresh, overlay, and task-handler update below, so raw + // webview fields the profile schema strips cannot enter the shared + // store, sibling view state, or task configuration. Fail closed when + // the read-back fails: the raw caller payload must never stand in for + // the validated record, so the landed save is compensated and the + // mutation group fails instead of propagating unvalidated settings. + let normalizedSettings: ProviderSettings + try { + const { + name: _savedName, + id: _savedId, + ...storedRecord + } = await this.providerSettingsManager.getProfile({ name }) + normalizedSettings = storedRecord as ProviderSettings + } catch (error) { + // Fail closed: compensate the landed manager record and fail the + // group so raw webview data cannot reach shared writes, sibling + // overlays, or task configuration. + await this._restoreProviderManagerRecord(name, managerSnapshot) + throw new Error( + `Provider profile '${name}' could not be read back after save: ${error instanceof Error ? error.message : String(error)}`, ) + } - if (failedActivation) throw failedActivation.reason + let activationMode: Mode | undefined + let priorModeConfigId: string | undefined + try { + if (activate) { + const { mode } = await this.getState() + activationMode = mode + + // These promises do the following: + // 1. Adds or updates the list of provider profiles. + // 2. Sets the current provider profile. + // 3. Sets the current mode's provider profile. + // 4. Copies the provider settings to the context. + // + // Note: 1, 2, and 4 can be done in one `ContextProxy` call: + // this.contextProxy.setValues({ ...providerSettings, listApiConfigMeta: ..., currentApiConfigName: ... }) + // We should probably switch to that and verify that it works. + // I left the original implementation in just to be safe. + try { + priorModeConfigId = await this.providerSettingsManager.getModeConfigId(mode) + } catch { + // Best-effort snapshot: when the prior mapping cannot be read the + // compensation restores the mapping as absent. + } + // `allSettled` so the compensation below never races a write still in flight. + const activationResults = await Promise.allSettled([ + this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()), + // Route through setValue so the in-memory viewLocalState buffer tracks the + // activated profile: a plain global write would leave a stale loaded + // currentApiConfigName shadowing the new value in getValues(). + this.setValue("currentApiConfigName", name), + // Route through this.setModeConfig rather than the manager call so + // this provider's own mode mapping commits with the activation: an + // activation that updates only the manager leaves a stale cached id + // here, and the next switch back to the mode reads that cache. Review + // thread 4593061270 (node PRRT_kwDOSK-bwM64MFr- in my capture), printed + // at line 3410 of ebfff264 with original_line 3410 and unresolved, names + // the staleness; the expression changed here sits at line 3417 of + // this head. + this.setModeConfig(mode, id), + this.contextProxy.setProviderSettings(normalizedSettings), + // setProviderSettings writes the shared store directly, bypassing the + // view-local mutation path: clear this view's buffered apiConfiguration + // overlay (if any) so a stale loaded profile cannot keep shadowing the + // new settings in getState(). + this._saveViewLocalStateFromMutation({ apiConfiguration: undefined }), + ]) + const failedActivation = activationResults.find( + (result): result is PromiseRejectedResult => result.status === "rejected", + ) - if (signal.aborted) return id + if (failedActivation) throw failedActivation.reason - // Change the provider for the current task. - // TODO: We should rename `buildApiHandler` for clarity (e.g. `getProviderClient`). - this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true }) + // Change the provider for the current task. + // TODO: We should rename `buildApiHandler` for clarity (e.g. `getProviderClient`). + this.updateTaskApiHandlerIfNeeded(normalizedSettings, { forceRebuild: true }) - // Keep the current task's sticky provider profile in sync with the newly-activated profile. - await this.persistStickyProviderProfileToCurrentTask(name) - } else { - await this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()) + // Keep the current task's sticky provider profile in sync with the newly-activated profile. + await this.persistStickyProviderProfileToCurrentTask(name) + } else { + await this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()) + + // A save that does not activate still changes the profile's settings, and + // every view pinned to it buffers a full copy of them. Refresh those views, + // refresh this view when it is the pinned view, and rebuild this view's own + // conversation when it follows the saved profile under another pin; otherwise + // their getState() keeps serving the settings captured before the save under + // the same name. + // Both rebuilds below happen inside this branch, so the task snapshot is taken + // here rather than at each call: a save that reaches neither rebuild leaves + // priorTaskConfig undefined and the compensation restores nothing it did not + // change. + const priorTask = this.getCurrentTask() + priorTaskConfig = priorTask?.apiConfiguration + priorTaskId = priorTask?.taskId + if (this.pinnedProfileName === name) { + await this._saveViewLocalStateFromMutation({ apiConfiguration: normalizedSettings }) + // Only rebuild when the task actually runs under the saved profile: a + // view pinned to this profile can hold a task that follows a different + // sticky profile, and the forced rebuild would silently switch that + // conversation to the saved profile's settings. + if (this.getCurrentTask()?.taskApiConfigName === name) { + this.updateTaskApiHandlerIfNeeded(normalizedSettings, { forceRebuild: true }) + } + } else if (this.getCurrentTask()?.taskApiConfigName === name) { + // The fan-out is taken over other instances only, so the conversation of + // the view performing this save is refreshed here. This view pins another + // profile, so its buffer keeps that profile's settings, but the task it + // runs follows the profile that was just saved and must stop sending the + // pre-save settings: review thread 4506513932, printed beside the refresh + // method below. Placed ahead of this view's own state post so the state + // re-posted below carries the rebuilt handler. + this.updateTaskApiHandlerIfNeeded(normalizedSettings, { forceRebuild: true }) + } + } + + await this.postStateToWebview() + + // The compensated write group above has committed: refresh the sibling + // views last, so a failure in any earlier step happens while their + // buffers and task handlers still hold the pre-save state (there is then + // nothing to roll back), and a refresh failure is logged instead of + // failing a save whose other writes already landed. + try { + await this.refreshViewLocalStateForUpdatedProfile(name, normalizedSettings) + } catch (refreshError) { + this.log( + `[ClineProvider] failed to refresh the sibling views pinned to '${name}': ${ + refreshError instanceof Error ? refreshError.message : String(refreshError) + }`, + ) + } + + // The create completed: the claim is spent and later rollbacks of + // other creates must see this one as finished - and spare the record + // it saved. + if (managerSnapshot.claimedCreate) { + markProfileCreateSucceeded(name) + if (releaseProfileCreate(name)) { + profileCreatesSucceeded.delete(name) + } + } + return id + } catch (error) { + // Compensate every write that may have landed, each restore awaited + // on its own so one failure cannot strand the rest: the manager + // record and selection first (the manager store is the source of + // truth that the profile list and the shared settings are derived + // from), then the mode mapping, then the shared and per-view state. + // The original failure is re-thrown for the caller. + await this._restoreProviderManagerRecord(name, managerSnapshot) + await this._restoreProviderManagerSelection(managerSnapshot) + if (activationMode !== undefined) { + try { + await this.providerSettingsManager.setModeConfig(activationMode, priorModeConfigId as string) + } catch (restoreError) { + this.log( + `[ClineProvider] profile-activation rollback failed for the mode mapping: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, + ) + } + } + await this._restoreProfileActivationState(preWriteSnapshot) + // Put this view.own task back the way it was, through the rebuild path the file + // already uses for it: the helper rebuilds the handler and syncs the parser from + // the settings it is given, and the identity option makes the call a no-op when + // the task was swapped or disposed while the compensation ran. Logged rather than + // thrown, matching the mode-mapping restore above, so a failed restore can neither + // strand the rest of the compensation nor replace the original error. The + // activating branch above rebuilds at line 3441 and keeps the same gap; it is + // named rather than widened here, because that branch has no state post between + // its rebuild and its last await for this save shape. + if (priorTaskConfig !== undefined && priorTaskId !== undefined) { + try { + this.updateTaskApiHandlerIfNeeded(priorTaskConfig, { + forceRebuild: true, + expectedCurrentTaskId: priorTaskId, + }) + } catch (restoreError) { + this.log( + `[ClineProvider] profile-save rollback failed for the task api handler: ${ + restoreError instanceof Error ? restoreError.message : String(restoreError) + }`, + ) + } + } + throw error } - - if (signal.aborted) return id - - await this.postStateToWebview() - return id } async deleteProviderProfile(profileToDelete: ProviderSettingsEntry) { @@ -2474,15 +3594,283 @@ export class ClineProvider throw new Error("You cannot delete the last profile") } - const entries = this.getProviderProfileEntries().filter(({ name }) => name !== profileToDelete.name) + // Snapshot the manager record and every persistence surface this + // deletion rewrites BEFORE the manager delete commits, so a failure + // inside the write group below can be compensated instead of leaving + // the secrets-backed record gone while metadata and view pins still + // reference it. + let previousRecord: Awaited> | undefined + let recordConfirmedAbsent = false + try { + previousRecord = await this.providerSettingsManager.getProfile({ name: profileToDelete.name }) + } catch { + // A rejected read is not a confirmed absence. This catch used to assume + // one, which let the delete below commit against a record that the + // compensation at the end of this method cannot restore without having + // read it. Confirm the absence with the manager's own existence read, + // hasConfig, the read the manager snapshot above already uses for this + // distinction; an existence read that fails confirms nothing. + let existsBefore: boolean | undefined + try { + existsBefore = await this.providerSettingsManager.hasConfig(profileToDelete.name) + } catch { + existsBefore = undefined + } + recordConfirmedAbsent = existsBefore === false + } - await this.contextProxy.setValues({ - ...globalSettings, - currentApiConfigName: profileToActivate, - listApiConfigMeta: entries, - }) + if (!previousRecord && !recordConfirmedAbsent) { + // Review thread 4593061279, printed at line 3522 of the head it was + // written against with original_line 3522: the profile exists and only + // its record failed to read, so stop before the deletion instead of + // stranding the list entry, the selection and the pins on a profile the + // compensation cannot put back. + throw new Error( + `Cannot delete profile '${profileToDelete.name}': its record could not be read, and its absence could not be confirmed`, + ) + } + const previousEntries = this.getProviderProfileEntries() + const previousSelection = globalSettings.currentApiConfigName + const previousSharedSettings = this.contextProxy.getProviderSettings() + const previousViewStates = this.getPersistedViewStates({ fresh: true }) + + // Remove the profile from the settings store (context.secrets) so it cannot be + // resurrected by a later listApiConfigMeta sync. A not-found rejection means + // the secret was already gone (e.g. pruned by an earlier run): branch on the + // typed ProviderSettingsNotFoundError so the stale list entry below is still + // pruned as an idempotent success, while any other failure (e.g. refusing to + // delete the last remaining configuration) propagates. Matching message text + // instead would let a profile whose name contains "not found" swallow an + // unrelated failure. + try { + await this.providerSettingsManager.deleteConfig(profileToDelete.name) + } catch (error) { + if (!(error instanceof ProviderSettingsNotFoundError)) { + throw error + } + this.log( + `deleteProviderProfile: settings for '${profileToDelete.name}' were not found; pruning the stale list entry only`, + ) + } - await this.postStateToWebview() + try { + const entries = this.getProviderProfileEntries().filter(({ name }) => name !== profileToDelete.name) + + // Write only the profile list back: replaying the full settings snapshot + // captured above would also rewrite unrelated keys (including viewStates, + // which ClineProvider mutates directly in storage for concurrent views) + // with this view's stale cached copy. + await this.contextProxy.setValue("listApiConfigMeta", entries) + + // Resolve the surviving profile's settings so this view and any other + // live view still pinned to the deleted profile can be re-pinned with + // a matching configuration. + let survivingSettings: ProviderSettings | undefined + try { + const { name: _survivingName, ...settings } = await this.providerSettingsManager.getProfile({ + name: profileToActivate, + }) + survivingSettings = settings as ProviderSettings + } catch (error) { + // Without the survivor's settings the re-point below would leave this view, + // and every view pinned to the deleted profile, serving the deleted + // profile's configuration under the survivor's name. When this deletion + // actually removed a stored record, fail it so the compensation restores the + // profile. An already-absent record is the idempotent prune path: the stale + // list entry must still be dropped, so that path continues and clears the + // deleted profile's residue from the affected views below. + this.log( + `[deleteProviderProfile] Unable to resolve API profile '${profileToActivate}': ${ + error instanceof Error ? error.message : String(error) + }`, + ) + if (previousRecord) { + throw new Error( + `Cannot delete profile '${profileToDelete.name}': the surviving profile '${profileToActivate}' could not be loaded`, + ) + } + } + + // Capture this view's pin before any rewrite: a view pinned to the + // deleted profile while the global selection points elsewhere must still be + // reconfigured, or getState() would keep the deleted profile's settings under + // the surviving profile's name. + const viewWasPinnedToDeleted = this.viewLocalState.currentApiConfigName === profileToDelete.name + const deletedWasGlobal = profileToDelete.name === globalSettings.currentApiConfigName + + if (viewWasPinnedToDeleted) { + // This view's pin now dangles: re-point it. setValue also persists the + // survivor to the shared store, which covers the deleted-was-global case + // for every other view as well as this one. + await this.setValue("currentApiConfigName", profileToActivate) + } else if (deletedWasGlobal) { + // The shared selection changed, but this view's own pin still names a + // surviving profile: update the shared store only, leaving the + // view-local pin untouched. + await this.contextProxy.setValue("currentApiConfigName", profileToActivate) + } + + if ((deletedWasGlobal || viewWasPinnedToDeleted) && survivingSettings) { + // The deleted profile was the active one (globally, or for this view), so + // the shared provider keys still carry its settings; replace them so + // getState() reports the surviving profile's configuration. + await this.contextProxy.setProviderSettings(survivingSettings) + + if (viewWasPinnedToDeleted) { + // This view's nested overlay (viewLocalState.apiConfiguration, seeded + // by loadViewState) still serves the deleted profile's configuration: + // replace it with the survivor's so the re-pointed pin serves matching + // settings. A view pinned to another profile keeps its own overlay. + await this._saveViewLocalStateFromMutation({ apiConfiguration: survivingSettings }) + } + } else if (viewWasPinnedToDeleted) { + // The survivor's settings could not be resolved (idempotent prune of a + // stale list entry): the pin was re-pointed, so this view's overlay must + // not keep serving the deleted profile's configuration under the + // survivor's name. + await this._saveViewLocalStateFromMutation({ apiConfiguration: undefined }) + } + + // The deleting view's own task must follow the deletion on this same + // commit. The re-pin pass at the end of this method filters this instance + // out of the only task-handler rebuild and sticky-name update (review + // thread 4593061285, written against original_line 3952, where that filter + // excludes the provider doing the deleting), so without this the view's pin + // and overlay name the survivor while its running conversation keeps the + // deleted profile's handler and name, and getStateToPostToWebview prefers + // the task's own values over this view's replacement state. Same guard the + // sibling pass uses: only a task that actually runs under the deleted + // profile is re-pointed. + if (this.getCurrentTask()?.taskApiConfigName === profileToDelete.name) { + // The sticky name may only follow the survivor once the survivor's settings resolved. + // When the deleted record was already gone and the survivor lookup failed, + // profileToActivate names a profile this deletion never read, and rewriting the + // task's sticky name to it would pin the running conversation to a profile whose + // settings this path does not have (review thread 4594194484). + if (survivingSettings) { + this.updateTaskApiHandlerIfNeeded(survivingSettings, { forceRebuild: true }) + await this.persistStickyProviderProfileToCurrentTask(profileToActivate) + } + } + + // Closed views keep their durable viewStates entry after disposal: a pin + // naming the deleted profile would rehydrate a missing profile name on + // the next load. Re-point those persisted pins to the survivor too. + await this.repointPersistedViewStates(profileToDelete.name, profileToActivate) + + await this.postStateToWebview() + + // Re-pin the other live views last: doing it mid-group would leave their + // buffers, rebuilt task handlers, and sticky profile names on the survivor + // while a later step's failure rolls the stored profile back - the + // compensation restores the record, the metadata, the shared settings, and + // the durable pins, but a sibling already moved in memory would need a + // reload to notice. Running it after every other write has committed + // leaves nothing to compensate, and a failure here is logged instead of + // resurrecting a profile the user deleted. + try { + await this.rePinViewLocalStateForDeletedProfile( + profileToDelete.name, + profileToActivate, + survivingSettings, + ) + } catch (repinError) { + this.log( + `[deleteProviderProfile] failed to re-pin the live views buffered on '${profileToDelete.name}': ${ + repinError instanceof Error ? repinError.message : String(repinError) + }`, + ) + } + } catch (error) { + // The manager delete committed but a later write failed: restore the + // deleted record first, then the shared metadata, selection, and shared + // settings the deletion had rewritten, and finally merge the affected + // persisted pins back. The merge re-reads the durable map and rewrites + // only entries that named the deleted profile in the pre-delete + // snapshot, so concurrent viewStates updates from sibling views + // survive. Each restore is independent and logged; the original + // failure is what the caller sees. + if (previousRecord) { + try { + // Keep the record's own id: mode mappings store the id, so restoring it + // under a generated id would leave the mapped mode pointing at a profile + // that no longer exists. + const { name: _previousName, ...previousSettings } = previousRecord + await this.providerSettingsManager.saveConfig(profileToDelete.name, previousSettings) + } catch (restoreError) { + this.log( + `[deleteProviderProfile] failed to restore the manager record '${profileToDelete.name}': ${ + restoreError instanceof Error ? restoreError.message : String(restoreError) + }`, + ) + } + } + try { + // Merge rather than clobber: another instance may have added + // profiles between the snapshot and the compensation. + const currentEntries = this.getProviderProfileEntries() + const deletedEntry = previousEntries.find((entry) => entry.name === profileToDelete.name) + if (deletedEntry && !currentEntries.some((entry) => entry.name === profileToDelete.name)) { + await this.contextProxy.setValue("listApiConfigMeta", [...currentEntries, deletedEntry]) + } + } catch (restoreError) { + this.log( + `[deleteProviderProfile] failed to restore the profile list: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, + ) + } + try { + await this.contextProxy.setValue("currentApiConfigName", previousSelection) + } catch (restoreError) { + this.log( + `[deleteProviderProfile] failed to restore the shared selection: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, + ) + } + try { + await this.contextProxy.setProviderSettings(previousSharedSettings) + } catch (restoreError) { + this.log( + `[deleteProviderProfile] failed to restore the shared provider settings: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, + ) + } + try { + const restore = ClineProvider.persistedViewStateWriteQueue.then(async () => { + const current = this.getPersistedViewStates({ fresh: true }) + const merged = { ...current } + let changed = false + for (const [viewId, entry] of Object.entries(previousViewStates)) { + if (entry?.currentApiConfigName !== profileToDelete.name) { + continue + } + const fresh = merged[viewId] + if (!fresh) { + // The entry disappeared while the deletion ran: restore the snapshot. + merged[viewId] = entry + changed = true + continue + } + // Undo only this deletion's re-point: a sibling may have changed other + // fields (for example the mode) while the deletion ran, and the fresh + // entry must keep them. When the fresh entry no longer names the + // survivor (still the pre-deletion name, or another profile), there is + // nothing to undo. + if (fresh.currentApiConfigName === profileToActivate) { + merged[viewId] = { ...fresh, currentApiConfigName: profileToDelete.name } + changed = true + } + } + if (changed) { + await this.contextProxy.setValue("viewStates", merged) + } + }) + ClineProvider.persistedViewStateWriteQueue = restore.catch(() => {}) + await restore + } catch (restoreError) { + this.log( + `[deleteProviderProfile] failed to restore the persisted view pins: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, + ) + } + throw error + } } private async persistStickyProviderProfileToCurrentTask( @@ -2525,8 +3913,15 @@ export class ClineProvider expectedCurrentTaskId?: string }, ) { - return this.enqueueProviderProfileMutation((signal) => - this.activateProviderProfileUnlocked(args, options, signal), + return this.enqueueProviderProfileMutation( + (signal) => this.activateProviderProfileUnlocked(args, options, signal), + { + // The queue stays owned until this run - including its compensation - settles: + // a group write that hangs past the mutation timeout must not let a later + // activation complete before this rollback, or the late restore would + // overwrite the later activation's selection and settings. + runToCompletion: true, + }, ) } @@ -2540,6 +3935,10 @@ export class ClineProvider }, signal?: AbortSignal, ): Promise { + // The manager selection written by activateProfile belongs to the same + // mutation group as the writes below: snapshot it first so a failed group + // compensates the manager store, not just its copies. + const managerSelectionSnapshot = await this._snapshotProviderManagerSelection() const { name, id, ...providerSettings } = await this.providerSettingsManager.activateProfile(args) if (signal?.aborted) return @@ -2550,11 +3949,34 @@ export class ClineProvider if (!skipCurrentTaskRebuild) { // See `upsertProviderProfile` for a description of what this is doing. - await Promise.all([ - this.contextProxy.setValue("listApiConfigMeta", await this.providerSettingsManager.listConfig()), - this.contextProxy.setValue("currentApiConfigName", name), - this.contextProxy.setProviderSettings(providerSettings), - ]) + const activationSnapshot = this._snapshotProfileActivationState() + try { + // `allSettled` so the compensation below never races a write still in flight. + const activationResults = await Promise.allSettled([ + this.contextProxy.setValue("listApiConfigMeta", await this.providerSettingsManager.listConfig()), + // Route through setValue so the in-memory viewLocalState buffer tracks the + // activated profile: a plain ContextProxy write would leave a stale loaded + // currentApiConfigName shadowing the new value in getValues(). + this.setValue("currentApiConfigName", name), + this.contextProxy.setProviderSettings(providerSettings), + // setProviderSettings writes the shared store directly, bypassing the + // view-local mutation path: clear this view's buffered apiConfiguration + // overlay (if any) so a stale loaded profile cannot keep shadowing the + // new settings in getState(). + this._saveViewLocalStateFromMutation({ apiConfiguration: undefined }), + ]) + const failedActivation = activationResults.find( + (result): result is PromiseRejectedResult => result.status === `rejected`, + ) + + if (failedActivation) throw failedActivation.reason + } catch (error) { + // Compensate every write that may have landed before the failure, + // including the manager selection written by activateProfile. + await this._restoreProviderManagerSelection(managerSelectionSnapshot) + await this._restoreProfileActivationState(activationSnapshot) + throw error + } } const { mode } = await this.getState() @@ -2587,6 +4009,191 @@ export class ClineProvider if (providerSettings.apiProvider && !skipCurrentTaskRebuild) { this.emit(RooCodeEventName.ProviderProfileChanged, { name, provider: providerSettings.apiProvider }) } + + // The write group above has committed: refresh the sibling views last, so a + // failure in any earlier step happens while their buffers and task handlers + // still hold the pre-activation state (nothing to roll back), and a refresh + // failure is logged instead of failing an activation whose other writes landed. + if (!skipCurrentTaskRebuild) { + try { + await this.refreshViewLocalStateForUpdatedProfile(name, providerSettings) + } catch (refreshError) { + this.log( + `[ClineProvider] failed to refresh the sibling views pinned to '${name}': ${ + refreshError instanceof Error ? refreshError.message : String(refreshError) + }`, + ) + } + } + } + + /** + /** + * Refresh the other live views after a profile is saved or activated. + * The two sets below are taken differently, on purpose, and the split is + * what review thread 4506513932 (node PRRT_kwDOSK-bwM61BXEu in my capture, + * original_line 542 of 446a89921fd7bdd235ec9e9729c7e9b6535030e8, where lines + * 541-542 are the pinnedProfileName getter the first filter reads) asks for. + * An upsert or activation rewrites the profile's settings in the shared store + * and in the store-backed manager, and a view whose buffer loaded that profile + * earlier keeps shadowing the stale settings in its getState() until its own + * next mutation: that overlay half stays taken from each view's pin. A task + * carries its own sticky profile name, so the handler half is taken from the + * task instead, and a delegated task that follows the saved profile is rebuilt + * in the view running it even when that view pins a different profile - the + * case this method used to miss, because a view whose pin named another + * profile was never in the set at all. The originating view is in neither set: + * it refreshes its buffer and rebuilds its own task at the mutation site above. + */ + private async refreshViewLocalStateForUpdatedProfile( + name: string, + providerSettings: ProviderSettings, + ): Promise { + const others = ClineProvider.getAllInstances().filter((instance) => instance !== this) + // The overlay half stays pinned-based: a view buffers a full copy of a + // profile's settings only while its own pin names that profile, and writing + // a buffer that intentionally holds another profile would re-point it. + const pinnedViews = others.filter((instance) => instance.pinnedProfileName === name) + // The handler half follows each task's own sticky profile name, so the + // conversation of a view pinned to another profile is still rebuilt on the + // saved settings. A view in the overlay half is refreshed there, so the two + // sets are disjoint by construction and no view is refreshed twice. + const taskBoundViews = others.filter( + (instance) => instance.pinnedProfileName !== name && instance.getCurrentTask()?.taskApiConfigName === name, + ) + + if (pinnedViews.length === 0 && taskBoundViews.length === 0) { + return + } + + await Promise.all([ + ...pinnedViews.map(async (instance) => { + // Direct private access: compile-time safe across sibling instances. + await instance._saveViewLocalStateFromMutation({ apiConfiguration: providerSettings }) + + // The active task of a pinned view holds its own API handler built from + // the profile's settings: rebuild it with the saved settings or the + // running conversation keeps sending the old token even though the + // view's buffer has caught up. Only rebuild when the task actually runs + // under the saved profile: a task that follows a different sticky + // profile must keep its own settings. Direct private access across + // sibling instances of the same class is compile-time safe. + if (instance.getCurrentTask()?.taskApiConfigName === name) { + instance.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true }) + } + await instance.postStateToWebview() + }), + // The task-only half rebuilds the handler and re-posts the state so that + // webview shows the settings its conversation now runs on, and leaves the + // buffer and the pin alone: the view still pins another profile. + ...taskBoundViews.map(async (instance) => { + // Direct private access across sibling instances of the same class is + // compile-time safe. + instance.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true }) + await instance.postStateToWebview() + }), + ]) + } + + /** + * Re-pin the other live views whose buffer still names a deleted profile: + * without this their in-memory buffer and durable viewStates entry keep + * serving the deleted profile's name and configuration on top of the + * surviving shared state. Each affected view's durable entry is re-pinned + * through the serialized write queue, so the rename survives reloads. + */ + private async rePinViewLocalStateForDeletedProfile( + deletedProfileName: string, + replacementName: string, + replacementSettings: ProviderSettings | undefined, + ): Promise { + const affected = ClineProvider.getAllInstances().filter( + (instance) => instance !== this && instance.pinnedProfileName === deletedProfileName, + ) + + if (affected.length === 0) { + return + } + + await Promise.all( + affected.map(async (instance) => { + const values: Partial & Partial = { + currentApiConfigName: replacementName, + } + + // Assign the overlay explicitly (even undefined) so it is replaced or + // cleared: without the replacement's settings the re-pinned view must fall + // back to the shared state instead of serving the deleted profile's + // configuration under the survivor's name. + values.apiConfiguration = replacementSettings + + // Direct private access: compile-time safe across sibling instances. + await instance._saveViewLocalStateFromMutation(values) + // The active task of a view pinned to the deleted profile holds its own API + // handler and sticky profile name built from the deleted profile: rebuild + // the handler with the replacement's settings and re-point the sticky name, + // or the running conversation keeps sending the deleted profile's + // configuration even though the view's buffer was re-pointed (the posted + // state prefers the task's own apiConfiguration). Only re-point when the + // task actually runs under the deleted profile: a view pinned to it can + // hold a task that follows a different sticky profile, and forcing the + // replacement would silently switch that conversation and rewrite its + // persisted profile name without the user asking. + if (instance.getCurrentTask()?.taskApiConfigName === deletedProfileName) { + if (replacementSettings) { + instance.updateTaskApiHandlerIfNeeded(replacementSettings, { forceRebuild: true }) + } + await instance.persistStickyProviderProfileToCurrentTask(replacementName) + } + await instance.postStateToWebview() + }), + ) + } + + /** + * Re-point live views still pinned to a profile that is being renamed onto + * the new name. A rename keeps the profile id, so a view pinned to the old + * name should follow the record instead of falling back to the shared + * selection: without this, the pin dangles at a name that no longer + * resolves and the buffered overlay keeps serving the pre-rename copy. + * Must run before the old name is deleted. + */ + public async repointViewLocalStateAfterProfileRename( + oldName: string, + newName: string, + renamedSettings: ProviderSettingsWithId | undefined, + ): Promise { + // Closed views keep their pin only in the persisted map: re-point those entries + // first so a view that launches after an intervening activation still follows the + // renamed profile instead of dangling at the deleted name. + await this.repointPersistedViewStates(oldName, newName) + const affected = ClineProvider.getAllInstances().filter((instance) => instance.pinnedProfileName === oldName) + + if (affected.length === 0) { + return + } + + await Promise.all( + affected.map(async (instance) => { + // Assigning the settings (even undefined) is what replaces or clears the + // overlay: the renamed record's current settings are the only correct + // overlay for a pin that now names the new profile. + await instance._saveViewLocalStateFromMutation({ + currentApiConfigName: newName, + apiConfiguration: renamedSettings, + }) + // A task running under the old name holds its own API handler and sticky + // profile name: re-point both, or the conversation keeps sending the + // pre-rename configuration under a name that no longer resolves. + if (instance.getCurrentTask()?.taskApiConfigName === oldName) { + if (renamedSettings) { + instance.updateTaskApiHandlerIfNeeded(renamedSettings, { forceRebuild: true }) + } + await instance.persistStickyProviderProfileToCurrentTask(newName) + } + await instance.postStateToWebview() + }), + ) } async updateCustomInstructions(instructions?: string) { @@ -2724,8 +4331,10 @@ export class ClineProvider // picks up the new token immediately for the current task. await this.upsertProviderProfile(entry.name, updated, true) } else { - // Non-active profiles just need the token saved to disk. - await this.providerSettingsManager.saveConfig(entry.name, updated) + // Non-active profiles need the token saved to disk and the views pinned + // to them refreshed: a direct saveConfig leaves a pinned view serving the + // old token until it reloads. + await this.upsertProviderProfile(entry.name, updated, false) } } } @@ -3568,12 +5177,18 @@ export class ClineProvider > > { const stateValues = this.contextProxy.getValues() + + // Merge viewLocalState on top of global state so a provider can serve + // state values scoped to its own view while preserving ContextProxy defaults. + const mergedStateValues = { ...stateValues, ...this.viewLocalState } + const customModes = await this.customModesManager.getCustomModes() // Determine apiProvider with the same logic as before, while filtering retired providers. + // Use mergedStateValues to prioritize viewLocalState for parallel mode support const apiProvider: ProviderName = - stateValues.apiProvider && !isRetiredProvider(stateValues.apiProvider) - ? stateValues.apiProvider + mergedStateValues.apiProvider && !isRetiredProvider(mergedStateValues.apiProvider) + ? mergedStateValues.apiProvider : providerIdentifiers.anthropic // Build the apiConfiguration object combining state values and secrets. @@ -3634,129 +5249,152 @@ export class ClineProvider const taskSyncEnabled: boolean = false // Return the same structure as before. + // A view-local profile is a complete snapshot, not a patch over the shared store. + // Spreading it on top of providerSettings would let a key the profile never defined + // leak in from another profile, which ContextProxy.setProviderSettings deliberately + // prevents by clearing omitted keys. Use the view's own settings in place and + // default an omitted apiProvider to Anthropic rather than to the shared + // provider: review thread PRRT_kwDOSK-bwM61BXE5, printed at line 5086 of + // f50c23bc81 with original_line 4987 and unread in the 2026-11-16 capture, + // reports that a pinned profile which carries no provider then starts tasks + // on Bedrock or OpenAI without their credentials. A view with no overlay at + // all still takes the shared settings below, which is the other thread's + // construct and untouched here. + // The overlay is read from the buffer itself: the raw apiConfiguration state key + // is a partial patch from shared-store paths, not a view snapshot. + const viewApiConfiguration = this.viewLocalState.apiConfiguration + const resolvedApiConfiguration = viewApiConfiguration + ? { + ...viewApiConfiguration, + apiProvider: viewApiConfiguration.apiProvider ?? providerIdentifiers.anthropic, + } + : providerSettings + return { - apiConfiguration: providerSettings, - lastShownAnnouncementId: stateValues.lastShownAnnouncementId, - customInstructions: stateValues.customInstructions, - apiModelId: stateValues.apiModelId, - alwaysAllowReadOnly: stateValues.alwaysAllowReadOnly ?? false, - alwaysAllowReadOnlyOutsideWorkspace: stateValues.alwaysAllowReadOnlyOutsideWorkspace ?? false, - allowedReadFiles: stateValues.allowedReadFiles ?? [], - alwaysAllowWrite: stateValues.alwaysAllowWrite ?? false, - alwaysAllowWriteOutsideWorkspace: stateValues.alwaysAllowWriteOutsideWorkspace ?? false, - alwaysAllowWriteProtected: stateValues.alwaysAllowWriteProtected ?? false, - allowedWriteFiles: stateValues.allowedWriteFiles ?? [], - alwaysAllowExecute: stateValues.alwaysAllowExecute ?? false, + apiConfiguration: resolvedApiConfiguration, + lastShownAnnouncementId: mergedStateValues.lastShownAnnouncementId, + customInstructions: mergedStateValues.customInstructions, + apiModelId: mergedStateValues.apiModelId, + alwaysAllowReadOnly: mergedStateValues.alwaysAllowReadOnly ?? false, + alwaysAllowReadOnlyOutsideWorkspace: mergedStateValues.alwaysAllowReadOnlyOutsideWorkspace ?? false, + allowedReadFiles: mergedStateValues.allowedReadFiles ?? [], + alwaysAllowWrite: mergedStateValues.alwaysAllowWrite ?? false, + alwaysAllowWriteOutsideWorkspace: mergedStateValues.alwaysAllowWriteOutsideWorkspace ?? false, + alwaysAllowWriteProtected: mergedStateValues.alwaysAllowWriteProtected ?? false, + allowedWriteFiles: mergedStateValues.allowedWriteFiles ?? [], + alwaysAllowExecute: mergedStateValues.alwaysAllowExecute ?? false, destructiveCommandGuardEnabled: - stateValues.destructiveCommandGuardEnabled ?? DEFAULT_DESTRUCTIVE_COMMAND_GUARD_ENABLED, + mergedStateValues.destructiveCommandGuardEnabled ?? DEFAULT_DESTRUCTIVE_COMMAND_GUARD_ENABLED, alwaysDenyUnapprovedCommands: - stateValues.alwaysDenyUnapprovedCommands ?? DEFAULT_ALWAYS_DENY_UNAPPROVED_COMMANDS, - alwaysAllowMcp: stateValues.alwaysAllowMcp ?? false, - alwaysAllowModeSwitch: stateValues.alwaysAllowModeSwitch ?? false, - alwaysAllowSubtasks: stateValues.alwaysAllowSubtasks ?? false, - alwaysAllowFollowupQuestions: stateValues.alwaysAllowFollowupQuestions ?? false, - followupAutoApproveTimeoutMs: stateValues.followupAutoApproveTimeoutMs ?? 60000, - diagnosticsEnabled: stateValues.diagnosticsEnabled ?? true, - allowedMaxRequests: stateValues.allowedMaxRequests, - allowedMaxCost: stateValues.allowedMaxCost, - autoCondenseContext: stateValues.autoCondenseContext ?? true, - autoCondenseContextPercent: stateValues.autoCondenseContextPercent ?? 100, + mergedStateValues.alwaysDenyUnapprovedCommands ?? DEFAULT_ALWAYS_DENY_UNAPPROVED_COMMANDS, + alwaysAllowMcp: mergedStateValues.alwaysAllowMcp ?? false, + alwaysAllowModeSwitch: mergedStateValues.alwaysAllowModeSwitch ?? false, + alwaysAllowSubtasks: mergedStateValues.alwaysAllowSubtasks ?? false, + alwaysAllowFollowupQuestions: mergedStateValues.alwaysAllowFollowupQuestions ?? false, + followupAutoApproveTimeoutMs: mergedStateValues.followupAutoApproveTimeoutMs ?? 60000, + diagnosticsEnabled: mergedStateValues.diagnosticsEnabled ?? true, + allowedMaxRequests: mergedStateValues.allowedMaxRequests, + allowedMaxCost: mergedStateValues.allowedMaxCost, + autoCondenseContext: mergedStateValues.autoCondenseContext ?? true, + autoCondenseContextPercent: mergedStateValues.autoCondenseContextPercent ?? 100, taskHistory: includeTaskHistory ? this.taskHistoryStore.getAll() : [], - allowedCommands: stateValues.allowedCommands, - deniedCommands: stateValues.deniedCommands, - soundEnabled: stateValues.soundEnabled ?? false, - ttsEnabled: stateValues.ttsEnabled ?? false, - ttsSpeed: stateValues.ttsSpeed ?? 1.0, - enableCheckpoints: stateValues.enableCheckpoints ?? true, - checkpointTimeout: stateValues.checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, - soundVolume: stateValues.soundVolume, - writeDelayMs: stateValues.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS, - diffFuzzyThreshold: stateValues.diffFuzzyThreshold ?? DEFAULT_DIFF_FUZZY_THRESHOLD, + allowedCommands: mergedStateValues.allowedCommands, + deniedCommands: mergedStateValues.deniedCommands, + soundEnabled: mergedStateValues.soundEnabled ?? false, + ttsEnabled: mergedStateValues.ttsEnabled ?? false, + ttsSpeed: mergedStateValues.ttsSpeed ?? 1.0, + enableCheckpoints: mergedStateValues.enableCheckpoints ?? true, + checkpointTimeout: mergedStateValues.checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, + soundVolume: mergedStateValues.soundVolume, + writeDelayMs: mergedStateValues.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS, + diffFuzzyThreshold: mergedStateValues.diffFuzzyThreshold ?? DEFAULT_DIFF_FUZZY_THRESHOLD, terminalShellIntegrationTimeout: - stateValues.terminalShellIntegrationTimeout ?? Terminal.defaultShellIntegrationTimeout, - terminalShellIntegrationDisabled: stateValues.terminalShellIntegrationDisabled ?? true, + mergedStateValues.terminalShellIntegrationTimeout ?? Terminal.defaultShellIntegrationTimeout, + terminalShellIntegrationDisabled: mergedStateValues.terminalShellIntegrationDisabled ?? true, collapseCommandOutputByDefault: - stateValues.collapseCommandOutputByDefault ?? DEFAULT_COLLAPSE_COMMAND_OUTPUT_BY_DEFAULT, - terminalCommandDelay: stateValues.terminalCommandDelay ?? 0, - terminalPowershellCounter: stateValues.terminalPowershellCounter ?? false, - terminalZshClearEolMark: stateValues.terminalZshClearEolMark ?? true, - terminalZshOhMy: stateValues.terminalZshOhMy ?? false, - terminalZshP10k: stateValues.terminalZshP10k ?? false, - terminalZdotdir: stateValues.terminalZdotdir ?? false, - terminalProfile: stateValues.terminalProfile, - mode: stateValues.mode ?? defaultModeSlug, - language: stateValues.language ?? formatLanguage(vscode.env.language), - mcpEnabled: stateValues.mcpEnabled ?? true, + mergedStateValues.collapseCommandOutputByDefault ?? DEFAULT_COLLAPSE_COMMAND_OUTPUT_BY_DEFAULT, + terminalCommandDelay: mergedStateValues.terminalCommandDelay ?? 0, + terminalPowershellCounter: mergedStateValues.terminalPowershellCounter ?? false, + terminalZshClearEolMark: mergedStateValues.terminalZshClearEolMark ?? true, + terminalZshOhMy: mergedStateValues.terminalZshOhMy ?? false, + terminalZshP10k: mergedStateValues.terminalZshP10k ?? false, + terminalZdotdir: mergedStateValues.terminalZdotdir ?? false, + terminalProfile: mergedStateValues.terminalProfile, + mode: (mergedStateValues.mode as Mode) ?? defaultModeSlug, + language: mergedStateValues.language ?? formatLanguage(vscode.env.language), + mcpEnabled: mergedStateValues.mcpEnabled ?? true, + mcpServers: this.mcpHub?.getAllServers() ?? [], - currentApiConfigName: stateValues.currentApiConfigName ?? "default", - listApiConfigMeta: stateValues.listApiConfigMeta ?? [], - pinnedApiConfigs: stateValues.pinnedApiConfigs ?? {}, - modeApiConfigs: stateValues.modeApiConfigs ?? ({} as Record), - customModePrompts: stateValues.customModePrompts ?? {}, - customSupportPrompts: stateValues.customSupportPrompts ?? {}, - enhancementApiConfigId: stateValues.enhancementApiConfigId, - experiments: stateValues.experiments ?? experimentDefault, - autoApprovalEnabled: stateValues.autoApprovalEnabled ?? false, + currentApiConfigName: mergedStateValues.currentApiConfigName ?? "default", + listApiConfigMeta: mergedStateValues.listApiConfigMeta ?? [], + pinnedApiConfigs: mergedStateValues.pinnedApiConfigs ?? {}, + modeApiConfigs: (mergedStateValues.modeApiConfigs as Record) ?? ({} as Record), + customModePrompts: mergedStateValues.customModePrompts ?? {}, + customSupportPrompts: mergedStateValues.customSupportPrompts ?? {}, + enhancementApiConfigId: mergedStateValues.enhancementApiConfigId, + experiments: mergedStateValues.experiments ?? experimentDefault, + autoApprovalEnabled: mergedStateValues.autoApprovalEnabled ?? false, customModes, - maxOpenTabsContext: stateValues.maxOpenTabsContext ?? 20, - maxWorkspaceFiles: stateValues.maxWorkspaceFiles ?? 200, - disabledTools: stateValues.disabledTools, - telemetrySetting: stateValues.telemetrySetting || "unset", - showRooIgnoredFiles: stateValues.showRooIgnoredFiles ?? false, - enableSubfolderRules: stateValues.enableSubfolderRules ?? false, - maxImageFileSize: stateValues.maxImageFileSize ?? 5, - maxTotalImageSize: stateValues.maxTotalImageSize ?? 20, - historyPreviewCollapsed: stateValues.historyPreviewCollapsed ?? false, - reasoningBlockCollapsed: stateValues.reasoningBlockCollapsed ?? true, - chatFontSize: stateValues.chatFontSize, - timeFormat: stateValues.timeFormat ?? "auto", - dateFormat: stateValues.dateFormat ?? "auto", - showRelativeTimes: stateValues.showRelativeTimes ?? true, - enterBehavior: stateValues.enterBehavior ?? "send", + maxOpenTabsContext: mergedStateValues.maxOpenTabsContext ?? 20, + maxWorkspaceFiles: mergedStateValues.maxWorkspaceFiles ?? 200, + disabledTools: mergedStateValues.disabledTools, + telemetrySetting: mergedStateValues.telemetrySetting || "unset", + showRooIgnoredFiles: mergedStateValues.showRooIgnoredFiles ?? false, + enableSubfolderRules: mergedStateValues.enableSubfolderRules ?? false, + maxImageFileSize: mergedStateValues.maxImageFileSize ?? 5, + maxTotalImageSize: mergedStateValues.maxTotalImageSize ?? 20, + historyPreviewCollapsed: mergedStateValues.historyPreviewCollapsed ?? false, + reasoningBlockCollapsed: mergedStateValues.reasoningBlockCollapsed ?? true, + chatFontSize: mergedStateValues.chatFontSize, + timeFormat: mergedStateValues.timeFormat ?? "auto", + dateFormat: mergedStateValues.dateFormat ?? "auto", + showRelativeTimes: mergedStateValues.showRelativeTimes ?? true, + enterBehavior: mergedStateValues.enterBehavior ?? "send", cloudUserInfo, cloudIsAuthenticated, sharingEnabled, publicSharingEnabled, organizationAllowList, organizationSettingsVersion, - customCondensingPrompt: stateValues.customCondensingPrompt, - codebaseIndexModels: stateValues.codebaseIndexModels ?? EMBEDDING_MODEL_PROFILES, + customCondensingPrompt: mergedStateValues.customCondensingPrompt, + codebaseIndexModels: mergedStateValues.codebaseIndexModels ?? EMBEDDING_MODEL_PROFILES, codebaseIndexConfig: { - codebaseIndexEnabled: stateValues.codebaseIndexConfig?.codebaseIndexEnabled ?? false, + codebaseIndexEnabled: mergedStateValues.codebaseIndexConfig?.codebaseIndexEnabled ?? false, codebaseIndexQdrantUrl: - stateValues.codebaseIndexConfig?.codebaseIndexQdrantUrl ?? "http://localhost:6333", + mergedStateValues.codebaseIndexConfig?.codebaseIndexQdrantUrl ?? "http://localhost:6333", codebaseIndexEmbedderProvider: - stateValues.codebaseIndexConfig?.codebaseIndexEmbedderProvider ?? providerIdentifiers.openai, - codebaseIndexEmbedderBaseUrl: stateValues.codebaseIndexConfig?.codebaseIndexEmbedderBaseUrl ?? "", - codebaseIndexEmbedderModelId: stateValues.codebaseIndexConfig?.codebaseIndexEmbedderModelId ?? "", + mergedStateValues.codebaseIndexConfig?.codebaseIndexEmbedderProvider ?? providerIdentifiers.openai, + codebaseIndexEmbedderBaseUrl: mergedStateValues.codebaseIndexConfig?.codebaseIndexEmbedderBaseUrl ?? "", + codebaseIndexEmbedderModelId: mergedStateValues.codebaseIndexConfig?.codebaseIndexEmbedderModelId ?? "", codebaseIndexEmbedderModelDimension: - stateValues.codebaseIndexConfig?.codebaseIndexEmbedderModelDimension, + mergedStateValues.codebaseIndexConfig?.codebaseIndexEmbedderModelDimension, codebaseIndexOpenAiCompatibleBaseUrl: - stateValues.codebaseIndexConfig?.codebaseIndexOpenAiCompatibleBaseUrl, - codebaseIndexSearchMaxResults: stateValues.codebaseIndexConfig?.codebaseIndexSearchMaxResults, - codebaseIndexSearchMinScore: stateValues.codebaseIndexConfig?.codebaseIndexSearchMinScore, - codebaseIndexBedrockRegion: stateValues.codebaseIndexConfig?.codebaseIndexBedrockRegion, - codebaseIndexBedrockProfile: stateValues.codebaseIndexConfig?.codebaseIndexBedrockProfile, + mergedStateValues.codebaseIndexConfig?.codebaseIndexOpenAiCompatibleBaseUrl, + codebaseIndexSearchMaxResults: mergedStateValues.codebaseIndexConfig?.codebaseIndexSearchMaxResults, + codebaseIndexSearchMinScore: mergedStateValues.codebaseIndexConfig?.codebaseIndexSearchMinScore, + codebaseIndexBedrockRegion: mergedStateValues.codebaseIndexConfig?.codebaseIndexBedrockRegion, + codebaseIndexBedrockProfile: mergedStateValues.codebaseIndexConfig?.codebaseIndexBedrockProfile, codebaseIndexOpenRouterSpecificProvider: - stateValues.codebaseIndexConfig?.codebaseIndexOpenRouterSpecificProvider, + mergedStateValues.codebaseIndexConfig?.codebaseIndexOpenRouterSpecificProvider, }, - profileThresholds: stateValues.profileThresholds ?? {}, + profileThresholds: mergedStateValues.profileThresholds ?? {}, lockApiConfigAcrossModes: this.context.workspaceState.get("lockApiConfigAcrossModes", false), - includeDiagnosticMessages: stateValues.includeDiagnosticMessages ?? true, - maxDiagnosticMessages: stateValues.maxDiagnosticMessages ?? 50, - includeTaskHistoryInEnhance: stateValues.includeTaskHistoryInEnhance ?? true, - taskTitleGenerationEnabled: stateValues.taskTitleGenerationEnabled ?? DEFAULT_TASK_TITLE_GENERATION_ENABLED, - taskTitleApiConfigId: stateValues.taskTitleApiConfigId, - includeCurrentTime: stateValues.includeCurrentTime ?? true, - includeCurrentCost: stateValues.includeCurrentCost ?? true, - maxGitStatusFiles: stateValues.maxGitStatusFiles ?? 0, + includeDiagnosticMessages: mergedStateValues.includeDiagnosticMessages ?? true, + maxDiagnosticMessages: mergedStateValues.maxDiagnosticMessages ?? 50, + includeTaskHistoryInEnhance: mergedStateValues.includeTaskHistoryInEnhance ?? true, + taskTitleGenerationEnabled: + mergedStateValues.taskTitleGenerationEnabled ?? DEFAULT_TASK_TITLE_GENERATION_ENABLED, + taskTitleApiConfigId: mergedStateValues.taskTitleApiConfigId, + includeCurrentTime: mergedStateValues.includeCurrentTime ?? true, + includeCurrentCost: mergedStateValues.includeCurrentCost ?? true, + maxGitStatusFiles: mergedStateValues.maxGitStatusFiles ?? 0, taskSyncEnabled, - imageGenerationProvider: stateValues.imageGenerationProvider, - openRouterImageApiKey: stateValues.openRouterImageApiKey, - openRouterImageGenerationSelectedModel: stateValues.openRouterImageGenerationSelectedModel, - autoCloseZooOpenedFiles: stateValues.autoCloseZooOpenedFiles, - autoCloseZooOpenedFilesAfterUserEdited: stateValues.autoCloseZooOpenedFilesAfterUserEdited, - autoCloseZooOpenedNewFiles: stateValues.autoCloseZooOpenedNewFiles, + imageGenerationProvider: mergedStateValues.imageGenerationProvider, + openRouterImageApiKey: mergedStateValues.openRouterImageApiKey, + openRouterImageGenerationSelectedModel: mergedStateValues.openRouterImageGenerationSelectedModel, + autoCloseZooOpenedFiles: mergedStateValues.autoCloseZooOpenedFiles, + autoCloseZooOpenedFilesAfterUserEdited: mergedStateValues.autoCloseZooOpenedFilesAfterUserEdited, + autoCloseZooOpenedNewFiles: mergedStateValues.autoCloseZooOpenedNewFiles, } } @@ -3829,7 +5467,75 @@ export class ClineProvider } public async setValue(key: K, value: RooCodeSettings[K]) { + // A mode slug is the one value this setter cannot invent: setValues refuses an unknown or + // non-string mode because a new Task would read it back from getState() and persist it into + // task history, and this single-value path feeds the same two layers - the shared store + // below and the per-view pin written after it - so the established check runs here first, + // before either write, against the built-in modes and the modes the manager knows at call + // time. The single-value setter carries no companion customModes payload, so a slug that + // is not registered yet is refused rather than trusted. An undefined value is a clear and + // not a slug, and every other key reaches both layers exactly as before. + if (key === "mode" && value !== undefined) { + const modeSlug: unknown = value + if ( + typeof modeSlug !== "string" || + !getModeBySlug(modeSlug, await this.customModesManager.getCustomModes()) + ) { + this.log(`[ClineProvider#setValue] Ignoring invalid mode "${String(modeSlug)}"`) + return + } + } + const previousSharedValues = { [key]: this.contextProxy.getValue(key) } as RooCodeSettings await this.contextProxy.setValue(key, value) + try { + await this._saveViewLocalStateFromMutation({ [key]: value }) + } catch (error) { + // The per-view record did not land: restore the prior shared value so the two + // persistence layers cannot diverge, then surface the original failure. + await this._restoreSharedValuesAfterFailedViewWrite(previousSharedValues) + throw error + } + } + + /** + * Restore shared values captured before a setter wrote them, used when the paired + * per-view persistence failed so the shared store cannot move ahead of the per-view + * record. A failed rollback is logged; the original failure is what callers see. + */ + private async _restoreSharedValuesAfterFailedViewWrite(previous: RooCodeSettings): Promise { + try { + await this.contextProxy.setValues(previous) + } catch (rollbackError) { + this.log( + `[ClineProvider] Shared-state rollback after failed per-view write failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, + ) + } + } + /** + * Rolls both mode selection layers back to their own prior values. The shared store and + * the per-view pin are separate durable writes, so each is awaited and logged on its own: + * a failed shared restore must not conceal a restored pin, and a layer whose prior value + * was unset goes back to unset rather than to a copy of the other layer. + */ + private async _restoreModeSelection( + previousMode: RooCodeSettings["mode"], + previousViewMode: RooCodeSettings["mode"], + failureStage: string, + ): Promise { + try { + await this.contextProxy.setValue("mode", previousMode) + } catch (rollbackError) { + this.log( + `[ClineProvider#createTask] Failed to restore the shared mode ${failureStage}: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, + ) + } + try { + await this.saveViewState("mode", previousViewMode) + } catch (rollbackError) { + this.log( + `[ClineProvider#createTask] Failed to restore the view mode pin ${failureStage}: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, + ) + } } public getValue(key: K) { @@ -3837,13 +5543,124 @@ export class ClineProvider } public getValues() { - return this.contextProxy.getValues() + return { ...this.contextProxy.getValues(), ...this.viewLocalState } } public async setValues(values: RooCodeSettings) { - await this.contextProxy.setValues( - withoutInvalidDisplaySettings(values, (key) => this.log(`[setValues] Ignored an invalid value for ${key}`)), + const sanitizedValues = withoutInvalidDisplaySettings({ ...values }, (key) => + this.log(`[setValues] Ignored an invalid value for ${key}`), ) + + if (sanitizedValues.mode !== undefined) { + // An unknown or non-string mode (e.g. from an API payload) must not be persisted: + // a new Task would read it from getState() and persist it into task history. + // A payload that carries its own customModes (createTask and setConfiguration + // call setValues before registering them) validates against those too, so a + // brand-new custom mode in the same payload is not silently dropped. + if ( + typeof sanitizedValues.mode !== "string" || + !getModeBySlug(sanitizedValues.mode, [ + ...(await this.customModesManager.getCustomModes()), + ...(sanitizedValues.customModes ?? []), + ]) + ) { + this.log(`[ClineProvider#setValues] Ignoring invalid mode "${String(sanitizedValues.mode)}"`) + delete sanitizedValues.mode + } + } + + const previousSharedValues = Object.fromEntries( + Object.keys(sanitizedValues).map((key) => [key, this.contextProxy.getValue(key as keyof RooCodeSettings)]), + ) as RooCodeSettings + await this.contextProxy.setValues(sanitizedValues) + try { + await this._saveViewLocalStateFromMutation(sanitizedValues) + } catch (error) { + // The per-view record did not land: restore the prior shared values so the two + // persistence layers cannot diverge, then surface the original failure. + await this._restoreSharedValuesAfterFailedViewWrite(previousSharedValues) + throw error + } + } + + /** + * Persists the view-local subset of a ContextProxy mutation, then updates the in-memory + * viewLocalState buffer. Persistence is awaited first so a failed durable write cannot + * leave the local cache ahead of the persisted state. + */ + private async _saveViewLocalStateFromMutation( + values: Partial & Partial, + ): Promise { + await this._persistViewLocalStateFromMutation(values) + this._updateViewLocalStateFromMutation(values) + } + + /** + * Update or invalidate viewLocalState when ContextProxy is mutated via setValues, setValue, + * profile upsert/activation/deletion, or resetState. This ensures the local cache stays in + * sync with global state changes that would otherwise be invisible behind mergedStateValues. + */ + private _updateViewLocalStateFromMutation(values: Partial & Partial): void { + if ("mode" in values) { + const val = values.mode + if (val === undefined || val === null) { + delete this.viewLocalState.mode + } else { + this.viewLocalState.mode = val + } + } + + if ("currentApiConfigName" in values) { + const val = values.currentApiConfigName + if (val === undefined || val === null) { + delete this.viewLocalState.currentApiConfigName + } else { + this.viewLocalState.currentApiConfigName = val + } + } + + if ("apiConfiguration" in values) { + const val = values.apiConfiguration + if (val === undefined || val === null) { + delete this.viewLocalState.apiConfiguration + } else { + this.viewLocalState.apiConfiguration = val + } + } + + // Flat provider-settings keys (PROVIDER_SETTINGS_KEYS) are shared settings: + // they are written through the ContextProxy above and must NOT be merged + // into viewLocalState.apiConfiguration, which would turn them into a + // per-view override masking later shared updates from other views. + } + + /** + * Writes the durably persisted subset of a mutation (mode and currentApiConfigName) + * into the registered viewStates map for this view. + */ + private async _persistViewLocalStateFromMutation( + values: Partial & Partial, + ): Promise { + const persistedValues: Partial = {} + + if ("mode" in values) { + persistedValues.mode = values.mode as PersistedViewState["mode"] + } + + if ("currentApiConfigName" in values) { + persistedValues.currentApiConfigName = values.currentApiConfigName + } + + if ("mode" in persistedValues || "currentApiConfigName" in persistedValues) { + await this.savePersistedViewState(persistedValues) + } + } + + /** + * Clear view-local state cache so that getState() falls back to ContextProxy defaults. + */ + private _clearViewLocalState(): void { + this.viewLocalState = {} } // dev @@ -3872,6 +5689,25 @@ export class ClineProvider } await this.contextProxy.resetAllState() + + // Clear view-local state cache so getState() falls back to ContextProxy defaults. + this._clearViewLocalState() + + // Clear this view's persisted entry too, so the reset selections are not + // re-applied from the durable viewStates pin after a reload. + // Review thread 4506513984 (original_line 5368): the clear above already compensates + // for its own rejected write, so the reset must not stop here. Profile removal, + // custom-mode reset and task removal below still have to run, and the failure is + // reported through the log channel the cloud-logout catch already uses. + try { + await this.clearPersistedViewState() + } catch (error) { + this.log( + `Failed to clear this view's persisted state during reset: ${error instanceof Error ? error.message : String(error)}`, + ) + // Continue with reset even if the durable clear fails. + } + await this.providerSettingsManager.resetAllConfigs() // Cached choices point at profiles that no longer exist; re-read the reset mapping. this.localModeConfigIds.clear() @@ -4406,32 +6242,54 @@ export class ClineProvider configuration: RooCodeSettings = {}, ): Promise { if (configuration) { - await this.setValues(configuration) + // Capture both selection layers that a failure ahead of, or inside, custom-mode + // registration must roll back to: setValues below persists the payload's mode to the + // shared store AND the per-view record while the payload's custom modes are still + // unregistered. The pin is read defensively because createTask is also driven through + // structural provider doubles that carry no view-local buffer. + const previousMode = this.contextProxy.getValue("mode") + const previousViewMode = this.viewLocalState?.mode + try { + await this.setValues(configuration) - if (configuration.allowedCommands) { - await vscode.workspace - .getConfiguration(Package.name) - .update("allowedCommands", configuration.allowedCommands, vscode.ConfigurationTarget.Global) - } + if (configuration.allowedCommands) { + await vscode.workspace + .getConfiguration(Package.name) + .update("allowedCommands", configuration.allowedCommands, vscode.ConfigurationTarget.Global) + } - if (configuration.deniedCommands) { - await vscode.workspace - .getConfiguration(Package.name) - .update("deniedCommands", configuration.deniedCommands, vscode.ConfigurationTarget.Global) - } + if (configuration.deniedCommands) { + await vscode.workspace + .getConfiguration(Package.name) + .update("deniedCommands", configuration.deniedCommands, vscode.ConfigurationTarget.Global) + } - if (configuration.commandExecutionTimeout !== undefined) { - await vscode.workspace - .getConfiguration(Package.name) - .update( - "commandExecutionTimeout", - configuration.commandExecutionTimeout, - vscode.ConfigurationTarget.Global, - ) - } + if (configuration.commandExecutionTimeout !== undefined) { + await vscode.workspace + .getConfiguration(Package.name) + .update( + "commandExecutionTimeout", + configuration.commandExecutionTimeout, + vscode.ConfigurationTarget.Global, + ) + } - if (configuration.currentApiConfigName) { - await this.setProviderProfile(configuration.currentApiConfigName) + if (configuration.currentApiConfigName) { + await this.setProviderProfile(configuration.currentApiConfigName) + } + } catch (error) { + // A failure ahead of registration - a named profile that does not exist is one, which + // setProviderProfile raises above - leaves both mode layers holding the slug the payload + // brought, so each layer rolls back to its own prior value before the original failure + // surfaces. The registration loop below keeps its own handler, which is why this window + // closes there rather than at the end of the method: a mode that became usable must stay + // selected when a later step fails. + await this._restoreModeSelection( + previousMode, + previousViewMode, + "after the profile selection failed before custom-mode registration", + ) + throw error } // Register custom modes so the CustomModesManager knows about them. @@ -4439,12 +6297,34 @@ export class ClineProvider // when it merges .roomodes + global settings on refresh. Persisting // via updateCustomMode ensures modes survive the merge cycle. if (configuration.customModes?.length) { - for (const mode of configuration.customModes) { - await this.customModesManager.updateCustomMode(mode.slug, mode) + try { + for (const mode of configuration.customModes) { + await this.customModesManager.updateCustomMode(mode.slug, mode) + } + } catch (error) { + // setValues already persisted the payload's mode to shared and per-view + // state; if registration fails the mode is not actually usable, so each + // layer rolls back to its own prior value (an unset pin stays unset) + // before the failure surfaces. Each restore is awaited on its own and + // logged on failure, never swallowed; the original failure is what + // callers see. + await this._restoreModeSelection( + previousMode, + previousViewMode, + "after custom-mode registration failed", + ) + throw error } } } + // A payload that names a provider drives the settings the new task starts with, and that + // read is taken here - ahead of the getState() await below - because the await is a + // scheduling point: another view's provider write can land inside it, and a read taken + // afterwards hands the new task whatever that write just put into the shared store + // instead of the settings this payload persisted through setValues (review thread + // 4595966639). + const payloadProviderSettings = configuration.apiProvider ? this.contextProxy.getProviderSettings() : undefined const { apiConfiguration, enableCheckpoints, @@ -4453,8 +6333,20 @@ export class ClineProvider organizationAllowList, diffFuzzyThreshold, } = await this.getState() + // A payload that names a provider must drive the task it creates. getState above + // returns the acting view's own snapshot whenever that buffer holds one, and that + // snapshot shadows the flat settings the setValues call just persisted for this same + // payload: review thread 4506517300, printed at line 5586 with original_line 5304, + // sits on the comment that deliberately keeps those flat keys out of the per-view + // buffer. Only the new task takes the settings the payload wrote; neither buffer is + // merged here, so the acting view keeps its snapshot for later reads and other + // views keep their overlays. A payload that carries provider keys without naming + // a provider keeps the snapshot, because nothing in the call claims precedence. The shared + // read taken above is this payload's own settings; the await below is where the other + // view's write got in. + const taskApiConfiguration = payloadProviderSettings ?? apiConfiguration const effectiveApiConfiguration = getEffectiveTaskApiConfiguration( - apiConfiguration, + taskApiConfiguration, options.handoffExecutionContext, ) @@ -4471,7 +6363,7 @@ export class ClineProvider const task = new Task({ provider: this, - apiConfiguration, + apiConfiguration: taskApiConfiguration, enableCheckpoints, checkpointTimeout, consecutiveMistakeLimit: effectiveApiConfiguration.consecutiveMistakeLimit, diff --git a/src/core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts b/src/core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts index 28531e964de..397ba8c5d4e 100644 --- a/src/core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts @@ -242,9 +242,15 @@ describe("ClineProvider - API Handler Rebuild Guard", () => { // Start without the snapshot from initial fixture storage; profile tests seed their own mapping. provider["initialModeConfigIds"] = Promise.resolve({}) - // Mock providerSettingsManager + // Mock providerSettingsManager. saveConfig repoints the CURRENT getProfile mock at + // the record it wrote: the real manager reads back the stored record, and + // persistProviderProfile builds its activation writes from that read-back. + const currentGetProfile = () => provider["providerSettingsManager"].getProfile as ReturnType ;(provider as any).providerSettingsManager = { - saveConfig: vi.fn().mockResolvedValue("test-id"), + saveConfig: vi.fn().mockImplementation(async (name: string, config: Record) => { + currentGetProfile().mockResolvedValue({ name, id: "test-id", ...config }) + return "test-id" + }), listConfig: vi.fn().mockResolvedValue([ { name: "test-config", @@ -853,8 +859,10 @@ describe("ClineProvider - API Handler Rebuild Guard", () => { const first = provider.activateProviderProfile({ name: "first-profile" }) const second = provider.activateProviderProfile({ name: "second-profile" }) - await Promise.resolve() - expect(events).toEqual(["first:start"]) + // The mutation now reads the manager selection snapshot before the + // manager write, so the first call lands a few microtasks later than a + // single tick would assume; wait for it deterministically instead. + await vi.waitFor(() => expect(events).toEqual(["first:start"])) resolveFirst() await first @@ -882,7 +890,58 @@ describe("ClineProvider - API Handler Rebuild Guard", () => { expect(setValueSpy).toHaveBeenCalledWith("currentApiConfigName", "second-profile") }) - test("timed-out mutations abort before writing state and advance the queue", async () => { + test("an activation that times out while queued behind another never starts", async () => { + vi.useFakeTimers() + let releaseFirst!: () => void + const firstActivation = new Promise((resolve) => { + releaseFirst = resolve + }) + provider["providerSettingsManager"].activateProfile = vi + .fn() + .mockImplementationOnce(async () => { + await firstActivation + return { + name: "first-profile", + id: "first-id", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "openai/gpt-4", + } + }) + .mockResolvedValueOnce({ + name: "second-profile", + id: "second-id", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "openai/gpt-4.1-mini", + }) + const setValueSpy = vi.spyOn(provider.contextProxy, "setValue") + + try { + // The first activation outlives the second call's timeout window: the + // second caller rejects while its callback is still queued. + const first = provider.activateProviderProfile({ name: "first-profile" }) + const firstResult = expect(first).rejects.toThrow("Provider profile mutation timed out") + await vi.advanceTimersByTimeAsync(1000) + const second = provider.activateProviderProfile({ name: "second-profile" }) + const secondResult = expect(second).rejects.toThrow("Provider profile mutation timed out") + await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS) + await firstResult + await secondResult + + // The first activation settles and the queue advances: the second must + // not start after its caller already saw a timeout, or it would change + // the selected profile while reporting failure. + releaseFirst() + // The queue tail settles only after the second run has been evaluated. + await provider["providerProfileMutationQueue"].catch(() => undefined) + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("first-profile") + expect(provider["providerSettingsManager"].activateProfile).toHaveBeenCalledTimes(1) + expect(setValueSpy).not.toHaveBeenCalledWith("currentApiConfigName", "second-profile") + } finally { + vi.useRealTimers() + } + }) + + test("timed-out activations run to completion and hold the queue", async () => { vi.useFakeTimers() const logSpy = vi.spyOn(provider, "log") const setValueSpy = vi.spyOn(provider.contextProxy, "setValue") @@ -914,20 +973,58 @@ describe("ClineProvider - API Handler Rebuild Guard", () => { await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS) await firstResult - // Queue advanced immediately on timeout — second enqueues now. + // The queue stays owned until the hung activation settles: the second + // activation waits, so the late rollback cannot land on top of it. const second = provider.activateProviderProfile({ name: "second-profile" }) - // activateProfile not yet called for second (it runs in the next microtask). + await vi.advanceTimersByTimeAsync(0) expect(provider["providerSettingsManager"].activateProfile).toHaveBeenCalledTimes(1) - // Resolve the first activation's inner promise so its in-flight mock can return. - // The aborted signal prevents it from writing any state. + // The first activation was not aborted: it completes its writes before + // the queue advances to the second. resolveFirst() + await vi.advanceTimersByTimeAsync(0) await expect(second).resolves.toBeUndefined() expect(provider["providerSettingsManager"].activateProfile).toHaveBeenCalledTimes(2) - // Aborted first activation wrote nothing; only second profile is set. - expect(setValueSpy).not.toHaveBeenCalledWith("currentApiConfigName", "first-profile") + expect(setValueSpy).toHaveBeenCalledWith("currentApiConfigName", "first-profile") expect(setValueSpy).toHaveBeenCalledWith("currentApiConfigName", "second-profile") + // The final shared selection is the second profile: no late write puts + // the first profile back on top. + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("second-profile") + expect(logSpy).toHaveBeenCalledWith( + "Provider profile mutation timed out; waiting for it to finish before the next mutation", + ) + } finally { + vi.useRealTimers() + } + }) + + test("a mutation queued without runToCompletion aborts its in-flight callback and advances the queue", async () => { + vi.useFakeTimers() + const logSpy = vi.spyOn(provider, "log") + let mutationSignal: AbortSignal | undefined + let started = 0 + const runMutation = (work: (signal: AbortSignal) => Promise) => + provider["enqueueProviderProfileMutation"]((signal) => { + mutationSignal = signal + started += 1 + return work(signal) + }) + + try { + const hanging = runMutation(() => new Promise(() => undefined)) + const rejected = expect(hanging).rejects.toThrow("Provider profile mutation timed out") + await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS) + await rejected + + // The default path aborts the mutation the caller stopped waiting for, so the + // callback sees a cancelled signal and the log names the abort. + expect(started).toBe(1) + expect(mutationSignal?.aborted).toBe(true) expect(logSpy).toHaveBeenCalledWith("Provider profile mutation timed out; aborting in-flight mutation") + + // The queue advanced on the timeout instead of waiting for the aborted run. + await runMutation(() => Promise.resolve()) + expect(started).toBe(2) } finally { vi.useRealTimers() } diff --git a/src/core/webview/__tests__/ClineProvider.lockApiConfig.spec.ts b/src/core/webview/__tests__/ClineProvider.lockApiConfig.spec.ts index ec8245cddb4..eba33ebe960 100644 --- a/src/core/webview/__tests__/ClineProvider.lockApiConfig.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.lockApiConfig.spec.ts @@ -405,4 +405,74 @@ describe("ClineProvider - Lock API Config Across Modes", () => { expect(activateProfileSpy).toHaveBeenCalledWith({ name: "architect-profile" }) }) }) + + describe("handleModeSwitch keeps an unmapped mode's default on the profile the view pins", () => { + beforeEach(async () => { + await provider.resolveWebviewView(mockWebviewView) + }) + + it("saves the pinned profile as the unmapped mode's default instead of the shared selection", async () => { + provider["initialModeConfigIds"] = Promise.resolve({}) + await mockContext.workspaceState.update("lockApiConfigAcrossModes", false) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "pinned-profile", id: "pinned-id", apiProvider: providerIdentifiers.anthropic }, + { name: "shared-profile", id: "shared-id", apiProvider: providerIdentifiers.anthropic }, + ]) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "pinned-profile", + apiProvider: providerIdentifiers.anthropic, + }) + // The divergence the finding names: this view pins one profile while the + // durable shared selection holds another. Bracket access is how this repo + // reaches these private members from its own tests. + await provider["updateGlobalState"]("currentApiConfigName", "shared-profile") + provider["viewLocalState"].currentApiConfigName = "pinned-profile" + // The divergence itself is asserted, so the run records the state the + // finding describes rather than trusting a console line the reporter may + // withhold: this view pins pinned-profile, the durable selection is + // shared-profile. + expect(provider.pinnedProfileName).toBe("pinned-profile") + expect(provider["getGlobalState"]("currentApiConfigName")).toBe("shared-profile") + + await provider.handleModeSwitch("architect") + + const savedDefault = provider["localModeConfigIds"].get("architect") + expect(savedDefault).toBe("pinned-id") + }) + }) + + describe("getState resolves a view overlay that omits apiProvider", () => { + beforeEach(async () => { + await provider.resolveWebviewView(mockWebviewView) + }) + + it("defaults the unset local provider to Anthropic instead of inheriting the shared provider", async () => { + // The observed state is asserted before the fix is applied, so the failing + // run prints what the pin inherits today: the overlay carries a model id + // and no apiProvider, while the shared store names Bedrock. + await provider["updateGlobalState"]("apiProvider", providerIdentifiers.bedrock) + await provider["updateGlobalState"]("apiModelId", "shared-model") + provider["viewLocalState"].apiConfiguration = { apiModelId: "pinned-model" } + + const state = await provider.getState() + + expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) + expect(state.apiConfiguration.apiModelId).toBe("pinned-model") + }) + + it("leaves the no-overlay branch on the shared settings, which is the other thread's construct", async () => { + // Control, not a fix: with no view overlay the resolver returns the shared + // settings object outright, so the activated-profile thread is answered by + // a different mechanism than the unset-provider default changed here. + await provider["updateGlobalState"]("apiProvider", providerIdentifiers.bedrock) + await provider["updateGlobalState"]("apiModelId", "shared-model") + delete provider["viewLocalState"].apiConfiguration + + const state = await provider.getState() + + expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.bedrock) + expect(state.apiConfiguration.apiModelId).toBe("shared-model") + }) + }) }) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index b364b5baa79..e91609b9df4 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -13,6 +13,7 @@ import pWaitFor from "p-wait-for" import { type ProviderSettingsEntry, type ProviderSettings, + type ProviderSettingsWithId, type ClineMessage, type ExtensionMessage, type ExtensionState, @@ -31,9 +32,10 @@ import { defaultModeSlug } from "../../../shared/modes" import { joinSegments } from "../../../shared/mentionSegments" import type { MentionSegment } from "@roo-code/types" import { experimentDefault } from "../../../shared/experiments" +import { EMBEDDING_MODEL_PROFILES } from "../../../shared/embeddingModels" import { setTtsEnabled } from "../../../utils/tts" import { ContextProxy } from "../../config/ContextProxy" -import { ProviderSettingsManager } from "../../config/ProviderSettingsManager" +import { ProviderSettingsManager, ProviderSettingsNotFoundError } from "../../config/ProviderSettingsManager" import { importSettingsFromPath } from "../../config/importExport" import { WorkspaceIndexingEnablementManager } from "../../../services/code-index/workspace-indexing-enablement-manager" import { Task, TaskOptions } from "../../task/Task" @@ -41,6 +43,7 @@ import { safeWriteJson } from "../../../utils/safeWriteJson" import { ClineProvider } from "../ClineProvider" import { webviewMessageHandler } from "../webviewMessageHandler" +import type { MdmService } from "../../../services/mdm/MdmService" import { Terminal } from "../../../integrations/terminal/Terminal" import { MessageManager } from "../../message-manager" import { forceFullModelDetailsLoad, hasLoadedFullDetails } from "../../../api/providers/fetchers/lmstudio" @@ -450,6 +453,41 @@ function expectMixedPayload(call: unknown[], context: string, sources: MentionSe expect(segments.filter((s) => s.source === "user").some((s) => s.text.includes("@/generated"))).toBe(false) } +/** + * Profile shape the stalled getProfile resolves to. ProviderSettings fields are + * optional, so a lookup that resolves name-only (a profile with no configured + * provider) still type-checks against the real getProfile return type. + */ +type StalledProfile = ProviderSettings & { name: string } + +/** + * Swap the provider's ProviderSettingsManager for a double whose getProfile + * stalls until the test resolves it, so tests can mutate view state while + * loadViewState is in flight. The double only backs getProfile, the member + * loadViewState awaits; the documented @ts-ignore replaces the per-test + * suppressions the inlined copies used. + */ +function stallProviderSettingsProfile(provider: ClineProvider) { + let resolveProfile: (value: StalledProfile) => void = () => {} + // Spy on the real manager instead of replacing it: getProfile is the only member + // loadViewState awaits, and a partial double hides any other member the path calls. + const getProfileSpy = vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(() => { + // Only one lookup is resolvable: resolveProfile is bound to the first + // promise's resolver, so a second getProfile would strand its promise. + // Fail loudly instead of hanging. + if (getProfileSpy.mock.calls.length > 1) { + throw new Error( + "stallProviderSettingsProfile: getProfile called more than once; only one lookup is resolvable", + ) + } + return new Promise((resolve) => (resolveProfile = resolve)) + }) + // Return a stable wrapper around the closure binding: resolveProfile is + // reassigned to the pending promise's resolver once getProfile is called, + // so returning the variable directly would hand the test the initial no-op. + return { getProfile: getProfileSpy, resolveProfile: (value: StalledProfile) => resolveProfile(value) } +} + describe("ClineProvider", () => { beforeAll(() => { vi.mocked(Task).mockImplementation(function (options: any) { @@ -487,6 +525,13 @@ describe("ClineProvider", () => { let mockPostMessage: any let updateGlobalStateSpy: any + afterEach(() => { + // Tests construct providers directly and many never dispose them; clear the + // static registry so a leaked instance cannot claim stable view state ids + // ahead of a later test. + ClineProvider["activeInstances"] = new Set() + }) + beforeEach(() => { vi.clearAllMocks() @@ -627,6 +672,18 @@ describe("ClineProvider", () => { expect(ClineProvider.getVisibleInstance()).toBe(provider) }) + describe("getInstanceForView", () => { + it("returns the instance that owns the given view", async () => { + await provider.resolveWebviewView(mockWebviewView) + + expect(ClineProvider.getInstanceForView(mockWebviewView)).toBe(provider) + }) + + it("returns undefined when no live instance owns the view", () => { + expect(ClineProvider.getInstanceForView({} as vscode.WebviewView)).toBeUndefined() + }) + }) + test("reports an unresolved webview as not visible", () => { expect(provider.isViewVisible).toBe(false) }) @@ -1246,7 +1303,7 @@ describe("ClineProvider", () => { }) test("does not reload full model details when the LM Studio model is already loaded", async () => { - vi.mocked(hasLoadedFullDetails).mockReturnValue(true) + vi.mocked(hasLoadedFullDetails).mockReturnValueOnce(true) await provider.performPreparationTasks({ apiConfiguration: { @@ -3456,6 +3513,26 @@ describe("ClineProvider", () => { await expect(provider.postMessageToWebview(message)).resolves.toBeUndefined() }) + test("postMessageToWebview does not await the webview ack", async () => { + await provider.resolveWebviewView(mockWebviewView) + + let releaseAck!: () => void + const ack = new Promise((resolve) => { + releaseAck = resolve + }) + mockPostMessage.mockImplementationOnce(() => ack) + + const message: ExtensionMessage = { type: "action", action: "chatButtonClicked" } + + // The caller must not wait for the renderer ack: a webview page remounted or disposed + // while the post is in flight never acknowledges it, and awaiting that promise would + // wedge every caller on the task critical path. + await provider.postMessageToWebview(message) + + expect(mockPostMessage).toHaveBeenCalledWith(message) + releaseAck() + }) + test("postMessageToWebview leaves originalContent of file-edit tool messages out of the state it posts", async () => { await provider.resolveWebviewView(mockWebviewView) @@ -3575,143 +3652,5024 @@ describe("ClineProvider", () => { }) test("postStateToWebview does not force action navigation for non-compliant MDM state", async () => { - const mdmService = { + // Structural double: the post path only reads these two members, and + // MdmService cannot be constructed as a plain object; Object.assign + // keeps this a single structural assertion. + const mdmService = Object.assign({} as MdmService, { requiresCloudAuth: vi.fn().mockReturnValue(true), isCompliant: vi.fn().mockReturnValue({ compliant: false, reason: "auth required" }), - } as any + }) + + provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + mdmService, + ) + + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockImplementation(async () => undefined) + vi.spyOn(provider, "getStateToPostToWebview").mockResolvedValue( + Object.assign({} as ExtensionState, { + version: "1.0.0", + }), + ) + + await provider.postStateToWebview() + + expect(postMessageSpy).toHaveBeenCalledTimes(1) + expect(postMessageSpy).not.toHaveBeenCalledWith(expect.objectContaining({ type: "action" })) + }) + + test("postStateToWebviewWithoutTaskHistory waits for the webview post boundary", async () => { + let releasePost!: () => void + const pendingPost = new Promise((resolve) => { + releasePost = resolve + }) + let statePostSettled = false + + vi.spyOn(provider, "getStateToPostToWebview").mockResolvedValue( + Object.assign({} as ExtensionState, { + taskHistory: [], + }), + ) + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockReturnValue(pendingPost) + + const statePost = provider.postStateToWebviewWithoutTaskHistory() + void statePost.then(() => { + statePostSettled = true + }) + await Promise.resolve() + + expect(postMessageSpy).toHaveBeenCalledOnce() + expect(statePostSettled).toBe(false) + + releasePost() + await statePost + expect(statePostSettled).toBe(true) + }) + + test.each([ + ["postStateToWebview", (currentProvider: ClineProvider) => currentProvider.postStateToWebview()], + [ + "postStateToWebviewWithoutTaskHistory", + (currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutTaskHistory(), + ], + ])("%s assigns message sequence numbers before asynchronous state construction", async (_methodName, postState) => { + let releaseOlderSnapshot!: (state: ExtensionState) => void + const olderSnapshot = new Promise((resolve) => { + releaseOlderSnapshot = resolve + }) + const baseState = await provider.getStateToPostToWebview({ includeTaskHistory: false }) + const emptyState: ExtensionState = { ...baseState, taskHistory: [], clineMessages: [] } + const readyState: ExtensionState = { + ...baseState, + taskHistory: [], + clineMessages: [{ ts: 1, type: "say", say: "text", text: "child ready" }], + } + + vi.spyOn(provider, "getStateToPostToWebview") + .mockReturnValueOnce(olderSnapshot) + .mockResolvedValueOnce(readyState) + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) + + const olderPost = postState(provider) + await Promise.resolve() + const newerPost = postState(provider) + await newerPost + releaseOlderSnapshot(emptyState) + await olderPost + + expect(postMessageSpy.mock.calls.map(([message]) => message.state?.clineMessages)).toEqual([ + readyState.clineMessages, + emptyState.clineMessages, + ]) + expect(postMessageSpy.mock.calls.map(([message]) => message.state?.clineMessagesSeq)).toEqual([2, 1]) + }) + + test.each([ + [ + "postStateToWebviewWithoutTaskHistory", + (currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutTaskHistory(), + ], + [ + "postStateToWebviewWithoutClineMessages", + (currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutClineMessages(), + ], + ])("%s skips task history computation", async (_methodName, postState) => { + const getAllSpy = vi.spyOn(provider.taskHistoryStore, "getAll") + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) + + await postState(provider) + + expect(getAllSpy).not.toHaveBeenCalled() + expect(postMessageSpy).toHaveBeenCalledOnce() + expect(postMessageSpy.mock.calls[0]?.[0].state).not.toHaveProperty("taskHistory") + }) + + test("getStateToPostToWebview computes task history once after its base state resolves", async () => { + const historyItem = { + id: "history-task", + number: 1, + ts: 1, + task: "History task", + tokensIn: 0, + tokensOut: 0, + totalCost: 0, + } + const originalGetState = provider.getState.bind(provider) + let baseStateResolved = false + const getStateSpy = vi.spyOn(provider, "getState").mockImplementation(async (options) => { + const state = await originalGetState(options) + baseStateResolved = true + return state + }) + const historyReadPhases: boolean[] = [] + const getAllSpy = vi.spyOn(provider.taskHistoryStore, "getAll").mockImplementation(() => { + historyReadPhases.push(baseStateResolved) + return [historyItem] + }) + + const state = await provider.getStateToPostToWebview() + + expect(getStateSpy).toHaveBeenCalledOnce() + expect(getStateSpy).toHaveBeenCalledWith({ includeTaskHistory: false }) + expect(getAllSpy).toHaveBeenCalledOnce() + expect(historyReadPhases).toEqual([true]) + expect(state.taskHistory).toEqual([historyItem]) + }) + + describe("viewId uniqueness", () => { + it("should assign unique viewId to each instance", async () => { + const provider1 = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const provider2 = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + // Each instance should have a unique viewId + expect(provider1.viewId).toBeDefined() + expect(provider2.viewId).toBeDefined() + expect(provider1.viewId).not.toBe(provider2.viewId) + + await provider1.dispose() + await provider2.dispose() + }) + + it("should have viewId in correct format: {renderContext}-{instanceCount}", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + expect(provider.viewId).toMatch(/^sidebar-\d+$/) + + await provider.dispose() + }) + + it("should increment instance count for each new instance", async () => { + const provider1 = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const provider2 = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + // First editor instance should be "editor-0" (or next available) + // Second editor instance should have a different number + const num1 = parseInt(provider1.viewId.split("-")[1]!) + const num2 = parseInt(provider2.viewId.split("-")[1]!) + + expect(num2).toBeGreaterThan(num1) + + await provider1.dispose() + await provider2.dispose() + }) + }) + + describe("saveViewState", () => { + it("should update viewLocalState and persist mode through registered viewStates", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + const contextProxySpy = vi.spyOn(provider.contextProxy, "setValue") + await provider["setViewStateId"]("stable-sidebar-view") + + await provider.saveViewState("mode", "architect") + + expect(provider["viewLocalState"].mode).toBe("architect") + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + "stable-sidebar-view": { mode: "architect" }, + }) + expect(contextProxySpy).toHaveBeenCalledWith( + "viewStates", + expect.objectContaining({ + "stable-sidebar-view": expect.objectContaining({ + mode: "architect", + updatedAt: expect.any(Number), + }), + }), + ) + expect(contextProxySpy).not.toHaveBeenCalledWith("__view_state_stable-sidebar-view_mode", expect.anything()) + + await provider.dispose() + }) + + it("should update viewLocalState and persist currentApiConfigName through registered viewStates", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("currentApiConfigName", "my-profile") + + expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + "stable-sidebar-view": { currentApiConfigName: "my-profile" }, + }) + + await provider.dispose() + }) + + it("should update viewLocalState for apiConfiguration without persisting provider settings or secrets", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + const testApiConfig = { + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "claude-3.5-sonnet", + openRouterApiKey: "secret-key", + } + + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("apiConfiguration", testApiConfig) + + expect(provider["viewLocalState"].apiConfiguration).toEqual(testApiConfig) + expect(provider.contextProxy.getValue("viewStates")).toBeUndefined() + + await provider.dispose() + }) + + it("should clear local override when saveViewState receives undefined", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider.saveViewState("mode", "architect") + expect(provider["viewLocalState"].mode).toBe("architect") + + await provider.saveViewState("mode", undefined) + + expect(Object.prototype.hasOwnProperty.call(provider["viewLocalState"], "mode")).toBe(false) + + await provider.dispose() + }) + + it("should clear the currentApiConfigName override when saveViewState receives undefined", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider.saveViewState("currentApiConfigName", "my-profile") + expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") + + await provider.saveViewState("currentApiConfigName", undefined) + + expect(Object.prototype.hasOwnProperty.call(provider["viewLocalState"], "currentApiConfigName")).toBe(false) + + await provider.dispose() + }) + + it("should not update viewLocalState when durable view-state persistence fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.spyOn(provider.contextProxy, "setValue").mockRejectedValueOnce(new Error("persist failed")) + + await provider["setViewStateId"]("stable-sidebar-view") + + await expect(provider.saveViewState("mode", "architect")).rejects.toThrow("persist failed") + expect(provider["viewLocalState"]).not.toHaveProperty("mode") + expect(provider.contextProxy.getValue("viewStates")).toBeUndefined() + + await provider.dispose() + }) + + it("should merge concurrent persisted updates from separate provider instances without lost viewStates", async () => { + const provider1 = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const provider2 = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider1["setViewStateId"]("stable-sidebar-view") + await provider2["setViewStateId"]("stable-editor-view") + + await Promise.all([ + provider1.saveViewState("mode", "architect"), + provider2.saveViewState("currentApiConfigName", "editor-profile"), + ]) + + expect(mockContext.globalState.get("viewStates")).toMatchObject({ + "stable-sidebar-view": { mode: "architect" }, + "stable-editor-view": { currentApiConfigName: "editor-profile" }, + }) + + await provider1.dispose() + await provider2.dispose() + }) + }) + + describe("loadViewState", () => { + it("should keep viewLocalState empty when no stable per-view values exist", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await vi.waitFor(() => { + expect(provider["viewLocalState"]).toEqual({}) + }) + + const state = await provider.getState() + // No per-view entry exists and the proxy's global-state cache is empty + // (initialize() is never called in this fixture; only "taskHistory" passes + // through to the context store), so getState() falls back to the shared + // defaults: mode "code" (defaultModeSlug) and currentApiConfigName "default". + expect(state.mode).toBe("code") + expect(state.currentApiConfigName).toBe("default") + + await provider.dispose() + }) + + it("should log and keep existing viewLocalState when loadViewState fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + + // Register a stable id so the load is not skipped by the ownership guard: + // only entries this instance authored are loaded under a temporary name. + await provider["setViewStateId"]("stable-sidebar-view") + + provider["viewLocalState"] = { mode: "architect" } + vi.spyOn(provider.contextProxy, "getValue").mockImplementation(() => { + throw new Error("load failed") + }) + + await provider["loadViewState"]() + + expect(provider["viewLocalState"].mode).toBe("architect") + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Error loading state")) + + await provider.dispose() + }) + }) + + describe("persisted view state pruning", () => { + it("should keep the newest 50 persisted view states", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const states = Object.fromEntries( + Array.from({ length: 55 }, (_, index) => [ + `view-${index}`, + { mode: `mode-${index}`, updatedAt: index }, + ]), + ) + + const pruned = provider["prunePersistedViewStates"](states) + + expect(Object.keys(pruned)).toHaveLength(50) + expect(pruned["view-54"]).toEqual({ mode: "mode-54", updatedAt: 54 }) + expect(pruned["view-5"]).toEqual({ mode: "mode-5", updatedAt: 5 }) + expect(pruned["view-4"]).toBeUndefined() + + await provider.dispose() + }) + }) + + describe("setViewStateId", () => { + it('should ignore "__proto__" and keep the temporary viewId', async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider["setViewStateId"]("__proto__") + + // "__proto__" is rejected before assignment so a per-view entry can never be + // keyed through the Object.prototype setter: the temporary id stays active and + // nothing is persisted under the reserved name. + expect(provider["viewStateId"]).toBe(provider.viewId) + expect(mockContext.globalState.get("viewStates")).toBeUndefined() + expect(provider["viewLocalState"]).toEqual({}) + + await provider.dispose() + }) + + it("restores the previous view id when the registration write fails so a later launch retries", async () => { + const contextProxy = new ContextProxy(mockContext) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + contextProxy, + new WebviewFocusTracker(), + ) + // Seed a pre-launch entry under the temporary id through the real write path, + // so the re-key has real work to do and records this instance as its author. + await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) + + const setValueSpy = vi.spyOn(contextProxy, "setValue").mockRejectedValue(new Error("storage down")) + + await expect(provider["setViewStateId"]("stable-sidebar-view")).rejects.toThrow("storage down") + + // The failed id must not stick: the provider keeps its previous (temporary) + // id so a later launch retries registration and the load instead of the + // guard early-returning for an id that was never persisted. + expect(provider["viewStateId"]).toBe(provider.viewId) + + // A later retry succeeds once the storage write works again, and the + // pre-launch entry lands under the registered id. + setValueSpy.mockRestore() + await provider["setViewStateId"]("stable-sidebar-view") + expect(provider["viewStateId"]).toBe("stable-sidebar-view") + expect(mockContext.globalState.get("viewStates")).toEqual({ + "stable-sidebar-view": { mode: "architect", updatedAt: 1 }, + }) + + await provider.dispose() + }) + }) + + describe("view state persistence edge cases", () => { + it("should read viewStates from the ContextProxy cache when not fresh", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("viewStates", { "stable-sidebar-view": { mode: "architect" } }) + expect(provider["getPersistedViewStates"]()).toEqual({ "stable-sidebar-view": { mode: "architect" } }) + await provider.dispose() + }) + + it("should treat a corrupted non-object viewStates value as an empty map", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // A string in storage is corrupt: the fresh-read guard must not spread it. + await mockContext.globalState.update("viewStates", "corrupted-storage-value") + expect(provider["getPersistedViewStates"]({ fresh: true })).toEqual({}) + await provider.dispose() + }) + + it("should merge saved fields, drop cleared fields and delete emptied entries", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + const save = provider.saveViewState.bind(provider) as (key: string, value: unknown) => Promise + const states = () => mockContext.globalState.get>("viewStates") ?? {} + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("mode", "architect") + await provider.saveViewState("currentApiConfigName", "profile-a") + const merged = states()["stable-sidebar-view"] + expect(merged).toMatchObject({ mode: "architect", currentApiConfigName: "profile-a" }) + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Saved mode for viewId")) + await save("mode", undefined) + expect(states()["stable-sidebar-view"]).toStrictEqual({ + currentApiConfigName: "profile-a", + updatedAt: expect.any(Number), + }) + await save("mode", null) + expect(states()["stable-sidebar-view"]).not.toHaveProperty("mode") + await provider.saveViewState("mode", "architect") + await save("currentApiConfigName", undefined) + expect(states()["stable-sidebar-view"]).toStrictEqual({ + mode: "architect", + updatedAt: expect.any(Number), + }) + await provider.saveViewState("currentApiConfigName", "profile-c") + await provider.saveViewState("mode", "architect") + expect(states()["stable-sidebar-view"]).toMatchObject({ + mode: "architect", + currentApiConfigName: "profile-c", + }) + await save("currentApiConfigName", null) + expect(states()["stable-sidebar-view"]).not.toHaveProperty("currentApiConfigName") + await save("mode", null) + expect(states()["stable-sidebar-view"]).toBeUndefined() + expect(provider["viewLocalState"]).toStrictEqual({}) // buffer ends fully cleared + await provider.dispose() + }) + + it("should rekey a pre-launch entry under the temporary id to the registered stable id", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Seed through the write path so this instance is the author of the entry under + // its temporary id; an entry authored by another session must not be adopted. + await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) + await provider["setViewStateId"]("stable-sidebar-view") + expect(mockContext.globalState.get("viewStates")).toEqual({ + "stable-sidebar-view": { mode: "architect", updatedAt: 1 }, + }) + await provider.dispose() + }) + + it("should keep the stable entry and drop the temporary entry when both exist", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Author the temporary entry through the write path so this instance owns it, + // then add a stable entry that already exists in storage. + await provider["savePersistedViewState"]({ mode: "temp-mode", updatedAt: 1 }) + await provider.contextProxy.setValue("viewStates", { + [provider.viewId]: { mode: "temp-mode", updatedAt: 1 }, + "stable-sidebar-view": { mode: "stable-mode", updatedAt: 5 }, + }) + await provider["setViewStateId"]("stable-sidebar-view") + expect(mockContext.globalState.get("viewStates")).toEqual({ + "stable-sidebar-view": { mode: "stable-mode", updatedAt: 5 }, + }) + await provider.dispose() + }) + + it("should clear only this view's entry without clobbering an entry only storage knows about", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-sidebar-view") + // The cache only knows this view's entry; storage gains an extra view directly. + await provider.contextProxy.setValue("viewStates", { "stable-sidebar-view": { mode: "architect" } }) + await mockContext.globalState.update("viewStates", { + "stable-sidebar-view": { mode: "architect" }, + "stable-editor-view": { mode: "code" }, + }) + await provider["clearPersistedViewState"]() + expect(mockContext.globalState.get("viewStates")).toEqual({ "stable-editor-view": { mode: "code" } }) + await provider.dispose() + }) + + it("should prune by updatedAt regardless of insertion order", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const states = Object.fromEntries( + Array.from({ length: 55 }, (_, index) => [ + `view-${index}`, + { mode: `mode-${index}`, updatedAt: (index * 7) % 55 }, + ]), + ) + const pruned = provider["prunePersistedViewStates"](states) + expect(Object.keys(pruned)).toHaveLength(50) + // view-1/view-54 survive the true newest-50 selection; view-8 (updatedAt 1) does not. + expect(pruned["view-1"]).toEqual({ mode: "mode-1", updatedAt: 7 }) + expect(pruned["view-54"]).toEqual({ mode: "mode-54", updatedAt: 48 }) + expect(pruned["view-8"]).toBeUndefined() + await provider.dispose() + }) + + it("should sanitize, reject blank and undefined ids, and no-op on the active id", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + await provider["setViewStateId"]("a b/c") + expect(provider["viewStateId"]).toBe("a_b_c") + await provider["setViewStateId"](undefined) + await provider["setViewStateId"](" ") + expect(provider["viewStateId"]).toBe("a_b_c") + logSpy.mockClear() + await provider["setViewStateId"]("a_b_c") + expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining("Loaded state for viewId")) + await provider.dispose() + }) + + it("should load persisted mode, profile name and resolved profile into viewLocalState", async () => { + const writer = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await writer["setViewStateId"]("shared-view") + await writer.saveViewState("mode", "architect") + await writer.saveViewState("currentApiConfigName", "my-profile") + + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + const getProfileSpy = vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "my-profile", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + // The ownership check requires the writer to release the id before the + // next view adopts it; the durable entry it wrote stays in storage. + await writer.dispose() + + await provider.contextProxy.setValue( + "viewStates", + mockContext.globalState.get("viewStates"), + ) + await provider["setViewStateId"]("shared-view") + expect(provider["viewLocalState"]).toEqual({ + mode: "architect", + currentApiConfigName: "my-profile", + apiConfiguration: { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }, + }) + expect(getProfileSpy).toHaveBeenCalledWith({ name: "my-profile" }) + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Loaded state for viewId")) + await provider.dispose() + }) + + it("should log a successful empty load when no persisted entry exists", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + await provider["setViewStateId"]("stable-sidebar-view") + expect(provider["viewLocalState"]).toEqual({}) + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Loaded state for viewId")) + await provider.dispose() + }) + + it("should keep the persisted profile name and log when the profile lookup fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockRejectedValue(new Error("profile missing")) + await provider.saveViewState("currentApiConfigName", "my-profile") + await provider["setViewStateId"]("stable-sidebar-view") + expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") + expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Unable to resolve API profile 'my-profile'")) + await provider.dispose() + }) + + it("should discard a stale load when the viewStateId changes during the profile lookup", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(() => { + provider["viewStateId"] = "superseded-view" + return Promise.resolve({ name: "my-profile", apiProvider: providerIdentifiers.openrouter }) + }) + await provider.saveViewState("currentApiConfigName", "my-profile") + await provider["setViewStateId"]("stable-sidebar-view") + expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") + const staleMsg = expect.stringContaining("Discarding stale state for superseded view id") + expect(logSpy).toHaveBeenCalledWith(staleMsg) + await provider.dispose() + }) + + it("should reapply fields mutated while the load is in flight and keep persisted values for untouched fields", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) + await provider.saveViewState("currentApiConfigName", "cfg-a") + const load = provider["setViewStateId"]("stable-sidebar-view") + + // Let the stalled lookup begin so the in-flight mutations and the resolver + // target the pending promise rather than the initial no-op. + await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) + + // Selections made while the profile lookup is in flight must survive the load. + await provider.saveViewState("mode", "architect") + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-y", + }) + + resolveProfile({ name: "cfg-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }) + await load + + // Dirty fields win over the loaded state; the untouched field keeps the persisted value. + expect(provider["viewLocalState"]).toEqual({ + mode: "architect", + currentApiConfigName: "cfg-a", + apiConfiguration: { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-y" }, + }) + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Loaded state for viewId")) + await provider.dispose() + }) + + it("should keep the persisted mode authoritative when the pre-load buffer is untouched", async () => { + const writer = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await writer["setViewStateId"]("shared-view") + await writer.saveViewState("mode", "code") + await writer.saveViewState("currentApiConfigName", "my-profile") + + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "my-profile", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + // A pre-load buffer write that was never persisted must not be merged over the load. + provider["viewLocalState"] = { mode: "architect" } + // The ownership check requires the writer to release the id before the + // next view adopts it; the durable entry it wrote stays in storage. + await writer.dispose() + + await provider.contextProxy.setValue( + "viewStates", + mockContext.globalState.get("viewStates"), + ) + await provider["setViewStateId"]("shared-view") + expect(provider["viewLocalState"].mode).toBe("code") + expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + await provider.dispose() + }) + + it("should not restore a persisted mode whose custom mode no longer exists", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + // The file-level modes mock resolves every slug to a mode; drop the pinned slug. + const modesModule = vi.mocked(await import("../../../shared/modes")) + const originalMode = modesModule.getModeBySlug("code") + modesModule.getModeBySlug.mockImplementation(((slug: string) => + slug === "deleted-custom-mode" ? undefined : originalMode) as typeof modesModule.getModeBySlug) + try { + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("mode", "deleted-custom-mode") + // Reload the persisted entry: the custom mode was deleted in the meantime. + await provider["loadViewState"]() + // The stale slug must not be restored into the buffer. + expect(provider["viewLocalState"]).not.toHaveProperty("mode") + expect(logSpy).toHaveBeenCalledWith( + expect.stringContaining('Ignoring unknown persisted mode "deleted-custom-mode"'), + ) + } finally { + modesModule.getModeBySlug.mockReturnValue(originalMode) + } + await provider.dispose() + }) + + it("should not resurrect a field cleared mid-load from the pre-load buffer", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) + // Persist a mode too: without it the load has no mode to resurrect, so the + // cleared-field assertion below would pass even if the loaded value clobbered + // the in-flight clear. + await provider.saveViewState("currentApiConfigName", "cfg-a") + await provider.saveViewState("mode", "code") + provider["viewLocalState"] = { ...provider["viewLocalState"], mode: "architect" } + const load = provider["setViewStateId"]("stable-sidebar-view") + + // Let the stalled lookup begin so the in-flight clear and the resolver + // target the pending promise rather than the initial no-op. + await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) + + // The user clears the mode while the load is in flight. + await provider.saveViewState("mode", undefined) + resolveProfile({ name: "cfg-a" }) + await load + + // The cleared field must stay absent rather than keeping the persisted or + // pre-load value; the untouched field keeps the persisted value. + expect(provider["viewLocalState"]).not.toHaveProperty("mode") + expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-a") + await provider.dispose() + }) + + it("should reapply an independently mutated mode when the load settles", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) + await provider.saveViewState("currentApiConfigName", "cfg-a") + const load = provider["setViewStateId"]("stable-sidebar-view") + + // Let the stalled lookup begin so the in-flight mutation and the resolver + // target the pending promise rather than the initial no-op. + await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) + // Only the mode is mutated while the profile lookup is in flight. + await provider.saveViewState("mode", "architect") + + resolveProfile({ name: "cfg-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }) + await load + + expect(provider["viewLocalState"]).toEqual({ + mode: "architect", + currentApiConfigName: "cfg-a", + apiConfiguration: { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }, + }) + await provider.dispose() + }) + + it("should reapply an independently mutated profile name when the load settles", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) + await provider.saveViewState("currentApiConfigName", "cfg-a") + const load = provider["setViewStateId"]("stable-sidebar-view") + + // Let the stalled lookup begin so the in-flight mutation and the resolver + // target the pending promise rather than the initial no-op. + await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) + // The profile name changes while the lookup is in flight; the load still + // resolves the name persisted at load start. + await provider.saveViewState("currentApiConfigName", "cfg-b") + + resolveProfile({ name: "cfg-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }) + await load + + // The in-flight selection wins over the loaded state. + expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-b") + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + expect(provider["viewLocalState"]).not.toHaveProperty("mode") + await provider.dispose() + }) + + it("should reapply an independently mutated apiConfiguration when the load settles", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) + await provider.saveViewState("currentApiConfigName", "cfg-a") + const load = provider["setViewStateId"]("stable-sidebar-view") + + // Let the stalled lookup begin so the in-flight mutation and the resolver + // target the pending promise rather than the initial no-op. + await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) + // Only the apiConfiguration is mutated while the profile lookup is in flight. + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-y", + }) + + resolveProfile({ name: "cfg-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }) + await load + + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-y", + }) + expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-a") + await provider.dispose() + }) + + it("should keep every persisted field authoritative when the load is untouched", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + await provider.saveViewState("mode", "code") + await provider.saveViewState("currentApiConfigName", "cfg-a") + const load = provider["setViewStateId"]("stable-sidebar-view") + + // Let the stalled lookup begin so the in-flight mutation and the resolver + // target the pending promise rather than the initial no-op. + await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) + // No mutation while the lookup is in flight: the persisted values must win. + resolveProfile({ name: "cfg-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }) + await load + + expect(provider["viewLocalState"]).toEqual({ + mode: "code", + currentApiConfigName: "cfg-a", + apiConfiguration: { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }, + }) + await provider.dispose() + }) + + it("should persist known modes and reject unknown or non-string modes", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + // The file-level modes mock resolves every slug to a mode; narrow it to the slugs under test. + const modesModule = vi.mocked(await import("../../../shared/modes")) + const originalMode = modesModule.getModeBySlug("code") + modesModule.getModeBySlug.mockImplementation(((slug: string) => + slug === "refactor" ? { slug } : undefined) as typeof modesModule.getModeBySlug) + try { + await provider.setValues({ mode: "refactor" }) + expect(mockContext.globalState.get("mode")).toBe("refactor") + expect(provider["viewLocalState"].mode).toBe("refactor") + await provider.setValues({ mode: "bogus-mode" }) + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Ignoring invalid mode "bogus-mode"')) + expect(mockContext.globalState.get("mode")).toBe("refactor") + expect(provider["viewLocalState"].mode).toBe("refactor") + // A non-string mode must be rejected before persistence; Object.assign + // keeps this a single structural assertion, so it must not reach global + // state or the buffer. + await provider.setValues(Object.assign({} as RooCodeSettings, { mode: 42 })) + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Ignoring invalid mode "42"')) + expect(mockContext.globalState.get("mode")).toBe("refactor") + expect(provider["viewLocalState"].mode).toBe("refactor") + } finally { + modesModule.getModeBySlug.mockReturnValue(originalMode) + } + await provider.dispose() + }) + + it("should refuse an unknown or non-string mode in setValue before either persistence layer is written", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + const sharedWrite = vi.spyOn(provider.contextProxy, "setValue") + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + // The file-level modes mock resolves every slug to a mode; narrow it to the slugs under test. + const modesModule = vi.mocked(await import("../../../shared/modes")) + const originalMode = modesModule.getModeBySlug("code") + modesModule.getModeBySlug.mockImplementation(((slug: string) => + slug === "refactor" ? { slug } : undefined) as typeof modesModule.getModeBySlug) + try { + await provider.setValue("mode", "refactor") + expect(mockContext.globalState.get("mode")).toBe("refactor") + expect(provider["viewLocalState"].mode).toBe("refactor") + // Object.assign keeps the non-string mode a single structural value rather than a + // double assertion; it must not reach either layer either. + const nonStringMode = Object.assign({} as RooCodeSettings, { mode: 42 }).mode + const writesBeforeRefusals = sharedWrite.mock.calls.length + await provider.setValue("mode", "bogus-mode") + await provider.setValue("mode", nonStringMode) + expect(logSpy).toHaveBeenCalledWith( + expect.stringContaining('[ClineProvider#setValue] Ignoring invalid mode "bogus-mode"'), + ) + expect(logSpy).toHaveBeenCalledWith( + expect.stringContaining('[ClineProvider#setValue] Ignoring invalid mode "42"'), + ) + // The shared write count is the ordering proof: the guard returned before + // contextProxy.setValue ran, and the per-view pin is only ever written after that + // call, so an unchanged pin plus an unchanged call count puts it ahead of both. + expect(sharedWrite.mock.calls.length).toBe(writesBeforeRefusals) + expect(mockContext.globalState.get("mode")).toBe("refactor") + expect(provider["viewLocalState"].mode).toBe("refactor") + } finally { + modesModule.getModeBySlug.mockReturnValue(originalMode) + } + await provider.dispose() + }) + + it("should write modes through setValue that the guard is meant to accept", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + // A slug the custom modes manager reports is a registered mode even though it is not + // built in, so the guard has to accept what the manager knows at call time. + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([ + { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, + ]) + const modesModule = vi.mocked(await import("../../../shared/modes")) + const originalMode = modesModule.getModeBySlug("code") + // Real seam: the guard asks the shipped lookup - src/shared/modes.ts rows 51-59, custom + // modes first and built-ins behind them - instead of an inline finder that knows only the + // two slugs this test happens to name (review thread 4595150531). vi.importActual skips + // this file's mock of the module, so the production predicate runs behind the mock's own + // identity, which is what ClineProvider imports. + const actualModes = await vi.importActual("../../../shared/modes") + modesModule.getModeBySlug.mockImplementation(actualModes.getModeBySlug) + try { + await provider.setValue("mode", "architect") + expect(mockContext.globalState.get("mode")).toBe("architect") + expect(provider["viewLocalState"].mode).toBe("architect") + await provider.setValue("mode", "reviewer") + expect(mockContext.globalState.get("mode")).toBe("reviewer") + expect(provider["viewLocalState"].mode).toBe("reviewer") + expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining('Ignoring invalid mode "reviewer"')) + // Clearing the mode is not a slug: an undefined value still reaches both layers. + await provider.setValue("mode", undefined) + expect(provider.getValue("mode")).toBeUndefined() + expect(provider["viewLocalState"]).not.toHaveProperty("mode") + // An unrelated single-value mutation is untouched by the mode guard. + await provider.setValue("writeDelayMs", 500) + expect(mockContext.globalState.get("writeDelayMs")).toBe(500) + } finally { + modesModule.getModeBySlug.mockReturnValue(originalMode) + } + await provider.dispose() + }) + + it("should apply setValue mutations to global state and keep or clear the right buffer fields", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const apiConfiguration = { apiProvider: providerIdentifiers.openrouter } + await provider.saveViewState("mode", "architect") + await provider.saveViewState("currentApiConfigName", "my-profile") + await provider.saveViewState("apiConfiguration", apiConfiguration) + // A mutation of an unrelated key reaches global state without dropping buffered fields. + await provider.setValue("writeDelayMs", 500) + expect(mockContext.globalState.get("writeDelayMs")).toBe(500) + expect(provider.getValues().writeDelayMs).toBe(500) + expect(provider["viewLocalState"].mode).toBe("architect") + expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") + expect(provider["viewLocalState"].apiConfiguration).toBe(apiConfiguration) + await provider.setValue("mode", undefined) + expect(provider["viewLocalState"]).not.toHaveProperty("mode") + await provider.setValue("currentApiConfigName", undefined) + expect(provider["viewLocalState"]).not.toHaveProperty("currentApiConfigName") + await provider.dispose() + }) + + it("should remove the buffered apiConfiguration when it is cleared", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const save = provider.saveViewState.bind(provider) as (key: string, value: unknown) => Promise + await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter }) + await provider.saveViewState("apiConfiguration", undefined) + expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") + await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter }) + await save("apiConfiguration", null) + expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") + await provider.dispose() + }) + + it("should clear viewLocalState and the persisted entry when resetting state", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.customModesManager, "resetCustomModes").mockResolvedValue(undefined) + // The modal answer is a string label; the last-typed vscode overload expects a + // MessageItem. A double assertion is the last-resort cast here (AGENTS.md): the + // production path compares the answer against the string label directly, so the + // runtime value must stay a string and cannot be a structural MessageItem double. + vi.mocked(vscode.window.showInformationMessage).mockResolvedValue( + t("common:answers.yes") as unknown as vscode.MessageItem, + ) + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("mode", "architect") + await provider.resetState() + expect(provider["viewLocalState"]).toEqual({}) + expect(mockContext.globalState.get("viewStates")).toEqual({}) + await provider.dispose() + }) + + it("runs the remaining reset cleanup when the persisted view-state clear fails", async () => { + const { t } = await import("../../../i18n") + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The modal answer is a string label; the last-typed vscode overload expects a + // MessageItem. A double assertion is the last-resort cast here (AGENTS.md): the + // production path compares the answer against the string label directly, so the + // runtime value must stay a string and cannot be a structural MessageItem double. + vi.mocked(vscode.window.showInformationMessage).mockResolvedValueOnce( + t("common:answers.yes") as unknown as vscode.MessageItem, + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.contextProxy, "resetAllState").mockResolvedValue(undefined) + const configsReset = vi + .spyOn(provider.providerSettingsManager, "resetAllConfigs") + .mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getModeConfigIds").mockResolvedValue({}) + // The shared custom-modes mock does not implement reset. + const modesReset = vi.fn().mockResolvedValue(undefined) + Object.assign(provider.customModesManager, { resetCustomModes: modesReset }) + const abortTask = vi.fn().mockResolvedValue(undefined) + // Members of this double are declared on Task: taskId at Task.ts 291, + // instanceId at 297 and abortTask at 3654, and emit is inherited from the + // typed EventEmitter that Task extends at Task.ts 290. The cast is the last + // resort here because the reset path only touches those four members. + const doomedTask = { taskId: "reset-task", instanceId: "reset-instance", emit: vi.fn(), abortTask } + Object.assign(provider, { taskRegistry: new TaskRegistry() }) + provider["taskRegistry"].push(doomedTask as unknown as Task) + const logLines: string[] = [] + vi.spyOn(provider, "log").mockImplementation((message: string) => { + logLines.push(message) + }) + await provider["setViewStateId"]("reset-failure-view") + await provider.saveViewState("mode", "architect") + // Installed after the setup write landed, so the only durable viewStates attempts + // below are the reset clear at ClineProvider.ts 5530 and the cache-restoring + // write its own catch issues at 5531. + const attempts: string[] = [] + vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key) => { + attempts.push(String(key)) + if (key === "viewStates") { + return Promise.reject(new Error("durable clear rejected")) + } + return Promise.resolve() + }) + await provider.resetState() + // The durable clear failed, so this view's entry stays stored; what must not be + // lost is the rest of the reset: the running task is aborted and dropped from + // the stack, stored profiles and custom modes are removed, and the failure is + // reported. Review thread 4506513984. + expect(provider["taskRegistry"].getById("reset-task")).toBeUndefined() + expect(abortTask).toHaveBeenCalledWith(true) + expect(configsReset).toHaveBeenCalledOnce() + expect(modesReset).toHaveBeenCalledOnce() + expect(logLines.filter((line: string) => line.includes("durable clear rejected")).length).toBe(1) + expect(attempts.filter((key: string) => key === "viewStates").length).toBe(2) + await provider.dispose() + }) + + it("keeps the reset cleanup unreported when the persisted view-state clear lands", async () => { + const { t } = await import("../../../i18n") + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.mocked(vscode.window.showInformationMessage).mockResolvedValueOnce( + t("common:answers.yes") as unknown as vscode.MessageItem, + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.contextProxy, "resetAllState").mockResolvedValue(undefined) + const configsReset = vi + .spyOn(provider.providerSettingsManager, "resetAllConfigs") + .mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getModeConfigIds").mockResolvedValue({}) + const modesReset = vi.fn().mockResolvedValue(undefined) + Object.assign(provider.customModesManager, { resetCustomModes: modesReset }) + const abortTask = vi.fn().mockResolvedValue(undefined) + const landedTask = { taskId: "reset-task", instanceId: "reset-instance", emit: vi.fn(), abortTask } + Object.assign(provider, { taskRegistry: new TaskRegistry() }) + provider["taskRegistry"].push(landedTask as unknown as Task) + const logLines: string[] = [] + vi.spyOn(provider, "log").mockImplementation((message: string) => { + logLines.push(message) + }) + await provider["setViewStateId"]("reset-landed-view") + await provider.saveViewState("mode", "architect") + const attempts: string[] = [] + vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key) => { + attempts.push(String(key)) + return Promise.resolve() + }) + await provider.resetState() + // Same cleanup as the failing case, with nothing rejected: the control keeps + // the new reporting honest, since a landed clear must not be reported. + expect(provider["taskRegistry"].getById("reset-task")).toBeUndefined() + expect(abortTask).toHaveBeenCalledWith(true) + expect(configsReset).toHaveBeenCalledOnce() + expect(modesReset).toHaveBeenCalledOnce() + expect(logLines.filter((line: string) => line.includes("persisted state during reset")).length).toBe(0) + expect(attempts.filter((key: string) => key === "viewStates").length).toBe(1) + await provider.dispose() + }) + + it("should roll back the shared write when setValue per-view persistence fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("mode", "architect") + const originalUpdate = mockContext.globalState.update + mockContext.globalState.update = vi.fn().mockImplementation((key: string) => { + if (key === "viewStates") { + return Promise.reject(new Error("storage unavailable")) + } + return Promise.resolve() + }) + + await expect(provider.setValue("mode", "code")).rejects.toThrow("storage unavailable") + // The shared store must not move ahead of the per-view record that failed. + expect(provider.getValue("mode")).toBe("architect") + + mockContext.globalState.update = originalUpdate + await provider.dispose() + }) + it("should roll back the shared writes when setValues per-view persistence fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("mode", "architect") + await provider.contextProxy.setValue("currentApiConfigName", "current-config") + const originalUpdate = mockContext.globalState.update + mockContext.globalState.update = vi.fn().mockImplementation((key: string) => { + if (key === "viewStates") { + return Promise.reject(new Error("storage unavailable")) + } + return Promise.resolve() + }) + + await expect(provider.setValues({ mode: "code", currentApiConfigName: "other-config" })).rejects.toThrow( + "storage unavailable", + ) + expect(provider.getValue("mode")).toBe("architect") + expect(provider.getValue("currentApiConfigName")).toBe("current-config") + expect(provider["viewLocalState"].mode).toBeUndefined() + + mockContext.globalState.update = originalUpdate + await provider.dispose() + }) + }) + + describe("provider profile mutations", () => { + it("should sync the view-local buffer when activating a profile over a loaded view state", async () => { + const writer = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await writer["setViewStateId"]("shared-view") + await writer.saveViewState("currentApiConfigName", "old-profile") + + const profile: ProviderSettingsEntry = { + name: "new-profile", + id: "new-id", + apiProvider: providerIdentifiers.openrouter, + } + + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue(profile) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([profile]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + // The ownership check requires the writer to release the id before the + // next view adopts it; the durable entry it wrote stays in storage. + await writer.dispose() + + await provider.contextProxy.setValue( + "viewStates", + mockContext.globalState.get("viewStates"), + ) + await provider["setViewStateId"]("shared-view") + expect(provider.getValues().currentApiConfigName).toBe("old-profile") + + await provider.activateProviderProfile({ name: "new-profile" }) + + // The buffer must track the activated profile so getValues() agrees with the proxy. + expect(provider.getValues().currentApiConfigName).toBe("new-profile") + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("new-profile") + await provider.dispose() + }) + + it("should sync the view-local buffer when creating and activating a profile", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const profile: ProviderSettingsEntry = { + name: "fresh-profile", + id: "fresh-id", + apiProvider: providerIdentifiers.openrouter, + } + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("fresh-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([profile]) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "fresh-profile", + id: "fresh-id", + apiProvider: providerIdentifiers.openrouter, + }) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + await provider.setValue("currentApiConfigName", "stale-profile") + + await provider.upsertProviderProfile("fresh-profile", { apiProvider: providerIdentifiers.openrouter }) + + expect(provider.getValues().currentApiConfigName).toBe("fresh-profile") + await provider.dispose() + }) + + it("stops before deleting a profile whose record could only fail to be read", async () => { + // Review thread 4593061279, printed at ClineProvider.ts line 3522 with + // original_line 3522 and unresolved here: the deletion snapshot treated a + // rejected getProfile the same as a confirmed absence, so the delete + // committed and the compensation, which can only restore a record it read, + // left the profile gone while every reference was put back. The records below live in + // the manager's own secrets-backed store, so the assertions read the durable outcome. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + const doomedProfile: ProviderSettingsEntry = { + name: "doomed-profile", + id: "doomed-id", + apiProvider: providerIdentifiers.anthropic, + } + const survivorProfile: ProviderSettingsEntry = { + name: "survivor-profile", + id: "survivor-id", + apiProvider: providerIdentifiers.anthropic, + } + + // Real seam: the records go into the manager's own secrets-backed profiles through its + // production write, so the existence read this deletion branches on below is the + // manager's predicate and not a hand-rolled map (review thread 4593898959). The ids + // are the ones the list entries carry, so the manager's id/name pairing matches the + // metadata this view advertises. + for (const { name, id, apiKey } of [ + { name: "doomed-profile", id: "doomed-id", apiKey: "doomed-key" }, + { name: "survivor-profile", id: "survivor-id", apiKey: "keeper-key" }, + ]) { + await provider.providerSettingsManager.saveConfig(name, { + apiProvider: providerIdentifiers.anthropic, + apiKey, + id, + }) + } + + let snapshotReads = 0 + // Only the fault is planted: the first read of the doomed record rejects and every + // other read - by name or by id - is the manager's own. + const realGetProfile = provider.providerSettingsManager.getProfile.bind(provider.providerSettingsManager) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation((options) => { + if ("name" in options && options.name === "doomed-profile" && snapshotReads++ === 0) { + // Transient failure: the record exists and is readable on the next read. + return Promise.reject(new Error("secrets read failed")) + } + return realGetProfile(options) + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockImplementation(() => + Promise.resolve([doomedProfile, survivorProfile]), + ) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("doomed-profile") + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "survivor-profile", + id: "survivor-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "keeper-key", + }) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await provider.contextProxy.setValue("listApiConfigMeta", [doomedProfile, survivorProfile]) + await provider.setValue("currentApiConfigName", "doomed-profile") + + // A later metadata write in the deletion group fails once, which is the + // trigger for compensation; the compensation's own writes are allowed to run. + const realSetValue = provider.contextProxy.setValue.bind(provider.contextProxy) + let listWrites = 0 + vi.spyOn(provider.contextProxy, "setValue").mockImplementation((...args) => { + if (args[0] === "listApiConfigMeta" && listWrites++ === 0) { + return Promise.reject(new Error("metadata write failed")) + } + return realSetValue(...args) + }) + + let failure: unknown + try { + await provider.deleteProviderProfile(doomedProfile) + } catch (error) { + failure = error + } + + expect(failure).toBeInstanceOf(Error) + expect({ + recordStillStored: await provider.providerSettingsManager.hasConfig("doomed-profile"), + selectionNamesIt: provider.getValues().currentApiConfigName === "doomed-profile", + listNamesIt: (provider.contextProxy.getValue("listApiConfigMeta") as ProviderSettingsEntry[]).some( + (entry) => entry.name === "doomed-profile", + ), + }).toEqual({ + recordStillStored: true, + selectionNamesIt: true, + listNamesIt: true, + }) + + await provider.dispose() + }) + + it("should sync the view-local buffer when deleting the current profile", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const oldProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) + await provider.setValue("currentApiConfigName", "old-profile") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await provider.deleteProviderProfile(oldProfile) + + // The fallback profile must replace the deleted one in both the proxy and the buffer. + expect(provider.getValues().currentApiConfigName).toBe("keeper-profile") + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("keeper-profile") + await provider.dispose() + }) + + it("does not refresh the pinned sibling views when a compensated write of the upsert fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + sibling["viewLocalState"].currentApiConfigName = "saved-profile" + sibling["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "pre-save-key", + } + vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "saved-profile", + id: "saved-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "saved-key", + }) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("mode-id") + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("saved-profile") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("state write down")) + await provider.upsertProviderProfile("saved-profile", { apiProvider: providerIdentifiers.anthropic }) + // The sibling refresh runs only after every compensated write of the group + // committed: the failure above happens first, so the sibling still serves + // the settings it buffered before the save. + expect(sibling["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "pre-save-key", + }) + } finally { + await sibling.dispose() + await provider.dispose() + } + }) + it("refreshes a delegated task on the saved profile from the view that pins another profile", async () => { + // Review thread 4506513932 (node PRRT_kwDOSK-bwM61BXEu in my capture, + // original_line 542 of 446a89921fd7bdd235ec9e9729c7e9b6535030e8, where lines + // 541-542 are the pinnedProfileName getter the update-path filter reads, + // Minor under Functional Correctness with a Quick win, unresolved): refresh + // any delegated task using the updated profile even when its view pins a + // different profile, while keeping the overlay half pinned-based. Both halves + // are asserted as set membership: the overlay half is the only writer of a + // view's buffered apiConfiguration in this flow, so an untouched buffer + // identifies a view the refresh skipped. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const taskSibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const pinnedSibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + // The task sibling pins one profile and runs a task that follows the profile + // being saved: the task half must reach it, the overlay half must not. + const taskSiblingBuffer = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "pinned-sibling-buffered-settings", + } + taskSibling["viewLocalState"].currentApiConfigName = "profile-pinned-by-task-sibling" + taskSibling["viewLocalState"].apiConfiguration = taskSiblingBuffer + // The pinned sibling buffers the profile being saved and runs a task under + // it: it belongs to both halves, which is the behaviour the ask preserves. + pinnedSibling["viewLocalState"].currentApiConfigName = "profile-being-saved" + pinnedSibling["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "saved-sibling-buffered-settings", + } + const taskSiblingTask = { + taskId: "task-following-saved-profile", + taskApiConfigName: "profile-being-saved", + apiConfiguration: { apiProvider: providerIdentifiers.openrouter, apiKey: "stale-task-key" }, + updateApiConfiguration: vi.fn(), + setTaskApiConfigName: vi.fn(), + } + const pinnedSiblingTask = { + taskId: "task-following-pinned-profile", + taskApiConfigName: "profile-being-saved", + apiConfiguration: { apiProvider: providerIdentifiers.openrouter, apiKey: "stale-pinned-task-key" }, + updateApiConfiguration: vi.fn(), + setTaskApiConfigName: vi.fn(), + } + // The doubles stand in for live tasks; the double assertion is this file. + // existing shape for a getCurrentTask double (see the profile-deletion tests + // in this describe block), kept because a full Task needs an extension host. + vi.spyOn(taskSibling, "getCurrentTask").mockReturnValue( + taskSiblingTask as unknown as ReturnType, + ) + vi.spyOn(pinnedSibling, "getCurrentTask").mockReturnValue( + pinnedSiblingTask as unknown as ReturnType, + ) + // The updating view has no task of its own here, so its mutation site is out + // of the way and every rebuild below comes from the fan-out. + vi.spyOn(provider, "getCurrentTask").mockReturnValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(taskSibling, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(pinnedSibling, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "profile-being-saved", + id: "saved-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + const id = await provider.upsertProviderProfile( + "profile-being-saved", + { apiProvider: providerIdentifiers.anthropic, apiKey: "newly-saved-key" }, + false, + ) + expect(id).toBe("saved-id") + // Task half, and only the task half, for the sibling whose pin names another + // profile: its handler was rebuilt with the saved settings and its state was + // re-posted, so the running conversation stops sending the stale key. + expect(taskSiblingTask.updateApiConfiguration).toHaveBeenCalledTimes(1) + expect(taskSiblingTask.updateApiConfiguration).toHaveBeenCalledWith( + expect.objectContaining({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }), + ) + expect(taskSibling.postStateToWebview).toHaveBeenCalledTimes(1) + // Not in the overlay half: the buffer is still the very object this view + // loaded, and the pin still names this view profile rather than the profile + // another view saved. + expect(taskSibling["viewLocalState"].apiConfiguration).toBe(taskSiblingBuffer) + expect(taskSibling["viewLocalState"].currentApiConfigName).toBe("profile-pinned-by-task-sibling") + // The task keeps its own sticky profile name: only its handler settings move. + expect(taskSiblingTask.setTaskApiConfigName).not.toHaveBeenCalled() + // Both halves for the sibling whose pin matches the saved profile: its buffer + // is replaced with the stored settings and its handler is rebuilt. + expect(pinnedSibling["viewLocalState"].apiConfiguration).toEqual( + expect.objectContaining({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }), + ) + expect(pinnedSibling["viewLocalState"].currentApiConfigName).toBe("profile-being-saved") + expect(pinnedSiblingTask.updateApiConfiguration).toHaveBeenCalledTimes(1) + expect(pinnedSibling.postStateToWebview).toHaveBeenCalledTimes(1) + // Wait on the serialized view-state write queue so queued persistence finishes + // while the console spies are still installed and teardown has no pending writes. + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await taskSibling.dispose() + await pinnedSibling.dispose() + await provider.dispose() + } + }) + + it("rebuilds the updating view's own task when that task follows the profile it saves under another pin", async () => { + // The self question of the same ask: the update arrives from this provider, + // which the fan-out has always excluded, so the rebuild of this view. + // own task belongs at the mutation site. The view pins one profile and the + // task it runs follows the profile it saves: before this change neither the + // mutation site (gated on the pin) nor the fan-out (gated on being another + // instance) rebuilt it, and the task kept sending the pre-save settings. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const ownBuffer = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "updating-view-buffered-settings", + } + provider["viewLocalState"].currentApiConfigName = "profile-pinned-by-updating-view" + provider["viewLocalState"].apiConfiguration = ownBuffer + const ownTask = { + taskId: "task-of-updating-view", + taskApiConfigName: "profile-self-saved-under-another-pin", + apiConfiguration: { apiProvider: providerIdentifiers.openrouter, apiKey: "stale-own-task-key" }, + updateApiConfiguration: vi.fn(), + setTaskApiConfigName: vi.fn(), + } + vi.spyOn(provider, "getCurrentTask").mockReturnValue( + ownTask as unknown as ReturnType, + ) + const postStateSpy = vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "profile-self-saved-under-another-pin", + id: "saved-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + const id = await provider.upsertProviderProfile( + "profile-self-saved-under-another-pin", + { apiProvider: providerIdentifiers.anthropic, apiKey: "newly-saved-key" }, + false, + ) + expect(id).toBe("saved-id") + // Exactly one rebuild, from the mutation site, and exactly one state post: the + // exclusion of this instance from the fan-out is not a second behaviour change + // because the originating view is refreshed where its own write lands. + expect(ownTask.updateApiConfiguration).toHaveBeenCalledTimes(1) + expect(ownTask.updateApiConfiguration).toHaveBeenCalledWith( + expect.objectContaining({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }), + ) + expect(postStateSpy).toHaveBeenCalledTimes(1) + // The pin is untouched: a save that does not activate does not re-point the + // updating view's buffer onto the profile it merely saved. + expect(provider["viewLocalState"].apiConfiguration).toBe(ownBuffer) + expect(provider["viewLocalState"].currentApiConfigName).toBe("profile-pinned-by-updating-view") + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await provider.dispose() + } + }) + + it("restores the acting view's own task when a non-activating save fails after its rebuild", async () => { + // Review thread 4594702295 (created 2026-11-17T02:56:13Z, printed at line 3471 of + // ClineProvider.ts with original_line 3471) names the compensation gap: both rebuilds + // in the non-activating branch land ahead of the state post, and every restore in the + // catch covers the manager record, the manager selection, the mode mapping and the + // shared/per-view state - none of them touches the task. This view pins one profile + // and its own task follows the profile being saved, so the rebuild runs and the + // post rejects: the task must go back to the configuration it ran on before the save. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const ownBuffer = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "updating-view-buffered-settings", + } + provider["viewLocalState"].currentApiConfigName = "profile-pinned-by-updating-view" + provider["viewLocalState"].apiConfiguration = ownBuffer + const ownTask = { + taskId: "task-restored-after-post-failure", + taskApiConfigName: "profile-self-saved-then-rolled-back", + apiConfiguration: { apiProvider: providerIdentifiers.openrouter, apiKey: "pre-save-own-task-key" }, + updateApiConfiguration: vi.fn(), + setTaskApiConfigName: vi.fn(), + } + // The double stands in for a live task in this file existing getCurrentTask + // shape; a full Task needs an extension host. + vi.spyOn(provider, "getCurrentTask").mockReturnValue( + ownTask as unknown as ReturnType, + ) + vi.spyOn(provider, "postStateToWebview").mockRejectedValueOnce(new Error("state post rejected")) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "profile-self-saved-then-rolled-back", + id: "saved-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + // upsertProviderProfile owns the error surface: it logs, shows a message and + // returns undefined, so the failed post is proven by the absent id and by the + // task calls below rather than by a thrown error at this call. + const id = await provider.upsertProviderProfile( + "profile-self-saved-then-rolled-back", + { apiProvider: providerIdentifiers.anthropic, apiKey: "newly-saved-key" }, + false, + ) + expect(id).toBeUndefined() + // Both halves of the task move, in this order: the rebuild carries the settings + // this save wrote, the compensation carries the settings the task ran on before + // it. The second call is the restore the thread names. + expect(ownTask.updateApiConfiguration).toHaveBeenCalledTimes(2) + expect(ownTask.updateApiConfiguration.mock.calls[0][0]).toEqual( + expect.objectContaining({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }), + ) + expect(ownTask.updateApiConfiguration.mock.calls[1][0]).toEqual( + expect.objectContaining({ + apiProvider: providerIdentifiers.openrouter, + apiKey: "pre-save-own-task-key", + }), + ) + // Only the settings move back: this save never re-pointed the sticky name, so + // the compensation may not move it either. + expect(ownTask.setTaskApiConfigName).not.toHaveBeenCalled() + expect(provider["viewLocalState"].currentApiConfigName).toBe("profile-pinned-by-updating-view") + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await provider.dispose() + } + }) + + it("restores the acting view's own task when a pinned-profile save fails after its rebuild", async () => { + // The same compensation on the other branch of the same save: here the view pins + // the profile it saves, so its buffer is rewritten first and its task rebuilt at + // line 3461 of ClineProvider.ts before the state post rejects. The task half of + // the restore has to cover both rebuilds, not only the one the thread points at. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const ownBuffer = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "pinned-view-buffered-settings", + } + provider["viewLocalState"].currentApiConfigName = "profile-self-saved-and-pinned" + provider["viewLocalState"].apiConfiguration = ownBuffer + const ownTask = { + taskId: "task-restored-after-pinned-save-failure", + taskApiConfigName: "profile-self-saved-and-pinned", + apiConfiguration: { + apiProvider: providerIdentifiers.openrouter, + apiKey: "pre-save-pinned-task-key", + }, + updateApiConfiguration: vi.fn(), + setTaskApiConfigName: vi.fn(), + } + vi.spyOn(provider, "getCurrentTask").mockReturnValue( + ownTask as unknown as ReturnType, + ) + vi.spyOn(provider, "postStateToWebview").mockRejectedValueOnce(new Error("state post rejected")) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "profile-self-saved-and-pinned", + id: "saved-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + const id = await provider.upsertProviderProfile( + "profile-self-saved-and-pinned", + { apiProvider: providerIdentifiers.anthropic, apiKey: "newly-saved-key" }, + false, + ) + expect(id).toBeUndefined() + expect(ownTask.updateApiConfiguration).toHaveBeenCalledTimes(2) + expect(ownTask.updateApiConfiguration.mock.calls[0][0]).toEqual( + expect.objectContaining({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }), + ) + expect(ownTask.updateApiConfiguration.mock.calls[1][0]).toEqual( + expect.objectContaining({ + apiProvider: providerIdentifiers.openrouter, + apiKey: "pre-save-pinned-task-key", + }), + ) + expect(ownTask.setTaskApiConfigName).not.toHaveBeenCalled() + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await provider.dispose() + } + }) + + it("leaves the pinned sibling's buffer and task handler pre-save when a write of the group fails", async () => { + // Preserve-clause control for review thread 4506513932, printed beside the + // test above: the sibling refresh is still the last step of the group, so a + // failing write ahead of it leaves both the pinned buffer and the pinned + // task handler on the pre-save state, and the log names the earlier write + // rather than a refresh failure. The ordering and the logged-not-thrown shape + // are what the answered thread 4506517321 gates; widening the sets does not + // move them. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const bufferedSettings = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "pre-save-sibling-settings", + } + sibling["viewLocalState"].currentApiConfigName = "profile-gated-by-write-order" + sibling["viewLocalState"].apiConfiguration = bufferedSettings + const siblingTask = { + taskId: "task-following-gated-profile", + taskApiConfigName: "profile-gated-by-write-order", + apiConfiguration: { apiProvider: providerIdentifiers.openrouter, apiKey: "pre-save-task-key" }, + updateApiConfiguration: vi.fn(), + setTaskApiConfigName: vi.fn(), + } + vi.spyOn(sibling, "getCurrentTask").mockReturnValue( + siblingTask as unknown as ReturnType, + ) + vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "profile-gated-by-write-order", + id: "saved-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("mode-id") + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue( + "profile-gated-by-write-order", + ) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + // The state post of the activation group fails, which is a write of the group + // and happens before the sibling refresh is invoked. + vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("state write down")) + const logLines: string[] = [] + vi.spyOn(provider, "log").mockImplementation((message: string) => { + logLines.push(message) + }) + const id = await provider.upsertProviderProfile("profile-gated-by-write-order", { + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }) + // The save failed on its own write: upsertProviderProfile swallows the failure + // and reports no id, and the log line that names the cause is the earlier + // write, not a sibling refresh. + expect(id).toBeUndefined() + expect(logLines.filter((line: string) => line.includes("state write down")).length).toBe(1) + expect( + logLines.filter((line: string) => line.includes("failed to refresh the sibling views")).length, + ).toBe(0) + // Neither half of the refresh ran for the pinned sibling: no overlay write, + // and the task handler still holds the settings it was built with. + expect(sibling["viewLocalState"].apiConfiguration).toBe(bufferedSettings) + expect(siblingTask.updateApiConfiguration).not.toHaveBeenCalled() + expect(sibling.postStateToWebview).not.toHaveBeenCalled() + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await sibling.dispose() + await provider.dispose() + } + }) + + it("logs a failed sibling refresh instead of failing the save whose writes landed", async () => { + // The other half of the preserve clause: the refresh is logged rather than + // thrown, so a view whose own refresh step fails cannot turn a committed save + // into a failed one. Review thread 4506513932, printed beside the test above. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + sibling["viewLocalState"].currentApiConfigName = "profile-refreshed-and-thrown" + sibling["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "pre-refresh-sibling-settings", + } + const siblingTask = { + taskId: "task-following-thrown-profile", + taskApiConfigName: "profile-refreshed-and-thrown", + apiConfiguration: { apiProvider: providerIdentifiers.openrouter, apiKey: "pre-refresh-task-key" }, + updateApiConfiguration: vi.fn(), + setTaskApiConfigName: vi.fn(), + } + vi.spyOn(sibling, "getCurrentTask").mockReturnValue( + siblingTask as unknown as ReturnType, + ) + // The refresh reaches this view, rewrites its buffer, and then fails when it + // re-posts its state: the failure is the last step of the save. + vi.spyOn(sibling, "postStateToWebview").mockRejectedValue(new Error("sibling post down")) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "profile-refreshed-and-thrown", + id: "saved-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + const logLines: string[] = [] + vi.spyOn(provider, "log").mockImplementation((message: string) => { + logLines.push(message) + }) + const id = await provider.upsertProviderProfile( + "profile-refreshed-and-thrown", + { apiProvider: providerIdentifiers.anthropic, apiKey: "newly-saved-key" }, + false, + ) + // The save reports the id its own write produced even though the sibling + // refresh threw, and the throw is what the log line names. + expect(id).toBe("saved-id") + expect(logLines.filter((line: string) => line.includes("sibling post down")).length).toBe(1) + expect( + logLines.filter((line: string) => line.includes("failed to refresh the sibling views")).length, + ).toBe(1) + expect(sibling["viewLocalState"].apiConfiguration).toEqual( + expect.objectContaining({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }), + ) + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await sibling.dispose() + await provider.dispose() + } + }) + + it("fails the upsert and compensates the record when the post-save read-back fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The pre-save snapshot sees the prior record; the post-save read-back + // fails: the raw caller payload must never stand in for the validated + // stored record. + let saved = false + const saveSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig").mockImplementation(async () => { + saved = true + return "p-id" + }) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async () => { + if (saved) { + throw new Error("read-back down") + } + return { + name: "p", + id: "p-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "prior-key", + } + }) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("p") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + const setValueSpy = vi.spyOn(provider.contextProxy, "setValue") + + await expect( + provider["persistProviderProfile"]( + "p", + { apiProvider: providerIdentifiers.anthropic, apiKey: "raw-key" }, + true, + new AbortController().signal, + ), + ).rejects.toThrow("could not be read back") + + // The landed save was compensated with the prior record, and no + // activation write carried the raw payload into the shared store. + expect(saveSpy).toHaveBeenLastCalledWith("p", expect.objectContaining({ apiKey: "prior-key" })) + expect(setValueSpy).not.toHaveBeenCalledWith("currentApiConfigName", "p") + + await provider.dispose() + }) + + it("restores the manager record and shared state when a post-delete write fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const oldProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) + await provider.setValue("currentApiConfigName", "old-profile") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => { + if ("name" in params && params.name === "old-profile") { + return { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + apiKey: "old-key", + } + } + return { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "keeper-key", + } + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + const saveSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("x") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + // The first write after the committed manager delete fails: the + // deletion must be compensated, not left half-applied. + vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key) => { + if (key === "listApiConfigMeta") { + throw new Error("state write down") + } + }) + + await expect(provider.deleteProviderProfile(oldProfile)).rejects.toThrow("state write down") + + // The secrets-backed record was restored with its pre-delete settings. + expect(saveSpy).toHaveBeenCalledWith("old-profile", expect.objectContaining({ apiKey: "old-key" })) + + await provider.dispose() + }) + + it("fails the deletion and keeps the record id when the surviving profile cannot be read", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const oldProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) + await provider.setValue("currentApiConfigName", "old-profile") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => { + if ("name" in params && params.name === "old-profile") { + return { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "old-key", + } + } + throw new Error("survivor read failed") + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + const saveSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("x") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + await expect(provider.deleteProviderProfile(oldProfile)).rejects.toThrow( + "the surviving profile 'keeper-profile' could not be loaded", + ) + // The store is the only source of the deleted record's settings: the restore + // must keep the record's own id so the mode mappings that store the id keep + // resolving to it. + expect(saveSpy).toHaveBeenCalledWith( + "old-profile", + expect.objectContaining({ id: "old-id", openRouterApiKey: "old-key" }), + ) + await provider.dispose() + }) + + it("leaves the pinned sibling views on the deleted profile when a later deletion step fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const oldProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) + await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") + sibling["viewLocalState"].currentApiConfigName = "old-profile" + sibling["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "deleted-profile-secret", + } + vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => { + if ("name" in params && params.name === "old-profile") { + return { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter } + } + return { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic } + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("x") + // The last step of the group fails, so the deletion is compensated: the + // sibling must still serve the deleted profile it was pinned to, because the + // live re-pin runs only after every other write has committed. + vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("state write down")) + await expect(provider.deleteProviderProfile(oldProfile)).rejects.toThrow("state write down") + expect(sibling["viewLocalState"].currentApiConfigName).toBe("old-profile") + expect(sibling["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "deleted-profile-secret", + }) + } finally { + await sibling.dispose() + await provider.dispose() + } + }) + + it("preserves sibling view-state fields written while a failed deletion rolls back", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const oldProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) + await provider.setValue("currentApiConfigName", "old-profile") + await provider.contextProxy.setValue("viewStates", { + "view-1": { currentApiConfigName: "old-profile", mode: "code", updatedAt: 1 }, + }) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => { + if ("name" in params && params.name === "old-profile") { + return { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter } + } + return { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic } + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("x") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + const originalSetValue = provider.contextProxy.setValue.bind(provider.contextProxy) + // A sibling view switches its mode after the deletion snapshotted viewStates but + // before the failing write; the rollback must keep that newer mode. + vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key, value) => { + if (key === "listApiConfigMeta") { + await originalSetValue("viewStates", { + "view-1": { currentApiConfigName: "old-profile", mode: "architect", updatedAt: 2 }, + }) + throw new Error("state write down") + } + return originalSetValue(key, value) + }) + + await expect(provider.deleteProviderProfile(oldProfile)).rejects.toThrow("state write down") + + const viewStates = provider.contextProxy.getValue("viewStates") as Record> + // Only the deletion's own re-point would be undone; the sibling's newer mode + // survives because the fresh entry still names the pre-deletion profile. + expect(viewStates["view-1"].mode).toBe("architect") + expect(viewStates["view-1"].currentApiConfigName).toBe("old-profile") + expect(viewStates["view-1"].updatedAt).toBe(2) + + await provider.dispose() + }) + + it("keeps the mutation queue owned by a mode switch past its timeout", async () => { + vi.useFakeTimers() + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + // Bracket access: handleModeSwitchUnlocked is private; the double + // assertion is the only way to install the gate on the prototype. + const proto = ClineProvider.prototype as unknown as { + handleModeSwitchUnlocked: (...args: unknown[]) => Promise + } + const switchSpy = vi.spyOn(proto, "handleModeSwitchUnlocked").mockReturnValue(gate) + + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + // The caller-side timeout rejection is expected: runToCompletion only + // keeps the QUEUE waiting for the run, it does not silence the caller. + const switchSettled = provider.handleModeSwitch("programmer").catch(() => undefined) + await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) + + // The queue tail is still the mode switch: a later mutation must + // not start while the switch's writes are still in flight. + let secondStarted = false + void provider["enqueueProviderProfileMutation"](async () => { + secondStarted = true + }) + await vi.advanceTimersByTimeAsync(0) + expect(secondStarted).toBe(false) + + release() + await switchSettled + await vi.advanceTimersByTimeAsync(0) + expect(secondStarted).toBe(true) + + switchSpy.mockRestore() + vi.useRealTimers() + await provider.dispose() + }) + + it("does not resurrect a pruned sibling entry that the sibling cleared mid-window", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-tomb-view") + // A full 50-entry map: the activation write evicts the oldest entry (the + // sibling's), the sibling then clears it mid-window, and the tombstone + // must outrank the tracked eviction during rollback. + const seeded: Record = { + "sibling-view": { currentApiConfigName: "sibling-profile", updatedAt: 0 }, + } + for (let i = 0; i < 49; i++) { + seeded["filler-" + i] = { currentApiConfigName: "filler-profile", updatedAt: i + 1 } + } + await provider.contextProxy.setValue("viewStates", seeded) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id") + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("old-mode-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "new-profile", + id: "rec-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("old-profile") + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "old-profile", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + // After the activation write evicted the oldest entry, the sibling + // intentionally clears it; the rollback must leave it absent. + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockImplementation(async () => { + await provider["clearPersistedViewState"]("sibling-view") + throw new Error("mode write failed") + }) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await expect( + provider.upsertProviderProfile("new-profile", { apiProvider: providerIdentifiers.anthropic }, true), + ).resolves.toBeUndefined() + + const restored = provider.contextProxy.getValue("viewStates") as Record + expect(restored["sibling-view"]).toBeUndefined() + expect(restored["filler-0"]).toBeDefined() + await provider.dispose() + }) + it("should swallow only the typed not-found signal when pruning a stale profile entry", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const staleProfile: ProviderSettingsEntry = { + name: "stale-profile", + id: "stale-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + await provider.contextProxy.setValue("listApiConfigMeta", [staleProfile, keeperProfile]) + await provider.setValue("currentApiConfigName", "keeper-profile") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + // The secret was already pruned: the typed not-found must be an idempotent + // success so the stale list entry is still removed. + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockRejectedValue( + new ProviderSettingsNotFoundError(`Config 'stale-profile' not found`), + ) + + await provider.deleteProviderProfile(staleProfile) + + expect(provider.contextProxy.getValue("listApiConfigMeta")).toEqual([keeperProfile]) + await provider.dispose() + }) + + it("should propagate a non-not-found deletion failure for a profile named like the not-found message", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const profile: ProviderSettingsEntry = { + name: "not found config", + id: "nf-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + await provider.contextProxy.setValue("listApiConfigMeta", [profile, keeperProfile]) + await provider.setValue("currentApiConfigName", "keeper-profile") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + // An unrelated failure (wrapped the way deleteConfig wraps storage errors) + // must not be mistaken for the idempotent not-found path just because the + // profile name contains "not found". + const deleteConfigSpy = vi + .spyOn(provider.providerSettingsManager, "deleteConfig") + .mockRejectedValue( + new Error(`Failed to delete config: Error: storage write failed for 'not found config'`), + ) + + await expect(provider.deleteProviderProfile(profile)).rejects.toThrow("storage write failed") + + // The list entry must remain untouched when the deletion failed. + expect(provider.contextProxy.getValue("listApiConfigMeta")).toEqual([profile, keeperProfile]) + expect(deleteConfigSpy).toHaveBeenCalledTimes(1) + await provider.dispose() + }) + + it("reconfigures a view pinned to the deleted profile even when the global selection points elsewhere", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const oldProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) + // The global selection points at the keeper profile, but this view's buffer + // is still pinned to the profile being deleted (it loaded it earlier): + // the nested overlay still carries the deleted profile's configuration. + await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") + provider["viewLocalState"].currentApiConfigName = "old-profile" + provider["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "deleted-profile-secret", + } + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + const setProviderSettingsSpy = vi.spyOn(provider.contextProxy, "setProviderSettings") + + await provider.deleteProviderProfile(oldProfile) + + // The captured pin must still trigger the reconfiguration: the shared + // provider keys and the view-local buffer both take the surviving + // profile's settings, and the nested overlay is replaced wholesale so + // no key of the deleted profile survives. + expect(setProviderSettingsSpy).toHaveBeenCalledWith( + expect.objectContaining({ apiProvider: providerIdentifiers.anthropic }), + ) + expect(provider.getValues().currentApiConfigName).toBe("keeper-profile") + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + }) + await provider.dispose() + }) + + it("does not re-point a pinned sibling's task that follows another profile when its profile is deleted", async () => { + // Defensive: the doubles in this suite can leave console writes pending + // at worker teardown. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const oldProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) + await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") + // The sibling pins the profile being deleted, but its active task + // follows a different sticky profile: the deletion must re-point the + // sibling's buffer to the surviving profile without switching that + // conversation's handler or rewriting its persisted profile name. + sibling["viewLocalState"].currentApiConfigName = "old-profile" + sibling["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "deleted-profile-secret", + } + vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) + const siblingTask = { + apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key" }, + taskApiConfigName: "other-profile", + taskId: "sibling-task", + setTaskApiConfigName: vi.fn(), + updateApiConfiguration: vi.fn(), + } + vi.spyOn(sibling, "getCurrentTask").mockReturnValue( + siblingTask as unknown as ReturnType, + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + + await provider.deleteProviderProfile(oldProfile) + + // The sibling's view buffer is still re-pointed to the surviving + // profile... + expect(sibling["viewLocalState"].currentApiConfigName).toBe("keeper-profile") + expect(sibling["viewLocalState"].apiConfiguration).toEqual({ + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + }) + // ...but the task follows another profile: neither the handler rebuild + // nor the sticky-name rewrite may touch it. + expect(siblingTask.updateApiConfiguration).not.toHaveBeenCalled() + expect(siblingTask.setTaskApiConfigName).not.toHaveBeenCalled() + // Wait on the serialized view-state write queue that every + // viewStates mutation goes through, so queued persistence finishes + // while the console spies are still installed and teardown has no + // pending writes. + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await sibling.dispose() + await provider.dispose() + } + }) + + it("reconfigures the deleting view's own task when that task runs the deleted profile", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const deletedProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + const deletedSettings: ProviderSettings = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "deleted-profile-secret", + } + const keeperSettings: ProviderSettingsWithId = { + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "keeper-key", + } + await provider.contextProxy.setValue("listApiConfigMeta", [deletedProfile, keeperProfile]) + await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") + // The deleting view pins the profile it deletes and its own active task runs + // under that same profile. The re-pin pass that rebuilds task handlers and + // re-points sticky names filters this instance out (the sibling tests below + // cover the other views), so unless this view is handled too the task keeps + // the deleted profile's handler and name while the pin and overlay already + // name the survivor, and getStateToPostToWebview prefers the task's own + // values over the replacement view state. + provider["viewLocalState"].currentApiConfigName = "old-profile" + provider["viewLocalState"].apiConfiguration = deletedSettings + const stickyWrite = vi.fn((name: string | undefined) => { + ownTask.taskApiConfigName = name ?? "" + }) + const handlerRebuild = vi.fn((settings: ProviderSettings) => { + ownTask.apiConfiguration = settings + }) + const ownTask = { + taskId: "deleting-view-task", + apiConfiguration: deletedSettings, + taskApiConfigName: "old-profile", + setTaskApiConfigName: stickyWrite, + updateApiConfiguration: handlerRebuild, + } + vi.spyOn(provider, "getCurrentTask").mockReturnValue( + // The double is structural: only the task fields this deletion path reads. + ownTask as unknown as ReturnType, + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + ...keeperSettings, + name: "keeper-profile", + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + + await provider.deleteProviderProfile(deletedProfile) + + // The durable outcome, not a call count: what the task holds and names, and + // what the posted state carries on top of the replacement view state. + const posted = await provider.getStateToPostToWebview() + expect({ + taskName: ownTask.taskApiConfigName, + taskSettings: ownTask.apiConfiguration, + postedName: posted.currentApiConfigName, + postedSettings: posted.apiConfiguration, + }).toEqual({ + taskName: "keeper-profile", + taskSettings: keeperSettings, + postedName: "keeper-profile", + postedSettings: keeperSettings, + }) + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await provider.dispose() + } + }) + + it("leaves the deleting view's task alone when that task follows another profile", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const deletedProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + const otherProfile: ProviderSettingsEntry = { + name: "other-profile", + id: "other-id", + apiProvider: providerIdentifiers.openrouter, + } + const ownSettings: ProviderSettings = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "own-task-secret", + } + await provider.contextProxy.setValue("listApiConfigMeta", [deletedProfile, keeperProfile, otherProfile]) + await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") + // Control for the guard: a view pinned to the deleted profile may hold a task + // that follows a different sticky profile. Re-pointing the pin must not switch + // that conversation or rewrite its persisted profile name, which is the same + // guard the sibling pass uses. + provider["viewLocalState"].currentApiConfigName = "old-profile" + provider["viewLocalState"].apiConfiguration = ownSettings + const stickyWrite = vi.fn((name: string | undefined) => { + ownTask.taskApiConfigName = name ?? "" + }) + const handlerRebuild = vi.fn((settings: ProviderSettings) => { + ownTask.apiConfiguration = settings + }) + const ownTask = { + taskId: "other-task", + apiConfiguration: ownSettings, + taskApiConfigName: "other-profile", + setTaskApiConfigName: stickyWrite, + updateApiConfiguration: handlerRebuild, + } + vi.spyOn(provider, "getCurrentTask").mockReturnValue( + ownTask as unknown as ReturnType, + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "keeper-key", + name: "keeper-profile", + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + + await provider.deleteProviderProfile(deletedProfile) + + const posted = await provider.getStateToPostToWebview() + expect({ + taskName: ownTask.taskApiConfigName, + taskSettings: ownTask.apiConfiguration, + stickyWrites: stickyWrite.mock.calls.length, + handlerRebuilds: handlerRebuild.mock.calls.length, + postedName: posted.currentApiConfigName, + }).toEqual({ + taskName: "other-profile", + taskSettings: ownSettings, + stickyWrites: 0, + handlerRebuilds: 0, + postedName: "other-profile", + }) + expect(provider["viewLocalState"].currentApiConfigName).toBe("keeper-profile") + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await provider.dispose() + } + }) + + it("leaves the view buffer untouched when the deleted profile is neither globally active nor view-pinned", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const oldProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + const otherProfile: ProviderSettingsEntry = { + name: "other-profile", + id: "other-id", + apiProvider: providerIdentifiers.openrouter, + } + await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile, otherProfile]) + // The global selection and this view's pin both name surviving profiles: + // the deletion must not reconfigure this view's settings, and the + // pinned view's nested overlay must survive byte-for-byte. + await provider.contextProxy.setValue("currentApiConfigName", "other-profile") + provider["viewLocalState"].currentApiConfigName = "keeper-profile" + provider["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.anthropic, + apiKey: "pinned-profile-secret", + } + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "other-profile", + id: "other-id", + apiProvider: providerIdentifiers.openrouter, + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + const setProviderSettingsSpy = vi + .spyOn(provider.contextProxy, "setProviderSettings") + .mockResolvedValue(undefined) + + await provider.deleteProviderProfile(oldProfile) + + // No reconfiguration: the guard must stay false when neither the global + // selection nor the view pin names the deleted profile, so the view + // keeps its own pin and its nested overlay while the shared store + // reports the global selection. + expect(setProviderSettingsSpy).not.toHaveBeenCalled() + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("other-profile") + expect(provider.getValues().currentApiConfigName).toBe("keeper-profile") + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "pinned-profile-secret", + }) + await provider.dispose() + }) + }) + + describe("local state isolation", () => { + it("should isolate mode state between instances", async () => { + const provider1 = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const provider2 = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider2.saveViewState("mode", "debugger") + await provider1.saveViewState("mode", "architect") + + const state1 = await provider1.getState() + const state2 = await provider2.getState() + + expect(state1.mode).toBe("architect") + expect(state2.mode).toBe("debugger") + + await provider1.dispose() + await provider2.dispose() + }) + + it("should isolate currentApiConfigName between instances", async () => { + const provider1 = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const provider2 = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + const saveViewState1 = provider1.saveViewState.bind(provider1) + const saveViewState2 = provider2.saveViewState.bind(provider2) + + await saveViewState1("currentApiConfigName", "profile-a") + await saveViewState2("currentApiConfigName", "profile-b") + + const state1 = await provider1.getState() + const state2 = await provider2.getState() + + expect(state1.currentApiConfigName).toBe("profile-a") + expect(state2.currentApiConfigName).toBe("profile-b") + + await provider1.dispose() + await provider2.dispose() + }) + }) + + describe("getState merging", () => { + it("should merge viewLocalState on top of global state", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + // Initially, getState should return values from contextProxy (global state) + let state = await provider.getState() + expect(state.mode).toBe("code") + + // After saveViewState, viewLocalState should take precedence + await provider.saveViewState("mode", "architect") + + state = await provider.getState() + expect(state.mode).toBe("architect") + + await provider.dispose() + }) + + it("should preserve global state values not overridden by viewLocalState", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider.saveViewState("mode", "architect") + + const state = await provider.getState() + + // mode should come from viewLocalState + expect(state.mode).toBe("architect") + + // Other values should still come from global state / contextProxy: the fixture's + // vscode.env.language is "en" and no custom modes are persisted. + expect(state.language).toBe("en") + expect(state.customModes).toEqual([]) + + await provider.dispose() + }) + + it("should let viewLocalState apiConfiguration override provider settings", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "local-key", + }) + + const state = await provider.getState() + + expect(state.apiConfiguration.apiProvider).toBe("openrouter") + expect(state.apiConfiguration.openRouterApiKey).toBe("local-key") + + await provider.dispose() + }) + + it("reports the fresh global apiConfiguration after a profile activation followed by a global settings write", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("activated-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "activated-profile", id: "activated-id", apiProvider: providerIdentifiers.anthropic }, + ]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await provider.upsertProviderProfile( + "activated-profile", + { apiProvider: providerIdentifiers.anthropic }, + true, + ) + + // Simulate api.setConfiguration (src/extension/api.ts): a global-only + // write that does not refresh the view-local buffer. + await provider.contextProxy.setValues({ + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "mock-key", + }) + + const state = await provider.getState({ includeTaskHistory: false }) + + // The fresh global selection must win: the activation's buffer write must + // not mask the later shared update (regression guard for the e2e + // provider-probe suites, which start tasks after a profile activation). + expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.openrouter) + await provider.dispose() + }) + + it("does not fill a pinned profile's omitted keys from the shared profile", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The pinned profile defines only its provider and key. + await provider.saveViewState("currentApiConfigName", "pinned-profile") + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "pinned-key", + }) + await provider.contextProxy.setProviderSettings({ + apiProvider: providerIdentifiers.openai, + openAiApiKey: "shared-key", + openAiBaseUrl: "https://shared.example", + }) + + const state = await provider.getState({ includeTaskHistory: false }) + + // A view-local profile is a complete snapshot, not a patch: a key the profile + // never defined must not leak in from the shared profile. + expect(state.apiConfiguration.openRouterApiKey).toBe("pinned-key") + expect(state.apiConfiguration).not.toHaveProperty("openAiBaseUrl") + expect(state.apiConfiguration).not.toHaveProperty("openAiApiKey") + await provider.dispose() + }) + + it("clears this view's buffered apiConfiguration when activating a different profile", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Seed the per-view buffer with profile A's settings, as loadViewState would + // after a restart with a pinned profile. + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "profile-a-key", + }) + + // Typed spies on the real manager (instance-scoped): the upsert-activate path + // reads only these methods, so no manager replacement is needed. + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("profile-b-id") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "profile-b", + id: "profile-b-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "profile-b", id: "profile-b-id", apiProvider: providerIdentifiers.anthropic }, + ]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await provider.upsertProviderProfile("profile-b", { apiProvider: providerIdentifiers.anthropic }, true) + + const state = await provider.getState({ includeTaskHistory: false }) + + // Activating profile B must clear profile A's buffered overlay so the shared + // settings (written by setProviderSettings) win; otherwise getState would + // report profile B's name with profile A's provider. + expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) + await provider.dispose() + }) + it("rolls back the profile activation writes when one concurrent write fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Seed the prior shared selection so the rollback restores a real state. + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + await provider.contextProxy.setValue("listApiConfigMeta", [ + { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.anthropic }, + ]) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "new-profile", id: "new-id", apiProvider: providerIdentifiers.openai }, + ]) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("old-mode-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "new-profile", + id: "old-rec-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("old-profile") + const activateProfileSpy = vi + .spyOn(provider.providerSettingsManager, "activateProfile") + .mockResolvedValue({ name: "old-profile", apiProvider: providerIdentifiers.anthropic }) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockRejectedValue( + new Error("mode write failed"), + ) + const setProviderSettingsSpy = vi.spyOn(provider.contextProxy, "setProviderSettings") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + // The outer upsert catch converts the failure into an undefined id (the + // user sees the error toast); the compensation must still have run. + await expect( + provider.upsertProviderProfile("new-profile", { apiProvider: providerIdentifiers.openai }, true), + ).resolves.toBeUndefined() + + // Every write that landed is compensated: the mode mapping returns to its + // prior id, and the selection, list, and shared settings are restored. + expect(provider.providerSettingsManager.setModeConfig).toHaveBeenCalledWith("code", "old-mode-id") + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile") + expect((provider.contextProxy.getValue("listApiConfigMeta") ?? []).map((entry) => entry.name)).toEqual([ + "old-profile", + ]) + expect(setProviderSettingsSpy).toHaveBeenCalledTimes(2) + // The manager store is compensated too: the record written by saveConfig + // returns to its prior content and the manager selection returns to the + // prior profile. + expect(provider.providerSettingsManager.saveConfig).toHaveBeenCalledWith("new-profile", { + id: "old-rec-id", + apiProvider: providerIdentifiers.anthropic, + }) + expect(activateProfileSpy).toHaveBeenCalledWith({ name: "old-profile" }) + await provider.dispose() + }) + it("rolls back the direct activation writes when one concurrent write fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Seed the prior shared selection so the rollback restores a real state. + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + await provider.contextProxy.setValue("listApiConfigMeta", [ + { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.anthropic }, + ]) + // Typed spies on the real manager (instance-scoped): the direct-activation path reads only + // these methods, so the manager stays in place and a method the path starts calling later is + // still the real one rather than undefined. + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "new-profile", + id: "new-id", + apiProvider: providerIdentifiers.openai, + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "new-profile", id: "new-id", apiProvider: providerIdentifiers.openai }, + ]) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("old-profile") + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider.contextProxy, "setProviderSettings").mockRejectedValue( + new Error("shared settings write failed"), + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await expect(provider.activateProviderProfile({ name: "new-profile" })).rejects.toThrow( + "shared settings write failed", + ) + + // The compensation waits for every group write to settle before restoring: + // the selection and the profile list return to the prior state even though + // the shared settings write rejected mid-group. + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile") + const restoredEntries = (provider.contextProxy.getValue("listApiConfigMeta") ?? []).map( + (entry) => entry.name, + ) + expect(restoredEntries).toEqual(["old-profile"]) + await provider.dispose() + }) + it("re-points closed views' persisted pins onto the surviving profile after a deletion", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-delete-view") + // A closed view's durable pin and this view's own pin both name the doomed + // profile; the deletion must move them to the survivor. + await provider.contextProxy.setValue("viewStates", { + "closed-view": { currentApiConfigName: "doomed-profile", updatedAt: 1 }, + "stable-delete-view": { mode: "code", currentApiConfigName: "doomed-profile", updatedAt: 2 }, + }) + await provider.contextProxy.setValue("listApiConfigMeta", [ + { name: "doomed-profile", id: "doomed-id", apiProvider: providerIdentifiers.anthropic }, + { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.openrouter }, + ]) + await provider.saveViewState("currentApiConfigName", "doomed-profile") + // The deleted profile is the shared selection: the survivor resolution needs it. + await provider.contextProxy.setValue("currentApiConfigName", "doomed-profile") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.openrouter, + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("keeper-id") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await provider.deleteProviderProfile({ + name: "doomed-profile", + id: "doomed-id", + apiProvider: providerIdentifiers.anthropic, + }) + + const states = provider.contextProxy.getValue("viewStates") as Record> + expect(states["closed-view"].currentApiConfigName).toBe("keeper-profile") + await provider.dispose() + }) + + it("upserts activation writes from the stored normalized record, not the raw payload", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("profile-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue(undefined) + // The stored record is the normalized shape saveConfig persists: the schema + // parse strips the stray cross-provider field and keeps the stored model. + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + id: "profile-id", + name: "profile-a", + apiProvider: providerIdentifiers.anthropic, + apiModelId: "stored-model", + }) + const setProviderSettingsSpy = vi.spyOn(provider.contextProxy, "setProviderSettings") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await provider.upsertProviderProfile("profile-a", { + apiProvider: providerIdentifiers.anthropic, + apiModelId: "raw-model", + openRouterApiKey: "cross-provider-stray", + }) + + // The shared store receives the stored record: the raw payload's stray + // cross-provider field must not reach it (or the sibling overlays and + // task handler refreshed from the same value). + expect(setProviderSettingsSpy).toHaveBeenCalledWith({ + apiProvider: providerIdentifiers.anthropic, + apiModelId: "stored-model", + }) + await provider.dispose() + }) + + it("deletes the newly created manager record when a later activation write fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The profile is new: hasConfig confirms absence even though getProfile + // reports it through an untyped wrapper error. + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(false) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockRejectedValue( + new Error("Config with name 'new-profile' not found"), + ) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "new-profile", id: "new-id", apiProvider: providerIdentifiers.openai }, + ]) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockRejectedValue( + new Error("mode write failed"), + ) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("old-profile") + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "old-profile", + apiProvider: providerIdentifiers.anthropic, + }) + const deleteConfigSpy = vi + .spyOn(provider.providerSettingsManager, "deleteConfig") + .mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await expect( + provider.upsertProviderProfile("new-profile", { apiProvider: providerIdentifiers.openai }, true), + ).resolves.toBeUndefined() + + // Compensation must delete the record the mutation created, not skip the + // restore because the lookup threw an untyped not-found. + expect(deleteConfigSpy).toHaveBeenCalledWith("new-profile") + await provider.dispose() + }) + + it("refreshes this view's buffer when a pinned profile is saved without activation", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Seed the per-view buffer as loadViewState would after a restart with a + // pinned profile: the pin and a full copy of its settings. + await provider.saveViewState("currentApiConfigName", "pinned-profile") + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.zooGateway, + zooSessionToken: "old-token", + }) + + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("pinned-id") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "pinned-profile", + id: "pinned-id", + apiProvider: providerIdentifiers.zooGateway, + zooSessionToken: "new-token", + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "pinned-profile", id: "pinned-id", apiProvider: providerIdentifiers.zooGateway }, + ]) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + // A token refresh saves the pinned profile without activating it. + await provider.upsertProviderProfile( + "pinned-profile", + { apiProvider: providerIdentifiers.zooGateway, zooSessionToken: "new-token" }, + false, + ) + + // The buffer must not keep serving the token captured before the save. + const state = await provider.getState({ includeTaskHistory: false }) + expect(state.apiConfiguration.zooSessionToken).toBe("new-token") + await provider.dispose() + }) + + it("keeps the mode mapping on the profile a successful activation saved", async () => { + // Review thread 4593061270, whose node id in my capture is + // PRRT_kwDOSK-bwM64MFr-, printed at ClineProvider.ts line 3410 with + // original_line 3410 and unresolved: the activation group updated the + // manager's mode mapping only, so this provider's own cache kept the + // pre-save profile and a later switch back to the mode selected it again. + // The assertion below reads what a later switch sees, not how many times a + // setter was called. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("y-id") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "y-profile", + id: "y-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "x-profile", id: "x-id", apiProvider: providerIdentifiers.anthropic }, + { name: "y-profile", id: "y-id", apiProvider: providerIdentifiers.anthropic }, + ]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("x-id") + vi.spyOn(provider.providerSettingsManager, "getModeConfigIds").mockResolvedValue({ code: "x-id" }) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + // The opening mapping is code -> x-id, in both caches a switch reads. + provider["localModeConfigIds"].set("code", "x-id") + provider["initialModeConfigIds"] = Promise.resolve({ code: "x-id" }) + await provider["updateGlobalState"]("mode", "code") + await provider.setValue("currentApiConfigName", "x-profile") + + // Saving and activating y-profile for the current mode. + await provider.upsertProviderProfile("y-profile", { apiProvider: providerIdentifiers.anthropic }, true) + + // Switch away and back, which is how a stale mapping surfaces. + await provider.handleModeSwitch("architect") + await provider.handleModeSwitch("code") + + expect(await provider["getModeConfigId"]("code")).toBe("y-id") + expect(provider.getValues().currentApiConfigName).toBe("y-profile") + + await provider.dispose() + }) + + it("does not delete a newly created record while another create for the same name is in flight", async () => { + const providerA = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const providerB = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + for (const instance of [providerA, providerB]) { + vi.spyOn(instance.providerSettingsManager, "hasConfig").mockResolvedValue(false) + vi.spyOn(instance.providerSettingsManager, "getCurrentProfileName").mockResolvedValue(undefined) + } + const deleteSpyA = vi.spyOn(providerA.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + const deleteSpyB = vi.spyOn(providerB.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + + // Both views confirm the name is absent before saving it: each create is + // claimed so a rollback can tell whose deletion is safe. + const snapshotA = await providerA["_snapshotProviderManagerState"]("dup-profile") + const snapshotB = await providerB["_snapshotProviderManagerState"]("dup-profile") + expect(snapshotA.claimedCreate).toBe(true) + expect(snapshotB.claimedCreate).toBe(true) + + // A's activation fails while B's create for the same name is still in + // flight: the surviving record may belong to B, so A must not delete it. + await providerA["_restoreProviderManagerRecord"]("dup-profile", snapshotA) + expect(deleteSpyA).not.toHaveBeenCalled() + + // B fails too: the last claimant to settle owns the deletion. + await providerB["_restoreProviderManagerRecord"]("dup-profile", snapshotB) + expect(deleteSpyB).toHaveBeenCalledWith("dup-profile") + + await providerA.dispose() + await providerB.dispose() + }) + + it("keeps the record when a sibling create succeeded before this create failed", async () => { + const providerA = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const providerB = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + for (const instance of [providerA, providerB]) { + vi.spyOn(instance.providerSettingsManager, "hasConfig").mockResolvedValue(false) + vi.spyOn(instance.providerSettingsManager, "getCurrentProfileName").mockResolvedValue(undefined) + vi.spyOn(instance.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(instance.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + vi.spyOn(instance.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(instance.providerSettingsManager, "saveConfig").mockResolvedValue("b-id") + vi.spyOn(instance.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "dup-profile", + id: "b-id", + apiProvider: providerIdentifiers.openai, + }) + vi.spyOn(instance.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "dup-profile", + id: "b-id", + apiProvider: providerIdentifiers.openai, + }) + vi.spyOn(instance, "postStateToWebview").mockResolvedValue(undefined) + } + const deleteSpyA = vi.spyOn(providerA.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + + // A confirms the name is absent and claims the create. + const snapshotA = await providerA["_snapshotProviderManagerState"]("dup-profile") + expect(snapshotA.claimedCreate).toBe(true) + + // B creates the same profile successfully: its claim is spent and the + // record belongs to B's save. + await expect( + providerB.upsertProviderProfile("dup-profile", { apiProvider: providerIdentifiers.openai }, true), + ).resolves.toBe("b-id") + + // A's activation group fails after B already landed: deleting would + // discard the profile B saved. + await providerA["_restoreProviderManagerRecord"]("dup-profile", snapshotA) + expect(deleteSpyA).not.toHaveBeenCalled() + + // The bookkeeping is cleared once the last claimant settles: a later + // failed create for the same name owns its deletion again. + const snapshotA2 = await providerA["_snapshotProviderManagerState"]("dup-profile") + await providerA["_restoreProviderManagerRecord"]("dup-profile", snapshotA2) + expect(deleteSpyA).toHaveBeenCalledWith("dup-profile") + + await providerA.dispose() + await providerB.dispose() + }) + + it("spends the create claim when the profile save itself fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(false) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue(undefined) + const deleteSpy = vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig") + .mockRejectedValueOnce(new Error("store write failed")) + .mockResolvedValue("profile-id") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + // The first create fails inside saveConfig: its rollback must spend the claim + // even though the record write itself is what failed. + await provider.upsertProviderProfile("leaky-profile", { apiProvider: providerIdentifiers.openai }, false) + + // A second create of the same name now fails during activation instead. + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockRejectedValue( + new Error("mode write failed"), + ) + await provider.upsertProviderProfile("leaky-profile", { apiProvider: providerIdentifiers.openai }, true) + + // A claim leaked by the first create would make this rollback defer to a + // create that never happened and strand the landed record: the deletion + // must land. + expect(deleteSpy).toHaveBeenCalledWith("leaky-profile") + await provider.dispose() + }) + + it("keeps this view's own profile pin when an activation rollback restores the shared selection", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-sidebar-view") + // The view pins profile-a while another view's choice sits in the shared + // selection. + await provider.saveViewState("currentApiConfigName", "profile-a") + await provider.contextProxy.setValue("currentApiConfigName", "profile-b") + + const snapshot = provider["_snapshotProfileActivationState"]() + // The activation moved the shared selection; a later write failed. + await provider.setValue("currentApiConfigName", "profile-c") + await provider["_restoreProfileActivationState"](snapshot) + + // The shared selection returns to its prior value... + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("profile-b") + // ...but this view's own pin is restored to its own choice, not the + // shared one: the rollback must not replace the pin with profile-b. + expect(provider["viewLocalState"].currentApiConfigName).toBe("profile-a") + const viewStates = mockContext.globalState.get("viewStates") as Record> + expect(viewStates["stable-sidebar-view"].currentApiConfigName).toBe("profile-a") + await provider.dispose() + }) + + it("does not rewrite unrelated global keys when an activation rollback restores provider settings", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const snapshot = provider["_snapshotProfileActivationState"]() + // An unrelated key legitimately changes while the activation group is in + // flight. + await provider.contextProxy.setValue("customInstructions", "written during activation") + await provider["_restoreProfileActivationState"](snapshot) + // The rollback restores provider settings only; it must not replay the + // whole global-state copy over keys that moved in the meantime. + expect(provider.contextProxy.getValue("customInstructions")).toBe("written during activation") + await provider.dispose() + }) + + it("restores the cached viewStates map when a persisted view-state write fails durably", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-sidebar-view") + await provider.contextProxy.setValue("viewStates", { + "other-view": { mode: "code", updatedAt: 1 }, + }) + // The next durable write fails; the cache was already updated optimistically. + const updateSpy = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { + throw new Error("durable write failed") + }) + + await expect(provider["savePersistedViewState"]({ mode: "architect", updatedAt: 2 })).rejects.toThrow( + "durable write failed", + ) + + // The in-memory cache must match durable storage: an entry that never + // reached disk cannot stay visible through getValue. + expect(provider.contextProxy.getValue("viewStates")).toEqual({ + "other-view": { mode: "code", updatedAt: 1 }, + }) + updateSpy.mockRestore() + await provider.dispose() + }) + + it("restores the cached viewStates map when a re-key write fails durably", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Seed a pre-launch entry under the temporary id through the real write + // path, so the re-key has a real entry to move and this instance authored it. + await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) + + // The re-key's durable write fails; the cache was already updated optimistically. + const updateSpy = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { + throw new Error("durable write failed") + }) + + await expect(provider["rekeyPersistedViewStateEntry"]("stable-sidebar-view")).rejects.toThrow( + "durable write failed", + ) + + // The cache must match durable storage: the stable entry never reached disk, + // and the retry path depends on the temporary entry still being visible. + expect(provider.contextProxy.getValue("viewStates")).toEqual({ + [provider.viewId]: { mode: "architect", updatedAt: 1 }, + }) + // Authorship survives the failure so a later registration can re-key again. + expect(provider["wroteUnderTemporaryViewStateId"]).toBe(true) + updateSpy.mockRestore() + await provider.dispose() + }) + + it("drops the clear tombstone when the durable clear write fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-tomb-view") + await provider.contextProxy.setValue("viewStates", { + "victim-view": { currentApiConfigName: "victim-profile", updatedAt: 1 }, + }) + // The clear's durable write rejects: the entry it removed from the cache is + // still stored, so the tombstone this call added has to come back off - a + // later activation that prunes the entry would otherwise skip the rollback + // restore and lose an entry no clear ever removed. + const clearFailure = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { + throw new Error("durable clear failed") + }) + + await expect(provider["clearPersistedViewState"]("victim-view")).rejects.toThrow("durable clear failed") + clearFailure.mockRestore() + + expect(ClineProvider["clearedViewStateIds"].has("victim-view")).toBe(false) + const afterClear = provider.contextProxy.getValue("viewStates") as Record + expect(afterClear["victim-view"]).toBeDefined() + await provider.dispose() + }) + + it("restores the cached viewStates map when a clear write fails durably", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-sidebar-view") + await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) + + // The clear's durable write fails; the cache was already updated optimistically. + const updateSpy = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { + throw new Error("durable write failed") + }) + + await expect(provider["clearPersistedViewState"]()).rejects.toThrow("durable write failed") + + // The cache must match durable storage: the entry was never removed on + // disk, so it must stay visible through getValue. + expect(provider.contextProxy.getValue("viewStates")).toEqual({ + "stable-sidebar-view": { mode: "architect", updatedAt: 1 }, + }) + updateSpy.mockRestore() + await provider.dispose() + }) + + it("restores the cached viewStates map when a persisted re-point write fails durably", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("viewStates", { + "stable-sidebar-view": { currentApiConfigName: "profile-old", updatedAt: 1 }, + "other-view": { mode: "code", currentApiConfigName: "profile-keep", updatedAt: 2 }, + }) + + // The re-point's durable write fails; the cache was already updated optimistically. + const updateSpy = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { + throw new Error("durable write failed") + }) + + await expect(provider["repointPersistedViewStates"]("profile-old", "profile-new")).rejects.toThrow( + "durable write failed", + ) + + // The cache must match durable storage: the re-pointed pins never reached disk, + // so the pre-re-point map must stay visible. + expect(provider.contextProxy.getValue("viewStates")).toEqual({ + "stable-sidebar-view": { currentApiConfigName: "profile-old", updatedAt: 1 }, + "other-view": { mode: "code", currentApiConfigName: "profile-keep", updatedAt: 2 }, + }) + updateSpy.mockRestore() + await provider.dispose() + }) + + it("restores the complete durable viewStates map when an activation rollback follows a pruning pin write", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-activation-view") + // A full map: the activation's own pin write prunes the oldest entry. + const seeded: Record = {} + for (let i = 1; i <= 50; i++) { + seeded["view-" + i] = { mode: "code", updatedAt: i } + } + await provider.contextProxy.setValue("viewStates", seeded) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("old-mode-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "new-profile", + id: "rec-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("old-profile") + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "old-profile", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockRejectedValue( + new Error("mode write failed"), + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + // The outer upsert catch converts the failure into an undefined id. + await expect( + provider.upsertProviderProfile("new-profile", { apiProvider: providerIdentifiers.anthropic }, true), + ).resolves.toBeUndefined() + + // The rollback restores the exact pre-activation map: the sibling the + // pruning evicted is back with its original metadata. + const restored = provider.contextProxy.getValue("viewStates") as Record + expect(restored["view-1"]).toEqual({ mode: "code", updatedAt: 1 }) + await provider.dispose() + }) + it("keeps sibling viewStates writes that land during an activation rollback", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-merge-view") + await provider.contextProxy.setValue("viewStates", { "old-view": { mode: "code", updatedAt: 1 } }) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id") + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("old-mode-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "new-profile", + id: "rec-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("old-profile") + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "old-profile", + apiProvider: providerIdentifiers.anthropic, + }) + // A sibling instance persists its own entry while the activation group is + // in flight; the rollback must not replay the stale snapshot over it. + vi.spyOn(provider.providerSettingsManager, "listConfig").mockImplementation(async () => { + const current = (provider.contextProxy.getValue("viewStates") ?? {}) as Record + await provider.contextProxy.setValue("viewStates", { + ...current, + "sibling-view": { mode: "architect", updatedAt: 99 }, + }) + return [] + }) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockRejectedValue( + new Error("mode write failed"), + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + // The outer upsert catch converts the failure into an undefined id. + await expect( + provider.upsertProviderProfile("new-profile", { apiProvider: providerIdentifiers.anthropic }, true), + ).resolves.toBeUndefined() + + // The rollback restores what the activation pruned without erasing the + // sibling's newer entry. + const restored = provider.contextProxy.getValue("viewStates") as Record + expect(restored["sibling-view"]).toEqual({ mode: "architect", updatedAt: 99 }) + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile") + await provider.dispose() + }) + + it("does not resurrect a sibling pin cleared after the activation snapshot", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-clear-view") + await provider.contextProxy.setValue("viewStates", { + "sibling-view": { currentApiConfigName: "sibling-profile", updatedAt: 5 }, + "old-view": { mode: "code", updatedAt: 1 }, + }) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id") + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("old-mode-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "new-profile", + id: "rec-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("old-profile") + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "old-profile", + apiProvider: providerIdentifiers.anthropic, + }) + // Mid-group, after the rollback snapshot, the sibling intentionally clears + // its only persisted selection: the deletion is newer than the snapshot and + // must survive the rollback. + vi.spyOn(provider.providerSettingsManager, "listConfig").mockImplementation(async () => { + const current = (provider.contextProxy.getValue("viewStates") ?? {}) as Record< + string, + { mode?: string; currentApiConfigName?: string; updatedAt?: number } + > + delete current["sibling-view"] + await provider.contextProxy.setValue("viewStates", { ...current }) + return [] + }) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockRejectedValue( + new Error("mode write failed"), + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + // The outer upsert catch converts the failure into an undefined id. + await expect( + provider.upsertProviderProfile("new-profile", { apiProvider: providerIdentifiers.anthropic }, true), + ).resolves.toBeUndefined() + + const restored = provider.contextProxy.getValue("viewStates") as Record + // The rollback must not treat the sibling's clear as activation pruning. + expect(restored["sibling-view"]).toBeUndefined() + expect(restored["old-view"]).toEqual({ mode: "code", updatedAt: 1 }) + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile") + await provider.dispose() + }) + + it("re-points live views pinned to a renamed profile onto the new name", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("currentApiConfigName", "profile-old") + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "old-key", + }) + + await provider["repointViewLocalStateAfterProfileRename"]("profile-old", "profile-new", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "renamed-key", + }) + + expect(provider["viewLocalState"].currentApiConfigName).toBe("profile-new") + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "renamed-key", + }) + const viewStates = mockContext.globalState.get("viewStates") as Record> + expect(viewStates["stable-sidebar-view"].currentApiConfigName).toBe("profile-new") + await provider.dispose() + }) + it("re-points persisted pins of closed views onto the renamed profile", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // A closed view's durable pin names the profile about to be renamed; no + // live instance carries it, so only the persisted map can repair it. + await provider.contextProxy.setValue("viewStates", { + "closed-view": { currentApiConfigName: "profile-old", mode: "code", updatedAt: 1 }, + }) + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("currentApiConfigName", "profile-old") + + await provider["repointViewLocalStateAfterProfileRename"]("profile-old", "profile-new", { + apiProvider: providerIdentifiers.openrouter, + }) + + const viewStates = mockContext.globalState.get("viewStates") as Record> + // The closed view must launch onto the renamed profile instead of dangling at + // the deleted name and being repaired to whatever the shared selection became + // in the meantime. + expect(viewStates["closed-view"].currentApiConfigName).toBe("profile-new") + expect(viewStates["stable-sidebar-view"].currentApiConfigName).toBe("profile-new") + await provider.dispose() + }) + + it("clears this view's buffered apiConfiguration when directly activating a profile", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Seed the per-view buffer with profile A's settings, as loadViewState would + // after a restart with a pinned profile. + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "profile-a-key", + }) + + // Typed spies on the real manager (instance-scoped): the direct-activation path + // reads only these methods, so no manager replacement is needed. + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "profile-b", + id: "profile-b-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "profile-b", id: "profile-b-id", apiProvider: providerIdentifiers.anthropic }, + ]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + // The direct-activation path (activateProviderProfileUnlocked) carries its own + // overlay-clearing call, distinct from upsertProviderProfile's. + await provider.activateProviderProfile({ name: "profile-b" }) + + const state = await provider.getState({ includeTaskHistory: false }) + + expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) + await provider.dispose() + }) + + it("should merge getValues from ContextProxy with view-local values taking precedence", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const contextProxyAccess = provider.contextProxy as { + setValues: (values: Partial) => Promise + } + await contextProxyAccess.setValues({ + mode: "debugger", + currentApiConfigName: "shared-profile", + apiConfiguration: { + apiProvider: providerIdentifiers.anthropic, + apiKey: "shared-key", + }, + customModePrompts: { code: { roleDefinition: "shared" } }, + }) + + await provider.saveViewState("mode", "architect") + await provider.saveViewState("currentApiConfigName", "view-profile") + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "view-key", + }) + + const values = provider.getValues() + + expect(values.mode).toBe("architect") + expect(values.currentApiConfigName).toBe("view-profile") + expect(values.apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "view-key", + }) + expect(values.customModePrompts).toEqual({ code: { roleDefinition: "shared" } }) + + await provider.dispose() + }) + + it("should keep flat provider settings out of the view-local buffer", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "openrouter/old-model", + }) + + await provider.setValues({ + apiProvider: providerIdentifiers.bedrock, + awsUseApiKey: true, + awsApiKey: "mock-key", + awsRegion: "us-east-1", + apiModelId: "anthropic.claude-opus-4-8-20261215-v1:0", + awsBedrockEndpoint: "http://127.0.0.1:4567", + awsBedrockEndpointEnabled: true, + }) + + // Flat provider-settings keys are shared settings: they must flow through + // the ContextProxy only and must not be merged into the view-local buffer, + // which would turn them into a per-view override masking later shared + // updates from other views. The explicit view-local override survives. + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "openrouter/old-model", + }) + expect(provider.contextProxy.getValue("apiProvider")).toBe(providerIdentifiers.bedrock) + expect(provider.contextProxy.getValue("awsBedrockEndpoint")).toBe("http://127.0.0.1:4567") + + await provider.dispose() + }) + + it("should persist setValue mutations for view-local mode", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider["setViewStateId"]("stable-sidebar-view") + await provider.setValue("mode", "architect") + + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + "stable-sidebar-view": { mode: "architect" }, + }) + + await provider.dispose() + }) + + it("should persist setValues mutations for view-local API profile", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider["setViewStateId"]("stable-sidebar-view") + await provider.setValues({ currentApiConfigName: "profile-from-set-values" }) + + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + "stable-sidebar-view": { currentApiConfigName: "profile-from-set-values" }, + }) + + await provider.dispose() + }) + + it("should drop an unknown mode from setValues while keeping valid modes", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + // This file's getModeBySlug mock resolves every slug; narrow it to the slugs + // under test so "not-a-real-mode" is rejected like the real lookup would. + const modesModule = vi.mocked(await import("../../../shared/modes")) + const originalMode = modesModule.getModeBySlug("code") + modesModule.getModeBySlug.mockImplementation(((slug: string) => + ["code", "architect"].includes(slug) ? { slug } : undefined) as typeof modesModule.getModeBySlug) + + try { + await provider.setValues({ mode: "not-a-real-mode" }) + + expect(provider.contextProxy.getValue("mode")).toBeUndefined() + expect(provider["viewLocalState"].mode).toBeUndefined() + + await provider.setValues({ mode: "architect" }) + + expect(provider.contextProxy.getValue("mode")).toBe("architect") + expect(provider["viewLocalState"].mode).toBe("architect") + } finally { + modesModule.getModeBySlug.mockReturnValue(originalMode) + } + + await provider.dispose() + }) + + it("should keep a mode whose custom definition arrives in the same setValues payload", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + // createTask and setConfiguration call setValues(configuration) before + // registering configuration.customModes: the payload's own modes must count + // as valid even though the manager has not registered them yet. + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + const modesModule = vi.mocked(await import("../../../shared/modes")) + const originalMode = modesModule.getModeBySlug("code") + modesModule.getModeBySlug.mockImplementation(((slug: string, customModes?: { slug: string }[]) => + customModes?.some((mode) => mode.slug === slug) + ? { slug } + : undefined) as typeof modesModule.getModeBySlug) + + try { + await provider.setValues({ + customModes: [{ slug: "new-mode", name: "New Mode", roleDefinition: "test", groups: ["read"] }], + mode: "new-mode", + }) + + expect(provider.contextProxy.getValue("mode")).toBe("new-mode") + expect(provider["viewLocalState"].mode).toBe("new-mode") + } finally { + modesModule.getModeBySlug.mockReturnValue(originalMode) + } + + await provider.dispose() + }) + + it("deregisters the provider even when MCP cleanup rejects during dispose", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + // An MCP client whose disposal rejects used to abort dispose() before + // the registry cleanup below it: the provider stayed in activeInstances + // while _disposed was already set, so no later retry could repair the + // registration. Deregistration now runs in a finally path. + provider["mcpHub"] = { + unregisterClient: vi.fn().mockRejectedValue(new Error("mcp disposal down")), + } as unknown as ClineProvider["mcpHub"] + expect(ClineProvider.getAllInstances()).toContain(provider) + + await expect(provider.dispose()).rejects.toThrow("mcp disposal down") + + expect(ClineProvider.getAllInstances()).not.toContain(provider) + }) + + it("restores the previous mode when custom-mode registration fails during createTask", async () => { + await provider.setValues({ mode: "architect" }) + // setValues mirrors the write into the view buffer; drop it so this case + // models a view that never pinned a mode of its own. + delete provider["viewLocalState"].mode + provider["customModesManager"].updateCustomMode = vi.fn().mockRejectedValue(new Error("registration down")) + + await expect( + provider.createTask( + undefined, + undefined, + undefined, + {}, + { + mode: "reviewer", + customModes: [ + { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, + ], + }, + ), + ).rejects.toThrow("registration down") + + // The payload's mode reached shared + per-view state through setValues + // before registration failed; the failure path must roll both back. + expect(provider.getValues().mode).toBe("architect") + // The view had no pin before, and an unset pin must stay unset rather + // than becoming an explicit copy of the shared value. + expect(provider["viewLocalState"].mode).toBeUndefined() + }) + + it("restores the view's own mode pin separately when custom-mode registration fails", async () => { + await provider.setValues({ mode: "code" }) + provider["viewLocalState"].mode = "architect" + provider["customModesManager"].updateCustomMode = vi.fn().mockRejectedValue(new Error("registration down")) + + await expect( + provider.createTask( + undefined, + undefined, + undefined, + {}, + { + mode: "reviewer", + customModes: [ + { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, + ], + }, + ), + ).rejects.toThrow("registration down") + + // Shared and per-view selections roll back to their own prior values: + // the view keeps its architect pin, the shared store keeps code. + expect(provider["viewLocalState"].mode).toBe("architect") + expect(provider.contextProxy.getValue("mode")).toBe("code") + expect(provider.getValues().mode).toBe("architect") + }) + + it("rolls both mode layers back when profile activation fails before custom-mode registration", async () => { + await provider.setValues({ mode: "code" }) + await provider.saveViewState("mode", "architect") + // The ask's scenario is a payload naming a profile that does not exist. The activation + // stub below stands in for the rejection setProviderProfile raises, and the row below + // asserts the rejection is this planted error object, so a reader can tell the failure + // under test is the one planted here and not a casualty of the surrounding setup. + const activationFailure = new Error("profile activation down") + const activateSpy = vi.spyOn(provider, "activateProviderProfile").mockRejectedValue(activationFailure) + const updateCustomMode = vi.fn().mockResolvedValue(undefined) + provider["customModesManager"].updateCustomMode = updateCustomMode + + await expect( + provider.createTask( + undefined, + undefined, + undefined, + {}, + { + mode: "reviewer", + currentApiConfigName: "missing-profile", + customModes: [ + { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, + ], + }, + ), + ).rejects.toBe(activationFailure) + + expect(activateSpy).toHaveBeenCalledTimes(1) + expect(activateSpy).toHaveBeenCalledWith({ name: "missing-profile" }) + // Never called: the payload died in profile activation, so the failure sits in the + // stretch that runs ahead of the registration loop, which is the window the fix widens. + expect(updateCustomMode).not.toHaveBeenCalled() + + // Each layer returns to its own prior selection: the shared store keeps code, the + // view keeps its architect pin, rather than both holding the payload's reviewer. + expect(provider.contextProxy.getValue("mode")).toBe("code") + expect(provider["viewLocalState"].mode).toBe("architect") + }) + + it("leaves an unset view mode pin unset when profile activation fails before custom-mode registration", async () => { + await provider.setValues({ mode: "architect" }) + // setValues mirrors the payload into the view buffer; drop it so this row models a + // view that never pinned a mode of its own. + delete provider["viewLocalState"].mode + const activationFailure = new Error("profile activation down") + vi.spyOn(provider, "activateProviderProfile").mockRejectedValue(activationFailure) + provider["customModesManager"].updateCustomMode = vi.fn().mockResolvedValue(undefined) + + await expect( + provider.createTask( + undefined, + undefined, + undefined, + {}, + { + mode: "reviewer", + currentApiConfigName: "missing-profile", + customModes: [ + { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, + ], + }, + ), + ).rejects.toBe(activationFailure) + + expect(provider["customModesManager"].updateCustomMode).not.toHaveBeenCalled() + expect(provider.contextProxy.getValue("mode")).toBe("architect") + // An unset pin stays unset instead of becoming an explicit copy of the shared value. + expect(provider["viewLocalState"].mode).toBeUndefined() + }) + + it("does not restore either mode layer when a failure follows successful custom-mode registration", async () => { + await provider.setValues({ mode: "code" }) + await provider.saveViewState("mode", "architect") + const updateCustomMode = vi.fn().mockResolvedValue(undefined) + provider["customModesManager"].updateCustomMode = updateCustomMode + // The ask leaves restoration alone once registration succeeds, so the failure here + // lands after the loop, on the task-configuration read. + vi.spyOn(provider, "getState").mockRejectedValue(new Error("state read down")) + + await expect( + provider.createTask( + undefined, + undefined, + undefined, + {}, + { + mode: "reviewer", + customModes: [ + { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, + ], + }, + ), + ).rejects.toThrow("state read down") + + expect(updateCustomMode).toHaveBeenCalledTimes(1) + expect(provider.contextProxy.getValue("mode")).toBe("reviewer") + expect(provider["viewLocalState"].mode).toBe("reviewer") + }) + + it("restores the view pin and rewrites an unchanged shared mode when activation fails before registration", async () => { + await provider.setValues({ mode: "code" }) + await provider.saveViewState("mode", "architect") + const activationFailure = new Error("profile activation down") + vi.spyOn(provider, "activateProviderProfile").mockRejectedValue(activationFailure) + provider["customModesManager"].updateCustomMode = vi.fn().mockResolvedValue(undefined) + + // The payload's mode equals the shared prior value, so the shared layer gains nothing + // new from the rollback while the per-view layer does: the pin comes back from + // reviewer to architect. The shared layer is re-served its own prior value, which is + // an added same-value write on a path that previously ran no restore at all. + await expect( + provider.createTask( + undefined, + undefined, + undefined, + {}, + { + mode: "code", + currentApiConfigName: "missing-profile", + customModes: [{ slug: "code", name: "Code", roleDefinition: "Writes code", groups: [] }], + }, + ), + ).rejects.toBe(activationFailure) + + expect(provider["viewLocalState"].mode).toBe("architect") + expect(provider.contextProxy.getValue("mode")).toBe("code") + expect(provider.getValues().mode).toBe("architect") + }) + it("gives a task created from flat provider settings the payload provider instead of the acting view snapshot", async () => { + // The acting view holds an OpenRouter snapshot of its own while the payload + // brings flat Bedrock settings, which setValues persists as shared settings. + // Review thread 4506517300 reports that the created task then keeps the view + // snapshot. This row pins the payload-winning direction and the next row pins + // the opposite direction so the snapshot is not simply discarded. + provider["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + apiKey: "view-snapshot-key", + } + + await provider.createTask( + undefined, + undefined, + undefined, + { startTask: false }, + { + apiProvider: providerIdentifiers.bedrock, + awsRegion: "us-east-1", + awsAccessKey: "payload-bedrock-access-key", + }, + ) + + // The beforeEach above clears mocks, so the newest Task construction belongs to + // this call. TaskOptions.apiConfiguration is the member createTask hands the + // task; src/core/task/Task.ts declares it at line 253 of that interface. + const created = vi.mocked(Task).mock.calls.at(-1)?.[0] + expect(created?.apiConfiguration.apiProvider).toBe(providerIdentifiers.bedrock) + expect(created?.apiConfiguration.awsRegion).toBe("us-east-1") + expect(created?.apiConfiguration.awsAccessKey).toBe("payload-bedrock-access-key") + // The payload reached shared state and neither buffer was merged, so this view + // keeps its own snapshot for every later getState: the ask asks for both. + expect(provider.getValues().apiProvider).toBe(providerIdentifiers.bedrock) + expect(provider["viewLocalState"].apiConfiguration?.apiProvider).toBe(providerIdentifiers.openrouter) + + await provider.dispose() + }) + + it("keeps the acting view snapshot for a created task when the payload names no provider", async () => { + provider["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + apiKey: "view-snapshot-key", + } + + await provider.createTask(undefined, undefined, undefined, { startTask: false }, { mode: "code" }) + + const created = vi.mocked(Task).mock.calls.at(-1)?.[0] + expect(created?.apiConfiguration.apiProvider).toBe(providerIdentifiers.openrouter) + expect(created?.apiConfiguration.apiKey).toBe("view-snapshot-key") + + await provider.dispose() + }) + it("takes the payload's provider settings from the read ahead of the state await", async () => { + // Review thread 4595966639: createTask awaited getState() and read the shared provider + // settings only afterwards, so another view's write can land inside that await and + // become the new task's configuration instead of the settings this payload just + // persisted. The await is held open here, the competing write is issued while it is + // open, and the created task reports which read won. + const lateWrite: ProviderSettings = { apiProvider: providerIdentifiers.openai, apiKey: "late-writer-key" } + provider["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + apiKey: "view-snapshot-key", + } + let openStateRead!: () => void + const stateRead = new Promise((resolve) => { + openStateRead = resolve + }) + // The planted getState runs the view's own read only after the competing write lands, + // so what it hands back is the post-await view of the world: the other view's settings, + // not this payload's. + const realGetState = provider.getState.bind(provider) + vi.spyOn(provider, "getState").mockImplementation(async () => { + await stateRead + return { ...(await realGetState()), apiConfiguration: lateWrite } + }) + + const creating = provider.createTask( + undefined, + undefined, + undefined, + { startTask: false }, + { + apiProvider: providerIdentifiers.bedrock, + awsRegion: "us-east-1", + awsAccessKey: "payload-bedrock-access-key", + }, + ) + // setValues has returned by the time getState is entered, so the payload's settings are + // already the shared settings that the read ahead of the await must take. + await vi.waitFor(() => expect(provider.getState).toHaveBeenCalledTimes(1)) + await provider.contextProxy.setProviderSettings(lateWrite) + openStateRead() + + await creating + + const created = vi.mocked(Task).mock.calls.at(-1)?.[0] + // The payload's provider is the field that moves: it is what the two reads disagree on, + // because a competing provider write renames the shared settings while leaving the + // other provider's keys behind. + expect(created?.apiConfiguration.apiProvider).toBe(providerIdentifiers.bedrock) + expect(created?.apiConfiguration.awsAccessKey).toBe("payload-bedrock-access-key") + // The competing write is still what the shared store holds afterwards, so the two rows + // above pin the earlier read rather than the value that was current when getState + // resolved. + expect(provider.contextProxy.getProviderSettings().apiProvider).toBe(providerIdentifiers.openai) + + await provider.dispose() + }) + it("should sanitize raw viewStateId before using it as persisted viewStates key", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider["setViewStateId"]("tab panel/with.dots and spaces") + await provider.setValue("mode", "architect") + + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + tab_panel_with_dots_and_spaces: { mode: "architect" }, + }) + expect(provider.contextProxy.getValue("viewStates")).not.toHaveProperty("tab panel/with.dots and spaces") + + await provider.dispose() + }) + + it("should persist queued writes under the viewStateId active when the change was made", async () => { + let releaseFirstWrite!: () => void + const firstWriteStarted = new Promise((resolve) => { + mockContext.globalState.update = vi + .fn() + .mockImplementationOnce((key: string, value: unknown) => { + mockContext.globalState.get = vi + .fn() + .mockImplementation((lookupKey: string) => (lookupKey === key ? value : undefined)) + resolve() + return new Promise((writeResolve) => { + releaseFirstWrite = writeResolve + }) + }) + .mockImplementation((key: string, value: unknown) => { + mockContext.globalState.get = vi + .fn() + .mockImplementation((lookupKey: string) => (lookupKey === key ? value : undefined)) + return Promise.resolve() + }) + }) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider["setViewStateId"]("view-a") + const firstSave = provider.saveViewState("mode", "architect") + await firstWriteStarted + await provider["setViewStateId"]("view-b") + releaseFirstWrite() + await firstSave + + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + "view-a": { mode: "architect" }, + }) + expect(provider.contextProxy.getValue("viewStates")).not.toHaveProperty("view-b") + + await provider.dispose() + }) + + it("should preserve persisted viewStates entry when an editor provider is disposed during teardown", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider["setViewStateId"]("tab-to-preserve") + await provider.saveViewState("mode", "architect") + expect(provider.contextProxy.getValue("viewStates")).toHaveProperty("tab-to-preserve") + + await provider.dispose() + + expect(provider.contextProxy.getValue("viewStates")).toHaveProperty("tab-to-preserve") + }) + + it("should read viewStates fresh from storage so out-of-proxy writes are not clobbered", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider["setViewStateId"]("view-a") + await provider.saveViewState("mode", "architect") + + // Simulate a concurrent writer (another view's provider) updating the shared + // map directly in storage, bypassing this proxy's cache. + const stored = (await mockContext.globalState.get>("viewStates")) ?? {} + await mockContext.globalState.update("viewStates", { + ...stored, + "view-b": { mode: "debug", updatedAt: 1 }, + }) + + await provider.saveViewState("mode", "code") + + // The serialized write must have merged on top of the fresh storage value, not + // on top of this proxy's stale cache. + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + "view-a": { mode: "code" }, + "view-b": { mode: "debug" }, + }) + + await provider.dispose() + }) + + it("should re-key durable viewStates entries from the temporary pre-launch view id", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + // A change made before the stable id is registered persists under the + // temporary id so it is not lost; registration re-keys it to the stable id. + await provider.saveViewState("mode", "architect") + + expect(provider["viewLocalState"].mode).toBe("architect") + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + [provider.viewId]: { mode: "architect" }, + }) + + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("mode", "debugger") + + const viewStates = provider.contextProxy.getValue("viewStates") as Record + expect(viewStates["stable-sidebar-view"]).toMatchObject({ mode: "debugger" }) + expect(viewStates[provider.viewId]).toBeUndefined() + + await provider.dispose() + }) + + it("should drop the temporary viewStates entry when a stable entry already exists", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + // A stable entry already exists (e.g. persisted by an earlier registration); + // it must win over this instance's temporary entry. + await provider.contextProxy.setValue("viewStates", { + "stable-sidebar-view": { mode: "debugger", updatedAt: 2 }, + }) + + // Author the temporary entry through the real write path so this instance + // owns it: unowned entries are never re-keyed. + await provider.saveViewState("mode", "architect") + + await provider["setViewStateId"]("stable-sidebar-view") + + const viewStates = provider.contextProxy.getValue("viewStates") as Record + expect(viewStates["stable-sidebar-view"]).toMatchObject({ mode: "debugger" }) + expect(viewStates[provider.viewId]).toBeUndefined() + expect(provider["viewLocalState"].mode).toBe("debugger") + + await provider.dispose() + }) + + it("should discard a stale loadViewState when a newer view id is registered during the load", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + // Seed persisted entries under both ids through the proxy so the loads + // observe them via the cached read path: the temporary entry holds a + // pre-registration selection, the stable entry the post-registration one. + await provider.contextProxy.setValue("viewStates", { + [provider.viewId]: { mode: "architect", currentApiConfigName: "ghost-profile", updatedAt: 1 }, + "stable-sidebar-view": { mode: "debug", updatedAt: 2 }, + }) + + // Hang the temporary entry's profile lookup so that load is still in flight + // when the stable id is registered. + let releaseGhost!: () => void + const ghostLoad = new Promise((resolve) => { + releaseGhost = resolve + }) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockReturnValue( + ghostLoad.then(() => + Object.assign({} as Awaited>, { + name: "ghost-profile", + id: "ghost-id", + apiProvider: providerIdentifiers.anthropic, + }), + ), + ) - provider = new ClineProvider( - mockContext, - mockOutputChannel, - "sidebar", - new ContextProxy(mockContext), - new WebviewFocusTracker(), - mdmService, - ) + const staleLoad = provider["loadViewState"]() - const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockImplementation(async () => undefined) - vi.spyOn(provider as any, "getStateToPostToWebview").mockResolvedValue({ version: "1.0.0" }) + // Register the stable id without awaiting its load: the re-key drops the + // temporary entry (the stable one already exists) and the registration's own + // load settles on the stable entry immediately. + const register = provider["setViewStateId"]("stable-sidebar-view") + await register - await provider.postStateToWebview() + releaseGhost() + await staleLoad - expect(postMessageSpy).toHaveBeenCalledTimes(1) - expect(postMessageSpy).not.toHaveBeenCalledWith(expect.objectContaining({ type: "action" })) - }) + // The stale (temporary-id) load must not overwrite the stable id's load. + expect(provider["viewLocalState"]).toEqual({ mode: "debug" }) - test("postStateToWebviewWithoutTaskHistory waits for the webview post boundary", async () => { - let releasePost!: () => void - const pendingPost = new Promise((resolve) => { - releasePost = resolve + await provider.dispose() }) - let statePostSettled = false + }) - vi.spyOn(provider, "getStateToPostToWebview").mockResolvedValue({ - taskHistory: [], - } as unknown as ExtensionState) - const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockReturnValue(pendingPost) + describe("getState default values", () => { + it("should fall back to defaults for unset state values", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) - const statePost = provider.postStateToWebviewWithoutTaskHistory() - void statePost.then(() => { - statePostSettled = true + const state = await provider.getState() + + expect(state.mode).toBe("code") + expect(state.currentApiConfigName).toBe("default") + expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) + expect(state.alwaysAllowReadOnly).toBe(false) + expect(state.alwaysAllowReadOnlyOutsideWorkspace).toBe(false) + expect(state.alwaysAllowWrite).toBe(false) + expect(state.alwaysAllowWriteOutsideWorkspace).toBe(false) + expect(state.alwaysAllowWriteProtected).toBe(false) + expect(state.alwaysAllowExecute).toBe(false) + expect(state.alwaysAllowMcp).toBe(false) + expect(state.alwaysAllowModeSwitch).toBe(false) + expect(state.alwaysAllowSubtasks).toBe(false) + expect(state.alwaysAllowFollowupQuestions).toBe(false) + expect(state.followupAutoApproveTimeoutMs).toBe(60000) + expect(state.diagnosticsEnabled).toBe(true) + expect(state.soundEnabled).toBe(false) + expect(state.ttsEnabled).toBe(false) + expect(state.ttsSpeed).toBe(1) + expect(state.enableCheckpoints).toBe(true) + expect(state.checkpointTimeout).toBe(DEFAULT_CHECKPOINT_TIMEOUT_SECONDS) + expect(state.terminalPowershellCounter).toBe(false) + expect(state.terminalZshClearEolMark).toBe(true) + expect(state.terminalZshOhMy).toBe(false) + expect(state.terminalZshP10k).toBe(false) + expect(state.terminalZdotdir).toBe(false) + expect(state.mcpEnabled).toBe(true) + expect(state.listApiConfigMeta).toEqual([]) + expect(state.pinnedApiConfigs).toEqual({}) + expect(state.modeApiConfigs).toEqual({}) + expect(state.customSupportPrompts).toEqual({}) + expect(state.experiments).toEqual(experimentDefault) + expect(state.autoApprovalEnabled).toBe(false) + expect(state.maxOpenTabsContext).toBe(20) + expect(state.maxWorkspaceFiles).toBe(200) + expect(state.telemetrySetting).toBe("unset") + expect(state.enableSubfolderRules).toBe(false) + expect(state.maxImageFileSize).toBe(5) + expect(state.maxTotalImageSize).toBe(20) + expect(state.historyPreviewCollapsed).toBe(false) + expect(state.reasoningBlockCollapsed).toBe(true) + expect(state.enterBehavior).toBe("send") + expect(state.codebaseIndexModels).toEqual(EMBEDDING_MODEL_PROFILES) + expect(state.codebaseIndexConfig).toEqual({ + codebaseIndexEnabled: false, + codebaseIndexQdrantUrl: "http://localhost:6333", + codebaseIndexEmbedderProvider: providerIdentifiers.openai, + codebaseIndexEmbedderBaseUrl: "", + codebaseIndexEmbedderModelId: "", + }) + expect(state.profileThresholds).toEqual({}) + expect(state.includeDiagnosticMessages).toBe(true) + expect(state.maxDiagnosticMessages).toBe(50) + expect(state.includeTaskHistoryInEnhance).toBe(true) + expect(state.includeCurrentTime).toBe(true) + expect(state.includeCurrentCost).toBe(true) + expect(state.maxGitStatusFiles).toBe(0) + expect(state.language).toBe("en") + + await provider.dispose() }) - await Promise.resolve() - expect(postMessageSpy).toHaveBeenCalledOnce() - expect(statePostSettled).toBe(false) + it("should report a non-retired apiProvider from state instead of the anthropic fallback", async () => { + const contextProxy = new ContextProxy(mockContext) + await contextProxy.setValues({ apiProvider: providerIdentifiers.openrouter }) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + contextProxy, + new WebviewFocusTracker(), + ) - releasePost() - await statePost - expect(statePostSettled).toBe(true) - }) + const state = await provider.getState() - test.each([ - ["postStateToWebview", (currentProvider: ClineProvider) => currentProvider.postStateToWebview()], - [ - "postStateToWebviewWithoutTaskHistory", - (currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutTaskHistory(), - ], - ])("%s assigns message sequence numbers before asynchronous state construction", async (_methodName, postState) => { - let releaseOlderSnapshot!: (state: ExtensionState) => void - const olderSnapshot = new Promise((resolve) => { - releaseOlderSnapshot = resolve + expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.openrouter) + + await provider.dispose() }) - const baseState = await provider.getStateToPostToWebview({ includeTaskHistory: false }) - const emptyState: ExtensionState = { ...baseState, taskHistory: [], clineMessages: [] } - const readyState: ExtensionState = { - ...baseState, - taskHistory: [], - clineMessages: [{ ts: 1, type: "say", say: "text", text: "child ready" }], - } - vi.spyOn(provider, "getStateToPostToWebview") - .mockReturnValueOnce(olderSnapshot) - .mockResolvedValueOnce(readyState) - const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) + it("should fill the apiConfiguration apiProvider from the raw state value when provider settings sanitize it away", async () => { + // "bogus-provider" is neither an active nor a retired provider, so + // ContextProxy.sanitizeProviderValues drops it from the provider + // settings; the raw state value still reaches apiConfiguration via + // the getState fill-in, which is what this assertion pins. + const contextProxy = new ContextProxy(mockContext) + // A single structural cast: the raw-state write must carry an + // un-sanitizable apiProvider value, which the typed setValues(RooCodeSettings) + // signature deliberately rejects. + const contextProxyAccess = contextProxy as { + setValues: (values: Record) => Promise + } + await contextProxyAccess.setValues({ apiProvider: "bogus-provider" }) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + contextProxy, + new WebviewFocusTracker(), + ) - const olderPost = postState(provider) - await Promise.resolve() - const newerPost = postState(provider) - await newerPost - releaseOlderSnapshot(emptyState) - await olderPost + const state = await provider.getState() - expect(postMessageSpy.mock.calls.map(([message]) => message.state?.clineMessages)).toEqual([ - readyState.clineMessages, - emptyState.clineMessages, - ]) - expect(postMessageSpy.mock.calls.map(([message]) => message.state?.clineMessagesSeq)).toEqual([2, 1]) - }) + expect(state.apiConfiguration.apiProvider).toBe("bogus-provider") - test.each([ - [ - "postStateToWebviewWithoutTaskHistory", - (currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutTaskHistory(), - ], - [ - "postStateToWebviewWithoutClineMessages", - (currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutClineMessages(), - ], - ])("%s skips task history computation", async (_methodName, postState) => { - const getAllSpy = vi.spyOn(provider.taskHistoryStore, "getAll") - const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) + await provider.dispose() + }) - await postState(provider) + it("should serve the embedding model profiles default when the stored value is cleared", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) - expect(getAllSpy).not.toHaveBeenCalled() - expect(postMessageSpy).toHaveBeenCalledOnce() - expect(postMessageSpy.mock.calls[0]?.[0].state).not.toHaveProperty("taskHistory") - }) + // The constructor seeds codebaseIndexModels into the context; with a truthy + // stored value the ?? default is unobservable (both ?? and && forms return + // the same profiles object). Clear the stored value so the read-time default + // is the one under test. + await provider.contextProxy.setValue("codebaseIndexModels", undefined) - test("getStateToPostToWebview computes task history once after its base state resolves", async () => { - const historyItem = { - id: "history-task", - number: 1, - ts: 1, - task: "History task", - tokensIn: 0, - tokensOut: 0, - totalCost: 0, - } - const originalGetState = provider.getState.bind(provider) - let baseStateResolved = false - const getStateSpy = vi.spyOn(provider, "getState").mockImplementation(async (options) => { - const state = await originalGetState(options) - baseStateResolved = true - return state - }) - const historyReadPhases: boolean[] = [] - const getAllSpy = vi.spyOn(provider.taskHistoryStore, "getAll").mockImplementation(() => { - historyReadPhases.push(baseStateResolved) - return [historyItem] - }) + const state = await provider.getState() - const state = await provider.getStateToPostToWebview() + expect(state.codebaseIndexModels).toBe(EMBEDDING_MODEL_PROFILES) - expect(getStateSpy).toHaveBeenCalledOnce() - expect(getStateSpy).toHaveBeenCalledWith({ includeTaskHistory: false }) - expect(getAllSpy).toHaveBeenCalledOnce() - expect(historyReadPhases).toEqual([true]) - expect(state.taskHistory).toEqual([historyItem]) + await provider.dispose() + }) }) describe("postStateToWebviewThrottled", () => { @@ -4064,6 +9022,47 @@ describe("ClineProvider", () => { expect(mockPostMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "state" })) }) + it("should re-pin the view to a valid global selection when the first listed profile has no name", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The view's pinned config no longer exists, the shared global selection is + // still valid, and the only listed profile is a legacy entry without a name + // (the cast keeps that intentionally missing field from widening the double). + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockImplementation( + async (name: string) => name === "global-valid", + ) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { id: "legacy-id", apiProvider: providerIdentifiers.openai }, + ] as ProviderSettingsEntry[]) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("legacy-id") + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + // The view's own pin points at a deleted profile; the shared global selection is still valid. + await provider.saveViewState("currentApiConfigName", "gone-pin") + await provider.contextProxy.setValue("currentApiConfigName", "global-valid") + + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview") + const contextProxySetValueSpy = vi.spyOn(provider.contextProxy, "setValue") + await webviewMessageHandler(provider, { type: "webviewDidLaunch" }) + // The launch flow's profile-list sync is fire-and-forget; wait for its final post. + await vi.waitFor(() => + expect(postMessageSpy).toHaveBeenCalledWith(expect.objectContaining({ type: "listApiConfig" })), + ) + + // The valid shared selection is adopted by this view only: the view-local pin switches to it + // while the shared global selection is left untouched for the other views. + expect(provider["viewLocalState"].currentApiConfigName).toBe("global-valid") + expect(mockContext.globalState.get("currentApiConfigName")).toBe("global-valid") + // A nameless first listed profile must never clear the shared selection with undefined. + expect(contextProxySetValueSpy).not.toHaveBeenCalledWith("currentApiConfigName", undefined) + + await provider.dispose() + }) + test("logs detached workspace initialization failures", async () => { await provider.resolveWebviewView(mockWebviewView) @@ -4880,6 +9879,8 @@ describe("ClineProvider", () => { provider["initialModeConfigIds"] = Promise.resolve({ architect: "test-id" }) ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), getModeConfigId: vi.fn().mockResolvedValue("test-id"), listConfig: vi.fn().mockResolvedValue([profile]), activateProfile: vi.fn().mockResolvedValue(profile), @@ -5132,6 +10133,8 @@ describe("ClineProvider", () => { const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), getModeConfigId: vi.fn().mockResolvedValue(undefined), listConfig: vi .fn() @@ -5161,6 +10164,8 @@ describe("ClineProvider", () => { } ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), activateProfile: vi.fn().mockResolvedValue(profile), listConfig: vi.fn().mockResolvedValue([profile]), setModeConfig: vi.fn(), @@ -5188,6 +10193,8 @@ describe("ClineProvider", () => { } ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), activateProfile: vi.fn().mockResolvedValue(profile), listConfig: vi.fn().mockResolvedValue([profile]), setModeConfig: vi.fn(), @@ -5363,13 +10370,24 @@ describe("ClineProvider", () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] + const savedForReadBack1: Record> = {} ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), listConfig: vi .fn() .mockResolvedValue([ { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic }, ]), - saveConfig: vi.fn().mockResolvedValue("test-id"), + saveConfig: vi.fn(async (name: string, settings: Record) => { + savedForReadBack1[name] = settings + return "test-id" + }), + getProfile: vi.fn(async ({ name }: { name: string }) => ({ + name, + id: "test-id", + ...savedForReadBack1[name], + })), setModeConfig: vi.fn(), } as any @@ -5715,6 +10733,8 @@ describe("ClineProvider", () => { provider["initialModeConfigIds"] = Promise.resolve({ architect: "saved-config-id" }) ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), getModeConfigId: vi.fn().mockResolvedValue("saved-config-id"), listConfig: vi.fn().mockResolvedValue([profile]), activateProfile: vi.fn().mockResolvedValue(profile), @@ -5739,6 +10759,8 @@ describe("ClineProvider", () => { test("keeps the current config locally when switching to a mode without a config", async () => { ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), getModeConfigId: vi.fn().mockResolvedValue(undefined), listConfig: vi .fn() @@ -5801,6 +10823,8 @@ describe("ClineProvider", () => { // Mock provider settings manager ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), getModeConfigId: vi.fn().mockResolvedValue(undefined), listConfig: vi.fn().mockResolvedValue([]), } @@ -5827,8 +10851,10 @@ describe("ClineProvider", () => { expect(mockCustomModesManager.getCustomModes).toHaveBeenCalled() expect(getModeBySlug).toHaveBeenCalledWith("non-existent-mode", expect.any(Array)) - // Verify fallback to default mode - expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "code") + // Verify fallback to default mode, view-locally: history restore no longer + // writes the shared global mode + expect(provider["viewLocalState"].mode).toBe("code") + expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "code") expect(logSpy).toHaveBeenCalledWith( "Mode 'non-existent-mode' from history no longer exists. Falling back to default mode 'code'.", ) @@ -5866,6 +10892,8 @@ describe("ClineProvider", () => { // Mock provider settings manager ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), getModeConfigId: vi.fn().mockResolvedValue("config-id"), listConfig: vi .fn() @@ -5901,8 +10929,9 @@ describe("ClineProvider", () => { expect(mockCustomModesManager.getCustomModes).toHaveBeenCalled() expect(getModeBySlug).toHaveBeenCalledWith("custom-mode", expect.any(Array)) - // Verify mode was preserved - expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "custom-mode") + // Verify mode was preserved view-locally (no shared global mode write) + expect(provider["viewLocalState"].mode).toBe("custom-mode") + expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "custom-mode") expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining("no longer exists")) // Verify history item mode was not changed @@ -5930,6 +10959,8 @@ describe("ClineProvider", () => { // Mock provider settings manager ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), getModeConfigId: vi.fn().mockResolvedValue(undefined), listConfig: vi.fn().mockResolvedValue([]), } @@ -5949,8 +10980,9 @@ describe("ClineProvider", () => { // Initialize with history item await provider.createTaskWithHistoryItem(historyItem) - // Verify mode was preserved - expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "architect") + // Verify mode was preserved view-locally (no shared global mode write) + expect(provider["viewLocalState"].mode).toBe("architect") + expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "architect") // Verify history item mode was not changed expect(historyItem.mode).toBe("architect") @@ -5961,6 +10993,8 @@ describe("ClineProvider", () => { // Mock provider settings manager ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), getModeConfigId: vi.fn().mockResolvedValue(undefined), listConfig: vi.fn().mockResolvedValue([]), } @@ -6006,6 +11040,8 @@ describe("ClineProvider", () => { // Mock provider settings manager to throw error ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), getModeConfigId: vi.fn().mockResolvedValue("config-id"), listConfig: vi .fn() @@ -6108,6 +11144,8 @@ describe("ClineProvider", () => { const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), setModeConfig: vi.fn().mockRejectedValue(new Error("Failed to update mode config")), listConfig: vi .fn() @@ -6140,9 +11178,20 @@ describe("ClineProvider", () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] + const savedForReadBack2: Record> = {} ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), setModeConfig: vi.fn(), - saveConfig: vi.fn().mockResolvedValue(undefined), + saveConfig: vi.fn(async (name: string, settings: Record) => { + savedForReadBack2[name] = settings + return undefined + }), + getProfile: vi.fn(async ({ name }: { name: string }) => ({ + name, + id: undefined, + ...savedForReadBack2[name], + })), listConfig: vi .fn() .mockResolvedValue([ @@ -6185,9 +11234,20 @@ describe("ClineProvider", () => { ;(buildApiHandler as any).mockImplementationOnce(() => { throw new Error("API handler error") }) + const savedForReadBack3: Record> = {} ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), setModeConfig: vi.fn(), - saveConfig: vi.fn().mockResolvedValue(undefined), + saveConfig: vi.fn(async (name: string, settings: Record) => { + savedForReadBack3[name] = settings + return undefined + }), + getProfile: vi.fn(async ({ name }: { name: string }) => ({ + name, + id: undefined, + ...savedForReadBack3[name], + })), listConfig: vi .fn() .mockResolvedValue([ @@ -6228,9 +11288,20 @@ describe("ClineProvider", () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] + const savedForReadBack4: Record> = {} ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), setModeConfig: vi.fn(), - saveConfig: vi.fn().mockResolvedValue(undefined), + saveConfig: vi.fn(async (name: string, settings: Record) => { + savedForReadBack4[name] = settings + return undefined + }), + getProfile: vi.fn(async ({ name }: { name: string }) => ({ + name, + id: undefined, + ...savedForReadBack4[name], + })), listConfig: vi .fn() .mockResolvedValue([ @@ -7016,6 +12087,11 @@ describe("getTelemetryProperties", () => { const { CloudService } = await import("@roo-code/cloud") const mockCloudService = { isAuthenticated: vi.fn().mockReturnValue(true), + + // Provider dispose detaches the settings listener; later tests construct + // and dispose providers against this surviving instance getter. + on: vi.fn(), + off: vi.fn(), } // Update the existing mock @@ -7034,6 +12110,11 @@ describe("getTelemetryProperties", () => { const { CloudService } = await import("@roo-code/cloud") const mockCloudService = { isAuthenticated: vi.fn().mockReturnValue(false), + + // Provider dispose detaches the settings listener; later tests construct + // and dispose providers against this surviving instance getter. + on: vi.fn(), + off: vi.fn(), } // Update the existing mock @@ -7075,6 +12156,11 @@ describe("getTelemetryProperties", () => { isAuthenticated: vi.fn().mockImplementation(() => { throw new Error("Authentication check error") }), + + // Provider dispose detaches the settings listener; later tests construct + // and dispose providers against this surviving instance getter. + on: vi.fn(), + off: vi.fn(), } // Update the existing mock @@ -8678,6 +13764,8 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), listConfig: vi.fn().mockResolvedValue([]), } @@ -8709,6 +13797,8 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { const saveConfig = vi.fn().mockResolvedValue(undefined) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), listConfig: vi.fn().mockResolvedValue([ { name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }, { name: "Backup Zoo", apiProvider: providerIdentifiers.zooGateway }, @@ -8737,12 +13827,15 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }), true, ) - expect(saveConfig).toHaveBeenCalledWith( + // The non-active profile now goes through upsertProviderProfile so the views + // pinned to it are refreshed, not just the file on disk. + expect(upsertSpy).toHaveBeenCalledWith( "Backup Zoo", expect.objectContaining({ zooSessionToken: "new-token", zooGatewayBaseUrl: "https://www.zoocode.dev/api/gateway/v1", }), + false, ) }) @@ -8750,6 +13843,8 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { vi.spyOn(provider, "getState").mockRejectedValue(new Error("state unavailable")) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), listConfig: vi.fn().mockResolvedValue([]), } @@ -8768,6 +13863,8 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { const handleSpy = vi.spyOn(provider, "handleZooCodeCallback").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), listConfig: vi.fn(), } @@ -8783,6 +13880,8 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), listConfig: vi .fn() .mockResolvedValue([{ name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }]), @@ -8804,6 +13903,8 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { const handleSpy = vi.spyOn(provider, "handleZooCodeCallback").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), listConfig: vi .fn() .mockResolvedValue([{ name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }]), @@ -8824,6 +13925,8 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { const handleSpy = vi.spyOn(provider, "handleZooCodeCallback").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion the write now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), listConfig: vi .fn() .mockResolvedValue([{ name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }]), @@ -8839,4 +13942,212 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }) }) }) + describe("profile save without activation and overlay completeness", () => { + it("refreshes views pinned to a profile saved without activation", async () => { + // Defensive: the doubles in this suite can leave console writes pending + // at worker teardown. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + // The sibling loaded the profile earlier: its buffer pins the name and + // carries the settings snapshot taken at that load. + sibling["viewLocalState"].currentApiConfigName = "saved-profile" + sibling["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.anthropic, + apiKey: "old-key", + } + vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) + + // The sibling has an active task built from the pre-save settings. + // Task is a class; the double assertion is the only way to attach a + // minimal double without the full provider/services graph. + const siblingTask = { + apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "old-key" }, + taskApiConfigName: "saved-profile", + updateApiConfiguration: vi.fn(), + } + vi.spyOn(sibling, "getCurrentTask").mockReturnValue( + siblingTask as unknown as ReturnType, + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + id: "saved-id", + name: "saved-profile", + apiProvider: providerIdentifiers.anthropic, + apiKey: "new-key", + }) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + + await provider.upsertProviderProfile( + "saved-profile", + { apiProvider: providerIdentifiers.anthropic, apiKey: "new-key" }, + false, + ) + + // A save that does not activate still rewrites the profile; the pinned + // sibling must not keep serving the pre-save snapshot. + expect(sibling["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "new-key", + }) + + // The active task's handler must be rebuilt with the saved settings, + // not just the view buffer. + expect(siblingTask.updateApiConfiguration).toHaveBeenCalledWith({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "new-key", + }) + // Wait on the serialized view-state write queue that every + // viewStates mutation goes through, so queued persistence finishes + // while the console spies are still installed and teardown has no + // pending writes. + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await sibling.dispose() + } + }) + + it("does not rebuild a pinned sibling's task that runs under another profile", async () => { + // Defensive: the doubles in this suite can leave console writes pending + // at worker teardown. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + // The sibling pins the saved profile, but its active task follows a + // different sticky profile: the save must refresh the view overlay + // without switching that conversation to the saved profile's settings. + sibling["viewLocalState"].currentApiConfigName = "saved-profile" + sibling["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.anthropic, + apiKey: "old-key", + } + vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) + + const siblingTask = { + apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key" }, + taskApiConfigName: "other-profile", + updateApiConfiguration: vi.fn(), + } + vi.spyOn(sibling, "getCurrentTask").mockReturnValue( + siblingTask as unknown as ReturnType, + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "saved-profile", + id: "saved-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "new-key", + }) + await provider.upsertProviderProfile( + "saved-profile", + { apiProvider: providerIdentifiers.anthropic, apiKey: "new-key" }, + false, + ) + + // The pinned view's overlay still catches up with the saved settings... + expect(sibling["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "new-key", + }) + // ...but the task runs under another profile: its handler must not be + // switched to the saved profile's settings. + expect(siblingTask.updateApiConfiguration).not.toHaveBeenCalled() + // Wait on the serialized view-state write queue that every + // viewStates mutation goes through, so queued persistence finishes + // while the console spies are still installed and teardown has no + // pending writes. + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await sibling.dispose() + } + }) + + it("does not rebuild the acting view's task when it runs under another profile", async () => { + // The acting view pins the saved profile while its own task follows a + // different sticky profile: the non-activating save refreshes the view + // overlay but must leave the task's handler alone. + const task = { + apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key" }, + taskApiConfigName: "other-profile", + updateApiConfiguration: vi.fn(), + } + vi.spyOn(provider, "getCurrentTask").mockReturnValue( + task as unknown as ReturnType, + ) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + provider["viewLocalState"].currentApiConfigName = "saved-profile" + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "saved-profile", + id: "saved-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "new-key", + }) + + await provider.upsertProviderProfile( + "saved-profile", + { apiProvider: providerIdentifiers.anthropic, apiKey: "new-key" }, + false, + ) + + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "new-key", + }) + expect(task.updateApiConfiguration).not.toHaveBeenCalled() + }) + it("does not leak shared provider keys into a pinned view's api configuration", async () => { + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + // The shared store sits on a profile with keys the pinned profile never + // sets; spreading the overlay over the shared keys would report a mixed + // configuration (e.g. another profile's model id and region). + await provider.contextProxy.setValue("apiProvider", providerIdentifiers.bedrock) + await provider.contextProxy.setValue("apiModelId", "anthropic.claude-v1") + await provider.contextProxy.setValue("awsRegion", "us-east-1") + provider["viewLocalState"].currentApiConfigName = "pinned-profile" + provider["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.anthropic, + apiKey: "k", + } + + // The cloud doubles in this suite make getState() log its defensive catch + // branches; silence them so teardown has no pending console writes. + vi.spyOn(console, "error").mockImplementation(() => {}) + + const state = await provider.getState() + + expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) + expect(state.apiConfiguration.apiKey).toBe("k") + expect(state.apiConfiguration.apiModelId).toBeUndefined() + expect(state.apiConfiguration.awsRegion).toBeUndefined() + + // Let any deferred logging settle while the spies are installed. + await new Promise((resolve) => setTimeout(resolve, 50)) + }) + }) }) diff --git a/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts index f73101d4eeb..978615c7330 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts @@ -121,6 +121,8 @@ vi.mock("@roo-code/cloud", () => ({ get instance() { return { isAuthenticated: vi.fn().mockReturnValue(false), + on: vi.fn(), + off: vi.fn(), } }, }, @@ -229,6 +231,17 @@ describe("ClineProvider - Sticky Mode", () => { beforeEach(async () => { vi.clearAllMocks() + // vi.clearAllMocks clears call records but leaves implementations in place, so a test + // that answers getModeBySlug with undefined - the deleted-mode scenario below does - hands + // its not-found answer to every later suite once the mode setter consults the function. + // Re-apply the module mock's own default before each test instead. + const modesModule = vi.mocked(await import("../../../shared/modes")) + modesModule.getModeBySlug.mockReturnValue({ + slug: "code", + name: "Code Mode", + roleDefinition: "You are a code assistant", + groups: ["read", "edit"], + }) if (!TelemetryService.hasInstance()) { TelemetryService.createInstance([]) @@ -335,6 +348,47 @@ describe("ClineProvider - Sticky Mode", () => { await provider.resolveWebviewView(mockWebviewView) }) + it("restores the task history mode and _taskMode when the shared mode write fails", async () => { + await provider.resolveWebviewView(mockWebviewView) + + const mockTask = { + taskId: "rollback-task-id", + _taskMode: "code", + emit: vi.fn(), + saveClineMessages: vi.fn(), + clineMessages: [], + apiConversationHistory: [], + updateApiConfiguration: vi.fn(), + } + + await provider.addClineToStack(mockTask as unknown as Task) + await seedTaskHistory([ + { + id: mockTask.taskId, + ts: Date.now(), + task: "Test task", + number: 1, + tokensIn: 0, + tokensOut: 0, + cacheWrites: 0, + cacheReads: 0, + totalCost: 0, + mode: "code", + }, + ]) + + // The durable shared-mode write is the last write of the switch and it + // rejects: the task history entry and _taskMode already carry the new mode, + // so the failure has to put them back instead of leaving the task on a mode + // that was never persisted. + vi.spyOn(provider, "setValue").mockRejectedValue(new Error("durable mode write failed")) + + await expect(provider.handleModeSwitch("architect")).rejects.toThrow("durable mode write failed") + + expect(provider["getTaskHistoryItem"](mockTask.taskId)?.mode).toBe("code") + expect(mockTask._taskMode).toBe("code") + }) + it("should save mode to task metadata when switching modes", async () => { // Create a mock task const mockTask = new Task({ @@ -472,6 +526,299 @@ describe("ClineProvider - Sticky Mode", () => { }), ) }) + + it("should sync the view-local mode buffer when switching modes after a restored view state", async () => { + // Simulate the history-restore path: saveViewState is what + // createTaskWithHistoryItem uses to pin a saved mode into the + // view-local buffer, leaving a stale mode there until the next mutation. + await provider.saveViewState("mode", "code") + + // Global-only mode switch with no active task. + await provider.handleModeSwitch("architect") + + // The durable global write still happens... + expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "architect") + + // ...and the in-memory buffer must not keep serving the stale restored + // mode: getValues() merges viewLocalState on top of the ContextProxy + // values, so an unsynced buffer would hide the fresh mode from consumers. + expect(provider["viewLocalState"].mode).toBe("architect") + + // The durable per-view write must land too: a regression that left the + // persisted entry on the stale restored mode would reload it on restart. + // setValue awaits the serialized write queue, so the entry is settled here. + const persisted = provider["getPersistedViewStates"]()[provider["viewStateId"]] + expect(persisted.mode).toBe("architect") + expect(provider.getValues().mode).toBe("architect") + }) + + it("bails out before any task write when the mutation signal is already aborted", async () => { + // A minimal typed double keeps the test focused on the mode-switch contract. + // The literal is asserted as Partial so its private members (_taskMode, + // saveClineMessages) stay out of the Object.assign intersection type, which + // would otherwise collapse to never. + const mockTask = Object.assign( + {} as Task, + { + taskId: "test-task-id", + taskMode: "code", + _taskMode: undefined as string | undefined, + emit: vi.fn(), + saveClineMessages: vi.fn(), + clineMessages: [], + apiConversationHistory: [], + updateApiConfiguration: vi.fn(), + } as Partial, + ) + + const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { + return Promise.resolve([]) + }) + await provider.addClineToStack(mockTask) + + const abortedController = new AbortController() + abortedController.abort() + await provider["handleModeSwitchUnlocked"]("architect", mockTask, abortedController.signal) + + expect(mockTask.emit).not.toHaveBeenCalledWith("taskModeSwitched", mockTask.taskId, "architect") + expect(updateTaskHistorySpy).not.toHaveBeenCalled() + expect(mockTask["_taskMode"]).toBeUndefined() + expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "architect") + }) + + it("rolls back the landed history write and leaves no partial mode state when the signal aborts in flight", async () => { + // A minimal typed double keeps the test focused on the mode-switch contract. + // The literal is asserted as Partial so its private members (_taskMode, + // saveClineMessages) stay out of the Object.assign intersection type, which + // would otherwise collapse to never. + const mockTask = Object.assign( + {} as Task, + { + taskId: "test-task-id", + taskMode: "code", + _taskMode: "code", + emit: vi.fn(), + saveClineMessages: vi.fn(), + clineMessages: [], + apiConversationHistory: [], + updateApiConfiguration: vi.fn(), + } as Partial, + ) + + const historyItem: HistoryItem = { + id: "test-task-id", + ts: Date.now(), + task: "Test task", + mode: "code", + number: 1, + tokensIn: 0, + tokensOut: 0, + cacheWrites: 0, + cacheReads: 0, + totalCost: 0, + } + vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem) + + // The history write settles only after the abort lands: the first call is + // controlled, the rollback call resolves immediately. + let releaseUpdate!: (value: HistoryItem[]) => void + const updateTaskHistorySpy = vi + .spyOn(provider, "updateTaskHistory") + .mockImplementationOnce( + () => + new Promise((resolve) => { + releaseUpdate = resolve + }), + ) + .mockResolvedValueOnce([]) + await provider.addClineToStack(mockTask) + + const controller = new AbortController() + const switchPromise = provider["handleModeSwitchUnlocked"]("architect", mockTask, controller.signal) + + await vi.waitFor(() => { + expect(updateTaskHistorySpy).toHaveBeenCalledTimes(1) + }) + controller.abort() + releaseUpdate([]) + await switchPromise + + // The persisted new mode is rolled back to the pre-switch item. + expect(updateTaskHistorySpy).toHaveBeenCalledTimes(2) + expect(updateTaskHistorySpy).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ id: "test-task-id", mode: "architect" }), + ) + expect(updateTaskHistorySpy).toHaveBeenNthCalledWith(2, historyItem) + // No partial mode state: the task keeps its previous mode, nothing was + // emitted, and the durable provider mode write never happened. + expect(mockTask["_taskMode"]).toBe("code") + expect(mockTask.emit).not.toHaveBeenCalledWith("taskModeSwitched", mockTask.taskId, "architect") + expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "architect") + }) + + it("keeps the cancellation result when the abort rollback write itself fails", async () => { + const mockTask = Object.assign( + {} as Task, + { + taskId: "test-task-id", + taskMode: "code", + _taskMode: "code", + emit: vi.fn(), + saveClineMessages: vi.fn(), + clineMessages: [], + apiConversationHistory: [], + updateApiConfiguration: vi.fn(), + } as Partial, + ) + + const historyItem: HistoryItem = { + id: "test-task-id", + ts: Date.now(), + task: "Test task", + mode: "code", + number: 1, + tokensIn: 0, + tokensOut: 0, + cacheWrites: 0, + cacheReads: 0, + totalCost: 0, + } + vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem) + + // The first write settles after the abort lands; the rollback write rejects: + // the failure is logged with its own message and the cancelled switch still + // resolves (it must not surface as the switch's persistence error). + let releaseUpdate!: (value: HistoryItem[]) => void + const updateTaskHistorySpy = vi + .spyOn(provider, "updateTaskHistory") + .mockImplementationOnce( + () => + new Promise((resolve) => { + releaseUpdate = resolve + }), + ) + .mockRejectedValueOnce(new Error("rollback write failed")) + await provider.addClineToStack(mockTask) + + const controller = new AbortController() + const switchPromise = provider["handleModeSwitchUnlocked"]("architect", mockTask, controller.signal) + + await vi.waitFor(() => { + expect(updateTaskHistorySpy).toHaveBeenCalledTimes(1) + }) + controller.abort() + releaseUpdate([]) + await expect(switchPromise).resolves.toBeUndefined() + + expect(updateTaskHistorySpy).toHaveBeenCalledTimes(2) + expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( + expect.stringContaining("Failed to roll back mode switch"), + ) + }) + + it("preserves fields persisted during the pending window when rolling back the mode", async () => { + const mockTask = Object.assign( + {} as Task, + { + taskId: "test-task-id", + taskMode: "code", + _taskMode: "code", + emit: vi.fn(), + saveClineMessages: vi.fn(), + clineMessages: [], + apiConversationHistory: [], + updateApiConfiguration: vi.fn(), + } as Partial, + ) + + const preSwitchItem: HistoryItem = { + id: "test-task-id", + ts: Date.now(), + task: "Test task", + mode: "code", + number: 1, + tokensIn: 0, + tokensOut: 0, + cacheWrites: 0, + cacheReads: 0, + totalCost: 0, + } + // While the history write is in flight the running task persists other fields + // of the same item; the store now returns that updated item. + const updatedItem: HistoryItem = { + ...preSwitchItem, + mode: "architect", + tokensIn: 42, + totalCost: 0.5, + } + const storeGet = vi + .spyOn(provider.taskHistoryStore, "get") + .mockReturnValueOnce(preSwitchItem) + .mockReturnValue(updatedItem) + + let releaseUpdate!: (value: HistoryItem[]) => void + const updateTaskHistorySpy = vi + .spyOn(provider, "updateTaskHistory") + .mockImplementationOnce( + () => + new Promise((resolve) => { + releaseUpdate = resolve + }), + ) + .mockResolvedValueOnce([]) + await provider.addClineToStack(mockTask) + + const controller = new AbortController() + const switchPromise = provider["handleModeSwitchUnlocked"]("architect", mockTask, controller.signal) + + await vi.waitFor(() => { + expect(updateTaskHistorySpy).toHaveBeenCalledTimes(1) + }) + controller.abort() + releaseUpdate([]) + await expect(switchPromise).resolves.toBeUndefined() + + // The rollback restores only the mode: the fields persisted during the + // pending window (tokensIn, totalCost) survive the rollback write. + expect(updateTaskHistorySpy).toHaveBeenCalledTimes(2) + expect(storeGet).toHaveBeenCalledTimes(2) + expect(updateTaskHistorySpy).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ id: "test-task-id", mode: "code", tokensIn: 42, totalCost: 0.5 }), + ) + }) + + it("proceeds normally when no mutation signal is provided", async () => { + // A minimal typed double keeps the test focused on the mode-switch contract. + // The literal is asserted as Partial so its private members (_taskMode, + // saveClineMessages) stay out of the Object.assign intersection type, which + // would otherwise collapse to never. + const mockTask = Object.assign( + {} as Task, + { + taskId: "test-task-id", + taskMode: "code", + _taskMode: undefined as string | undefined, + emit: vi.fn(), + saveClineMessages: vi.fn(), + clineMessages: [], + apiConversationHistory: [], + updateApiConfiguration: vi.fn(), + } as Partial, + ) + + vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { + return Promise.resolve([]) + }) + await provider.addClineToStack(mockTask) + + await provider["handleModeSwitchUnlocked"]("architect", mockTask, undefined) + + expect(mockTask.emit).toHaveBeenCalledWith("taskModeSwitched", mockTask.taskId, "architect") + expect(mockTask["_taskMode"]).toBe("architect") + expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "architect") + }) }) describe("createTaskWithHistoryItem", () => { @@ -492,14 +839,15 @@ describe("ClineProvider - Sticky Mode", () => { mode: "architect", // Saved mode } - // Mock updateGlobalState to track mode updates - const updateGlobalStateSpy = vi.spyOn(provider as any, "updateGlobalState").mockResolvedValue(undefined) + // Register a stable view id so the durable per-view write is persisted + await provider["setViewStateId"]("stable-test-view") // Initialize task with history item await provider.createTaskWithHistoryItem(historyItem) - // Verify mode was restored via updateGlobalState - expect(updateGlobalStateSpy).toHaveBeenCalledWith("mode", "architect") + // Verify mode was restored into the view-local pin (no shared global write) + expect(provider["viewLocalState"].mode).toBe("architect") + expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "architect") }) it("should use current mode if history item has no saved mode", async () => { @@ -776,7 +1124,9 @@ describe("ClineProvider - Sticky Mode", () => { // Restore the task from history await provider.createTaskWithHistoryItem(historyItem) - // Verify that the mode was restored + // Verify that history restoration reaches both the view-local pin and public state. + expect(provider["viewLocalState"].mode).toBe("architect") + const state = await provider.getState() expect(state.mode).toBe("architect") @@ -968,11 +1318,34 @@ describe("ClineProvider - Sticky Mode", () => { // Clear previous calls vi.mocked(mockContext.globalState.update).mockClear() - // Try to switch to invalid mode - it will actually switch + // The module mock answers every slug, and this slug is what the row is about, so narrow + // it here: the durable write now consults getModeBySlug and has to find nothing. + const modesModule = vi.mocked(await import("../../../shared/modes")) + const defaultGetModeBySlug = modesModule.getModeBySlug.getMockImplementation() + modesModule.getModeBySlug.mockReturnValue(undefined) + const logSpy = vi.spyOn(provider, "log") + const sharedModeBefore = provider.getValue("mode") + const pinnedModeBefore = provider["viewLocalState"].mode + const taskModeBefore = mockTask["_taskMode"] + await provider.handleModeSwitch("invalid-mode" as any) - // The mode WILL be updated to invalid-mode (this is the actual behavior) - expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "invalid-mode") + if (defaultGetModeBySlug) { + modesModule.getModeBySlug.mockImplementation(defaultGetModeBySlug) + } + + // The setter refuses the slug ahead of both persistence layers, so the shared write + // and the per-view pin stay exactly where they were and the log names the refusal. + // The task-level writes land before the durable write and are only compensated when + // that write throws, so the in-memory mode of the task on the stack does move; that + // split is pinned here rather than described away. + expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "invalid-mode") + expect(provider.getValue("mode")).toBe(sharedModeBefore) + expect(provider["viewLocalState"].mode).toBe(pinnedModeBefore) + expect(mockTask["_taskMode"]).not.toBe(taskModeBefore) + expect(logSpy).toHaveBeenCalledWith( + expect.stringContaining('[ClineProvider#setValue] Ignoring invalid mode "invalid-mode"'), + ) }) it("should handle errors during mode switch gracefully", async () => { @@ -1281,4 +1654,148 @@ describe("ClineProvider - Sticky Mode", () => { }) }) }) + + describe("persisted view state keys", () => { + it("does not resolve a view id that names an Object.prototype key through the chain", async () => { + await provider.resolveWebviewView(mockWebviewView) + + // Seed through the durable write path so later writes land in the same + // backing map the assertions read: a frozen get() literal would make every + // post-write assertion read the seed no matter what the provider wrote. + await provider.contextProxy.setValue("viewStates", { "stable-test-view": { mode: "architect" } }) + + const states = provider["getPersistedViewStates"]({ fresh: true }) + expect(Object.getPrototypeOf(states)).toBeNull() + // A view id such as "constructor" must read as an absent entry, not as the + // inherited Object function, otherwise the rekey deletes the temporary entry + // and never writes it under the stable key. + expect(states["constructor"]).toBeUndefined() + expect(states["stable-test-view"]).toEqual({ mode: "architect" }) + + // Registering such an id must not make an inherited member look like a + // persisted entry: the lookup still reports an absent entry, so the rekey keeps the + // temporary entry instead of deleting it. + await provider["setViewStateId"]("constructor") + expect(provider["getPersistedViewStates"]({ fresh: true })["constructor"]).toBeUndefined() + }) + + it("does not load a temporary-id entry that an earlier session wrote", async () => { + // Temporary names restart from 0 on every host start, so storage can still hold + // an entry under this instance's name from a previous session. Seed the entry + // through the ContextProxy before the provider is constructed so the ordinary + // loadViewState read (which goes through the proxy cache) actually sees it. + const tempId = `sidebar-${ClineProvider["nextViewId"]}` + const proxy = new ContextProxy(mockContext) + await proxy.setValue("viewStates", { + [tempId]: { mode: "architect", currentApiConfigName: "stale-profile" }, + }) + + const fresh = new ClineProvider(mockContext, mockOutputChannel, "sidebar", proxy, new WebviewFocusTracker()) + expect(fresh.viewId).toBe(tempId) + + // Await the load itself instead of a fixed timer: the negative + // assertion must run after the load has definitely finished. + await fresh["loadViewState"]() + + // The unowned temporary-id entry must not be adopted... + expect(fresh["viewLocalState"]).toStrictEqual({}) + + // ...and the shared values still win, so the stale entry cannot reach getState(). + const state = await fresh.getState() + expect(state.mode).toBe("code") + expect(state.currentApiConfigName).not.toBe("stale-profile") + }) + + it("does not merge a stale temporary-id entry into this instance's first durable write", async () => { + // A first write under an unowned temporary id claims the slot: fields left by an + // earlier session under the same name must not be adopted (and later re-keyed to + // the stable id) by merging into the colliding entry. + const tempId = `sidebar-${ClineProvider["nextViewId"]}` + const proxy = new ContextProxy(mockContext) + await proxy.setValue("viewStates", { [tempId]: { currentApiConfigName: "old-profile", updatedAt: 1 } }) + + const fresh = new ClineProvider(mockContext, mockOutputChannel, "sidebar", proxy, new WebviewFocusTracker()) + expect(fresh.viewId).toBe(tempId) + + await fresh.saveViewState("mode", "code") + + const states = fresh["getPersistedViewStates"]({ fresh: true }) + expect(states[tempId]).toEqual({ mode: "code", updatedAt: expect.any(Number) }) + expect(fresh["viewLocalState"].currentApiConfigName).toBeUndefined() + }) + + it("does not mark the temporary id as authored when the durable write fails", async () => { + // Authorship must be recorded only after the write lands: a failed persistence + // that still marked the id owned would let a later load adopt an entry that was + // never actually stored. + const tempId = `sidebar-${ClineProvider["nextViewId"]}` + const proxy = new ContextProxy(mockContext) + const fresh = new ClineProvider(mockContext, mockOutputChannel, "sidebar", proxy, new WebviewFocusTracker()) + expect(fresh.viewId).toBe(tempId) + + const originalUpdate = mockContext.globalState.update + mockContext.globalState.update = vi.fn().mockImplementation((key: string, _value: unknown) => { + if (key === "viewStates") { + return Promise.reject(new Error("storage unavailable")) + } + return Promise.resolve() + }) + + await expect(fresh.saveViewState("mode", "code")).rejects.toThrow("storage unavailable") + expect(fresh["wroteUnderTemporaryViewStateId"]).toBe(false) + + mockContext.globalState.update = originalUpdate + }) + + it("does not adopt an entry under the temporary name that this instance never wrote", async () => { + await provider.resolveWebviewView(mockWebviewView) + + // Temporary ids restart from 0 on every host start, so the same name can + // belong to a different session. An entry this instance never wrote must not + // be adopted as this view's state. + // Seed through the durable write path so the assertions below read the + // same backing map a re-key adoption would write to: a frozen get() + // literal made the negative assertion unable to fail. + await provider.contextProxy.setValue("viewStates", { [provider.viewId]: { mode: "architect" } }) + + await provider["setViewStateId"]("stable-test-view") + + const states = provider["getPersistedViewStates"]({ fresh: true }) + expect(states[provider.viewId]).toEqual({ mode: "architect" }) + expect(states["stable-test-view"]).toBeUndefined() + }) + }) + + describe("setViewStateId input validation", () => { + it("ignores a non-string viewStateId from a crafted message", async () => { + const before = provider["viewStateId"] + // A crafted postMessage can carry any JSON value despite the declared type. + await provider.setViewStateId(42 as unknown as string) + expect(provider["viewStateId"]).toBe(before) + }) + + it("ignores an oversized viewStateId", async () => { + const before = provider["viewStateId"] + await provider.setViewStateId("x".repeat(200)) + expect(provider["viewStateId"]).toBe(before) + }) + + it("refuses a viewStateId already claimed by another live view", async () => { + const other = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + await other.setViewStateId("claimed-by-other-view") + await provider.setViewStateId("claimed-by-other-view") + expect(provider["viewStateId"]).not.toBe("claimed-by-other-view") + expect(other["viewStateId"]).toBe("claimed-by-other-view") + } finally { + await other.dispose() + } + }) + }) }) diff --git a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts index 9b5996a6ea1..0ca09ab6b39 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts @@ -1138,4 +1138,126 @@ describe("ClineProvider - Sticky Provider Profile", () => { ) }) }) + + describe("deleteProviderProfile", () => { + it("removes the stored profile so a dangling mode mapping can no longer re-activate it", async () => { + await provider.resolveWebviewView(mockWebviewView) + + // Seed the stored profile settings: the default profile plus a child + // profile (mirroring the cross-profile subtasks e2e scenario), with the + // "ask" mode mapped to the child profile. + const defaultId = await provider.providerSettingsManager.saveConfig("default", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "mock-key", + openRouterModelId: "openai/gpt-4.1", + }) + const childId = await provider.providerSettingsManager.saveConfig("subtask-child-profile", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "mock-key", + openRouterModelId: "openai/gpt-4.1-mini", + }) + await provider.providerSettingsManager.setModeConfig("ask", childId) + + // The UI-facing list mirrors the store, as maintained by upsert/activate. + await provider.contextProxy.setValues({ + listApiConfigMeta: [ + { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, + { name: "subtask-child-profile", id: childId, apiProvider: providerIdentifiers.openrouter }, + ], + currentApiConfigName: "subtask-child-profile", + }) + + await provider.deleteProviderProfile({ + name: "subtask-child-profile", + id: childId, + apiProvider: providerIdentifiers.openrouter, + }) + + // The deleted profile's settings are gone from the manager store. + const remaining = await provider.providerSettingsManager.listConfig() + expect(remaining.some((config) => config.name === "subtask-child-profile")).toBe(false) + await expect( + provider.providerSettingsManager.getProfile({ name: "subtask-child-profile" }), + ).rejects.toThrow(/subtask-child-profile.*not found/) + + // The mode mapping still points at the deleted id, but it no longer + // resolves to a stored profile, so handleModeSwitch falls through to the + // current configuration instead of re-activating the deleted profile. + const savedConfigId = await provider.providerSettingsManager.getModeConfigId("ask") + expect(savedConfigId).toBe(childId) + expect(remaining.find(({ id }) => id === savedConfigId)).toBeUndefined() + + // The context was repointed at the surviving profile. + const values = provider.contextProxy.getValues() + expect(values.currentApiConfigName).toBe("default") + expect(values.listApiConfigMeta?.map((entry) => entry.name)).toEqual(["default"]) + }) + + it("treats an already-gone secret as success so the stale list entry is still pruned", async () => { + await provider.resolveWebviewView(mockWebviewView) + + // Only the default profile exists in the store: the ghost profile's secret + // was already gone (e.g. pruned by an earlier run) but its list entry + // survived. + const defaultId = await provider.providerSettingsManager.saveConfig("default", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "mock-key", + openRouterModelId: "openai/gpt-4.1", + }) + await provider.contextProxy.setValues({ + listApiConfigMeta: [ + { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, + { name: "ghost-profile", id: "ghost-id", apiProvider: providerIdentifiers.openrouter }, + ], + currentApiConfigName: "ghost-profile", + }) + + // The manager's "not found" rejection must not surface to the caller ... + await expect( + provider.deleteProviderProfile({ + name: "ghost-profile", + id: "ghost-id", + apiProvider: providerIdentifiers.openrouter, + }), + ).resolves.not.toThrow() + + // ... it prunes the stale list entry and repoints the selection. + const values = provider.contextProxy.getValues() + expect(values.currentApiConfigName).toBe("default") + expect(values.listApiConfigMeta?.map((entry) => entry.name)).toEqual(["default"]) + }) + + it("still refuses to delete the last stored profile when a stale list entry remains", async () => { + await provider.resolveWebviewView(mockWebviewView) + + const defaultId = await provider.providerSettingsManager.saveConfig("default", { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "mock-key", + openRouterModelId: "openai/gpt-4.1", + }) + // A ghost list entry survives next to the only real profile, so the + // provider-level "last profile" guard does not fire: the refusal must come + // from the settings store itself. + await provider.contextProxy.setValues({ + listApiConfigMeta: [ + { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, + { name: "ghost-profile", id: "ghost-id", apiProvider: providerIdentifiers.openrouter }, + ], + currentApiConfigName: "default", + }) + + await expect( + provider.deleteProviderProfile({ + name: "default", + id: defaultId, + apiProvider: providerIdentifiers.openrouter, + }), + ).rejects.toThrow("Cannot delete the last remaining configuration") + + // Nothing was repointed or pruned. + const values = provider.contextProxy.getValues() + expect(values.currentApiConfigName).toBe("default") + expect(values.listApiConfigMeta?.map((entry) => entry.name)).toEqual(["default", "ghost-profile"]) + }) + }) }) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index e1cc7dc8445..39f9dce41c2 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -77,11 +77,12 @@ vi.mock("@roo-code/telemetry", () => ({ }, })) -import type { ModelRecord } from "@roo-code/types" +import type { ModelRecord, RooCodeSettings } from "@roo-code/types" import * as vsCodeLmProvider from "../../../api/providers/vscode-lm" import * as copilotProvider from "../../../api/providers/github-copilot" import { webviewMessageHandler } from "../webviewMessageHandler" +import { ProviderSettingsManager } from "../../config/ProviderSettingsManager" import { registerCopilotModelBroadcast } from "../../../services/language-models/copilotModelBroadcast" import type { ClineProvider } from "../ClineProvider" import { experimentDefault } from "../../../shared/experiments" @@ -111,6 +112,7 @@ const mockFetchOpenAiCodexRateLimitInfo = vi.mocked(fetchOpenAiCodexRateLimitInf const mockClineProvider = { getState: vi.fn(), postMessageToWebview: vi.fn(), + saveViewState: vi.fn(), customModesManager: { getCustomModes: vi.fn(), deleteCustomMode: vi.fn(), @@ -127,6 +129,16 @@ const mockClineProvider = { setValue: vi.fn(), getValue: vi.fn(), }, + // Delegates to contextProxy.setValue so existing assertions keep holding while + // the updateSettings flow is exercised through the provider-level mutation path. + setValue: vi + .fn() + .mockImplementation((key: string, value: unknown) => + mockClineProvider.contextProxy.setValue( + key as keyof RooCodeSettings, + value as RooCodeSettings[keyof RooCodeSettings], + ), + ), log: vi.fn(), postStateToWebview: vi.fn(), resolveWebviewThemeFixtureProbe: vi.fn(), @@ -138,6 +150,31 @@ const mockClineProvider = { cwd: "/mock/workspace", } as unknown as ClineProvider +// The webviewDidLaunch suite replaces these mockClineProvider members with +// per-test doubles. Snapshot the module-level originals at collection time and +// restore them in that suite's own afterEach, so the launch stubs never leak +// into the suites that run after it (vitest runs suites in file order). +// Single structural cast: the class types these members as methods / readonly +// properties, which cannot be re-assigned to swap in a per-test double. +const launchSuiteSnapshot = (() => { + const view = mockClineProvider as { + setViewStateId: unknown + workspaceTracker: unknown + providerSettingsManager: unknown + activateProviderProfile: unknown + getMcpHub: unknown + getStateToPostToWebview: unknown + } + return { + setViewStateId: view.setViewStateId, + workspaceTracker: view.workspaceTracker, + providerSettingsManager: view.providerSettingsManager, + activateProviderProfile: view.activateProviderProfile, + getMcpHub: view.getMcpHub, + getStateToPostToWebview: view.getStateToPostToWebview, + } +})() + describe("webviewMessageHandler - Copilot authentication", () => { beforeEach(() => { vi.clearAllMocks() @@ -866,6 +903,226 @@ import { Terminal } from "../../../integrations/terminal/Terminal" import { TerminalRegistry } from "../../../integrations/terminal/TerminalRegistry" import { providerIdentifiers, retiredProviderIdentifiers } from "@roo-code/types/provider-identifiers" +describe("webviewMessageHandler - webviewDidLaunch", () => { + // Single structural view of the provider members this suite reassigns at runtime: + // the class type declares several of them as getters / readonly, so the fixture + // type is the writable view of the same object (no cast through unknown needed). + type LaunchProviderFixture = { + setViewStateId: (viewStateId: string) => Promise + workspaceTracker: { initializeFilePaths: () => Promise } + providerSettingsManager: { + listConfig: () => Promise + hasConfig: (name: string) => Promise + getProfile: (options: { name: string }) => Promise + } + activateProviderProfile: (options: { name: string }) => Promise + getMcpHub: () => unknown + getStateToPostToWebview: () => Promise<{ telemetrySetting: string }> + } + const double = mockClineProvider as LaunchProviderFixture + + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(mockClineProvider.getState).mockResolvedValue( + Object.assign({} as Awaited>, { + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + currentApiConfigName: "view-local-profile", + }), + ) + double.setViewStateId = vi.fn().mockResolvedValue(undefined) + double.workspaceTracker = { initializeFilePaths: vi.fn().mockResolvedValue(undefined) } + double.providerSettingsManager = { + listConfig: vi + .fn() + .mockResolvedValue([{ name: "shared-profile", apiProvider: providerIdentifiers.anthropic }]), + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi.fn().mockResolvedValue({ + id: "shared-profile-id", + name: "shared-profile", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }), + } + double.activateProviderProfile = vi.fn().mockResolvedValue(undefined) + double.getMcpHub = vi.fn().mockReturnValue(undefined) + double.getStateToPostToWebview = vi.fn().mockResolvedValue({ telemetrySetting: "disabled" }) + vi.mocked(mockClineProvider.customModesManager.getCustomModes).mockResolvedValue([]) + // Key-aware so a mutated global-state key (e.g. "") resolves to nothing instead + // of the canned value, keeping the re-pin branch's global lookup observable. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "currentApiConfigName" ? "shared-profile" : undefined, + ) + vi.mocked(mockClineProvider.contextProxy.setValue).mockResolvedValue(undefined) + }) + + it("validates the view-local currentApiConfigName on launch", async () => { + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + + expect(double.setViewStateId).toHaveBeenCalledWith("view-1") + + // The merged (view-local) name is validated first; the shared global is only + // consulted when the view-local name is invalid. + expect(double.providerSettingsManager.hasConfig).toHaveBeenCalledWith("view-local-profile") + expect(mockClineProvider.providerSettingsManager.hasConfig).toHaveBeenCalledWith("shared-profile") + // Both names are invalid in this setup, so the shared global is repaired. + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("currentApiConfigName", "shared-profile") + expect(mockClineProvider.activateProviderProfile).toHaveBeenCalledWith({ name: "shared-profile" }) + }) + + it("re-pins only the view when its profile is missing but the shared global is still valid", async () => { + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation( + async (name: string) => name === "shared-profile", + ) + // The order matters more than the individual calls: the re-pin changes what this view + // resolves to, and neither write below posts anything by itself. + const order: string[] = [] + vi.mocked(mockClineProvider.saveViewState).mockImplementation(async (...args: unknown[]) => { + order.push(`save:${String(args[0])}`) + }) + vi.mocked(mockClineProvider.postStateToWebview).mockImplementation(async () => { + order.push("post") + }) + + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + // The view pin is re-pinned to the first available profile, + // and the shared global selection is left untouched: no global write, no global activation. + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("currentApiConfigName", "shared-profile") + // A re-pin that leaves the overlay empty is half a repair: a view whose overlay carries a + // name but no apiConfiguration resolves that field from the shared store, so it would + // display its own pin while running whatever profile the shared selection names next. The + // seed mirrors loadViewState - the stored record without its name. + expect(double.providerSettingsManager.getProfile).toHaveBeenCalledWith({ name: "shared-profile" }) + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("apiConfiguration", { + id: "shared-profile-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }) + expect(mockClineProvider.saveViewState).not.toHaveBeenCalledWith("apiConfiguration", undefined) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith( + "currentApiConfigName", + "shared-profile", + ) + expect(mockClineProvider.activateProviderProfile).not.toHaveBeenCalled() + + // A repaired pin is half a repair until the state is posted: the listApiConfig message + // that follows the re-pin carries the profile list only, so without a state post the + // webview keeps rendering the profile that no longer resolves until some other message + // arrives. + expect(order).toContain("post") + expect(order.lastIndexOf("post")).toBeGreaterThan(order.lastIndexOf("save:currentApiConfigName")) + }) + + it("re-pins the view to the shared global profile rather than the first listed profile", async () => { + double.providerSettingsManager.listConfig = vi.fn().mockResolvedValue([ + { name: "first-listed", apiProvider: providerIdentifiers.anthropic }, + { name: "shared-profile", apiProvider: providerIdentifiers.anthropic }, + ]) + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation( + async (name: string) => name === "shared-profile", + ) + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + // The view pin follows the still-valid shared global selection, not the first + // profile in the list; the global selection is left untouched. + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("currentApiConfigName", "shared-profile") + expect(mockClineProvider.saveViewState).not.toHaveBeenCalledWith("currentApiConfigName", "first-listed") + expect(mockClineProvider.activateProviderProfile).not.toHaveBeenCalled() + }) + + it("seeds the re-pinned profile's settings before persisting the re-pin so a failed pin stays retryable", async () => { + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation( + async (name: string) => name === "shared-profile", + ) + const calls: Array<[string, unknown]> = [] + const originalSaveViewState = mockClineProvider.saveViewState + mockClineProvider.saveViewState = vi.fn(async (key: string, value: unknown) => { + calls.push([key, value]) + if (key === "currentApiConfigName") { + throw new Error("pin write failed") + } + }) + try { + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + } finally { + mockClineProvider.saveViewState = originalSaveViewState + } + + // The seed must land before the pin write: a failed seed leaves the pin unwritten, so the + // merged selection stays invalid and the repair retries on the next launch instead of a + // valid pin serving the deleted profile's buffered settings. + expect(calls[0]).toEqual([ + "apiConfiguration", + { id: "shared-profile-id", apiProvider: providerIdentifiers.anthropic, apiKey: "sk-shared-profile" }, + ]) + expect(calls).toContainEqual(["currentApiConfigName", "shared-profile"]) + }) + + it("re-pins without a settings snapshot when the profile record vanishes before the seed read", async () => { + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation( + async (name: string) => name === "shared-profile", + ) + vi.mocked(double.providerSettingsManager.getProfile).mockRejectedValue(new Error("profile vanished mid-flight")) + + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + + // A seed read that fails must not cost the view the repair: the overlay falls back to empty + // and the pin still lands, so the re-pin is not swallowed by the catch around this block. + expect(double.providerSettingsManager.getProfile).toHaveBeenCalledWith({ name: "shared-profile" }) + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("apiConfiguration", undefined) + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("currentApiConfigName", "shared-profile") + expect(mockClineProvider.log).toHaveBeenCalledWith( + expect.stringContaining('Seed read failed for "shared-profile"'), + ) + }) + + it("records the legacy repair without activating a profile when no name is listed", async () => { + double.providerSettingsManager.listConfig = vi + .fn() + .mockResolvedValue([{ apiProvider: providerIdentifiers.anthropic }]) + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockResolvedValue(false) + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + // The legacy repair still records the (empty) selection, but does not activate a + // profile that has no name. + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("currentApiConfigName", undefined) + expect(mockClineProvider.activateProviderProfile).not.toHaveBeenCalled() + }) + + it("logs and continues launch when view-state registration fails", async () => { + double.setViewStateId = vi.fn().mockRejectedValue(new Error("storage down")) + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + + // The failed registration is logged ... + expect(mockClineProvider.log).toHaveBeenCalledWith(expect.stringContaining("view-state registration failed")) + // ... launch handling still posts the initial state ... + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + // ... and marks the view as launched. + expect(mockClineProvider.isViewLaunched).toBe(true) + }) + + afterEach(() => { + const view = mockClineProvider as { + setViewStateId: unknown + workspaceTracker: unknown + providerSettingsManager: unknown + activateProviderProfile: unknown + getMcpHub: unknown + getStateToPostToWebview: unknown + } + view.setViewStateId = launchSuiteSnapshot.setViewStateId + view.workspaceTracker = launchSuiteSnapshot.workspaceTracker + view.providerSettingsManager = launchSuiteSnapshot.providerSettingsManager + view.activateProviderProfile = launchSuiteSnapshot.activateProviderProfile + view.getMcpHub = launchSuiteSnapshot.getMcpHub + view.getStateToPostToWebview = launchSuiteSnapshot.getStateToPostToWebview + }) +}) + describe("webviewMessageHandler - requestLmStudioModels", () => { beforeEach(() => { vi.clearAllMocks() @@ -1929,6 +2186,152 @@ describe("webviewMessageHandler - mcpEnabled", () => { }) }) +describe("webviewMessageHandler - updateSettings profile pin", () => { + // The seed and the generic write both land on this module-level double, so snapshot the + // originals at collection time and put them back after each row: a mockImplementation left + // in place would leak into the suites that run after this one. + const originals = { + saveViewState: mockClineProvider.saveViewState, + setValue: mockClineProvider.setValue, + providerSettingsManager: (mockClineProvider as unknown as { providerSettingsManager: unknown }) + .providerSettingsManager, + } + + afterEach(() => { + const view = mockClineProvider as unknown as Record + view.saveViewState = originals.saveViewState + view.setValue = originals.setValue + view.providerSettingsManager = originals.providerSettingsManager + }) + + it("pairs the selected profile's settings with a name-only updateSettings write", async () => { + // Review thread 4506513968, printed at ClineProvider.ts line 5528 with original_line 5288: + // an updateSettings payload carrying only currentApiConfigName moved this view's pin and + // left the previously hydrated profile's settings serving it, because getState treats the + // view's overlay as a complete snapshot rather than a patch over the shared store. The + // record below carries settings that differ from anything the view could have kept. + const view = mockClineProvider as unknown as { + providerSettingsManager: { getProfile: ReturnType } + } + view.providerSettingsManager = { + getProfile: vi.fn().mockResolvedValue({ + name: "profile-b", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-b", + }), + } + const order: string[] = [] + vi.mocked(mockClineProvider.saveViewState).mockImplementation(async (...args: unknown[]) => { + order.push(`seed:${String(args[0])}`) + }) + vi.mocked(mockClineProvider.setValue).mockImplementation(async (key: string, value: unknown) => { + order.push(`write:${key}`) + await mockClineProvider.contextProxy.setValue( + key as keyof RooCodeSettings, + value as RooCodeSettings[keyof RooCodeSettings], + ) + }) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { currentApiConfigName: "profile-b" }, + }) + + // The selected record is read, and what reaches the overlay is the record without its + // name - the shape loadViewState and the launch repair already seed with. + expect(view.providerSettingsManager.getProfile).toHaveBeenCalledWith({ name: "profile-b" }) + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("apiConfiguration", { + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-b", + }) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("currentApiConfigName", "profile-b") + // Order is the finding: a pin that lands before its settings do leaves the view naming one + // profile while running another. + expect(order).toEqual(["seed:apiConfiguration", "write:currentApiConfigName"]) + }) + + it("clears the overlay instead of serving a stale one when the selected record cannot be read", async () => { + const view = mockClineProvider as unknown as { + providerSettingsManager: { getProfile: ReturnType } + } + view.providerSettingsManager = { + getProfile: vi.fn().mockRejectedValue(new Error("secrets read failed")), + } + const logSpy = vi.mocked(mockClineProvider.log) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { currentApiConfigName: "profile-b" }, + }) + + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Unable to resolve API profile 'profile-b'")) + // An unreadable record must not leave the previous profile's settings under the new name: + // the overlay is cleared, which is what an unresolvable pin already means elsewhere. + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("apiConfiguration", undefined) + // The pin itself still lands, so the selection is not silently dropped. + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("currentApiConfigName", "profile-b") + }) + + it("restores the view's prior overlay when the pin write fails after the seed", async () => { + // Review thread 4595383337: this handler seeds the view's overlay from the selected + // record and only then writes the pin. When that write rejects, the seeded settings + // must not stay behind under a pin that never moved, so the handler has to put back + // the overlay this view held before the seed. + const view = mockClineProvider as unknown as Record + view.pinnedProfileOverlay = { apiProvider: providerIdentifiers.anthropic } + const seedView = mockClineProvider as unknown as { + providerSettingsManager: { getProfile: ReturnType } + } + seedView.providerSettingsManager = { + getProfile: vi.fn().mockResolvedValue({ + name: "profile-b", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-b", + }), + } + const order: string[] = [] + const overlayTag = (value: unknown): string => + typeof value === "object" && value !== null && "apiProvider" in value ? String(value.apiProvider) : "none" + const saveViewStateMock = vi.mocked(mockClineProvider.saveViewState) + const setValueMock = vi.mocked(mockClineProvider.setValue) + // This file shares one set of module-level doubles between its suites, and the + // afterEach above restores their identities, not their implementations: capture + // what each did before this row and put it back when the row is done. + const previousSaveViewState = saveViewStateMock.getMockImplementation() + saveViewStateMock.mockImplementation(async (...args: unknown[]) => { + order.push(`overlay:${overlayTag(args[1])}`) + }) + // The pin write is called once here, so a one-shot implementation cannot leak. + setValueMock.mockImplementationOnce(async (key: string, value: unknown) => { + order.push(`write:${key}=${String(value)}`) + throw new Error("pin write failed") + }) + let thrown: unknown + try { + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { currentApiConfigName: "profile-b" }, + }) + } catch (error) { + thrown = error + } finally { + if (previousSaveViewState) { + saveViewStateMock.mockImplementation(previousSaveViewState) + } else { + saveViewStateMock.mockImplementation(async () => undefined) + } + delete view.pinnedProfileOverlay + } + expect(thrown).toBeInstanceOf(Error) + // The seed lands, the pin write fails, and only then does the overlay go back to + // what this view held before the seed - anthropic, not the seeded openrouter record. + expect(order).toEqual(["overlay:openrouter", "write:currentApiConfigName=profile-b", "overlay:anthropic"]) + expect(mockClineProvider.saveViewState).toHaveBeenLastCalledWith("apiConfiguration", { + apiProvider: providerIdentifiers.anthropic, + }) + }) +}) + describe("webviewMessageHandler - destructiveCommandGuardEnabled", () => { beforeEach(() => { vi.clearAllMocks() @@ -1997,6 +2400,37 @@ describe("webviewMessageHandler - destructiveCommandGuardEnabled", () => { expect(ensureDcgInstalled).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("destructiveCommandGuardEnabled", false) }) + + it("routes the write through provider.setValue so view-local state stays in sync", async () => { + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { destructiveCommandGuardEnabled: false }, + }) + + // The provider-level call is the write path under test. The mock forwards to + // contextProxy.setValue, so an assertion on the proxy alone would also pass + // if the handler bypassed the provider and skipped the view-local sync. + expect(mockClineProvider.setValue).toHaveBeenCalledWith("destructiveCommandGuardEnabled", false) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("destructiveCommandGuardEnabled", false) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) + }) + + // viewStates is server-owned: a crafted updatedSettings payload that echoes the + // whole map back must not rewrite (or clobber) the persisted per-view state, + // while sibling keys in the same payload still persist normally. + it("does not let updateSettings rewrite the server-owned viewStates map", async () => { + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { + viewStates: { injected: { mode: "architect" } }, + alwaysDenyUnapprovedCommands: true, + }, + }) + + expect(mockClineProvider.setValue).not.toHaveBeenCalledWith("viewStates", expect.anything()) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("viewStates", expect.anything()) + expect(mockClineProvider.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) + }) }) // A plain boolean needs no normalization branch in the updateSettings loop, @@ -2526,21 +2960,22 @@ describe("zooCodeSignOut", () => { getValues: vi.fn().mockReturnValue({ currentApiConfigName: "Zoo Gateway" }), } ;(mockClineProvider as any).providerSettingsManager = { + // Pass-through double for the cross-instance exclusion this writer now takes. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), + hasConfig: vi.fn().mockResolvedValue(true), listConfig: vi.fn().mockResolvedValue([ { name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }, { name: "Backup Zoo", apiProvider: providerIdentifiers.zooGateway }, ]), - getProfile: vi - .fn() - .mockResolvedValueOnce({ - apiProvider: providerIdentifiers.zooGateway, - zooSessionToken: "token-active", - zooGatewayModelId: "anthropic/claude-sonnet-4", - }) - .mockResolvedValueOnce({ - apiProvider: providerIdentifiers.zooGateway, - zooSessionToken: "token-backup", - }), + getProfile: vi.fn(async ({ name }: { name: string }) => + name === "Backup Zoo" + ? { apiProvider: providerIdentifiers.zooGateway, zooSessionToken: "token-backup" } + : { + apiProvider: providerIdentifiers.zooGateway, + zooSessionToken: "token-active", + zooGatewayModelId: "anthropic/claude-sonnet-4", + }, + ), saveConfig, } ;(mockClineProvider as any).upsertProviderProfile = upsertProviderProfile @@ -2590,6 +3025,529 @@ describe("zooCodeSignOut", () => { }) }) +// Own describe for the persisted-only sign-out write and the cross-instance +// exclusion it takes. Typed widening rather than a cast: the spec-wide provider +// double declares only the members most tests drive, and these tests drive the +// manager surface. The doubles are installed wholesale and put back after each +// test so no implementation leaks into a later suite. +describe("webviewMessageHandler - zooCodeSignOut persisted-only write", () => { + const provider = mockClineProvider as unknown as { + providerSettingsManager: { + listConfig: ReturnType + getProfile: ReturnType + saveConfig: ReturnType + hasConfig: ReturnType + runExclusiveAcrossInstances: ReturnType + } + contextProxy: { + getProviderSettings: ReturnType + getValues: ReturnType + } + upsertProviderProfile: ReturnType + } + const originals = { + providerSettingsManager: provider.providerSettingsManager, + contextProxy: provider.contextProxy, + upsertProviderProfile: provider.upsertProviderProfile, + } + afterEach(() => { + provider.providerSettingsManager = originals.providerSettingsManager + provider.contextProxy = originals.contextProxy + provider.upsertProviderProfile = originals.upsertProviderProfile + }) + // The record the handler reads outside the exclusion, and the one the store + // holds once the exclusion is held: a rename on another view is modelled by the + // second read returning a different record under the same name. + const readOutsideExclusion = { + apiProvider: providerIdentifiers.zooGateway, + zooSessionToken: "token-backup", + zooGatewayModelId: "model-before", + } + const wire = (readInsideExclusion: () => Promise, nameStillPresent: boolean) => { + const order: string[] = [] + provider.upsertProviderProfile = vi.fn().mockResolvedValue(undefined) + provider.contextProxy = { + getProviderSettings: vi.fn().mockReturnValue({ apiProvider: providerIdentifiers.anthropic }), + getValues: vi.fn().mockReturnValue({ currentApiConfigName: "some-other-profile" }), + } + provider.providerSettingsManager = { + listConfig: vi + .fn() + .mockResolvedValue([{ name: "Backup Zoo", apiProvider: providerIdentifiers.zooGateway }]), + getProfile: vi + .fn() + .mockResolvedValueOnce(readOutsideExclusion) + .mockImplementation(async () => { + order.push("readInsideExclusion") + return readInsideExclusion() + }), + hasConfig: vi.fn(async () => { + order.push("hasConfig") + return nameStillPresent + }), + runExclusiveAcrossInstances: vi.fn(async (callback: () => Promise) => { + order.push("exclusionEntered") + return callback() + }), + saveConfig: vi.fn(async (_name: string, value: Record) => { + order.push(`write:${String(value.zooGatewayModelId)}`) + }), + } + return order + } + + it("re-reads the persisted-only profile inside the exclusion so the write carries the current record", async () => { + const order = wire( + async () => ({ + apiProvider: providerIdentifiers.zooGateway, + zooSessionToken: "token-backup", + zooGatewayModelId: "model-after", + }), + true, + ) + await webviewMessageHandler(mockClineProvider, { type: "zooCodeSignOut" }) + expect(order).toEqual(["exclusionEntered", "hasConfig", "readInsideExclusion", "write:model-after"]) + expect(provider.providerSettingsManager.saveConfig).toHaveBeenCalledWith( + "Backup Zoo", + expect.not.objectContaining({ zooSessionToken: expect.anything() }), + ) + }) + + it("skips the persisted-only write when the name is renamed away before the exclusion is held", async () => { + const order = wire( + async () => ({ + apiProvider: providerIdentifiers.zooGateway, + zooSessionToken: "token-backup", + zooGatewayModelId: "model-after", + }), + false, + ) + await webviewMessageHandler(mockClineProvider, { type: "zooCodeSignOut" }) + expect(order).toEqual(["exclusionEntered", "hasConfig"]) + expect(provider.providerSettingsManager.hasConfig).toHaveBeenCalledWith("Backup Zoo") + expect(provider.providerSettingsManager.saveConfig).not.toHaveBeenCalled() + }) + + it("skips the persisted-only write when the re-read shows the token was already cleared", async () => { + const order = wire( + async () => ({ + apiProvider: providerIdentifiers.zooGateway, + zooGatewayModelId: "model-after", + }), + true, + ) + await webviewMessageHandler(mockClineProvider, { type: "zooCodeSignOut" }) + expect(order).toEqual(["exclusionEntered", "hasConfig", "readInsideExclusion"]) + expect(provider.providerSettingsManager.saveConfig).not.toHaveBeenCalled() + }) +}) + +describe("webviewMessageHandler - renameApiConfiguration", () => { + // Double assertion: the spec-wide provider double only declares the members + // most tests drive; this structural widening keeps these tests free of any. + const provider = mockClineProvider as unknown as { + providerSettingsManager: { + getProfile: ReturnType + saveConfig: ReturnType + deleteConfig: ReturnType + hasConfig: ReturnType + runExclusiveAcrossInstances: (cb: () => Promise) => Promise + } + repointViewLocalStateAfterProfileRename: ReturnType + activateProviderProfile: ReturnType + } + // The rename runs its name check, save, and compensation inside the manager's + // cross-instance critical section; this double runs the callback inline. + const runExclusiveAcrossInstances = (cb: () => Promise) => cb() + + // Capture the pre-suite values for the members this suite reassigns: + // vi.clearAllMocks() only resets call history - it never restores property + // assignments, so without this restore the rename doubles leak into every + // later suite in this file. + const originalRenameMembers = { + providerSettingsManager: provider.providerSettingsManager, + repointViewLocalStateAfterProfileRename: provider.repointViewLocalStateAfterProfileRename, + activateProviderProfile: provider.activateProviderProfile, + } + + afterEach(() => { + Object.assign(mockClineProvider, originalRenameMembers) + }) + + beforeEach(() => { + vi.clearAllMocks() + }) + + it("re-points views pinned to the old name before the old name is deleted", async () => { + const order: string[] = [] + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi.fn().mockResolvedValue({ id: "profile-id", apiProvider: providerIdentifiers.anthropic }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn(async () => { + order.push("delete") + }), + } + const repoint = vi.fn(async () => { + order.push("repoint") + }) + provider.repointViewLocalStateAfterProfileRename = repoint + provider.activateProviderProfile = vi.fn().mockResolvedValue(undefined) + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + + expect(repoint).toHaveBeenCalledWith("old-profile", "new-profile", { + apiProvider: providerIdentifiers.anthropic, + id: "profile-id", + }) + // The re-point must precede the deletion: a pinned view switches while the + // old name still resolves, instead of dangling for a window. + expect(order).toEqual(["repoint", "delete"]) + }) + + it("runs the name check, the save, and the compensation inside the shared critical section", async () => { + const events: string[] = [] + provider.providerSettingsManager = { + runExclusiveAcrossInstances: async (cb: () => Promise) => { + events.push("enter") + try { + return await cb() + } finally { + events.push("exit") + } + }, + hasConfig: vi.fn(async () => { + events.push("hasConfig") + return false + }), + getProfile: vi.fn().mockResolvedValue({ id: "profile-id", apiProvider: providerIdentifiers.anthropic }), + saveConfig: vi.fn(async () => { + events.push("saveConfig") + }), + deleteConfig: vi.fn(async () => { + events.push("deleteConfig") + }), + } + provider.repointViewLocalStateAfterProfileRename = vi.fn().mockResolvedValue(undefined) + provider.activateProviderProfile = vi.fn(async () => { + events.push("activate") + }) + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + + // The check, the save, and the rollback must share one critical section: + // separate locked calls let another view's same-name create fit between + // the check and the save, and the rollback then deletes that record. + expect(events[0]).toBe("enter") + expect(events.filter((event) => event === "enter")).toHaveLength(1) + expect(events).toContain("hasConfig") + expect(events).toContain("saveConfig") + expect(events).toContain("deleteConfig") + // The activation that follows takes the provider's mutation queue, not the manager lock, + // so it runs after the critical section closed. The double records the activation in the + // same event log the rest of the case reads, instead of leaving the claim in prose. + expect(events).toContain("activate") + expect(events.indexOf("activate")).toBeGreaterThan(events.indexOf("exit")) + expect(events.at(-1)).toBe("activate") + }) + + it("rolls the new profile back when the re-point fails", async () => { + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi.fn().mockResolvedValue({ id: "profile-id", apiProvider: providerIdentifiers.anthropic }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn().mockResolvedValue(undefined), + } + const repoint = vi.fn().mockRejectedValueOnce(new Error("repoint failed")) + provider.repointViewLocalStateAfterProfileRename = repoint + provider.activateProviderProfile = vi.fn().mockResolvedValue(undefined) + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + + // A failed re-point must abort before deleting the old name: deleting it + // while views still pin it would dangle every affected view. The rename's + // own durable write is rolled back instead - views back to the old name and + // the new record removed - so a failed rename cannot leave a duplicate. + expect(repoint).toHaveBeenCalledTimes(2) + expect(repoint).toHaveBeenLastCalledWith("new-profile", "old-profile", { + apiProvider: providerIdentifiers.anthropic, + id: "profile-id", + }) + expect(provider.providerSettingsManager.deleteConfig).not.toHaveBeenCalledWith("old-profile") + expect(provider.providerSettingsManager.deleteConfig).toHaveBeenCalledWith("new-profile") + expect(provider.activateProviderProfile).not.toHaveBeenCalled() + expect(mockClineProvider.log).toHaveBeenCalledWith(expect.stringContaining("Error rename api configuration")) + }) + + it("restores the old pin and removes the new profile when the deletion fails", async () => { + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi.fn().mockResolvedValue({ id: "profile-id", apiProvider: providerIdentifiers.anthropic }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn(async (name: string) => { + if (name === "old-profile") { + throw new Error("delete failed") + } + }), + } + const repoint = vi.fn().mockResolvedValue(undefined) + provider.repointViewLocalStateAfterProfileRename = repoint + provider.activateProviderProfile = vi.fn().mockResolvedValue(undefined) + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + + // A half-finished rename must not leave views pinned to the new name while + // both profiles exist: re-point them back and drop the new record. + expect(repoint).toHaveBeenCalledWith("new-profile", "old-profile", { + apiProvider: providerIdentifiers.anthropic, + id: "profile-id", + }) + expect(provider.providerSettingsManager.deleteConfig).toHaveBeenCalledWith("new-profile") + expect(provider.activateProviderProfile).not.toHaveBeenCalled() + expect(mockClineProvider.log).toHaveBeenCalledWith(expect.stringContaining("Error rename api configuration")) + }) + + it("leaves the shared selection on a name that still exists when activation fails after the rename commits", async () => { + // State the run leaves behind, printed before any choice was made: the rename + // deletes oldName inside the shared section and re-points views, so a rejection + // from the activation that follows the section happens when oldName is already + // gone. The doubles below keep a stored-name set and a shared selection so the + // surviving names and the selection can both be read out. + const stored = ["old-profile"] + let sharedSelection = "old-profile" + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn(async () => false), + getProfile: vi.fn(async ({ name }: { name: string }) => ({ + id: "profile-id", + apiProvider: providerIdentifiers.anthropic, + name, + })), + saveConfig: vi.fn(async (name: string) => { + if (stored.indexOf(name) < 0) { + stored.push(name) + } + return "profile-id" + }), + deleteConfig: vi.fn(async (name: string) => { + const at = stored.indexOf(name) + if (at < 0) { + throw new Error("no such profile") + } + stored.splice(at, 1) + }), + } + provider.repointViewLocalStateAfterProfileRename = vi.fn(async () => {}) + provider.activateProviderProfile = vi.fn(async ({ name }: { name?: string }) => { + if (name === "new-profile") { + throw new Error("shared settings write rejected") + } + sharedSelection = name ?? sharedSelection + }) + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + + // The selection the world is left with: whatever the handler last wrote for + // currentApiConfigName, or the name it started from when the handler wrote + // nothing at all. + const selectionWrites = (mockClineProvider.contextProxy.setValue as ReturnType).mock.calls + .filter((call: unknown[]) => call[0] === "currentApiConfigName") + .map((call: unknown[]) => String(call[1])) + const finalSelection = selectionWrites.length ? selectionWrites[selectionWrites.length - 1] : sharedSelection + console.log( + "PROBE_STATE stored_names " + JSON.stringify(stored.slice().sort()) + " shared_selection " + finalSelection, + ) + expect(stored.slice().sort()).toEqual(["new-profile"]) + expect(stored).toContain(finalSelection) + }) + + it("re-points views with the stored record instead of the raw webview payload", async () => { + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi.fn().mockResolvedValueOnce({ id: "profile-id" }).mockResolvedValueOnce({ + id: "profile-id", + apiProvider: providerIdentifiers.anthropic, + apiModelId: "stored-model", + }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn().mockResolvedValue(undefined), + } + const repoint = vi.fn().mockResolvedValue(undefined) + provider.repointViewLocalStateAfterProfileRename = repoint + provider.activateProviderProfile = vi.fn().mockResolvedValue(undefined) + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + + // saveConfig normalizes the record; the views and task handlers must receive + // that stored copy, not the raw webview payload with its unvalidated fields. + expect(repoint).toHaveBeenCalledWith("old-profile", "new-profile", { + id: "profile-id", + apiProvider: providerIdentifiers.anthropic, + apiModelId: "stored-model", + }) + }) + + it("rejects a rename onto an existing profile without saving", async () => { + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(true), + getProfile: vi.fn().mockResolvedValue({ id: "profile-id" }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn().mockResolvedValue(undefined), + } + provider.repointViewLocalStateAfterProfileRename = vi.fn().mockResolvedValue(undefined) + provider.activateProviderProfile = vi.fn().mockResolvedValue(undefined) + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "Foo", newName: "foo" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + + // The webview's name validation treats a case-only difference from the + // current profile as the current profile, so a case-only collision would + // otherwise overwrite the existing record - and the delete-failure rollback + // would then delete a profile the rename never owned. + expect(provider.providerSettingsManager.saveConfig).not.toHaveBeenCalled() + expect(provider.providerSettingsManager.deleteConfig).not.toHaveBeenCalled() + expect(mockClineProvider.log).toHaveBeenCalledWith(expect.stringContaining("Error rename api configuration")) + }) + + it("removes the new profile when the normalized read-back fails", async () => { + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi + .fn() + .mockResolvedValueOnce({ id: "profile-id", apiProvider: providerIdentifiers.anthropic }) + .mockRejectedValueOnce(new Error("read failed")), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn().mockResolvedValue(undefined), + } + const repoint = vi.fn().mockResolvedValue(undefined) + provider.repointViewLocalStateAfterProfileRename = repoint + provider.activateProviderProfile = vi.fn().mockResolvedValue(undefined) + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + + // The save landed but the normalized record is unreadable: the new record + // is removed so the failed rename cannot leave both names resolving to the + // same id, and no view is re-pointed onto an unverifiable record. + expect(repoint).not.toHaveBeenCalled() + expect(provider.providerSettingsManager.deleteConfig).toHaveBeenCalledWith("new-profile") + expect(provider.activateProviderProfile).not.toHaveBeenCalled() + expect(mockClineProvider.log).toHaveBeenCalledWith(expect.stringContaining("Error rename api configuration")) + }) + + it("restores the previously stored settings when the deletion fails", async () => { + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi + .fn() + .mockResolvedValueOnce({ + id: "profile-id", + apiProvider: providerIdentifiers.anthropic, + apiModelId: "old-model", + }) + .mockResolvedValueOnce({ + id: "profile-id", + apiProvider: providerIdentifiers.anthropic, + apiModelId: "new-model", + }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn(async (name: string) => { + if (name === "old-profile") { + throw new Error("delete failed") + } + }), + } + const repoint = vi.fn().mockResolvedValue(undefined) + provider.repointViewLocalStateAfterProfileRename = repoint + provider.activateProviderProfile = vi.fn().mockResolvedValue(undefined) + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiModelId: "new-model" }, + }) + + // Views rolled back to oldName must serve what oldName actually stores: the + // attempted settings were never persisted under the old name. + expect(repoint).toHaveBeenLastCalledWith("new-profile", "old-profile", { + apiProvider: providerIdentifiers.anthropic, + id: "profile-id", + apiModelId: "old-model", + }) + }) + + it("logs a failed rename compensation", async () => { + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi.fn().mockResolvedValue({ id: "profile-id", apiProvider: providerIdentifiers.anthropic }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn(async (name: string) => { + if (name === "old-profile") { + throw new Error("delete failed") + } + }), + } + const repoint = vi.fn(async (from: string) => { + if (from === "new-profile") { + throw new Error("compensation failed") + } + }) + provider.repointViewLocalStateAfterProfileRename = repoint + provider.activateProviderProfile = vi.fn().mockResolvedValue(undefined) + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + + // When the compensation itself fails both names can remain stored; the log + // must record that, not only the original deletion error. + expect(mockClineProvider.log).toHaveBeenCalledWith( + expect.stringContaining("Rename compensation failed after delete rejection"), + ) + expect(mockClineProvider.log).toHaveBeenCalledWith(expect.stringContaining("Error rename api configuration")) + }) +}) + describe("webviewMessageHandler - kimiCodeSignIn", () => { beforeEach(() => { vi.clearAllMocks() @@ -3318,3 +4276,120 @@ describe("updateSettings with the display settings", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("constructor", "x") }) }) + +describe("webviewMessageHandler - ordinary profile writes and the rename transaction", () => { + // Double assertion: the spec-wide provider double only declares the members + // most tests drive; this structural widening keeps these tests free of any. + const provider = mockClineProvider as unknown as { + providerSettingsManager: { + hasConfig: ReturnType + getProfile: ReturnType + saveConfig: ReturnType + listConfig: ReturnType + deleteConfig: ReturnType + runExclusiveAcrossInstances: (cb: () => Promise) => Promise + } + repointViewLocalStateAfterProfileRename: ReturnType + activateProviderProfile: ReturnType + upsertProviderProfile: ReturnType + } + const originalMembers = { + providerSettingsManager: provider.providerSettingsManager, + repointViewLocalStateAfterProfileRename: provider.repointViewLocalStateAfterProfileRename, + activateProviderProfile: provider.activateProviderProfile, + upsertProviderProfile: provider.upsertProviderProfile, + } + afterEach(() => { + Object.assign(mockClineProvider, originalMembers) + }) + beforeEach(() => { + vi.clearAllMocks() + }) + + it("keeps an ordinary profile write out of the rename's shared critical section", async () => { + const events: string[] = [] + // Manual deferred, stated rather than hidden: the race needs the rename to + // still be inside its critical section when the second writer starts, and + // no production timing gives that window reliably, so this test holds the + // transaction open on a promise it controls. + let holdOpen!: () => void + const heldOpen = new Promise((resolve) => { + holdOpen = resolve + }) + let releaseHold!: () => void + const holdReleased = new Promise((resolve) => { + releaseHold = resolve + }) + // Real seam: the production cross-instance queue itself, not a local copy of its tail + // chaining (review thread 4593787854). The method keys the shared lock on the private + // `secretsKey` getter and nothing else, so the host below is a real instance of the class + // carrying a spec-only key instead of an extension context: Object.create supplies the + // prototype's own method, and the single assertion names what the property descriptor + // supplies - a private getter is not part of the class's structural shape, so no + // structural object could. The key is this test's own, so its critical sections chain + // onto each other and onto no other test's queue. + const sharedQueueHost = Object.create(ProviderSettingsManager.prototype, { + secretsKey: { value: "webview-message-handler-spec-rename-queue" }, + }) as ProviderSettingsManager + const runExclusiveAcrossInstances = (cb: () => Promise) => + sharedQueueHost.runExclusiveAcrossInstances(cb) + const configs: Record> = { + "old-profile": { id: "old-id", apiProvider: providerIdentifiers.anthropic }, + } + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn(async () => { + events.push("renameHasConfig") + holdOpen() + await holdReleased + return false + }), + getProfile: vi.fn(async ({ name }: { name: string }) => configs[name] ?? { id: "unknown" }), + saveConfig: vi.fn(async (name: string, config: Record) => { + if (name === "old-profile") { + events.push("ordinaryWrite") + } else { + events.push("renameSave") + } + configs[name] = config + return config.id as string + }), + listConfig: vi.fn(async () => Object.keys(configs).map((name) => ({ name, id: String(configs[name].id) }))), + deleteConfig: vi.fn(async (name: string) => { + events.push("renameDelete") + delete configs[name] + }), + } + provider.repointViewLocalStateAfterProfileRename = vi.fn(async () => { + events.push("renameRepoint") + }) + provider.activateProviderProfile = vi.fn(async () => {}) + provider.upsertProviderProfile = vi.fn(async () => {}) + + const rename = webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + // Both message handlers run concurrently: the rename enters the shared + // section first, and the ordinary write starts while that section is held + // open on the deferred above. With the exclusion the writer takes now, its + // save chains onto the queue behind the rename; without it the save runs + // inside the rename's transaction. + const ordinary = (async () => { + await heldOpen + return webviewMessageHandler(mockClineProvider, { + type: "saveApiConfiguration", + text: "old-profile", + apiConfiguration: { apiProvider: providerIdentifiers.openai }, + }) + })() + releaseHold() + + await Promise.all([rename, ordinary]) + + expect(events).toEqual(["renameHasConfig", "renameSave", "renameRepoint", "renameDelete", "ordinaryWrite"]) + expect(Object.keys(configs).sort()).toEqual(["new-profile", "old-profile"]) + expect(configs["old-profile"]).toEqual({ apiProvider: providerIdentifiers.openai }) + }) +}) diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6641ff259f1..766a7253c66 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -601,7 +601,20 @@ export const webviewMessageHandler = async ( provider.resolveWebviewThemeFixtureProbe(message.requestId, message.themeFixture) } break - case "webviewDidLaunch": + case "webviewDidLaunch": { + // A failed view-state registration must not abort launch handling: the + // initial state, theme and API-configuration sync below still run, and the + // provider restores its previous viewStateId on failure (setViewStateId) so + // a later launch retries registration and loadViewState instead of + // treating the failed id as already handled. + try { + await provider.setViewStateId(message.viewStateId) + } catch (error) { + provider.log( + `[webviewDidLaunch] view-state registration failed: ${error instanceof Error ? error.message : String(error)}`, + ) + } + // Load custom modes first const customModes = await provider.customModesManager.getCustomModes() await updateGlobalState("customModes", customModes) @@ -650,17 +663,70 @@ export const webviewMessageHandler = async ( } } - const currentConfigName = getGlobalState("currentApiConfigName") + const currentState = await provider.getState() + const currentConfigName = currentState.currentApiConfigName if (currentConfigName) { if (!(await provider.providerSettingsManager.hasConfig(currentConfigName))) { - // Current config name not valid, get first config in list. + // The merged name (which may be this view's durable pin) no longer + // resolves. When the shared global selection is still valid, re-pin + // only this view so the global selection is left untouched; only + // repair the global when it is invalid as well. + const globalConfigName = getGlobalState("currentApiConfigName") + const globalStillValid = + !!globalConfigName && + (await provider.providerSettingsManager.hasConfig(globalConfigName)) const name = listApiConfig[0]?.name - await updateGlobalState("currentApiConfigName", name) - if (name) { - await provider.activateProviderProfile({ name }) - return + if (globalStillValid && globalConfigName) { + // Re-pin this view to the still-valid shared global selection (not the + // first listed profile) so the view adopts the shared choice; the + // global selection itself is left untouched. + // Seed the pinned profile's snapshot instead of only clearing the buffer: a view whose + // overlay carries a name but no apiConfiguration resolves that field from the shared + // ContextProxy - getState merges viewLocalState over it at ClineProvider.ts:4913 - so the + // view would show its own pin while running whatever profile the shared store names next. + // The snapshot is taken the way loadViewState takes it (ClineProvider.ts:1137-1140): the + // stored record without its name. + // Seed before the pin write. A seed write that fails leaves the pin unwritten, so the + // invalid selection stays retryable on the next launch, and a seed that lands while the + // pin write fails leaves the view holding the settings of the profile it is about to be + // pinned to rather than the missing profile's stale buffer. + let seedSettings: ProviderSettings | undefined + try { + const { name: _seedProfileName, ...seedProfile } = + await provider.providerSettingsManager.getProfile({ + name: globalConfigName, + }) + seedSettings = seedProfile as ProviderSettings + } catch (error) { + // The record can vanish between the hasConfig check above and this read. Fall back to + // an empty overlay - what a re-pin left before the seed existed - so the pin write + // still lands instead of the whole repair being lost to this error. + provider.log( + `[webviewDidLaunch] Seed read failed for "${globalConfigName}"; re-pinning without a settings snapshot: ${String(error)}`, + ) + } + // The durable view entry carries only mode and currentApiConfigName (see + // _persistViewLocalStateFromMutation), so this seed is an in-memory overlay write; the + // pin below is what persists. + await provider.saveViewState("apiConfiguration", seedSettings) + await provider.saveViewState("currentApiConfigName", globalConfigName) + // The repair changes what this view resolves to, so the state has to be posted: the + // two writes above update provider state without posting it, and the listApiConfig + // message below carries the profile list only, so without this the webview keeps + // rendering the profile that no longer resolves until another message arrives. + await provider.postStateToWebview() + // Fall through: refresh listApiConfigMeta and post listApiConfig + // to this webview below. + } else { + // Current config name not valid, get first config in list. + await updateGlobalState("currentApiConfigName", name) + + if (name) { + await provider.activateProviderProfile({ name }) + return + } } } } @@ -710,6 +776,7 @@ export const webviewMessageHandler = async ( provider.isViewLaunched = true break + } case "webviewHeartbeat": // Confirm renderer liveness and advance the watchdog recovery health window. provider.updateWebviewHeartbeat() @@ -794,12 +861,23 @@ export const webviewMessageHandler = async ( } for (const [key, value] of Object.entries(message.updatedSettings)) { + // Only the pin branch below assigns this: the overlay this view held before that + // branch moved it, kept so a pin write that fails can put it back. + let priorViewOverlay: ProviderSettings | undefined // An invalid display value is ignored, before anything is done for it. if (isInvalidDisplayValue(key, value)) { provider.log(`[updateSettings] Ignored an invalid value for ${key}`) continue } + // viewStates is server-owned per-view persistence (identity pins and + // loaded-profile overlays). The settings UI never puts it into + // updatedSettings, so a crafted renderer payload must not be able to + // rewrite the whole map through the generic loop below. + if (key === "viewStates") { + continue + } + let newValue = value if (key === "language") { @@ -907,9 +985,48 @@ export const webviewMessageHandler = async ( if (!value) { continue } + } else if (key === "currentApiConfigName") { + // A name-only write moves this view's pin and leaves behind the overlay it hydrated + // from the profile it was pinned to: getState reads viewLocalState.apiConfiguration as a + // complete snapshot rather than a patch over the shared store, so the view keeps running + // the previous profile's settings under the new name. Pair the write the way the launch + // repair does above - read the selected record and seed the overlay with that record + // without its name, before the pin write at the end of this loop. A record that cannot be + // read clears the overlay instead, so the failure leaves the shared settings in place + // rather than some other profile's. The seed is in-memory only (_persistViewLocalStateFrom + // Mutation carries mode and currentApiConfigName), so the durable write stays the pin. + const pinnedName = typeof value === "string" ? value : undefined + priorViewOverlay = provider.pinnedProfileOverlay + if (pinnedName) { + try { + const { name: _seedProfileName, ...seedProfile } = + await provider.providerSettingsManager.getProfile({ name: pinnedName }) + await provider.saveViewState("apiConfiguration", seedProfile as ProviderSettings) + } catch (error) { + provider.log( + `[updateSettings] Unable to resolve API profile '${pinnedName}'; cleared this view's settings overlay instead of keeping the previous profile's: ${error instanceof Error ? error.message : String(error)}`, + ) + await provider.saveViewState("apiConfiguration", undefined) + } + } else { + // The pin is being cleared, so nothing should keep serving settings under no name. + await provider.saveViewState("apiConfiguration", undefined) + } } - await provider.contextProxy.setValue(key as keyof RooCodeSettings, newValue) + // Route through provider.setValue so view-local buffer/pin sync stays + // consistent with the other mutation paths. + try { + await provider.setValue(key as keyof RooCodeSettings, newValue) + } catch (error) { + if (key === "currentApiConfigName") { + // Review thread 4595383337: the pin did not move, so the overlay this iteration + // seeded or cleared cannot stay under the name it is pinned to now - put back + // exactly what this view held before the branch ran. + await provider.saveViewState("apiConfiguration", priorViewOverlay) + } + throw error + } } } catch (error) { failed = true @@ -1719,9 +1836,7 @@ export const webviewMessageHandler = async ( // containment as a literal and escape only after that later decode. if (fromMarkdown) { const decoded = decodeUntrustedPathToStable(rawPath) - // Stryker disable next-line ConditionalExpression,BlockStatement: hostile non-stabilizing encodings are unreachable from the webview (its posts are plain link targets); the bound is defensive if (decoded === null) { - // Stryker disable next-line CallExpression: hostile non-stabilizing encodings are pinned by the direct decodeUntrustedPathToStable bound test; the webview never posts such values rejectOutsideWorkspace() break } @@ -2483,10 +2598,20 @@ export const webviewMessageHandler = async ( } case "saveApiConfiguration": if (message.text && message.apiConfiguration) { + const profileName = message.text + const profileSettings = message.apiConfiguration try { - await provider.providerSettingsManager.saveConfig(message.text, message.apiConfiguration) - const listApiConfig = await provider.providerSettingsManager.listConfig() - await updateGlobalState("listApiConfigMeta", listApiConfig) + // Ask quoted from the review thread at this file's line 2613: ordinary + // profile writes must participate in the same cross-instance exclusion + // the rename takes, without that exclusion being reacquired inside the + // rename transaction. This arm is a separate entry point, outside the + // rename's critical section, so it acquires the section here rather than + // wrapping the rename body a second time. + await provider.providerSettingsManager.runExclusiveAcrossInstances(async () => { + await provider.providerSettingsManager.saveConfig(profileName, profileSettings) + const listApiConfig = await provider.providerSettingsManager.listConfig() + await updateGlobalState("listApiConfigMeta", listApiConfig) + }) } catch (error) { provider.log( `Error save api configuration: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, @@ -2516,26 +2641,128 @@ export const webviewMessageHandler = async ( } case "renameApiConfiguration": if (message.values && message.apiConfiguration) { + // Whether the shared critical section finished, and under which name it committed: + // the catch below cannot re-derive either, because a rejection from the + // activation after the section looks the same as a failure inside it. + let renameCommitted = false + let committedNewName: string | undefined try { const { oldName, newName } = message.values + // Two facts the catch below needs and cannot re-derive: whether the + // transaction committed, and under which name the rename committed it. if (oldName === newName) { break } - // Load the old configuration to get its ID. - const { id } = await provider.providerSettingsManager.getProfile({ name: oldName }) + // The webview's name validation treats a case-only difference from the + // current profile as the current profile, so a case-only collision reaches + // here as a rename onto an existing record. Reject it instead of + // overwriting that profile: the rollback below would otherwise delete a + // record the rename never owned. + + // The name check, the save, and the compensation run in one critical + // section shared with every other view's manager (each view builds its own + // `ProviderSettingsManager` over the same secrets): with separate locked + // calls, a same-name create from another view fits between the check and + // the save, and the rollback then deletes that view's record. + await provider.providerSettingsManager.runExclusiveAcrossInstances(async () => { + if (await provider.providerSettingsManager.hasConfig(newName)) { + throw new Error(`A profile named '${newName}' already exists`) + } + + // Load the old configuration to get its ID, and keep its full stored + // record: a rollback must re-point views to the settings oldName actually + // persists, not to the payload the rename attempted. + const { name: _previousName, ...previousRecord } = + await provider.providerSettingsManager.getProfile({ name: oldName }) + const { id } = previousRecord + + // Create a new configuration with the new name and old ID. + await provider.providerSettingsManager.saveConfig(newName, { ...message.apiConfiguration, id }) + + // saveConfig normalizes the record (legacy downgrades, schema parse): hand + // the stored copy to the views and task handlers instead of the raw + // webview payload, so unvalidated fields cannot bypass the profile-schema + // normalization on the way into view state. When the read-back fails the + // rename cannot proceed on a trustworthy record: remove the new record + // before reporting so the failed rename cannot leave both names resolving + // to the same id. + let normalizedRenamed: typeof previousRecord + try { + const { name: _renamedName, ...renamedRecord } = + await provider.providerSettingsManager.getProfile({ name: newName }) + normalizedRenamed = renamedRecord + } catch (error) { + try { + await provider.providerSettingsManager.deleteConfig(newName) + } catch (cleanupError) { + provider.log( + `Rename rollback failed to remove '${newName}': ${JSON.stringify(cleanupError, Object.getOwnPropertyNames(cleanupError), 2)}`, + ) + } + throw error + } - // Create a new configuration with the new name and old ID. - await provider.providerSettingsManager.saveConfig(newName, { ...message.apiConfiguration, id }) + // Re-point live views pinned to the old name before it stops + // resolving: the rename keeps the id, so their pins should follow the + // record instead of dangling, and their overlays must serve the + // renamed settings rather than the pre-rename copy. A failed re-point can + // leave views already following newName, so undo this rename's own + // durable write before reporting: the reverse re-point returns the views + // that moved (the others never left oldName) and the new record goes + // away, leaving the pre-rename state intact. + try { + await provider.repointViewLocalStateAfterProfileRename(oldName, newName, normalizedRenamed) + } catch (error) { + try { + await provider.repointViewLocalStateAfterProfileRename(newName, oldName, previousRecord) + await provider.providerSettingsManager.deleteConfig(newName) + } catch (compensationError) { + provider.log( + `Rename compensation failed after re-point rejection: ${JSON.stringify(compensationError, Object.getOwnPropertyNames(compensationError), 2)}`, + ) + } + throw error + } - // Delete the old configuration. - await provider.providerSettingsManager.deleteConfig(oldName) + // Delete the old configuration. A failure here would leave both names + // resolving and every live view pinned to the new name: undo the re-point + // with the previously stored record - not the attempted payload, which was + // never persisted under the old name - and drop the new record so the + // pre-rename state survives intact. A failed compensation is logged: both + // names can then remain stored, and the log is the only trace of that + // inconsistency. + try { + await provider.providerSettingsManager.deleteConfig(oldName) + } catch (error) { + try { + await provider.repointViewLocalStateAfterProfileRename(newName, oldName, previousRecord) + await provider.providerSettingsManager.deleteConfig(newName) + } catch (compensationError) { + provider.log( + `Rename compensation failed after delete rejection: ${JSON.stringify(compensationError, Object.getOwnPropertyNames(compensationError), 2)}`, + ) + } + throw error + } + renameCommitted = true + committedNewName = newName + }) // Re-activate to update the global settings related to the // currently activated provider profile. await provider.activateProviderProfile({ name: newName }) } catch (error) { + // The ask at this file's line 2690 offers two shapes for a failed rename: + // roll it back, or treat it as committed and make the shared selection name a + // profile that exists. A rejection from the activation above arrives after the + // transaction committed - oldName already deleted, views and tasks already + // re-pointed - so this branch takes the second shape: the rename stands and the + // shared selection is moved onto the stored name instead of left on the deleted one. + if (renameCommitted && committedNewName) { + await updateGlobalState("currentApiConfigName", committedNewName) + } provider.log( `Error rename api configuration: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, ) @@ -3232,7 +3459,27 @@ export const webviewMessageHandler = async ( `[zooCodeSignOut] Cleared zooSessionToken from "${entry.name}" profile and updated in-memory handler`, ) } else if (profile.zooSessionToken) { - await provider.providerSettingsManager.saveConfig(entry.name, cleanedProfile) + // Same exclusion as the rename, taken at the point this write enters: + // a persisted-only profile rewrite is an ordinary profile write, and a + // rename in flight on another view must not interleave with it. + // The record above was read before this exclusion was held, so a rename + // or a token clear on another view can supersede it in between; re-read + // under the same exclusion the write takes, and skip when the name is gone + // or its token is already gone, so this write never resurrects a superseded + // snapshot. + await provider.providerSettingsManager.runExclusiveAcrossInstances(async () => { + if (!(await provider.providerSettingsManager.hasConfig(entry.name))) { + return + } + const currentProfile = await provider.providerSettingsManager.getProfile({ + name: entry.name, + }) + if (!currentProfile.zooSessionToken) { + return + } + const { zooSessionToken: _supersededToken, ...currentCleaned } = currentProfile + await provider.providerSettingsManager.saveConfig(entry.name, currentCleaned) + }) provider.log(`[zooCodeSignOut] Cleared zooSessionToken from "${entry.name}" profile`) } } catch (profileError) { diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a9..1fad7b0e65f 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -901,12 +901,12 @@ }, "core/webview/__tests__/ClineProvider.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 195 + "count": 193 } }, "core/webview/__tests__/ClineProvider.sticky-mode.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 27 + "count": 26 } }, "core/webview/__tests__/ClineProvider.sticky-profile.spec.ts": { diff --git a/src/package.json b/src/package.json index 47b4649169d..b7eb0898d01 100644 --- a/src/package.json +++ b/src/package.json @@ -95,6 +95,26 @@ "title": "%command.settings.title%", "icon": "$(settings-gear)" }, + { + "command": "zoo-code.plusButtonClickedInTab", + "title": "%command.newTask.title%", + "icon": "$(edit)" + }, + { + "command": "zoo-code.settingsButtonClickedInTab", + "title": "%command.settings.title%", + "icon": "$(settings-gear)" + }, + { + "command": "zoo-code.marketplaceButtonClickedInTab", + "title": "%command.marketplace.title%", + "icon": "$(extensions)" + }, + { + "command": "zoo-code.historyButtonClickedInTab", + "title": "%command.history.title%", + "icon": "$(history)" + }, { "command": "zoo-code.openInNewTab", "title": "%command.openInNewTab.title%", @@ -251,22 +271,22 @@ ], "editor/title": [ { - "command": "zoo-code.plusButtonClicked", + "command": "zoo-code.plusButtonClickedInTab", "group": "navigation@1", "when": "activeWebviewPanelId == zoo-code.TabPanelProvider" }, { - "command": "zoo-code.settingsButtonClicked", + "command": "zoo-code.settingsButtonClickedInTab", "group": "navigation@2", "when": "activeWebviewPanelId == zoo-code.TabPanelProvider" }, { - "command": "zoo-code.marketplaceButtonClicked", + "command": "zoo-code.marketplaceButtonClickedInTab", "group": "navigation@3", "when": "activeWebviewPanelId == zoo-code.TabPanelProvider" }, { - "command": "zoo-code.historyButtonClicked", + "command": "zoo-code.historyButtonClickedInTab", "group": "overflow@1", "when": "activeWebviewPanelId == zoo-code.TabPanelProvider" }, @@ -275,6 +295,24 @@ "group": "overflow@2", "when": "activeWebviewPanelId == zoo-code.TabPanelProvider" } + ], + "commandPalette": [ + { + "command": "zoo-code.plusButtonClickedInTab", + "when": "false" + }, + { + "command": "zoo-code.settingsButtonClickedInTab", + "when": "false" + }, + { + "command": "zoo-code.marketplaceButtonClickedInTab", + "when": "false" + }, + { + "command": "zoo-code.historyButtonClickedInTab", + "when": "false" + } ] }, "keybindings": [ diff --git a/webview-ui/src/context/ExtensionStateContext.tsx b/webview-ui/src/context/ExtensionStateContext.tsx index 38bec0fd8b6..b2499d8fd79 100644 --- a/webview-ui/src/context/ExtensionStateContext.tsx +++ b/webview-ui/src/context/ExtensionStateContext.tsx @@ -635,7 +635,10 @@ export const ExtensionStateContextProvider: React.FC<{ }, [handleMessage]) useEffect(() => { - vscode.postMessage({ type: "webviewDidLaunch" }) + vscode.postMessage({ + type: "webviewDidLaunch", + viewStateId: typeof vscode.getViewStateId === "function" ? vscode.getViewStateId() : undefined, + }) }, []) // Apply the configurable chat font size as a CSS variable. When unset, the diff --git a/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx b/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx index 71580979605..a106bcd3828 100644 --- a/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx +++ b/webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx @@ -22,8 +22,16 @@ import { mergeExtensionState, createInitialExtensionState, } from "../ExtensionStateContext" +import { vscode } from "@src/utils/vscode" import { StringCache } from "@/utils/stringCache" +vi.mock("@src/utils/vscode", () => ({ + vscode: { + postMessage: vi.fn(), + getViewStateId: vi.fn(() => "view-a"), + }, +})) + const TestComponent = () => { const { allowedCommands, @@ -140,8 +148,29 @@ const InitialStateTestComponent = () => { ) } +const ViewLocalStateTestComponent = () => { + const { mode, setMode, currentApiConfigName, setCurrentApiConfigName } = useExtensionState() + + return ( +
+
{mode}
+
{currentApiConfigName}
+ + +
+ ) +} + describe("ExtensionStateContext", () => { afterEach(() => vi.restoreAllMocks()) + beforeEach(() => { + vi.clearAllMocks() + }) + it.each([ ["the item matches the pinned task id and no item is loaded yet", "task-a", undefined, "task-a", true], ["the item belongs to another task", "task-a", undefined, "task-b", false], @@ -613,6 +642,74 @@ describe("ExtensionStateContext", () => { expectMessages([currentMessage]) }) + it("posts webviewDidLaunch with the stable viewStateId from vscode API", () => { + render( + + + , + ) + + expect(vscode.getViewStateId).toHaveBeenCalled() + expect(vscode.postMessage).toHaveBeenCalledWith({ type: "webviewDidLaunch", viewStateId: "view-a" }) + }) + + it("posts webviewDidLaunch without a viewStateId when getViewStateId is unavailable", () => { + const savedGetViewStateId = vscode.getViewStateId + Object.defineProperty(vscode, "getViewStateId", { configurable: true, value: undefined }) + try { + render( + + + , + ) + + expect(vscode.postMessage).toHaveBeenCalledWith({ type: "webviewDidLaunch", viewStateId: undefined }) + } finally { + Object.defineProperty(vscode, "getViewStateId", { configurable: true, value: savedGetViewStateId }) + } + }) + + it("applies mode and profile from a later state payload after local edits", () => { + render( + + + , + ) + + act(() => { + window.dispatchEvent( + new MessageEvent("message", { + data: { + type: "state", + state: { mode: "code", currentApiConfigName: "profile-a", apiConfiguration: {} }, + }, + }), + ) + }) + expect(screen.getByTestId("view-local-mode")).toHaveTextContent("code") + expect(screen.getByTestId("view-local-api-config")).toHaveTextContent("profile-a") + + act(() => { + screen.getByTestId("set-local-mode").click() + screen.getByTestId("set-local-api-config").click() + }) + expect(screen.getByTestId("view-local-mode")).toHaveTextContent("ask") + expect(screen.getByTestId("view-local-api-config")).toHaveTextContent("local-profile") + + act(() => { + window.dispatchEvent( + new MessageEvent("message", { + data: { + type: "state", + state: { mode: "architect", currentApiConfigName: "profile-b", apiConfiguration: {} }, + }, + }), + ) + }) + expect(screen.getByTestId("view-local-mode")).toHaveTextContent("architect") + expect(screen.getByTestId("view-local-api-config")).toHaveTextContent("profile-b") + }) + it("initializes with empty allowedCommands array", () => { render( diff --git a/webview-ui/src/utils/__tests__/vscode.spec.ts b/webview-ui/src/utils/__tests__/vscode.spec.ts new file mode 100644 index 00000000000..d030e04951d --- /dev/null +++ b/webview-ui/src/utils/__tests__/vscode.spec.ts @@ -0,0 +1,384 @@ +import { VSCodeAPIWrapper } from "../vscode" + +const originalCrypto = globalThis.crypto +const originalLocalStorage = globalThis.localStorage + +// Minimal Storage surface for VSCodeAPIWrapper browser fallback tests. Typed +// precisely (instead of casting to Storage) so each double only promises the +// members the wrapper actually touches. +interface MockStorage { + getItem(key: string): string | null + setItem(key: string, value: string): void + removeItem(key: string): void + clear(): void +} + +const createMockStorage = (initialState: Record = {}): MockStorage => { + const state = { ...initialState } + return { + getItem: vi.fn((key: string) => state[key] ?? null), + setItem: vi.fn((key: string, value: string) => { + state[key] = value + }), + removeItem: vi.fn((key: string) => { + delete state[key] + }), + clear: vi.fn(() => { + for (const key of Object.keys(state)) { + delete state[key] + } + }), + } +} + +describe("VSCodeAPIWrapper", () => { + afterEach(() => { + vi.restoreAllMocks() + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: originalCrypto, + }) + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: originalLocalStorage, + }) + }) + + it("reuses the persisted webview viewStateId when browser storage is available", () => { + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: createMockStorage({ vscodeState: JSON.stringify({ viewStateId: "persisted-view" }) }), + }) + const wrapper = new VSCodeAPIWrapper() + + expect(wrapper.getViewStateId()).toBe("persisted-view") + }) + + it("replaces a stored Object.prototype member id with a generated one", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID: vi.fn(() => "generated-view") }, + }) + const storage = createMockStorage({ vscodeState: JSON.stringify({ viewStateId: "constructor" }) }) + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + // The host's setViewStateId rejects every Object.prototype member name; accepting + // "constructor" here would make every launch message rejected and strand the + // pre-launch entry under the temporary id forever. + expect(wrapper.getViewStateId()).toBe("generated-view") + expect(JSON.parse(storage.getItem("vscodeState")!)).toMatchObject({ viewStateId: "generated-view" }) + }) + + it("creates and persists a new viewStateId when storage has been cleared", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID: vi.fn(() => "generated-view") }, + }) + const storage = createMockStorage() + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + expect(wrapper.getViewStateId()).toBe("generated-view") + expect(JSON.parse(storage.getItem("vscodeState")!)).toMatchObject({ viewStateId: "generated-view" }) + }) + + it("falls back to in-memory state when browser storage access is restricted", () => { + const randomUUID = vi.fn().mockReturnValueOnce("memory-view").mockReturnValueOnce("new-memory-view") + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID }, + }) + const storage: MockStorage = { + getItem: vi.fn(() => { + throw new Error("storage denied") + }), + setItem: vi.fn(() => { + throw new Error("storage denied") + }), + removeItem: vi.fn(() => { + throw new Error("storage denied") + }), + clear: vi.fn(() => { + throw new Error("storage denied") + }), + } + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + expect(wrapper.getViewStateId()).toBe("memory-view") + expect(wrapper.getViewStateId()).toBe("memory-view") + expect(randomUUID).toHaveBeenCalledTimes(1) + expect(storage.getItem).toHaveBeenCalled() + expect(storage.setItem).toHaveBeenCalled() + }) + + it("falls back to a timestamp-random id when crypto.randomUUID is unavailable", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: {}, + }) + vi.spyOn(Date, "now").mockReturnValue(1700000000000) + vi.spyOn(Math, "random").mockReturnValue(0.987654321) + const storage = createMockStorage() + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + // 1700000000000.toString(36) === "loyw3v28" and (0.987654321).toString(36) === + // "0.zk00000ytu", so the deterministic fallback id drops the "0." prefix. + expect(wrapper.getViewStateId()).toBe("loyw3v28-zk00000ytu") + expect(JSON.parse(storage.getItem("vscodeState")!)).toMatchObject({ viewStateId: "loyw3v28-zk00000ytu" }) + }) + + it("falls back to a timestamp-random id when the crypto global is undefined", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: undefined, + }) + vi.spyOn(Date, "now").mockReturnValue(1700000000000) + vi.spyOn(Math, "random").mockReturnValue(0.987654321) + const storage = createMockStorage() + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + // 1700000000000.toString(36) === "loyw3v28" and (0.987654321).toString(36) === + // "0.zk00000ytu", so the deterministic fallback id drops the "0." prefix. + expect(wrapper.getViewStateId()).toBe("loyw3v28-zk00000ytu") + expect(JSON.parse(storage.getItem("vscodeState")!)).toMatchObject({ viewStateId: "loyw3v28-zk00000ytu" }) + }) + + it("falls back to a timestamp-random id when the crypto object lacks randomUUID", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { "": 1 }, + }) + vi.spyOn(Date, "now").mockReturnValue(1700000000000) + vi.spyOn(Math, "random").mockReturnValue(0.987654321) + const storage = createMockStorage() + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + // A truthy crypto global without a randomUUID member must still take the + // deterministic fallback: 1700000000000.toString(36) === "loyw3v28" and + // (0.987654321).toString(36) === "0.zk00000ytu", so the id drops the "0." prefix. + expect(wrapper.getViewStateId()).toBe("loyw3v28-zk00000ytu") + expect(JSON.parse(storage.getItem("vscodeState")!)).toMatchObject({ viewStateId: "loyw3v28-zk00000ytu" }) + }) + + it("creates a new viewStateId when the stored state parses to JSON null", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID: vi.fn(() => "after-null-view") }, + }) + const storage = createMockStorage({ vscodeState: "null" }) + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + expect(wrapper.getViewStateId()).toBe("after-null-view") + expect(JSON.parse(storage.getItem("vscodeState")!)).toMatchObject({ viewStateId: "after-null-view" }) + }) + + it("replaces an empty persisted viewStateId with a freshly created one", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID: vi.fn(() => "refilled-view") }, + }) + const storage = createMockStorage({ vscodeState: JSON.stringify({ viewStateId: "" }) }) + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + expect(wrapper.getViewStateId()).toBe("refilled-view") + expect(JSON.parse(storage.getItem("vscodeState")!)).toMatchObject({ viewStateId: "refilled-view" }) + }) + + it("replaces a non-object persisted state with a freshly created viewStateId", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID: vi.fn(() => "replaced-string-view") }, + }) + // A persisted JSON string is truthy but not an object: the guard must keep it out of + // the fresh state, so the persisted record contains only the new viewStateId. + const storage = createMockStorage({ vscodeState: JSON.stringify("stale-string-state") }) + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + expect(wrapper.getViewStateId()).toBe("replaced-string-view") + expect(JSON.parse(storage.getItem("vscodeState")!)).toEqual({ viewStateId: "replaced-string-view" }) + }) + + it("returns the normalized id when the persisted id needs the extension-side cleanup", () => { + const randomUUID = vi.fn(() => "should-not-be-generated") + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID }, + }) + // ClineProvider.setViewStateId trims and rewrites unsafe characters, so the + // webview must report the same normalized id instead of the raw stored value. + const storage = createMockStorage({ vscodeState: JSON.stringify({ viewStateId: " side 1 " }) }) + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + expect(wrapper.getViewStateId()).toBe("side_1") + expect(wrapper.getViewStateId()).toBe("side_1") + expect(randomUUID).not.toHaveBeenCalled() + }) + + it("generates a fresh id when the persisted id is whitespace-only", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID: vi.fn(() => "ws-refilled-view") }, + }) + const storage = createMockStorage({ vscodeState: JSON.stringify({ viewStateId: " " }) }) + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + expect(wrapper.getViewStateId()).toBe("ws-refilled-view") + expect(JSON.parse(storage.getItem("vscodeState")!)).toEqual({ viewStateId: "ws-refilled-view" }) + }) + + it("generates a fresh id when the persisted id is the __proto__ string", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID: vi.fn(() => "proto-refused-view") }, + }) + const storage = createMockStorage({ vscodeState: JSON.stringify({ viewStateId: "__proto__" }) }) + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + expect(wrapper.getViewStateId()).toBe("proto-refused-view") + expect(JSON.parse(storage.getItem("vscodeState")!)).toEqual({ viewStateId: "proto-refused-view" }) + }) + + it("keeps one generated id when a write fails while stale persisted state stays readable", () => { + const randomUUID = vi.fn().mockReturnValueOnce("gen-one").mockReturnValueOnce("gen-two") + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID }, + }) + // Storage still serves a stale persisted state (e.g. pre-identity webview state + // without a viewStateId) while setItem throws: without the write-failure flag, + // every getViewStateId call would re-read the stale JSON and generate a fresh id. + const storage: MockStorage = { + getItem: vi.fn(() => JSON.stringify({ mode: "architect" })), + setItem: vi.fn(() => { + throw new Error("write denied") + }), + removeItem: vi.fn(), + clear: vi.fn(), + } + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + const first = wrapper.getViewStateId() + const second = wrapper.getViewStateId() + + expect(first).toBe("gen-one") + expect(second).toBe("gen-one") // no flap: the in-memory state stays authoritative + expect(wrapper.getState()).toEqual({ mode: "architect", viewStateId: "gen-one" }) + expect(randomUUID).toHaveBeenCalledTimes(1) + }) + + it("keeps the in-memory viewStateId when setItem is unavailable while reads still work", () => { + const randomUUID = vi.fn().mockReturnValueOnce("no-setitem-view").mockReturnValueOnce("flapped-view") + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID }, + }) + const backing: Record = { vscodeState: JSON.stringify({ mode: "architect" }) } + const storage = { + getItem: vi.fn((key: string) => backing[key] ?? null), + removeItem: vi.fn(), + clear: vi.fn(), + } + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + expect(wrapper.getViewStateId()).toBe("no-setitem-view") + // The persisted JSON never gained the id: the in-memory state stays authoritative + // instead of re-reading the stale JSON on every call. + expect(wrapper.getViewStateId()).toBe("no-setitem-view") + expect(wrapper.getState()).toEqual({ mode: "architect", viewStateId: "no-setitem-view" }) + expect(randomUUID).toHaveBeenCalledTimes(1) + }) + + it("treats persisted storage as authoritative again once a write recovers", () => { + Object.defineProperty(globalThis, "crypto", { + configurable: true, + value: { randomUUID: vi.fn(() => "recovered-view") }, + }) + const backing: Record = { vscodeState: JSON.stringify({ mode: "architect" }) } + let writesFail = true + const storage: MockStorage = { + getItem: vi.fn((key: string) => backing[key] ?? null), + setItem: vi.fn((key: string, value: string) => { + if (writesFail) { + throw new Error("write denied") + } + backing[key] = value + }), + removeItem: vi.fn(), + clear: vi.fn(), + } + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: storage, + }) + const wrapper = new VSCodeAPIWrapper() + + // The first generation cannot be persisted: the in-memory state is authoritative. + expect(wrapper.getViewStateId()).toBe("recovered-view") + expect(wrapper.getState()).toEqual({ mode: "architect", viewStateId: "recovered-view" }) + + // A later write succeeds: the flag clears and the persisted JSON is + // authoritative again for reads. + writesFail = false + wrapper.setState({ mode: "code", viewStateId: "recovered-view" }) + expect(backing.vscodeState).toBe(JSON.stringify({ mode: "code", viewStateId: "recovered-view" })) + // An external writer refreshes the persisted record: a recovered wrapper must see + // it (flag cleared); a still-flagged wrapper would keep the in-memory copy. + backing.vscodeState = JSON.stringify({ mode: "code", viewStateId: "recovered-view", external: true }) + expect(wrapper.getState()).toEqual({ mode: "code", viewStateId: "recovered-view", external: true }) + }) +}) diff --git a/webview-ui/src/utils/vscode.ts b/webview-ui/src/utils/vscode.ts index 2cc0a589095..f64a774e586 100644 --- a/webview-ui/src/utils/vscode.ts +++ b/webview-ui/src/utils/vscode.ts @@ -11,8 +11,13 @@ import { WebviewMessage } from "@roo/WebviewMessage" * dev server by using native web browser features that mock the functionality * enabled by acquireVsCodeApi. */ -class VSCodeAPIWrapper { +export class VSCodeAPIWrapper { private readonly vsCodeApi: WebviewApi | undefined + private fallbackState: unknown | undefined + // Once a persistent-storage write fails (setItem throws or is unavailable), + // the persisted JSON is stale: the in-memory fallbackState is authoritative + // for getState() until a write succeeds again. + private storageWriteFailed: boolean = false constructor() { // Check if the acquireVsCodeApi function exists in the current development @@ -22,6 +27,49 @@ class VSCodeAPIWrapper { } } + /** + * Generates a unique identifier for this webview instance. + * + * @remarks Used only when no persisted identifier exists yet. + */ + private createViewStateId(): string { + if (typeof crypto !== "undefined" && "randomUUID" in crypto) { + return crypto.randomUUID() + } + + return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}` + } + + /** + * Returns the stable view state identifier for this webview, creating and persisting + * one on first use so the extension can keep per-view state isolated across providers. + */ + public getViewStateId(): string { + const currentState = this.getState() + const stateObject = + currentState && typeof currentState === "object" && !Array.isArray(currentState) + ? (currentState as Record) + : {} + const existingViewStateId = stateObject.viewStateId + + // Mirror the ClineProvider.setViewStateId validation so the webview never + // registers an id the extension would reject: trim, replace unsafe + // characters, and drop whitespace-only values plus every Object.prototype + // member name. "__proto__" alone is not enough: ids like "constructor" or + // "toString" survive the host's normalization and would be refused there + // forever, stranding this view's pre-launch entry under the temporary id. + const normalizedViewStateId = + typeof existingViewStateId === "string" ? existingViewStateId.trim().replace(/[^A-Za-z0-9_-]/g, "_") : "" + + if (normalizedViewStateId && !Object.prototype.hasOwnProperty.call(Object.prototype, normalizedViewStateId)) { + return normalizedViewStateId + } + + const viewStateId = this.createViewStateId() + this.setState({ ...stateObject, viewStateId }) + return viewStateId + } + /** * Post a message (i.e. send arbitrary data) to the owner of the webview. * @@ -49,10 +97,24 @@ class VSCodeAPIWrapper { public getState(): unknown | undefined { if (this.vsCodeApi) { return this.vsCodeApi.getState() - } else { - const state = localStorage.getItem("vscodeState") - return state ? JSON.parse(state) : undefined } + + if (this.storageWriteFailed) { + // A previous write could not be persisted: reading localStorage would + // return stale JSON, so the in-memory fallback is authoritative. + return this.fallbackState + } + + try { + if (typeof localStorage?.getItem === "function") { + const state = localStorage.getItem("vscodeState") + return state ? JSON.parse(state) : this.fallbackState + } + } catch { + return this.fallbackState + } + + return this.fallbackState } /** @@ -69,10 +131,24 @@ class VSCodeAPIWrapper { public setState(newState: T): T { if (this.vsCodeApi) { return this.vsCodeApi.setState(newState) - } else { - localStorage.setItem("vscodeState", JSON.stringify(newState)) - return newState } + + this.fallbackState = newState + + try { + if (typeof localStorage?.setItem === "function") { + localStorage.setItem("vscodeState", JSON.stringify(newState)) + this.storageWriteFailed = false + } else { + this.storageWriteFailed = true + } + } catch { + // Storage can be unavailable in restricted webview/browser contexts. + // The in-memory fallback above keeps a stable viewStateId for this session. + this.storageWriteFailed = true + } + + return newState } } From c2927eda806208e16e7268ad58a4d3653e266439 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 07:49:48 +0800 Subject: [PATCH 02/34] [cr 4746968738] read the view settings overlay together with its pin getState pinned the profile name from a snapshot of the merged view state but read the settings overlay again after the custom modes and allow-list awaits, so a selection completing inside one of those awaits paired this view pin with the other profile own settings. The overlay is now captured at the same instant as the pin, and the returned configuration is built from that capture. The added spec row drives the interleaving through a cloud double whose allow-list read awaits the public per-view writer, and asserts the buffer holds the competing profile afterwards so the pending window is not vacuous. Reported by CodeRabbit in PR 1552 at src/core/webview/ClineProvider.ts line 5265. --- src/core/webview/ClineProvider.ts | 11 +++- .../webview/__tests__/ClineProvider.spec.ts | 59 +++++++++++++++++++ 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 0a5a853e662..738f5c47d2f 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -5181,6 +5181,11 @@ export class ClineProvider // Merge viewLocalState on top of global state so a provider can serve // state values scoped to its own view while preserving ContextProxy defaults. const mergedStateValues = { ...stateValues, ...this.viewLocalState } + // The settings overlay is read at the same instant as the pin above, not again after the + // awaits below. Both the custom-modes read and the cloud allow-list read are scheduling + // points where another selection can replace this view buffer, and a buffer read taken + // afterwards pairs this view pin with the settings of whichever profile won that race. + const viewApiConfiguration = this.viewLocalState.apiConfiguration const customModes = await this.customModesManager.getCustomModes() @@ -5260,9 +5265,9 @@ export class ClineProvider // on Bedrock or OpenAI without their credentials. A view with no overlay at // all still takes the shared settings below, which is the other thread's // construct and untouched here. - // The overlay is read from the buffer itself: the raw apiConfiguration state key - // is a partial patch from shared-store paths, not a view snapshot. - const viewApiConfiguration = this.viewLocalState.apiConfiguration + // The overlay is the buffer read captured together with the pin near the top of this method. + // The raw apiConfiguration state key is a partial patch from shared-store paths, not a view + // snapshot, so it stays out of this resolution. const resolvedApiConfiguration = viewApiConfiguration ? { ...viewApiConfiguration, diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index e91609b9df4..134d679e509 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6798,6 +6798,65 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("reports the pinned profile together with the overlay read at the same instant", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + const pinnedSettings = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "key-of-pinned-profile", + } + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("currentApiConfigName", "pinned-profile") + await provider.saveViewState("apiConfiguration", pinnedSettings) + + // The competing selection writes both fields through the production setter, so the + // per-view buffer holds another profile by the time getState resumes. + const competingSettings = { + apiProvider: providerIdentifiers.anthropic, + apiKey: "key-of-competing-profile", + } + const { CloudService } = await import("@roo-code/cloud") + const originalInstance = Object.getOwnPropertyDescriptor(CloudService, "instance") + Object.defineProperty(CloudService, "instance", { + get: () => ({ + isAuthenticated: () => false, + getUserInfo: () => null, + getOrganizationSettings: () => undefined, + // The window: getState is suspended inside this await while the competing + // selection completes, and only then does the allow-list read settle. + getAllowList: async () => { + // Both writes go through the public per-view writer, the same one a profile + // selection lands through, so the buffer keeps its real upstream flow. + await provider.saveViewState("currentApiConfigName", "competing-profile") + await provider.saveViewState("apiConfiguration", competingSettings) + return ORGANIZATION_ALLOW_ALL + }, + }), + configurable: true, + }) + + const state = await provider.getState().finally(() => { + if (originalInstance) { + Object.defineProperty(CloudService, "instance", originalInstance) + } + }) + + // The interleaving really happened inside the window: the buffer now holds the + // competing profile, so any settings read taken after the allow-list wait serves it. + expect(provider["viewLocalState"].apiConfiguration).toEqual(competingSettings) + // Name and settings must both describe the profile that was pinned when the read began. + expect(state.currentApiConfigName).toBe("pinned-profile") + expect(state.apiConfiguration).toEqual(pinnedSettings) + + await provider.dispose() + }) + it("reports the fresh global apiConfiguration after a profile activation followed by a global settings write", async () => { const provider = new ClineProvider( mockContext, From e5dd630aa370fd53f9f8a99f05b522376a62e625 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 07:54:04 +0800 Subject: [PATCH 03/34] [cr 4746968747] take the payload task settings before mode registration createTask read the shared provider settings only after the custom-mode loop, so a provider write from another view that landed while a registration await was pending became the new task own configuration instead of the settings the payload had just persisted. The capture now happens right after this call own writes and before the registration loop, and the task keeps that capture through the getState await that follows. The added spec row holds a registration open, lands an OpenAI write inside that window, and reads back which settings the created task received; it also asserts the shared store still holds the competing write afterwards so the window is shown to be real. Both new rows in this spec hold the logger info channel down: one console line per logged event left a pending console write at worker teardown and turned a green core lane run into a non-zero exit. That row is noted here because this commit also carries the line for the earlier new row. Reported by CodeRabbit in PR 1552 at src/core/webview/ClineProvider.ts line 6327. --- src/core/webview/ClineProvider.ts | 24 ++++--- .../webview/__tests__/ClineProvider.spec.ts | 62 +++++++++++++++++++ 2 files changed, 79 insertions(+), 7 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 738f5c47d2f..30e427eea7b 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -6246,6 +6246,10 @@ export class ClineProvider } = {}, configuration: RooCodeSettings = {}, ): Promise { + // The settings a payload that names its own provider hands to its task are captured + // inside the block below, ahead of the custom-mode registration awaits, and held here for + // the read further down. + let payloadProviderSettings: ProviderSettings | undefined if (configuration) { // Capture both selection layers that a failure ahead of, or inside, custom-mode // registration must roll back to: setValues below persists the payload's mode to the @@ -6297,6 +6301,13 @@ export class ClineProvider throw error } + // A payload that names a provider drives the settings its new task starts with, and the read + // is taken here: after this call own writes and before the custom-mode loop below, because + // each registration await is a scheduling point where another view provider write can + // land. A read taken after that loop hands the new task whatever the other write put into + // the shared store instead of the settings this payload persisted. + payloadProviderSettings = configuration.apiProvider ? this.contextProxy.getProviderSettings() : undefined + // Register custom modes so the CustomModesManager knows about them. // setValues writes to global state, but the manager overwrites that // when it merges .roomodes + global settings on refresh. Persisting @@ -6323,13 +6334,12 @@ export class ClineProvider } } - // A payload that names a provider drives the settings the new task starts with, and that - // read is taken here - ahead of the getState() await below - because the await is a - // scheduling point: another view's provider write can land inside it, and a read taken - // afterwards hands the new task whatever that write just put into the shared store - // instead of the settings this payload persisted through setValues (review thread - // 4595966639). - const payloadProviderSettings = configuration.apiProvider ? this.contextProxy.getProviderSettings() : undefined + // A payload that names a provider drives the settings the new task starts with: the capture + // taken above, ahead of the custom-mode loop, is what the task receives. Both that loop and + // the getState() await below are scheduling points where another view provider write can + // land, and a shared-store read taken after them hands the new task whatever that write just + // put there instead of the settings this payload persisted through setValues (review threads + // 4595966639 and cid 4746968747). const { apiConfiguration, enableCheckpoints, diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 134d679e509..ba214b6d582 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6807,6 +6807,10 @@ describe("ClineProvider", () => { new WebviewFocusTracker(), ) + // The extension logger writes one console line per event. This row holds the info + // channel down so it does not leave a pending console write at worker teardown. + vi.spyOn(console, "log").mockImplementation(() => {}) + const pinnedSettings = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "key-of-pinned-profile", @@ -8367,6 +8371,64 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("keeps the payload provider settings when a competing write lands during custom-mode registration", async () => { + // The payload read used to sit after the custom-mode loop, so a provider write that landed + // while a registration was pending became the new task own configuration instead of the + // settings this payload persisted. + // Same info-channel console chatter as the row above: held down so this row leaves no + // pending console write at worker teardown. + vi.spyOn(console, "log").mockImplementation(() => {}) + const lateWrite: ProviderSettings = { + apiProvider: providerIdentifiers.openai, + apiKey: "openai-write-during-registration", + } + provider["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + apiKey: "view-snapshot-key", + } + let openRegistration!: () => void + const registration = new Promise((resolve) => { + openRegistration = resolve + }) + const updateCustomMode = vi.fn(async () => { + await registration + }) + provider["customModesManager"].updateCustomMode = updateCustomMode + + const creating = provider.createTask( + undefined, + undefined, + undefined, + { startTask: false }, + { + apiProvider: providerIdentifiers.bedrock, + awsRegion: "us-east-1", + awsAccessKey: "payload-bedrock-access-key", + customModes: [ + { slug: "companion-mode", name: "Companion", roleDefinition: "Registers late", groups: [] }, + ], + }, + ) + + // The registration is pending: the payload write has landed and the loop is open. The + // competing provider write goes in inside that window, then the loop is released. + await vi.waitFor(() => expect(updateCustomMode).toHaveBeenCalledTimes(1)) + await provider.contextProxy.setProviderSettings(lateWrite) + openRegistration() + + await creating + + const created = vi.mocked(Task).mock.calls.at(-1)?.[0] + // The task keeps the settings this payload persisted rather than the settings that landed + // inside the registration window. + expect(created?.apiConfiguration.apiProvider).toBe(providerIdentifiers.bedrock) + expect(created?.apiConfiguration.awsAccessKey).toBe("payload-bedrock-access-key") + // The competing write is still what the shared store holds afterwards, so the window was + // real and the two rows above pin the earlier read, not the later world. + expect(provider.contextProxy.getProviderSettings().apiProvider).toBe(providerIdentifiers.openai) + + await provider.dispose() + }) it("should sanitize raw viewStateId before using it as persisted viewStates key", async () => { const provider = new ClineProvider( mockContext, From 15e1daca69f69f7bb5d5668101f4aca7f3067b0d Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:13:07 +0800 Subject: [PATCH 04/34] [cr 4746968724] reconfigure tasks on the deleted profile whatever pin The re-pin pass after a profile deletion selected the sibling instances to repair by their own view pin, so a view pinned to another profile was excluded before its task was ever looked at. The conversation of that view kept running the deleted profile handler and sticky name, and reopening its history cannot resolve a deleted name. The pass now selects two disjoint sets: views whose pin names the deleted profile are re-pinned as before, and views whose active task follows the deleted profile have their handler rebuilt and sticky name re-pointed while their own pin and overlay stay as they were. The new spec row pins a sibling view to the surviving profile, runs its task under the deleted profile, deletes that profile, and asserts the task settings and sticky name move while the sibling pin and overlay do not. Reported by CodeRabbit in PR 1552 at src/core/webview/ClineProvider.ts line 4112. --- src/core/webview/ClineProvider.ts | 32 ++++-- .../webview/__tests__/ClineProvider.spec.ts | 97 +++++++++++++++++++ 2 files changed, 123 insertions(+), 6 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 30e427eea7b..f8ae4f90dff 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -4107,16 +4107,26 @@ export class ClineProvider replacementName: string, replacementSettings: ProviderSettings | undefined, ): Promise { - const affected = ClineProvider.getAllInstances().filter( - (instance) => instance !== this && instance.pinnedProfileName === deletedProfileName, + const others = ClineProvider.getAllInstances().filter((instance) => instance !== this) + // The re-pin half stays pin-based: only a view whose own pin names the deleted profile may + // have its buffer and durable entry moved onto the survivor, and a view that pins another + // profile must keep that pin. + const pinnedViews = others.filter((instance) => instance.pinnedProfileName === deletedProfileName) + // The handler half follows each task own sticky profile name, so a conversation running + // under the deleted profile is rebuilt on the survivor settings even when its view pins a + // different profile. The two sets are disjoint by construction, so no view is handled twice. + const taskBoundViews = others.filter( + (instance) => + instance.pinnedProfileName !== deletedProfileName && + instance.getCurrentTask()?.taskApiConfigName === deletedProfileName, ) - if (affected.length === 0) { + if (pinnedViews.length === 0 && taskBoundViews.length === 0) { return } - await Promise.all( - affected.map(async (instance) => { + await Promise.all([ + ...pinnedViews.map(async (instance) => { const values: Partial & Partial = { currentApiConfigName: replacementName, } @@ -4147,7 +4157,17 @@ export class ClineProvider } await instance.postStateToWebview() }), - ) + // The task-only half rebuilds the handler and re-points the sticky profile name, and leaves + // the buffer alone: that view still pins a different profile, and its own pin must not be + // rewritten as a side effect of repairing the conversation. + ...taskBoundViews.map(async (instance) => { + if (replacementSettings) { + instance.updateTaskApiHandlerIfNeeded(replacementSettings, { forceRebuild: true }) + } + await instance.persistStickyProviderProfileToCurrentTask(replacementName) + await instance.postStateToWebview() + }), + ]) } /** diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index ba214b6d582..31fd1ca79c8 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6432,6 +6432,103 @@ describe("ClineProvider", () => { } }) + it("reconfigures a sibling task that runs the deleted profile while its view pins another", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const deletedProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + const deletedSettings: ProviderSettings = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "deleted-profile-secret", + } + const keeperSettings: ProviderSettingsWithId = { + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "keeper-key", + } + const otherSettings: ProviderSettings = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "pinned-elsewhere-key", + } + await provider.contextProxy.setValue("listApiConfigMeta", [deletedProfile, keeperProfile, { + name: "other-profile", + id: "other-id", + apiProvider: providerIdentifiers.openrouter, + }]) + await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") + // The sibling view pins a third profile while the conversation it runs follows the + // profile being deleted. Selecting the views to repair by pin alone excludes this view + // before its task is looked at, so the task keeps the deleted profile handler and sticky + // name after the record is gone, and reopening its history cannot resolve that name. + sibling["viewLocalState"].currentApiConfigName = "other-profile" + sibling["viewLocalState"].apiConfiguration = otherSettings + const siblingTask = { + taskId: "sibling-task-running-deleted-profile", + apiConfiguration: deletedSettings, + taskApiConfigName: "old-profile", + setTaskApiConfigName: vi.fn((name: string | undefined) => { + siblingTask.taskApiConfigName = name ?? "" + }), + updateApiConfiguration: vi.fn((settings: ProviderSettings) => { + siblingTask.apiConfiguration = settings + }), + } + // The double is structural: only the task fields this deletion path reads. + vi.spyOn(sibling, "getCurrentTask").mockReturnValue( + siblingTask as unknown as ReturnType, + ) + vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + ...keeperSettings, + name: "keeper-profile", + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + + await provider.deleteProviderProfile(deletedProfile) + + // The sibling own pin and its overlay name the third profile: the deletion repairs the + // conversation, so neither of them may move onto the survivor. + expect(sibling["viewLocalState"].currentApiConfigName).toBe("other-profile") + expect(sibling["viewLocalState"].apiConfiguration).toEqual(otherSettings) + // The task ran the deleted profile, so it follows the survivor: settings and sticky name. + expect(siblingTask.taskApiConfigName).toBe("keeper-profile") + expect(siblingTask.apiConfiguration).toEqual(keeperSettings) + const posted = await sibling.getStateToPostToWebview() + expect(posted.currentApiConfigName).toBe("keeper-profile") + expect(posted.apiConfiguration).toEqual(keeperSettings) + // Wait on the serialized view-state write queue so queued persistence finishes before + // teardown. + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await sibling.dispose() + await provider.dispose() + } + }) + it("reconfigures the deleting view's own task when that task runs the deleted profile", async () => { vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) From df508e2ebc257aed52ddcabf61e76193337e2d16 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:23:05 +0800 Subject: [PATCH 05/34] [cr 4746968732] rename tasks that follow the profile whatever pin The re-point pass after a profile rename selected the instances to repair by their own view pin, so a view pinned to a third profile was skipped even when the conversation it ran still followed the renamed name. That task kept its handler and a sticky name under a name that stops resolving once the record moves, and reopening its history cannot recover the profile it was running. The pass now selects two disjoint sets: views whose pin names the old name move their buffer onto the new name as before, and views whose active task follows the old name have the handler rebuilt and the sticky name renamed, while their own pin and overlay stay as they were. The new spec row pins a sibling view to a third profile, runs its task under the renamed profile, renames the profile, and asserts the task settings and sticky name follow the rename while the sibling pin and its overlay do not. Reported by CodeRabbit in PR 1552 at src/core/webview/ClineProvider.ts line 4192. --- src/core/webview/ClineProvider.ts | 28 +++++-- .../webview/__tests__/ClineProvider.spec.ts | 84 +++++++++++++++++-- 2 files changed, 102 insertions(+), 10 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index f8ae4f90dff..e26cd70db0b 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -4187,14 +4187,23 @@ export class ClineProvider // first so a view that launches after an intervening activation still follows the // renamed profile instead of dangling at the deleted name. await this.repointPersistedViewStates(oldName, newName) - const affected = ClineProvider.getAllInstances().filter((instance) => instance.pinnedProfileName === oldName) + // The re-point half stays pin-based: only a view whose own pin names the old name may have + // its buffer moved onto the new one. + const pinnedViews = ClineProvider.getAllInstances().filter((instance) => instance.pinnedProfileName === oldName) + // The handler half follows each task own sticky profile name, so a conversation still + // running under the old name is renamed even when its view pins a different profile. The + // two sets are disjoint by construction, so no view is handled twice. + const taskBoundViews = ClineProvider.getAllInstances().filter( + (instance) => + instance.pinnedProfileName !== oldName && instance.getCurrentTask()?.taskApiConfigName === oldName, + ) - if (affected.length === 0) { + if (pinnedViews.length === 0 && taskBoundViews.length === 0) { return } - await Promise.all( - affected.map(async (instance) => { + await Promise.all([ + ...pinnedViews.map(async (instance) => { // Assigning the settings (even undefined) is what replaces or clears the // overlay: the renamed record's current settings are the only correct // overlay for a pin that now names the new profile. @@ -4213,7 +4222,16 @@ export class ClineProvider } await instance.postStateToWebview() }), - ) + // The task-only half renames the handler and the sticky profile name and leaves the buffer + // alone: that view pins another profile, so its overlay must keep that profile settings. + ...taskBoundViews.map(async (instance) => { + if (renamedSettings) { + instance.updateTaskApiHandlerIfNeeded(renamedSettings, { forceRebuild: true }) + } + await instance.persistStickyProviderProfileToCurrentTask(newName) + await instance.postStateToWebview() + }), + ]) } async updateCustomInstructions(instructions?: string) { diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 31fd1ca79c8..9a696252fb6 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6473,11 +6473,15 @@ describe("ClineProvider", () => { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "pinned-elsewhere-key", } - await provider.contextProxy.setValue("listApiConfigMeta", [deletedProfile, keeperProfile, { - name: "other-profile", - id: "other-id", - apiProvider: providerIdentifiers.openrouter, - }]) + await provider.contextProxy.setValue("listApiConfigMeta", [ + deletedProfile, + keeperProfile, + { + name: "other-profile", + id: "other-id", + apiProvider: providerIdentifiers.openrouter, + }, + ]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") // The sibling view pins a third profile while the conversation it runs follows the // profile being deleted. Selecting the views to repair by pin alone excludes this view @@ -7899,6 +7903,76 @@ describe("ClineProvider", () => { expect(viewStates["stable-sidebar-view"].currentApiConfigName).toBe("profile-new") await provider.dispose() }) + it("re-names a task that follows the renamed profile while its view pins another", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const renamedSettings: ProviderSettingsWithId = { + id: "renamed-id", + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "renamed-key", + } + const pinnedElsewhereSettings: ProviderSettings = { + apiProvider: providerIdentifiers.anthropic, + apiKey: "pinned-elsewhere-key", + } + const staleTaskSettings: ProviderSettings = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "pre-rename-key", + } + // The sibling view pins a third profile, while the conversation it runs still follows + // the name being renamed. Selecting the views to repair by pin alone leaves that task + // holding a sticky name that stops resolving once the record moves. + sibling["viewLocalState"].currentApiConfigName = "profile-elsewhere" + sibling["viewLocalState"].apiConfiguration = pinnedElsewhereSettings + const siblingTask = { + taskId: "sibling-task-following-renamed-profile", + apiConfiguration: staleTaskSettings, + taskApiConfigName: "profile-old", + setTaskApiConfigName: vi.fn((name: string | undefined) => { + siblingTask.taskApiConfigName = name ?? "" + }), + updateApiConfiguration: vi.fn((settings: ProviderSettings) => { + siblingTask.apiConfiguration = settings + }), + } + // The double is structural: only the task fields this rename path reads. + vi.spyOn(sibling, "getCurrentTask").mockReturnValue( + siblingTask as unknown as ReturnType, + ) + vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) + + await provider["repointViewLocalStateAfterProfileRename"]("profile-old", "profile-new", renamedSettings) + + // The sibling own pin names a third profile: neither the pin nor its overlay may move. + expect(sibling["viewLocalState"].currentApiConfigName).toBe("profile-elsewhere") + expect(sibling["viewLocalState"].apiConfiguration).toEqual(pinnedElsewhereSettings) + // The task followed the renamed record, so its sticky name and handler move with it. + expect(siblingTask.taskApiConfigName).toBe("profile-new") + expect(siblingTask.apiConfiguration).toEqual(renamedSettings) + const posted = await sibling.getStateToPostToWebview() + expect(posted.currentApiConfigName).toBe("profile-new") + expect(posted.apiConfiguration).toEqual(renamedSettings) + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await sibling.dispose() + await provider.dispose() + } + }) it("re-points persisted pins of closed views onto the renamed profile", async () => { const provider = new ClineProvider( mockContext, From 646c1c54a07230c5540137092ec19cdc3ff9b248 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:54:58 +0800 Subject: [PATCH 06/34] [cr 4746968656] restore the map captured before a failed write The viewStates writers compensated a rejected durable write by reading the map back from globalState and writing that value again. A Memento applies an update to its in-memory copy before the durable write settles, and ContextProxy documents that a rejected update can leave the attempted value in memory, so that read-back returned the map the failed write had attempted. The compensation then persisted it: a save could reject while its new pin became durable on the next write, a rejected clear could erase an entry storage still held, and a rejected re-point or re-key could store a name that never landed. Each serialized writer now captures the map it is about to replace while it is still the durable value, and restores that snapshot when its write rejects. The four sites that re-read after the failure are named by this finding: the save, the clear, the re-point and the re-key. Two new spec rows drive a storage double that applies the attempted map before rejecting, which is the contract the compensation had assumed away, and assert that the stored map returns to the pre-write snapshot. Each row names the site whose snapshot it proves, so reverting one site still leaves the other row green. Reported by CodeRabbit in PR 1552 at src/core/webview/ClineProvider.ts line 894. --- src/core/webview/ClineProvider.ts | 82 +++++++++------- .../webview/__tests__/ClineProvider.spec.ts | 95 +++++++++++++++++++ 2 files changed, 143 insertions(+), 34 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index e26cd70db0b..979178228b5 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -838,6 +838,11 @@ export class ClineProvider // when the change was made, even if a newer id is registered while it is queued. const viewStateId = this.viewStateId const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + // The Memento applies an update to its in-memory map before the durable write settles, + // so reading it after a rejection reports the map this write attempted rather than what + // storage kept. Capture the map written while it is still the durable value, and + // restore that snapshot if the write rejects. + const durableBeforeWrite = this.context.globalState.get("viewStates") const states = this.getPersistedViewStates({ fresh: true }) // The first write to an unowned temporary id claims the slot instead of merging // into it: temporary names restart from 0 on every host start, so an entry under @@ -884,17 +889,15 @@ export class ClineProvider try { await this.contextProxy.setValue("viewStates", pruned) } catch (error) { - // updateGlobalState applies the new map to the in-memory cache before - // the durable write, so a rejected write leaves the cache claiming an - // entry that never reached disk. Restore the cache to the value durable - // storage actually holds (undefined when the key was never written); the - // cache update lands even if this compensating write also fails, so - // readers cannot observe the lost entry either way. + // A rejected write leaves the in-memory map holding the attempted value, so the + // compensation must come from the snapshot taken before this write mutated + // anything: re-reading the map here would persist the change whose write failed + // (a rejected pin would become durable on the next write). try { - await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) + await this.contextProxy.setValue("viewStates", durableBeforeWrite) } catch { - // The cache is updated before the durable attempt: it matches the - // durable value regardless of whether this restore write landed. + // The snapshot is what storage held when this write started: the restore is + // correct whether or not this compensating write itself landed. } throw error } @@ -916,6 +919,11 @@ export class ClineProvider */ private async clearPersistedViewState(viewStateId = this.viewStateId): Promise { const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + // The Memento applies an update to its in-memory map before the durable write settles, + // so reading it after a rejection reports the map this write attempted rather than what + // storage kept. Capture the map cleared while it is still the durable value, and + // restore that snapshot if the write rejects. + const durableBeforeWrite = this.context.globalState.get("viewStates") const states = this.getPersistedViewStates({ fresh: true }) delete states[viewStateId] // The tombstone claims the entry is gone, so only a landed clear may leave @@ -932,17 +940,15 @@ export class ClineProvider if (!wasCleared) { ClineProvider.clearedViewStateIds.delete(viewStateId) } - // updateGlobalState applies the new map to the in-memory cache before - // the durable write, so a rejected write leaves the cache missing an - // entry that durable storage still holds. Restore the cache to the - // value storage actually holds (undefined when the key was never - // written); the cache update lands even if this compensating write - // also fails, so readers cannot observe the loss either way. + // A rejected write leaves the in-memory map holding the attempted value, so the + // compensation must come from the snapshot taken before this write mutated + // anything: re-reading the map here would persist the change whose write failed + // (a clear would erase an entry durable storage still holds). try { - await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) + await this.contextProxy.setValue("viewStates", durableBeforeWrite) } catch { - // The cache is updated before the durable attempt: it matches the - // durable value regardless of whether this restore write landed. + // The snapshot is what storage held when this write started: the restore is + // correct whether or not this compensating write itself landed. } throw error } @@ -962,6 +968,11 @@ export class ClineProvider replacementProfileName: string, ): Promise { const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + // The Memento applies an update to its in-memory map before the durable write settles, + // so reading it after a rejection reports the map this write attempted rather than what + // storage kept. Capture the map re-pointed while it is still the durable value, and + // restore that snapshot if the write rejects. + const durableBeforeWrite = this.context.globalState.get("viewStates") const states = this.getPersistedViewStates({ fresh: true }) let changed = false @@ -990,15 +1001,15 @@ export class ClineProvider try { await this.contextProxy.setValue("viewStates", pruned) } catch (error) { - // updateGlobalState applies the new map to the in-memory cache - // before the durable write: restore the cache to the value durable - // storage actually holds so closed-view pins cannot serve re-pointed - // names that never reached disk, then let the caller compensate. + // A rejected write leaves the in-memory map holding the attempted value, so the + // compensation must come from the snapshot taken before this write mutated + // anything: re-reading the map here would persist the change whose write failed + // (a closed view would serve a re-pointed name that never reached disk). try { - await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) + await this.contextProxy.setValue("viewStates", durableBeforeWrite) } catch { - // The cache is updated before the durable attempt: it matches the - // durable value regardless of whether this restore write landed. + // The snapshot is what storage held when this write started: the restore is + // correct whether or not this compensating write itself landed. } throw error } @@ -1042,6 +1053,11 @@ export class ClineProvider return } + // The Memento applies an update to its in-memory map before the durable write settles, + // so reading it after a rejection reports the map this write attempted rather than what + // storage kept. Capture the map re-keyed while it is still the durable value, and + // restore that snapshot if the write rejects. + const durableBeforeWrite = this.context.globalState.get("viewStates") const states = this.getPersistedViewStates({ fresh: true }) const previous = states[previousViewStateId] @@ -1066,17 +1082,15 @@ export class ClineProvider try { await this.contextProxy.setValue("viewStates", pruned) } catch (error) { - // updateGlobalState applies the new map to the in-memory cache before - // the durable write, so a rejected re-key would leave the cache serving - // the stable entry while durable storage still holds the temporary one. - // Restore the cache to the value durable storage actually holds (the same - // rollback savePersistedViewState applies), so a later load or a retry of - // the registration sees the pre-rekey entry. + // A rejected write leaves the in-memory map holding the attempted value, so the + // compensation must come from the snapshot taken before this write mutated + // anything: re-reading the map here would persist the change whose write failed + // (a re-key would make the stable id durable while the temporary entry is still the stored one). try { - await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) + await this.contextProxy.setValue("viewStates", durableBeforeWrite) } catch { - // The cache is updated before the durable attempt: it matches the - // durable value regardless of whether this restore write landed. + // The snapshot is what storage held when this write started: the restore is + // correct whether or not this compensating write itself landed. } throw error } diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 9a696252fb6..e09b0063235 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -4002,6 +4002,101 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("restores the map captured before a rejected view-state save", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("currentApiConfigName", "durable-profile") + const durableBeforeWrite = { + ...(mockContext.globalState.get("viewStates") as Record), + } + // The double models the Memento contract ContextProxy documents: an update lands in + // the in-memory copy before the durable write settles, so after a rejection the map + // read back is the attempted one rather than what storage kept. + const originalUpdate = mockContext.globalState.update.bind(mockContext.globalState) + const updateSpy = vi + .spyOn(mockContext.globalState, "update") + .mockImplementationOnce(async (...args: Parameters) => { + await originalUpdate(...args) + throw new Error("durable write rejected after the in-memory update") + }) + + await expect(provider.saveViewState("currentApiConfigName", "rejected-profile")).rejects.toThrow( + "durable write rejected after the in-memory update", + ) + + // Durable storage must go back to the map this write started from. Re-reading the map + // inside the catch would report the attempted map and persist the pin whose save failed. + expect(mockContext.globalState.get("viewStates")).toEqual(durableBeforeWrite) + expect(provider["getPersistedViewStates"]({ fresh: true })).toEqual(durableBeforeWrite) + expect( + ( + provider["getPersistedViewStates"]({ fresh: true })["stable-sidebar-view"] as Record< + string, + unknown + > + ).currentApiConfigName, + ).toBe("durable-profile") + // The buffer is only updated after the durable write lands, so the rejected name never + // enters the view state either. + expect(provider["viewLocalState"].currentApiConfigName).toBe("durable-profile") + updateSpy.mockRestore() + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await provider.dispose() + } + }) + + it("restores the map captured before a rejected re-point write", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + await provider["setViewStateId"]("stable-sidebar-view") + // A closed view left a pin naming the profile that is about to be removed. + await provider.contextProxy.setValue("viewStates", { + "closed-view": { mode: "code", currentApiConfigName: "profile-old", updatedAt: 1 }, + "other-view": { mode: "architect", currentApiConfigName: "profile-keep", updatedAt: 2 }, + }) + const durableBeforeWrite = { + ...(mockContext.globalState.get("viewStates") as Record), + } + const originalUpdate = mockContext.globalState.update.bind(mockContext.globalState) + const updateSpy = vi + .spyOn(mockContext.globalState, "update") + .mockImplementationOnce(async (...args: Parameters) => { + await originalUpdate(...args) + throw new Error("durable write rejected after the in-memory update") + }) + + await expect(provider["repointPersistedViewStates"]("profile-old", "profile-new")).rejects.toThrow( + "durable write rejected after the in-memory update", + ) + + // The re-point never reached disk, so the stored map must be the one captured before + // the rewrite: a closed view may not rehydrate a profile name that was never written. + expect(mockContext.globalState.get("viewStates")).toEqual(durableBeforeWrite) + expect( + (provider["getPersistedViewStates"]({ fresh: true })["closed-view"] as Record) + .currentApiConfigName, + ).toBe("profile-old") + updateSpy.mockRestore() + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await provider.dispose() + } + }) + it("should merge concurrent persisted updates from separate provider instances without lost viewStates", async () => { const provider1 = new ClineProvider( mockContext, From 73e0e8d7236eecf54479289a91d4344798d8dade Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:32:45 +0800 Subject: [PATCH 07/34] store the record of the writer that succeeded across view races [cr 4746968694] The provider profile mutation queue is a per-view field, so two views of one window can each snapshot a new profile name as absent before either writes: the later write then replaces the record the earlier save created, and the rollback of the failed writer - reading a snapshot that says the record was absent while the successful writer already marked its create - skips the delete and leaves the rejected settings stored instead of the record that succeeded. Snapshot, record write and compensation now run inside the stored profile namespace exclusion that the rename and the save arms already take, so writers sharing the stored profiles serialize while views over a different namespace stay independent. The mutation queue stays per-view: mode switching, activation and deletion keep their own queue and their own timeout budget, and no queued callback reaches an enqueuing entry point on another view. Witness: two live providers over one stored namespace with each write parked on its payload and the read-back armed to fail after the second write. Red at the parent with the stored record read back as the rejected settings, green here as the settings that succeeded. --- src/core/webview/ClineProvider.ts | 14 +- .../ClineProvider.apiHandlerRebuild.spec.ts | 4 + ...eProvider.profileMutationExclusion.spec.ts | 473 ++++++++++++++++++ 3 files changed, 490 insertions(+), 1 deletion(-) create mode 100644 src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 979178228b5..356faf3a082 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3235,7 +3235,19 @@ export class ClineProvider ): Promise { try { return await this.enqueueProviderProfileMutation( - (signal) => this.persistProviderProfile(name, providerSettings, activate, signal), + (signal) => + // The snapshot, the record write and the compensation that undo them are one critical + // section of the stored profile namespace. Every view of this window builds its own + // `ProviderSettingsManager` over the same stored profiles, so without this exclusion two + // views can both snapshot a new name as absent before either writes: the later write then + // overwrites the record the earlier save created, and the compensation of the failed + // writer - reading a snapshot that says the record was absent while the successful writer + // already marked its create - leaves the rejected settings stored instead of the record + // that succeeded. The mutation queue stays per-view, so mode switching, activation and + // deletion in another view keep their own queue and their own timeout budget. + this.providerSettingsManager.runExclusiveAcrossInstances(() => + this.persistProviderProfile(name, providerSettings, activate, signal), + ), { runToCompletion: true }, ) } catch (error) { diff --git a/src/core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts b/src/core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts index 397ba8c5d4e..3a58126681f 100644 --- a/src/core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts @@ -273,6 +273,10 @@ describe("ClineProvider - API Handler Rebuild Guard", () => { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "openai/gpt-4", }), + // The profile write path runs inside the stored namespace exclusion. This double is + // one manager for one view, so there is nothing to exclude against: run the callback + // inline, the way the other provider doubles do. + runExclusiveAcrossInstances: (cb: () => Promise) => cb(), } // Get the buildApiHandler mock diff --git a/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts b/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts new file mode 100644 index 00000000000..ddcb29b7927 --- /dev/null +++ b/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts @@ -0,0 +1,473 @@ +// npx vitest run --config vitest.core.config.ts core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts +import * as vscode from "vscode" +import { makeCompositeDisposable } from "../../../test-utils/vscode" + +import { TelemetryService } from "@roo-code/telemetry" +import type { ProviderSettings, ProviderSettingsWithId } from "@roo-code/types" +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" + +import { ContextProxy } from "../../config/ContextProxy" +import type { ProviderSettingsManager } from "../../config/ProviderSettingsManager" +import { WebviewFocusTracker } from "../WebviewFocusTracker" +import { ClineProvider } from "../ClineProvider" + +// Mock setup mirrors ClineProvider.apiHandlerRebuild.spec.ts, the proven shape for +// building live ClineProvider instances under vitest.core.config.ts. +vi.mock("fs/promises", () => ({ + mkdir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), + readFile: vi.fn().mockResolvedValue(""), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("../../../utils/storage", () => ({ + getSettingsDirectoryPath: vi.fn().mockResolvedValue("/test/settings/path"), + getTaskDirectoryPath: vi.fn().mockResolvedValue("/test/task/path"), + getGlobalStoragePath: vi.fn().mockResolvedValue("/test/storage/path"), +})) + +vi.mock("p-wait-for", () => ({ + __esModule: true, + default: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("delay", () => { + const delayFn = (_ms: number) => Promise.resolve() + delayFn.createDelay = () => delayFn + delayFn.reject = () => Promise.reject(new Error("Delay rejected")) + delayFn.range = () => Promise.resolve() + return { default: delayFn } +}) + +vi.mock("vscode", () => ({ + ExtensionContext: vi.fn(), + OutputChannel: vi.fn(), + WebviewView: vi.fn(), + Disposable: { from: (...subscriptions: vscode.Disposable[]) => makeCompositeDisposable(...subscriptions) }, + Uri: { + joinPath: vi.fn(), + file: vi.fn(), + }, + commands: { + executeCommand: vi.fn().mockResolvedValue(undefined), + }, + window: { + showInformationMessage: vi.fn(), + showWarningMessage: vi.fn(), + showErrorMessage: vi.fn(), + onDidChangeActiveTextEditor: vi.fn(() => ({ dispose: vi.fn() })), + }, + workspace: { + getConfiguration: vi.fn().mockReturnValue({ + get: vi.fn().mockReturnValue([]), + update: vi.fn(), + }), + onDidChangeConfiguration: vi.fn().mockImplementation(() => { + return { + dispose: vi.fn(), + } + }), + }, + env: { + uriScheme: "vscode", + language: "en", + appName: "Visual Studio Code", + }, + ExtensionMode: { + Production: 1, + Development: 2, + Test: 3, + }, + version: "1.85.0", +})) + +vi.mock("../../../utils/tts", () => ({ + setTtsEnabled: vi.fn(), + setTtsSpeed: vi.fn(), +})) + +vi.mock("../../../api", () => ({ + buildApiHandler: vi.fn(), +})) + +vi.mock("../../../integrations/workspace/WorkspaceTracker", () => { + return { + default: vi.fn().mockImplementation(function () { + return { + initializeFilePaths: vi.fn(), + dispose: vi.fn(), + } + }), + } +}) + +vi.mock("../../task/Task", () => ({ + Task: vi.fn().mockImplementation(function () { + return { + taskId: "test-task-id", + api: undefined, + abortTask: vi.fn(), + clineMessages: [], + apiConversationHistory: [], + emit: vi.fn(), + setTaskApiConfigName: vi.fn(), + updateApiConfiguration: vi.fn(), + } + }), +})) + +vi.mock("@roo-code/cloud", () => ({ + CloudService: { + hasInstance: vi.fn().mockReturnValue(true), + get instance() { + return { + isAuthenticated: vi.fn().mockReturnValue(false), + } + }, + }, + getRooCodeApiUrl: vi.fn().mockReturnValue("https://app.roocode.com"), +})) + +const PROFILE_NAME = "shared-new-profile" +const PARKED_NAME = "parked-new-profile" +const SEED_PROFILE_NAME = "seed-profile" +const STORE_ROUNDS = 300 + +const SETTINGS_A: ProviderSettings = { apiProvider: providerIdentifiers.anthropic, apiModelId: "model-a" } +const SETTINGS_B: ProviderSettings = { apiProvider: providerIdentifiers.anthropic, apiModelId: "model-b" } +const PATCHED_SEED_MODEL_ID = "model-seed-patched" + +const storedIdFor = (name: string) => `id-${name}` + +type StoreCall = { tag: string; method: string; name: string } + +function createDeferredGate() { + let release: () => void = () => {} + const promise = new Promise((resolve) => { + release = resolve + }) + return { promise, release } +} + +/** + * One stored provider-profile namespace shared by two views, which is the shape the host + * produces: the sidebar and each editor tab build their own `ProviderSettingsManager` over + * the same stored profiles. Every storage call is recorded twice, on entry and on return, + * tagged by the view that made it, so a row can name which writer reached the store and + * when. Each write can be parked on a gate opened by payload identity, and the read-back of + * a name can be armed to fail once a chosen write has landed - that is how a writer is made + * to reject after its own save succeeded. + */ +function createSharedProfileStore() { + const records = new Map() + const entered: StoreCall[] = [] + const returned: StoreCall[] = [] + const saveGates = new Map>() + const unreadable = new Set() + let unreadableMarker: { name: string; marker: ProviderSettings } | undefined + let currentProfileName = "default" + + records.set("default", { + id: storedIdFor("default"), + apiProvider: providerIdentifiers.anthropic, + apiModelId: "model-default", + }) + records.set("test-config", { + id: storedIdFor("test-config"), + apiProvider: providerIdentifiers.anthropic, + apiModelId: "model-test", + }) + records.set(SEED_PROFILE_NAME, { + id: storedIdFor(SEED_PROFILE_NAME), + apiProvider: providerIdentifiers.anthropic, + apiModelId: "model-seed", + }) + + const nameForId = (id: string) => Array.from(records.entries()).find(([, record]) => record.id === id)?.[0] + + const read = (name: string): ProviderSettingsWithId => { + const record = records.get(name) + if (!record) { + throw new Error(`Config with name ${name} was not found`) + } + if (unreadable.has(name)) { + throw new Error(`Config with name ${name} could not be read back`) + } + return record + } + + const store = { + record: (name: string) => records.get(name), + has: (name: string) => records.has(name), + calls: () => entered, + enteredCall: (tag: string, method: string, name?: string) => + entered.some( + (call) => call.tag === tag && call.method === method && (name === undefined || call.name === name), + ), + returnedCallCount: (tag: string) => returned.filter((call) => call.tag === tag).length, + deferSaveOf: (settings: ProviderSettings) => { + saveGates.set(settings, createDeferredGate()) + }, + releaseSave: (settings: ProviderSettings) => saveGates.get(settings)?.release(), + releaseAll: () => { + for (const gate of saveGates.values()) { + gate.release() + } + }, + armReadBackFailureAfter: (name: string, marker: ProviderSettings) => { + unreadableMarker = { name, marker } + }, + attach(manager: ProviderSettingsManager, tag: string) { + vi.spyOn(manager, "hasConfig").mockImplementation(async (name) => { + entered.push({ tag, method: "hasConfig", name }) + const exists = records.has(name) + returned.push({ tag, method: "hasConfig", name }) + return exists + }) + vi.spyOn(manager, "getProfile").mockImplementation(async (params) => { + const name = "name" in params ? params.name : (nameForId(params.id) ?? "") + entered.push({ tag, method: "getProfile", name }) + const record = read(name) + returned.push({ tag, method: "getProfile", name }) + return { ...record, name } + }) + vi.spyOn(manager, "saveConfig").mockImplementation(async (name, config) => { + entered.push({ tag, method: "saveConfig", name }) + const gate = saveGates.get(config) + if (gate) { + await gate.promise + } + const id = config.id ?? records.get(name)?.id ?? storedIdFor(name) + records.set(name, { ...config, id }) + if (unreadableMarker && unreadableMarker.name === name && unreadableMarker.marker === config) { + unreadable.add(name) + } + returned.push({ tag, method: "saveConfig", name }) + return id + }) + vi.spyOn(manager, "deleteConfig").mockImplementation(async (name) => { + entered.push({ tag, method: "deleteConfig", name }) + records.delete(name) + returned.push({ tag, method: "deleteConfig", name }) + }) + vi.spyOn(manager, "listConfig").mockImplementation(async () => { + entered.push({ tag, method: "listConfig", name: "*" }) + const entries = Array.from(records.entries()).map(([name, record]) => ({ name, id: record.id ?? "" })) + returned.push({ tag, method: "listConfig", name: "*" }) + return entries + }) + vi.spyOn(manager, "getCurrentProfileName").mockImplementation(async () => { + entered.push({ tag, method: "getCurrentProfileName", name: currentProfileName }) + const name = currentProfileName + returned.push({ tag, method: "getCurrentProfileName", name }) + return name + }) + vi.spyOn(manager, "activateProfile").mockImplementation(async (args) => { + const name = "name" in args ? args.name : (nameForId(args.id) ?? "") + entered.push({ tag, method: "activateProfile", name }) + const record = read(name) + currentProfileName = name + returned.push({ tag, method: "activateProfile", name }) + return { ...record, name } + }) + vi.spyOn(manager, "setModeConfig").mockImplementation(async (mode, configId) => { + entered.push({ tag, method: "setModeConfig", name: `${mode}:${configId}` }) + returned.push({ tag, method: "setModeConfig", name: `${mode}:${configId}` }) + }) + vi.spyOn(manager, "getModeConfigId").mockImplementation(async (mode) => { + entered.push({ tag, method: "getModeConfigId", name: mode }) + returned.push({ tag, method: "getModeConfigId", name: mode }) + return undefined + }) + vi.spyOn(manager, "getModeConfigIds").mockImplementation(async () => { + entered.push({ tag, method: "getModeConfigIds", name: "*" }) + returned.push({ tag, method: "getModeConfigIds", name: "*" }) + return {} + }) + }, + } + + return store +} + +function createMockContext(): vscode.ExtensionContext { + const globalState: Record = { + mode: "code", + currentApiConfigName: "test-config", + listApiConfigMeta: [ + { id: storedIdFor("test-config"), name: "test-config" }, + { id: storedIdFor("default"), name: "default" }, + ], + } + const secrets: Record = {} + + return { + extensionPath: "/test/path", + extensionUri: { fsPath: "/test/path" }, + globalState: { + get: vi.fn((key: string) => globalState[key]), + update: vi.fn((key: string, value: unknown) => (globalState[key] = value)), + keys: vi.fn(() => Object.keys(globalState)), + }, + secrets: { + get: vi.fn((key: string) => secrets[key]), + store: vi.fn((key: string, value: string | undefined) => (secrets[key] = value)), + delete: vi.fn((key: string) => delete secrets[key]), + }, + workspaceState: { + get: vi.fn(() => undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn(() => []), + }, + subscriptions: [], + extension: { packageJSON: { version: "1.0.0" } }, + globalStorageUri: { fsPath: "/test/storage/path" }, + } as unknown as vscode.ExtensionContext +} + +async function createView(store: ReturnType, tag: string): Promise { + const context = createMockContext() + const outputChannel = { + appendLine: vi.fn(), + clear: vi.fn(), + dispose: vi.fn(), + } as unknown as vscode.OutputChannel + const view = { + webview: { + postMessage: vi.fn().mockResolvedValue(true), + html: "", + options: {}, + onDidReceiveMessage: vi.fn(() => ({ dispose: vi.fn() })), + asWebviewUri: vi.fn((uri: string) => uri), + cspSource: "vscode-webview://test-csp-source", + }, + visible: true, + onDidDispose: vi.fn(() => ({ dispose: vi.fn() })), + onDidChangeVisibility: vi.fn(() => ({ dispose: vi.fn() })), + } as unknown as vscode.WebviewView + + const provider = new ClineProvider( + context, + outputChannel, + "sidebar", + new ContextProxy(context), + new WebviewFocusTracker(), + ) + // The persisted mode map is not part of this scenario; seed the window-local copy empty. + provider["initialModeConfigIds"] = Promise.resolve({}) + store.attach(provider.providerSettingsManager, tag) + await provider.resolveWebviewView(view) + + return provider +} + +async function waitForRounds(rounds: number, condition: () => boolean): Promise { + for (let round = 0; round < rounds; round++) { + if (condition()) { + return true + } + await new Promise((resolve) => setTimeout(resolve, 0)) + } + return condition() +} + +describe("ClineProvider - provider profile mutation exclusion", () => { + let store: ReturnType | undefined + let views: ClineProvider[] = [] + + beforeEach(() => { + vi.clearAllMocks() + + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } + }) + + afterEach(async () => { + store?.releaseAll() + // Drain any mutation still queued behind a released gate before the next row builds + // providers over a fresh store, so a parked writer cannot bleed into the next row. + await waitForRounds(20, () => false) + for (const view of views) { + await view.dispose().catch(() => {}) + } + views = [] + store = undefined + }) + + it("keeps the record of the writer that succeeded when two views create the same new name", async () => { + store = createSharedProfileStore() + const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) + views = [first, second] + + store.deferSaveOf(SETTINGS_A) + const firstSave = first.upsertProviderProfile(PROFILE_NAME, SETTINGS_A, false) + const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredCall("first", "saveConfig", PROFILE_NAME)) + expect(parked).toBe(true) + + store.deferSaveOf(SETTINGS_B) + const secondSave = second.upsertProviderProfile(PROFILE_NAME, SETTINGS_B, false) + + // The interleaving the row names is two snapshots taken before the first write lands. + // Waiting for the second writer to finish its two store reads before opening the first + // gate makes that ordering a fact rather than a hope; when the writers are serialized the + // second one parks on the shared exclusion instead, so this wait is capped by design. + await waitForRounds(STORE_ROUNDS, () => store!.returnedCallCount("second") >= 2) + store.releaseSave(SETTINGS_A) + + const firstResult = await firstSave + expect(firstResult).toBe(storedIdFor(PROFILE_NAME)) + + store.armReadBackFailureAfter(PROFILE_NAME, SETTINGS_B) + store.releaseSave(SETTINGS_B) + const secondResult = await secondSave + expect(secondResult).toBeUndefined() + + // The stored record is the successful writer record, not the settings the failed writer + // rejected, and not a record some compensation deleted out from under it. + expect(store.record(PROFILE_NAME)?.apiModelId).toBe(SETTINGS_A.apiModelId) + expect(store.record(PROFILE_NAME)).toStrictEqual({ ...SETTINGS_A, id: storedIdFor(PROFILE_NAME) }) + expect(store.has(PROFILE_NAME)).toBe(true) + + // Carriers: both writers really reached the store, in that order, and the failed writer + // compensated by restoring rather than by deleting. + const writerOrder = Array.from( + new Set( + store + .calls() + .filter((call) => call.method === "saveConfig" && call.name === PROFILE_NAME) + .map((call) => call.tag), + ), + ) + expect(writerOrder).toEqual(["first", "second"]) + expect(store.calls().some((call) => call.method === "deleteConfig")).toBe(false) + }) + + it("lets another view write while a view is parked inside its profile write", async () => { + store = createSharedProfileStore() + const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) + views = [first, second] + + store.deferSaveOf(SETTINGS_A) + const firstSave = first.upsertProviderProfile(PARKED_NAME, SETTINGS_A, false) + const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredCall("first", "saveConfig", PARKED_NAME)) + expect(parked).toBe(true) + + let patchSettled = false + const patch = second + .updateProfileModel(SEED_PROFILE_NAME, providerIdentifiers.anthropic, { apiModelId: PATCHED_SEED_MODEL_ID }) + .then(() => { + patchSettled = true + }) + const settled = await waitForRounds(STORE_ROUNDS, () => patchSettled) + + // The mutation queue stays per-view: only the stored-record critical section is shared. + // A class-wide queue would park this patch behind the deferred write above. + expect(settled).toBe(true) + expect(store.record(SEED_PROFILE_NAME)?.apiModelId).toBe(PATCHED_SEED_MODEL_ID) + + store.releaseSave(SETTINGS_A) + await Promise.all([firstSave, patch]) + }) +}) From da4db05c4f15cb88e2e7857ebd4dd7c1227cd73b Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:57:58 +0800 Subject: [PATCH 08/34] restore the task settings and sticky name an activating save moved [cr 4746968699] The activating branch of a profile save rebuilds the running conversation on the settings it just stored, then moves the task sticky profile name onto that profile, and the saved history line for the task moved with it. Only the non-activating branch captured a task configuration, so a state post that rejected after the sticky write rolled the stored profiles, the selection, the mode mapping and the view state back while this view conversation kept the rejected settings under a name nothing else named. The activating branch now captures the task identity, its configuration and its sticky name at the point the branch starts changing the task, and the compensation puts the handler back through the rebuild path the file already uses and the name back through the same path the write took, so the saved history line follows it. A save that fails before that point never moved the task and restores nothing it did not move, and a task swapped while the compensation ran is left alone by the identity guard. The mutation queue, the pending-operation timeout budget and every other entry point are untouched. Witness: one view whose own task follows the profile being activated, with the state post armed to reject after the sticky write completed. Red on the parent bytes, where the conversation stayed on the stored settings and the saved history stayed on the new name; green on these bytes. --- src/core/webview/ClineProvider.ts | 38 ++++-- .../webview/__tests__/ClineProvider.spec.ts | 110 ++++++++++++++++++ 2 files changed, 141 insertions(+), 7 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 356faf3a082..10cf3e49b4f 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3385,11 +3385,14 @@ export class ClineProvider // manager selection, the mode mapping and the shared/per-view state, so a rejected // post left the conversation this view runs sending the settings the failed save had // written while the durable stores went back to what they were. Captured here and - // assigned only by that branch, then restored through the rebuild path the file - // already uses for the task, with the task identity as the guard so a task swapped - // or disposed while the compensation ran is left alone. + // assigned by whichever branch is about to change this view's own task, then restored + // through the rebuild path the file already uses for the task, with the task identity + // as the guard so a task swapped or disposed while the compensation ran is left alone. + // The activating branch additionally moves the task sticky profile name, so it captures + // that name too and the catch below puts it back through the path the write took. let priorTaskConfig: ProviderSettings | undefined let priorTaskId: string | undefined + let priorTaskProfileName: string | undefined let id: string try { id = await this.providerSettingsManager.saveConfig(name, providerSettings) @@ -3494,6 +3497,14 @@ export class ClineProvider // Change the provider for the current task. // TODO: We should rename `buildApiHandler` for clarity (e.g. `getProviderClient`). + // Captured at the point this branch starts changing the task: the rebuild and the + // sticky-name write below both land ahead of the state post, while a failure before + // this point - a rejected activation write - leaves the task alone, so the catch + // restores nothing this save did not move. + const activatingTask = this.getCurrentTask() + priorTaskConfig = activatingTask?.apiConfiguration + priorTaskId = activatingTask?.taskId + priorTaskProfileName = activatingTask?.taskApiConfigName this.updateTaskApiHandlerIfNeeded(normalizedSettings, { forceRebuild: true }) // Keep the current task's sticky provider profile in sync with the newly-activated profile. @@ -3586,10 +3597,10 @@ export class ClineProvider // the settings it is given, and the identity option makes the call a no-op when // the task was swapped or disposed while the compensation ran. Logged rather than // thrown, matching the mode-mapping restore above, so a failed restore can neither - // strand the rest of the compensation nor replace the original error. The - // activating branch above rebuilds at line 3441 and keeps the same gap; it is - // named rather than widened here, because that branch has no state post between - // its rebuild and its last await for this save shape. + // strand the rest of the compensation nor replace the original error. Both branches of the + // save now capture what they were about to change. The activating branch also moved this + // task sticky profile name onto the saved profile, and its taskHistory entry moved with + // it, so the name goes back through the path the write took. if (priorTaskConfig !== undefined && priorTaskId !== undefined) { try { this.updateTaskApiHandlerIfNeeded(priorTaskConfig, { @@ -3604,6 +3615,19 @@ export class ClineProvider ) } } + if (priorTaskProfileName !== undefined && priorTaskProfileName !== name && priorTaskId !== undefined) { + try { + await this.persistStickyProviderProfileToCurrentTask(priorTaskProfileName, { + expectedCurrentTaskId: priorTaskId, + }) + } catch (restoreError) { + this.log( + `[ClineProvider] profile-save rollback failed for the task sticky profile name: ${ + restoreError instanceof Error ? restoreError.message : String(restoreError) + }`, + ) + } + } throw error } } diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index e09b0063235..b657913f174 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -5787,6 +5787,116 @@ describe("ClineProvider", () => { } }) + it("restores the acting task settings and sticky profile name when an activating save fails", async () => { + // Review thread 4746968699 (printed at ClineProvider.ts line 3474 with original_line + // 3474) names the activating twin of the two rows above: this branch rebuilds the handler + // and then moves the task sticky profile name, while only the non-activating branch captured + // a task configuration, so a rejected state post put the durable stores back and left this + // view conversation running the rejected settings under a name its saved history still + // carried. The failure is armed after the sticky-name write completed, the ordering that + // thread asks for. The task is a structural double, as in the two rows above: a full + // Task needs an extension host, so the cast onto the getCurrentTask return type is the + // shape this file already uses. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const ownTask = { + taskId: "task-activation-rolled-back-after-sticky-write", + taskApiConfigName: "profile-followed-before-activation", + apiConfiguration: { + apiProvider: providerIdentifiers.openrouter, + apiKey: "pre-activation-own-task-key", + }, + updateApiConfiguration: vi.fn(), + setTaskApiConfigName: vi.fn(), + } + // The saved history line the sticky write rewrites. This file mocks the task-history + // filesystem, so the store read the sticky path performs is served from this fixture + // copy rather than from the disk-backed cache. + const seededHistoryItem = { + id: ownTask.taskId, + task: "activation rollback", + ts: 1, + number: 1, + tokensIn: 0, + tokensOut: 0, + totalCost: 0, + apiConfigName: "profile-followed-before-activation", + } + vi.spyOn(provider.taskHistoryStore, "get").mockImplementation((taskId: string) => + taskId === ownTask.taskId ? seededHistoryItem : undefined, + ) + vi.spyOn(provider, "getCurrentTask").mockReturnValue( + ownTask as unknown as ReturnType, + ) + const historySpy = vi.spyOn(provider, "updateTaskHistory") + vi.spyOn(provider, "postStateToWebview").mockRejectedValueOnce(new Error("state post rejected")) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("saved-id") + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "activated-profile", + id: "saved-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("mode-id") + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue( + "activated-profile", + ) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + const id = await provider.upsertProviderProfile( + "activated-profile", + { apiProvider: providerIdentifiers.anthropic, apiKey: "newly-saved-key" }, + true, + ) + expect(id).toBeUndefined() + // Handler half: the save rebuilt the conversation on the settings it stored, the + // compensation rebuilds it on the settings it ran on before the save. + expect(ownTask.updateApiConfiguration).toHaveBeenCalledTimes(2) + expect(ownTask.updateApiConfiguration.mock.calls[0][0]).toEqual( + expect.objectContaining({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "newly-saved-key", + }), + ) + expect(ownTask.updateApiConfiguration.mock.calls[1][0]).toEqual( + expect.objectContaining({ + apiProvider: providerIdentifiers.openrouter, + apiKey: "pre-activation-own-task-key", + }), + ) + // Sticky-name half: the write moved the task and its saved history onto the + // activated profile; both go back through the same path, in that order. + expect(ownTask.setTaskApiConfigName.mock.calls.map((call) => call[0])).toEqual([ + "activated-profile", + "profile-followed-before-activation", + ]) + expect(historySpy.mock.calls.map((call) => call[0].apiConfigName)).toEqual([ + "activated-profile", + "profile-followed-before-activation", + ]) + // And the history line itself carries the name the task ran on before the save. + expect(historySpy.mock.calls[1][0]).toEqual( + expect.objectContaining({ + id: ownTask.taskId, + apiConfigName: "profile-followed-before-activation", + }), + ) + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await provider.dispose() + } + }) + it("leaves the pinned sibling's buffer and task handler pre-save when a write of the group fails", async () => { // Preserve-clause control for review thread 4506513932, printed beside the // test above: the sibling refresh is still the last step of the group, so a From 0e6b35c7dd1eafdd994df09e7f39271079acf687 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:18:01 +0800 Subject: [PATCH 09/34] restore the deleting view pin and overlay after a failed deletion [cr 4746968703] A deletion re-points this view own pin and settings overlay onto the surviving profile before the last write of the group. Its compensation put the deleted record, the profile list, the shared selection, the shared settings and the durable pins back, but nothing restored the in-memory pair, so a write that failed after the re-point left this view serving the survivor settings while every store named the deleted profile again. The pin and the overlay are now captured before the first write of the group, together with the two facts the group branches on, and the compensation puts both back through the same write path the re-point used. A view that never pinned the deleted profile is left alone, an absent pin stays absent, and a deletion whose writes all land keeps this view on the survivor. Witnesses: a deletion whose state write fails after the re-point, which is red on the parent bytes where the pin stayed on the survivor and green on these bytes, and a completed deletion that holds on both columns so an unconditional restore would not pass. --- src/core/webview/ClineProvider.ts | 39 +++++- .../webview/__tests__/ClineProvider.spec.ts | 131 ++++++++++++++++++ 2 files changed, 164 insertions(+), 6 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 10cf3e49b4f..23017421278 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3703,6 +3703,18 @@ export class ClineProvider ) } + // This view's own pin and settings overlay are re-pointed inside the group below, + // while the compensation at the end of this method restores only the durable + // surfaces: the record, the list, the shared selection, the shared settings and the + // persisted pins. Nothing put this view's in-memory pair back, so a failure after + // the re-point left getState() serving the survivor while every store named the + // deleted profile again. Captured before the first write of the group, together + // with the two facts the group branches on, and restored with them. + const priorViewPin = this.viewLocalState.currentApiConfigName + const priorViewOverlay = this.viewLocalState.apiConfiguration + const viewWasPinnedToDeleted = priorViewPin === profileToDelete.name + const deletedWasGlobal = profileToDelete.name === globalSettings.currentApiConfigName + try { const entries = this.getProviderProfileEntries().filter(({ name }) => name !== profileToDelete.name) @@ -3741,12 +3753,10 @@ export class ClineProvider } } - // Capture this view's pin before any rewrite: a view pinned to the - // deleted profile while the global selection points elsewhere must still be - // reconfigured, or getState() would keep the deleted profile's settings under - // the surviving profile's name. - const viewWasPinnedToDeleted = this.viewLocalState.currentApiConfigName === profileToDelete.name - const deletedWasGlobal = profileToDelete.name === globalSettings.currentApiConfigName + // The pin and the two facts this group branches on were captured above, before the + // first write: a view pinned to the deleted profile while the global selection points + // elsewhere must still be reconfigured, or getState() would keep the deleted + // profile's settings under the surviving profile's name. if (viewWasPinnedToDeleted) { // This view's pin now dangles: re-point it. setValue also persists the @@ -3882,6 +3892,23 @@ export class ClineProvider `[deleteProviderProfile] failed to restore the shared provider settings: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, ) } + // Undo this deletion's re-point of this view's own buffer, the two values the + // re-point above moved: the durable merge below only reaches entries that still + // name the deleted profile, so an in-memory pin left on the survivor would keep + // serving the survivor settings once the stores name the deleted profile again. + // An absent pin stays absent, matching the activation rollback's restore. + if (viewWasPinnedToDeleted) { + try { + await this._saveViewLocalStateFromMutation({ + currentApiConfigName: priorViewPin, + apiConfiguration: priorViewOverlay, + }) + } catch (restoreError) { + this.log( + `[deleteProviderProfile] failed to restore this view's live pin and settings overlay: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, + ) + } + } try { const restore = ClineProvider.persistedViewStateWriteQueue.then(async () => { const current = this.getPersistedViewStates({ fresh: true }) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index b657913f174..801662e7041 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6552,6 +6552,137 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("restores the deleting view pin and settings overlay when a post-delete write fails", async () => { + // Review thread 4746968703 (printed at ClineProvider.ts line 3705 with original_line + // 3705) names the gap: the re-pin pass re-points this view pin and overlay before the + // last write of the group, and the compensation restored the record, the list, the + // shared selection, the shared settings and the durable pins, but nothing put the + // in-memory pair back, so getState() kept serving the survivor while every store named + // the deleted profile again. The failure lands after the re-pin, which is how that + // thread frames it. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const oldProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + const deletedSettings = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "deleting-view-buffered-settings", + } + // The global selection points at the survivor while this view still pins the + // profile being deleted: the deletion re-points this view's own pair below. + await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) + await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") + provider["viewLocalState"].currentApiConfigName = "old-profile" + provider["viewLocalState"].apiConfiguration = deletedSettings + vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => { + if ("name" in params && params.name === "old-profile") { + return { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "deleting-view-buffered-settings", + } + } + return { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "keeper-key", + } + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("x") + // A write of the group after the re-pin fails: the record and the durable + // surfaces go back, and so must this view buffer. + vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("state write down")) + await expect(provider.deleteProviderProfile(oldProfile)).rejects.toThrow("state write down") + expect(provider["viewLocalState"].currentApiConfigName).toBe("old-profile") + expect(provider["viewLocalState"].apiConfiguration).toEqual(deletedSettings) + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await provider.dispose() + } + }) + + it("leaves the deleting view pin and overlay on the survivor when the deletion lands", async () => { + // The other half of review thread 4746968703 ask that the fix cover both + // outcomes: when every write of the group commits, the re-pointed pin and + // overlay must stay on the survivor. This row is the over-restore guard - it + // holds on the parent bytes too, because nothing there moved on success. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + try { + const oldProfile: ProviderSettingsEntry = { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + } + const keeperProfile: ProviderSettingsEntry = { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + } + // The survivor settings carry the record minus its name: the id stays, so the + // overlay must match the survivor record field for field. + const survivorSettings = { + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "keeper-key", + } + await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) + await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") + provider["viewLocalState"].currentApiConfigName = "old-profile" + provider["viewLocalState"].apiConfiguration = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "deleting-view-buffered-settings", + } + vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => { + if ("name" in params && params.name === "old-profile") { + return { + name: "old-profile", + id: "old-id", + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "deleting-view-buffered-settings", + } + } + return { + name: "keeper-profile", + id: "keeper-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "keeper-key", + } + }) + vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("x") + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + await provider.deleteProviderProfile(oldProfile) + expect(provider["viewLocalState"].currentApiConfigName).toBe("keeper-profile") + expect(provider["viewLocalState"].apiConfiguration).toEqual(survivorSettings) + await ClineProvider["persistedViewStateWriteQueue"] + } finally { + await provider.dispose() + } + }) + it("does not re-point a pinned sibling's task that follows another profile when its profile is deleted", async () => { // Defensive: the doubles in this suite can leave console writes pending // at worker teardown. From ab8b96bfb3ba4aa11da1f53dfb09f8cea4175990 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:41:29 +0800 Subject: [PATCH 10/34] run the profile model patch inside the stored record section [cr 4748668063] A profile save takes the critical section that ProviderSettingsManager.runExclusiveAcrossInstances keys on the secrets key of the manager: it snapshots the stored record, writes it, and when the read-back of that write fails it re-writes the snapshot it captured. A model patch waited only on its own view mutation queue, so a patch for the same profile from another view could land between that snapshot and its compensation, report success, and leave the record back on the older snapshot the saving view had taken. The patch read, its validation, its persist and its restore now run inside that same section, taken inside the per-view mutation queue in the same order the save takes it. Nothing reacquires the section while it is held: persistProviderProfile does not call the helper, the rename and the ordinary save arms take it at their own entry points outside this callback, and the allow-list read is already served from inside the callback by a path that does not take it. The helper keys the section on the secrets key, which resolves to a static prefix plus api_config, so the host has one stored profile namespace, and the cost of this change is that profile record write groups now serialize across views, including a patch to a profile no one else is touching. Two rows bound what stays outside the section: a patch that is only queued in its own view queue does not hold it, so a writer that needs the section completes, and the locked manager read paths of another view still complete while a view is parked inside its write group. Reviewer row 4748668057 asked that the expectation of a model patch running while another view is parked inside its profile write be kept. That premise belongs to the un-wrapped shape that 4748668063 asks to change, so the row is restated as waiting for the release, and the writes that do not contend are carried by the two rows above rather than dropped. Witnesses: three rows red on the parent bytes at their named assertions - a patch completing while a save was parked, a patch no longer the last writer of the name after a failed save compensated, and a patch merging a provider another view had already replaced - plus the two scope rows, which hold on both columns. Dropping the section re-colours the first two, moving it to cover only the write re-colours the third, and moving it outside the mutation queue re-colours the scope row. --- src/core/webview/ClineProvider.ts | 126 ++++++------ ...eProvider.profileMutationExclusion.spec.ts | 191 +++++++++++++++++- 2 files changed, 254 insertions(+), 63 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 23017421278..78a50dae37e 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3271,79 +3271,89 @@ export class ClineProvider try { await this.enqueueProviderProfileMutation( async (signal) => { - const { name: _name, ...stored } = await this.providerSettingsManager.getProfile({ name }) - - // Unset provider (e.g. the seeded default profile) resolves to anthropic, matching getState(). - const storedProvider = stored.apiProvider ?? providerIdentifiers.anthropic + // The stored record this patch reads and writes belongs to the same shared critical + // section a profile save takes above: every view builds its own + // ProviderSettingsManager over these profiles, so without this call another view + // can snapshot the profile, save it and compensate its own failed save right between + // this read and this write, and the patch above would report success over a record + // that no longer holds it. The section is taken inside the per-view mutation queue, in + // the same order the save above uses, and getState() is already called from inside this + // callback, so nothing here reacquires the section while it is held. + await this.providerSettingsManager.runExclusiveAcrossInstances(async () => { + const { name: _name, ...stored } = await this.providerSettingsManager.getProfile({ name }) + + // Unset provider (e.g. the seeded default profile) resolves to anthropic, matching getState(). + const storedProvider = stored.apiProvider ?? providerIdentifiers.anthropic + + if (storedProvider !== expectedProvider) { + throw new Error( + `Profile "${name}" provider changed from "${expectedProvider}" to "${storedProvider}"`, + ) + } - if (storedProvider !== expectedProvider) { - throw new Error( - `Profile "${name}" provider changed from "${expectedProvider}" to "${storedProvider}"`, - ) - } + const merged: Record = { ...stored, apiProvider: storedProvider } - const merged: Record = { ...stored, apiProvider: storedProvider } + for (const [key, value] of Object.entries(patch)) { + if (PROFILE_MODEL_ID_PATCH_KEYS.has(key)) { + if (typeof value !== "string" || value.length === 0) { + throw new Error(`Key "${key}" must be a non-empty string in a model patch`) + } - for (const [key, value] of Object.entries(patch)) { - if (PROFILE_MODEL_ID_PATCH_KEYS.has(key)) { - if (typeof value !== "string" || value.length === 0) { - throw new Error(`Key "${key}" must be a non-empty string in a model patch`) - } + merged[key] = value + } else if (PROFILE_MODEL_RESET_ONLY_KEYS.has(key)) { + if (value !== null && value !== undefined) { + throw new Error(`Key "${key}" can only be cleared in a model patch`) + } - merged[key] = value - } else if (PROFILE_MODEL_RESET_ONLY_KEYS.has(key)) { - if (value !== null && value !== undefined) { - throw new Error(`Key "${key}" can only be cleared in a model patch`) + delete merged[key] + } else { + throw new Error(`Key "${key}" is not allowed in a model patch`) } - - delete merged[key] - } else { - throw new Error(`Key "${key}" is not allowed in a model patch`) } - } - if (storedProvider === providerIdentifiers.bedrock) { - if (merged.apiModelId === BEDROCK_CUSTOM_ARN_MODEL_ID) { - // The allow-list only sees apiModelId, so a patch must not select an ARN it cannot supply. - if (!merged.awsCustomArn) { - throw new Error( - `Model "${BEDROCK_CUSTOM_ARN_MODEL_ID}" requires an existing custom ARN`, - ) - } - } else { - // A retained ARN would override the allow-listed model, so drop it with its context fields. - for (const key of PROFILE_MODEL_RESET_ONLY_KEYS) { - if (key.startsWith("aws")) delete merged[key] + if (storedProvider === providerIdentifiers.bedrock) { + if (merged.apiModelId === BEDROCK_CUSTOM_ARN_MODEL_ID) { + // The allow-list only sees apiModelId, so a patch must not select an ARN it cannot supply. + if (!merged.awsCustomArn) { + throw new Error( + `Model "${BEDROCK_CUSTOM_ARN_MODEL_ID}" requires an existing custom ARN`, + ) + } + } else { + // A retained ARN would override the allow-listed model, so drop it with its context fields. + for (const key of PROFILE_MODEL_RESET_ONLY_KEYS) { + if (key.startsWith("aws")) delete merged[key] + } } } - } - const { organizationAllowList } = await this.getState() + const { organizationAllowList } = await this.getState() - if (!ProfileValidator.isProfileAllowed(merged as ProviderSettings, organizationAllowList)) { - throw new OrganizationAllowListViolationError( - t("common:errors.violated_organization_allowlist"), - ) - } + if (!ProfileValidator.isProfileAllowed(merged as ProviderSettings, organizationAllowList)) { + throw new OrganizationAllowListViolationError( + t("common:errors.violated_organization_allowlist"), + ) + } - if (signal.aborted) return + if (signal.aborted) return - try { - await this.persistProviderProfile(name, merged as ProviderSettings, true, signal) - } catch (persistError) { - // Saving and activating are separate writes. Put the previous profile back so - // storage, context settings, and the task do not disagree about the model. try { - await this.persistProviderProfile(name, stored as ProviderSettings, true, signal) - } catch (restoreError) { - partialState = true - this.log( - `Error restoring profile after failed model update: ${JSON.stringify(restoreError, Object.getOwnPropertyNames(restoreError), 2)}`, - ) - } + await this.persistProviderProfile(name, merged as ProviderSettings, true, signal) + } catch (persistError) { + // Saving and activating are separate writes. Put the previous profile back so + // storage, context settings, and the task do not disagree about the model. + try { + await this.persistProviderProfile(name, stored as ProviderSettings, true, signal) + } catch (restoreError) { + partialState = true + this.log( + `Error restoring profile after failed model update: ${JSON.stringify(restoreError, Object.getOwnPropertyNames(restoreError), 2)}`, + ) + } - throw persistError - } + throw persistError + } + }) }, { runToCompletion: true }, ) diff --git a/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts b/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts index ddcb29b7927..67711e6e194 100644 --- a/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts @@ -240,6 +240,10 @@ function createSharedProfileStore() { } const id = config.id ?? records.get(name)?.id ?? storedIdFor(name) records.set(name, { ...config, id }) + // A landed write makes the name readable again: an armed read-back failure costs the + // writer it was armed for one read, and the writer that runs after it in the shared + // section reads the record the compensation above just stored, not a poisoned name. + unreadable.delete(name) if (unreadableMarker && unreadableMarker.name === name && unreadableMarker.marker === config) { unreadable.add(name) } @@ -444,7 +448,7 @@ describe("ClineProvider - provider profile mutation exclusion", () => { expect(store.calls().some((call) => call.method === "deleteConfig")).toBe(false) }) - it("lets another view write while a view is parked inside its profile write", async () => { + it("waits for the stored-record section another view is parked inside before applying a model patch", async () => { store = createSharedProfileStore() const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) views = [first, second] @@ -460,14 +464,191 @@ describe("ClineProvider - provider profile mutation exclusion", () => { .then(() => { patchSettled = true }) - const settled = await waitForRounds(STORE_ROUNDS, () => patchSettled) + const settledEarly = await waitForRounds(STORE_ROUNDS, () => patchSettled) + + // Review thread 4748668063 (printed at ClineProvider.ts line 3250 with original_line + // 3250) moved this expectation. The patch now takes the same stored-record critical + // section the save above holds, so while that save is parked the patch waits with it: the + // mutation queue stays per-view - and its per-view timeout budget is asserted by the + // provider profile mutation rows in ClineProvider.spec.ts - but the record section is + // shared, and a patch that wrote through a parked save had its change undone by the save + // that was still in flight. + expect(settledEarly).toBe(false) + expect(store.enteredCall("second", "saveConfig", SEED_PROFILE_NAME)).toBe(false) - // The mutation queue stays per-view: only the stored-record critical section is shared. - // A class-wide queue would park this patch behind the deferred write above. - expect(settled).toBe(true) + store.releaseSave(SETTINGS_A) + await Promise.all([firstSave, patch]) + expect(patchSettled).toBe(true) expect(store.record(SEED_PROFILE_NAME)?.apiModelId).toBe(PATCHED_SEED_MODEL_ID) + }) + + it("applies a model patch after another view compensates its failed write of the same profile", async () => { + // The lost update review thread 4748668063 names, at the pair of steps above: the save + // holds the shared stored-record section, and when its read-back fails its compensation + // re-writes the snapshot it took before that save. A model patch for the same profile from + // another view that wrote inside that window reported success while the record went back to + // the older snapshot, because nothing made the patch wait for the section. + store = createSharedProfileStore() + const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) + views = [first, second] + + store.deferSaveOf(SETTINGS_A) + const firstSave = first.upsertProviderProfile(SEED_PROFILE_NAME, SETTINGS_A, false) + const parked = await waitForRounds(STORE_ROUNDS, () => + store!.enteredCall("first", "saveConfig", SEED_PROFILE_NAME), + ) + expect(parked).toBe(true) + // The patch runs on the other view own queue, which the parked save does not hold, and it + // reaches the store only after the save above settles - which is the interleaving the thread + // names: snapshot taken, save in flight, patch queued behind it. + const patch = second.updateProfileModel(SEED_PROFILE_NAME, providerIdentifiers.anthropic, { + apiModelId: PATCHED_SEED_MODEL_ID, + }) + // The wait below is capped by design, exactly as the row above caps its own: on these + // bytes the patch cannot reach the store while the save holds the section, so it runs its + // full length, and on the parent bytes the patch reaches the store inside the window and + // the wait returns early. Either way the save below is released only after the patch had + // its turn, so the interleaving the thread names is a fact rather than a hope. + await waitForRounds(STORE_ROUNDS, () => store!.enteredCall("second", "saveConfig", SEED_PROFILE_NAME)) + store.armReadBackFailureAfter(SEED_PROFILE_NAME, SETTINGS_A) store.releaseSave(SETTINGS_A) await Promise.all([firstSave, patch]) + + // The patch is the last writer of the name, so the compensation above cannot have put its + // own older snapshot back over it. + const writersOfSeed = store + .calls() + .filter((call) => call.method === "saveConfig" && call.name === SEED_PROFILE_NAME) + .map((call) => call.tag) + expect(writersOfSeed.at(-1)).toBe("second") + expect(store.record(SEED_PROFILE_NAME)?.apiModelId).toBe(PATCHED_SEED_MODEL_ID) + }) + + it("declines a patch whose read went stale while it waited for the shared section", async () => { + // The read is part of the section for the same reason the write is, and this row is what + // makes that half load-bearing. The patch is queued while the other view parked save is in + // flight on the same profile. A patch that took only the write half of the section would + // still merge the provider it read before waiting and store that stale provider back over + // the record the other view had just written, because the guard above would have compared + // the patch against a record that no longer exists. Reading inside the section makes the + // guard see the newer provider, so the patch declines to write at all. + store = createSharedProfileStore() + const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) + views = [first, second] + + const movedSettings: ProviderSettings = { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "moved-by-the-other-view", + openRouterModelId: "model-moved", + } + store.deferSaveOf(movedSettings) + const firstSave = first.upsertProviderProfile(SEED_PROFILE_NAME, movedSettings, false) + const parked = await waitForRounds(STORE_ROUNDS, () => + store!.enteredCall("first", "saveConfig", SEED_PROFILE_NAME), + ) + expect(parked).toBe(true) + + let patchSettled = false + const patch = second + .updateProfileModel(SEED_PROFILE_NAME, providerIdentifiers.anthropic, { apiModelId: PATCHED_SEED_MODEL_ID }) + .then(() => { + patchSettled = true + }) + const settledEarly = await waitForRounds(STORE_ROUNDS, () => patchSettled) + expect(settledEarly).toBe(false) + + store.releaseSave(movedSettings) + await Promise.all([firstSave, patch]) + expect(patchSettled).toBe(true) + + // Only the other view wrote the name: the provider guard saw the newer record and the patch + // never reached the store. + const writersOfSeed = store + .calls() + .filter((call) => call.method === "saveConfig" && call.name === SEED_PROFILE_NAME) + .map((call) => call.tag) + expect(writersOfSeed).toEqual(["first"]) + expect(store.record(SEED_PROFILE_NAME)?.apiProvider).toBe(providerIdentifiers.openrouter) + }) + + it("keeps writes that do not contend for the record section away from a queued patch", async () => { + // Scope carrier for the section the row above waits on, and the check that the section is + // taken only where the record is touched. A patch that grabbed the section before entering + // its own view queue would hold it while sitting behind the unrelated task below, and the + // writer below - which needs the section for its own record write - would then wait on a + // lock nobody was using. On these bytes the patch has not reached the section yet, so the + // writer completes while the patch has not settled. + store = createSharedProfileStore() + const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) + views = [first, second] + + // An unrelated task holds the patch view own queue without ever touching the section. + const queueGate = createDeferredGate() + const queuedTask = second["enqueueProviderProfileMutation"](() => queueGate.promise, { + runToCompletion: true, + }) + let patchSettled = false + const patch = second + .updateProfileModel(SEED_PROFILE_NAME, providerIdentifiers.anthropic, { apiModelId: PATCHED_SEED_MODEL_ID }) + .then(() => { + patchSettled = true + }) + await waitForRounds(50, () => false) + + const firstWriterSettings: ProviderSettings = { + apiProvider: providerIdentifiers.anthropic, + apiModelId: "model-first-writer", + } + const firstSave = first.upsertProviderProfile(PARKED_NAME, firstWriterSettings, false) + const sameNamespaceSettled = await waitForRounds(STORE_ROUNDS, () => + store!.enteredCall("first", "saveConfig", PARKED_NAME), + ) + + expect(sameNamespaceSettled).toBe(true) + expect(patchSettled).toBe(false) + expect(store.record(SEED_PROFILE_NAME)?.apiModelId).toBe("model-seed") + + queueGate.release() + await Promise.all([queuedTask, patch, firstSave]) + expect(patchSettled).toBe(true) + expect(store.record(PARKED_NAME)?.apiModelId).toBe("model-first-writer") + }) + + it("lets another view read the stored profiles while a view is parked inside its write group", async () => { + // Width guard for the same section. While the writer above is parked inside its save, the + // locked read paths of another view - the profile list and the profile lookup every + // consumer uses - still complete, so the section bounds the record write group rather than + // every use of the stored profiles. A shape that put the section around the manager read + // path, or around every profile entry point, would be wider than the gap the thread names. + store = createSharedProfileStore() + const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) + views = [first, second] + + store.deferSaveOf(SETTINGS_A) + let firstSettled = false + const firstSave = first.upsertProviderProfile(PARKED_NAME, SETTINGS_A, false).then((id) => { + firstSettled = true + return id + }) + const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredCall("first", "saveConfig", PARKED_NAME)) + expect(parked).toBe(true) + + let readsDone = false + const profileReads = Promise.all([ + second.providerSettingsManager.listConfig(), + second.providerSettingsManager.getProfile({ name: SEED_PROFILE_NAME }), + ]).then(() => { + readsDone = true + }) + const readsCompleted = await waitForRounds(STORE_ROUNDS, () => readsDone) + + // The reads finished while the writer above was still parked inside its own write group. + expect(readsCompleted).toBe(true) + expect(firstSettled).toBe(false) + + store.releaseSave(SETTINGS_A) + await Promise.all([firstSave, profileReads]) + expect(firstSettled).toBe(true) }) }) From 6c1051d72454435cb6b5a3101c28e71b8c8f90b0 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:30:55 +0800 Subject: [PATCH 11/34] release the profile queue gate when a scope row assertion fails [cr 4749096381] The scope row parked an unrelated task in the patch view mutation queue and opened that gate only after its own assertions ran, so a failing assertion left the queued task and the model patch waiting on a gate nothing else opens: the afterEach hook releases the stored-profile save gates, never this row-local one. The parked mutation never starts, and its own thirty-second queue timeout is longer than the twenty-second test timeout this suite runs under, so nothing inside the run ever opens the gate again. The three scope assertions now sit in a try whose finally opens the gate and awaits the settled task, patch and writer. The success-path assertions stay after that block, so the row still names the same release ordering between the queued task, the patch and the section writer. Deleting the release call from the finally re-colours the scope row red on its own - it waits out the queue and dies at its test body, line 575 - so the release call, not the comment beside it, is what the row depends on. --- ...eProvider.profileMutationExclusion.spec.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts b/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts index 67711e6e194..d9ffc43cbd5 100644 --- a/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts @@ -605,12 +605,21 @@ describe("ClineProvider - provider profile mutation exclusion", () => { store!.enteredCall("first", "saveConfig", PARKED_NAME), ) - expect(sameNamespaceSettled).toBe(true) - expect(patchSettled).toBe(false) - expect(store.record(SEED_PROFILE_NAME)?.apiModelId).toBe("model-seed") + try { + expect(sameNamespaceSettled).toBe(true) + expect(patchSettled).toBe(false) + expect(store.record(SEED_PROFILE_NAME)?.apiModelId).toBe("model-seed") + } finally { + // Review thread 4749096381 (printed at line 590 with original_line 590): the release and the + // queue drain used to sit after the assertions above, so a failing assertion left the queued + // task and the patch parked on a gate nothing else opened - the afterEach hook releases only + // the store save gates, never this local one - and the run then sat out the mutation-queue + // timeout, with an unhandled rejection behind the reported failure. Both belong in a finally, + // so the gate opens and the queue drains whichever way the assertions go. + queueGate.release() + await Promise.allSettled([queuedTask, patch, firstSave]) + } - queueGate.release() - await Promise.all([queuedTask, patch, firstSave]) expect(patchSettled).toBe(true) expect(store.record(PARKED_NAME)?.apiModelId).toBe("model-first-writer") }) From b8a8b0a55e11360992bd35d69d4ed841a3df545d Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:53:33 +0800 Subject: [PATCH 12/34] run the profile mutation race against the real settings manager [cr 4748668057] The fixture replaced hasConfig, getProfile, saveConfig, deleteConfig, listConfig, activateProfile and the mode-map methods with callbacks that copied the production record lookup, chose the record id from the stored map and skipped the manager lock, the settings schema parse and the store path. A regression inside those paths could not fail this file: the row that lets another view read the stored profiles stayed green because of the callbacks, not because of what the code does. Each view now drives a real ProviderSettingsManager over one serialized profiles blob reached through the mocked secrets boundary, and the racing write parks inside that boundary at the stored-profiles key. The cross-instance lock stays the production one. The seven rows assert on what the manager itself returns - ids it generated, models it read back through its own load path, and writers whose store actually changed a named record - and a poison arm rewrites the next read so a failed read-back exercises the not-found branch inside the manager instead of a stub. A manager that takes the shared section while listing configs now colours that row red at line 788 and five more with it, while the same mutant stays green against the bytes this replaces, which is the shadowing the finding named. --- ...eProvider.profileMutationExclusion.spec.ts | 600 +++++++++++------- 1 file changed, 366 insertions(+), 234 deletions(-) diff --git a/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts b/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts index d9ffc43cbd5..43f0815b623 100644 --- a/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts @@ -3,11 +3,10 @@ import * as vscode from "vscode" import { makeCompositeDisposable } from "../../../test-utils/vscode" import { TelemetryService } from "@roo-code/telemetry" -import type { ProviderSettings, ProviderSettingsWithId } from "@roo-code/types" +import type { ProviderSettings } from "@roo-code/types" import { providerIdentifiers } from "@roo-code/types/provider-identifiers" import { ContextProxy } from "../../config/ContextProxy" -import type { ProviderSettingsManager } from "../../config/ProviderSettingsManager" import { WebviewFocusTracker } from "../WebviewFocusTracker" import { ClineProvider } from "../ClineProvider" @@ -134,13 +133,50 @@ const PARKED_NAME = "parked-new-profile" const SEED_PROFILE_NAME = "seed-profile" const STORE_ROUNDS = 300 -const SETTINGS_A: ProviderSettings = { apiProvider: providerIdentifiers.anthropic, apiModelId: "model-a" } -const SETTINGS_B: ProviderSettings = { apiProvider: providerIdentifiers.anthropic, apiModelId: "model-b" } +// One model id per writer: the marker a write carries is the model id it puts into the stored +// record, so a serialized payload names the writer that produced it and a row can park that +// write on its own marker at the storage boundary. +const MODEL_A = "model-a" +const MODEL_B = "model-b" +const MODEL_DEFAULT = "model-default" +const MODEL_TEST = "model-test" +const MODEL_SEED = "model-seed" +const MODEL_MOVED = "model-moved" +const MODEL_FIRST_WRITER = "model-first-writer" const PATCHED_SEED_MODEL_ID = "model-seed-patched" +const SETTINGS_A: ProviderSettings = { apiProvider: providerIdentifiers.anthropic, apiModelId: MODEL_A } +const SETTINGS_B: ProviderSettings = { apiProvider: providerIdentifiers.anthropic, apiModelId: MODEL_B } + +// The stored provider profiles live under one secrets key: the manager private static scope prefix +// plus api_config (ProviderSettingsManager.secretsKey, which is why one host has one stored +// profile namespace). Both views route their mocked context.secrets through that key, so the two +// views really contend for one stored namespace. +const PROFILES_SECRETS_KEY = "roo_cline_config_api_config" + const storedIdFor = (name: string) => `id-${name}` -type StoreCall = { tag: string; method: string; name: string } +/** + * The recording context.secrets handed to one view: the stored-profiles key is routed to the + * shared blob, while every other secret key stays view-local. + */ +type ProfilesSecretStorage = { + get: (key: string) => Promise + store: (key: string, value: string) => Promise + delete: (key: string) => Promise +} + +type BoundaryCall = { + tag: string + method: "get" | "store" | "delete" + /** The payload a store wrote, or the payload a get returned. Absent for a delete. */ + payload?: string + /** + * For a store: the names whose stored record this write changed. A write re-serializes the + * whole blob, so a name whose record comes out identical was not written by this call. + */ + changed?: string[] +} function createDeferredGate() { let release: () => void = () => {} @@ -150,152 +186,225 @@ function createDeferredGate() { return { promise, release } } +/** + * Key-sorted serialization, so comparing two records is a comparison of the stored value and not + * of the key order the schema happened to emit. + */ +function canonical(value: unknown): string { + if (value === null || typeof value !== "object") { + return JSON.stringify(value) ?? "undefined" + } + if (Array.isArray(value)) { + return `[${value.map(canonical).join(",")}]` + } + const entries = Object.entries(value as Record) + .filter(([, item]) => item !== undefined) + .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) + return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}` +} + +function parsedRecordOf(payload: string | undefined, name: string): Record | undefined { + if (payload === undefined) { + return undefined + } + try { + const profiles = JSON.parse(payload) as { apiConfigs?: Record> } + return profiles.apiConfigs?.[name] + } catch { + return undefined + } +} + +function blobNames(payload: string | undefined): string[] { + if (payload === undefined) { + return [] + } + try { + const profiles = JSON.parse(payload) as { apiConfigs?: Record } + return Object.keys(profiles.apiConfigs ?? {}) + } catch { + return [] + } +} + +function changedNamesBetween(previous: string | undefined, next: string | undefined): string[] { + const names = new Set([...blobNames(previous), ...blobNames(next)]) + return Array.from(names).filter( + (name) => canonical(parsedRecordOf(previous, name)) !== canonical(parsedRecordOf(next, name)), + ) +} + +function recordHoldsMarker(record: Record | undefined, marker: string): boolean { + // Quoted, so a marker cannot be satisfied by a longer model id that merely starts with it. + return record !== undefined && canonical(record).includes(`"${marker}"`) +} + /** * One stored provider-profile namespace shared by two views, which is the shape the host - * produces: the sidebar and each editor tab build their own `ProviderSettingsManager` over - * the same stored profiles. Every storage call is recorded twice, on entry and on return, - * tagged by the view that made it, so a row can name which writer reached the store and - * when. Each write can be parked on a gate opened by payload identity, and the read-back of - * a name can be armed to fail once a chosen write has landed - that is how a writer is made - * to reject after its own save succeeded. + * produces: the sidebar and each editor tab build their own ProviderSettingsManager over the same + * stored profiles. The fixture replaces no manager method. Both views run the real manager - its + * per-instance lock, its schema parsing, its load and its store - and share only the serialized + * blob behind a recording context.secrets proxy, which tags every boundary call with the view + * that made it. Review thread 4748668057 (printed at line 242 with original_line 242) asked for + * exactly this: the storage boundary is the seam, and a regression inside the manager - a dropped + * id, a read that stops going through secrets, a read path that takes the shared section - now + * fails these rows instead of hiding behind a callback that copied production logic. + * + * A write parks on the gate of the marker its payload carries. armRecordUnreadableAfter makes the + * next read after a chosen payload lands return a copy whose apiConfigs lack that name, so the + * manager own read-back of a landed write fails through its own not-found path and the writer + * compensates through its own restore paths. */ function createSharedProfileStore() { - const records = new Map() - const entered: StoreCall[] = [] - const returned: StoreCall[] = [] - const saveGates = new Map>() - const unreadable = new Set() - let unreadableMarker: { name: string; marker: ProviderSettings } | undefined - let currentProfileName = "default" - - records.set("default", { - id: storedIdFor("default"), - apiProvider: providerIdentifiers.anthropic, - apiModelId: "model-default", - }) - records.set("test-config", { - id: storedIdFor("test-config"), - apiProvider: providerIdentifiers.anthropic, - apiModelId: "model-test", - }) - records.set(SEED_PROFILE_NAME, { - id: storedIdFor(SEED_PROFILE_NAME), - apiProvider: providerIdentifiers.anthropic, - apiModelId: "model-seed", - }) + // The shape providerProfilesSchema accepts, so the manager own load() parses the seed exactly as + // it parses a write, and initialize() finds every migration already applied and writes nothing. + const blob: { value: string | undefined } = { + value: JSON.stringify( + { + currentApiConfigName: "default", + apiConfigs: { + default: { + id: storedIdFor("default"), + apiProvider: providerIdentifiers.anthropic, + apiModelId: MODEL_DEFAULT, + }, + "test-config": { + id: storedIdFor("test-config"), + apiProvider: providerIdentifiers.anthropic, + apiModelId: MODEL_TEST, + }, + [SEED_PROFILE_NAME]: { + id: storedIdFor(SEED_PROFILE_NAME), + apiProvider: providerIdentifiers.anthropic, + apiModelId: MODEL_SEED, + }, + }, + modeApiConfigs: {}, + migrations: { + rateLimitSecondsMigrated: true, + openAiHeadersMigrated: true, + consecutiveMistakeLimitMigrated: true, + toolRepetitionLimitsMigrated: true, + todoListEnabledMigrated: true, + claudeCodeLegacySettingsMigrated: true, + routerProviderMigrated: true, + }, + }, + null, + 2, + ), + } - const nameForId = (id: string) => Array.from(records.entries()).find(([, record]) => record.id === id)?.[0] + const entered: BoundaryCall[] = [] + const landed: BoundaryCall[] = [] + const storeGates = new Map>() + let unreadable: { name: string; marker: string } | undefined + let poisonNextReadOf: string | undefined - const read = (name: string): ProviderSettingsWithId => { - const record = records.get(name) - if (!record) { - throw new Error(`Config with name ${name} was not found`) + const readBlob = (): string | undefined => { + const value = blob.value + if (poisonNextReadOf === undefined) { + return value } - if (unreadable.has(name)) { - throw new Error(`Config with name ${name} could not be read back`) + const name = poisonNextReadOf + poisonNextReadOf = undefined + if (value === undefined || parsedRecordOf(value, name) === undefined) { + return value + } + const profiles = JSON.parse(value) as { apiConfigs: Record } + delete profiles.apiConfigs[name] + return JSON.stringify(profiles, null, 2) + } + + function createSecrets(tag: string) { + // Secret keys other than the stored profiles stay view-local exactly as the fixture had them; + // the namespace these rows contend for is the profile namespace. + const otherKeys: Record = {} + return { + get: vi.fn(async (key: string) => { + if (key !== PROFILES_SECRETS_KEY) { + return otherKeys[key] + } + const call: BoundaryCall = { tag, method: "get" } + entered.push(call) + call.payload = readBlob() + landed.push(call) + return call.payload + }), + store: vi.fn(async (key: string, value: string) => { + if (key !== PROFILES_SECRETS_KEY) { + otherKeys[key] = value + return + } + const previous = blob.value + const call: BoundaryCall = { tag, method: "store", payload: value } + entered.push(call) + // A write parks on every gate whose marker its payload carries. A gate stays open once + // released, so a later write that merely mentions the same model id walks past it. + for (const [marker, gate] of storeGates) { + if (value.includes(`"${marker}"`)) { + await gate.promise + } + } + call.changed = changedNamesBetween(previous, value) + blob.value = value + if (unreadable && value.includes(`"${unreadable.marker}"`)) { + poisonNextReadOf = unreadable.name + unreadable = undefined + } + landed.push(call) + }), + delete: vi.fn(async (key: string) => { + if (key !== PROFILES_SECRETS_KEY) { + delete otherKeys[key] + return + } + const call: BoundaryCall = { tag, method: "delete" } + entered.push(call) + blob.value = undefined + landed.push(call) + }), } - return record } const store = { - record: (name: string) => records.get(name), - has: (name: string) => records.has(name), - calls: () => entered, - enteredCall: (tag: string, method: string, name?: string) => + /** The stored record of a name, read back out of the blob the way the manager reads it. */ + record: (name: string) => parsedRecordOf(blob.value, name), + has: (name: string) => parsedRecordOf(blob.value, name) !== undefined, + blobText: () => blob.value, + /** A store this view entered whose payload carries marker in the record of name. */ + enteredStoreOf: (tag: string, name: string, marker: string) => entered.some( - (call) => call.tag === tag && call.method === method && (name === undefined || call.name === name), + (call) => + call.method === "store" && + call.tag === tag && + recordHoldsMarker(parsedRecordOf(call.payload, name), marker), ), - returnedCallCount: (tag: string) => returned.filter((call) => call.tag === tag).length, - deferSaveOf: (settings: ProviderSettings) => { - saveGates.set(settings, createDeferredGate()) + /** Reads this view completed through the shared profiles key. */ + getCount: (tag: string) => landed.filter((call) => call.method === "get" && call.tag === tag).length, + /** The views that changed the record of name, in the order those writes landed. */ + writersOf: (name: string) => + landed.filter((call) => call.method === "store" && call.changed?.includes(name)).map((call) => call.tag), + hadRecordDelete: () => landed.some((call) => call.method === "delete"), + deferStoreOf: (marker: string) => { + storeGates.set(marker, createDeferredGate()) }, - releaseSave: (settings: ProviderSettings) => saveGates.get(settings)?.release(), + releaseStore: (marker: string) => storeGates.get(marker)?.release(), releaseAll: () => { - for (const gate of saveGates.values()) { + for (const gate of storeGates.values()) { gate.release() } }, - armReadBackFailureAfter: (name: string, marker: ProviderSettings) => { - unreadableMarker = { name, marker } - }, - attach(manager: ProviderSettingsManager, tag: string) { - vi.spyOn(manager, "hasConfig").mockImplementation(async (name) => { - entered.push({ tag, method: "hasConfig", name }) - const exists = records.has(name) - returned.push({ tag, method: "hasConfig", name }) - return exists - }) - vi.spyOn(manager, "getProfile").mockImplementation(async (params) => { - const name = "name" in params ? params.name : (nameForId(params.id) ?? "") - entered.push({ tag, method: "getProfile", name }) - const record = read(name) - returned.push({ tag, method: "getProfile", name }) - return { ...record, name } - }) - vi.spyOn(manager, "saveConfig").mockImplementation(async (name, config) => { - entered.push({ tag, method: "saveConfig", name }) - const gate = saveGates.get(config) - if (gate) { - await gate.promise - } - const id = config.id ?? records.get(name)?.id ?? storedIdFor(name) - records.set(name, { ...config, id }) - // A landed write makes the name readable again: an armed read-back failure costs the - // writer it was armed for one read, and the writer that runs after it in the shared - // section reads the record the compensation above just stored, not a poisoned name. - unreadable.delete(name) - if (unreadableMarker && unreadableMarker.name === name && unreadableMarker.marker === config) { - unreadable.add(name) - } - returned.push({ tag, method: "saveConfig", name }) - return id - }) - vi.spyOn(manager, "deleteConfig").mockImplementation(async (name) => { - entered.push({ tag, method: "deleteConfig", name }) - records.delete(name) - returned.push({ tag, method: "deleteConfig", name }) - }) - vi.spyOn(manager, "listConfig").mockImplementation(async () => { - entered.push({ tag, method: "listConfig", name: "*" }) - const entries = Array.from(records.entries()).map(([name, record]) => ({ name, id: record.id ?? "" })) - returned.push({ tag, method: "listConfig", name: "*" }) - return entries - }) - vi.spyOn(manager, "getCurrentProfileName").mockImplementation(async () => { - entered.push({ tag, method: "getCurrentProfileName", name: currentProfileName }) - const name = currentProfileName - returned.push({ tag, method: "getCurrentProfileName", name }) - return name - }) - vi.spyOn(manager, "activateProfile").mockImplementation(async (args) => { - const name = "name" in args ? args.name : (nameForId(args.id) ?? "") - entered.push({ tag, method: "activateProfile", name }) - const record = read(name) - currentProfileName = name - returned.push({ tag, method: "activateProfile", name }) - return { ...record, name } - }) - vi.spyOn(manager, "setModeConfig").mockImplementation(async (mode, configId) => { - entered.push({ tag, method: "setModeConfig", name: `${mode}:${configId}` }) - returned.push({ tag, method: "setModeConfig", name: `${mode}:${configId}` }) - }) - vi.spyOn(manager, "getModeConfigId").mockImplementation(async (mode) => { - entered.push({ tag, method: "getModeConfigId", name: mode }) - returned.push({ tag, method: "getModeConfigId", name: mode }) - return undefined - }) - vi.spyOn(manager, "getModeConfigIds").mockImplementation(async () => { - entered.push({ tag, method: "getModeConfigIds", name: "*" }) - returned.push({ tag, method: "getModeConfigIds", name: "*" }) - return {} - }) + armRecordUnreadableAfter: (name: string, marker: string) => { + unreadable = { name, marker } }, + createSecrets, } return store } -function createMockContext(): vscode.ExtensionContext { +function createMockContext(secrets: ProfilesSecretStorage): vscode.ExtensionContext { const globalState: Record = { mode: "code", currentApiConfigName: "test-config", @@ -304,7 +413,6 @@ function createMockContext(): vscode.ExtensionContext { { id: storedIdFor("default"), name: "default" }, ], } - const secrets: Record = {} return { extensionPath: "/test/path", @@ -314,11 +422,7 @@ function createMockContext(): vscode.ExtensionContext { update: vi.fn((key: string, value: unknown) => (globalState[key] = value)), keys: vi.fn(() => Object.keys(globalState)), }, - secrets: { - get: vi.fn((key: string) => secrets[key]), - store: vi.fn((key: string, value: string | undefined) => (secrets[key] = value)), - delete: vi.fn((key: string) => delete secrets[key]), - }, + secrets, workspaceState: { get: vi.fn(() => undefined), update: vi.fn().mockResolvedValue(undefined), @@ -331,7 +435,7 @@ function createMockContext(): vscode.ExtensionContext { } async function createView(store: ReturnType, tag: string): Promise { - const context = createMockContext() + const context = createMockContext(store.createSecrets(tag)) const outputChannel = { appendLine: vi.fn(), clear: vi.fn(), @@ -360,12 +464,15 @@ async function createView(store: ReturnType, ta ) // The persisted mode map is not part of this scenario; seed the window-local copy empty. provider["initialModeConfigIds"] = Promise.resolve({}) - store.attach(provider.providerSettingsManager, tag) + // The manager constructor fires its own initialize() against the shared blob, and every later + // call chains onto the same per-instance lock. Draining it here keeps a startup write from + // landing between the row and its first boundary call, and keeps the seeded records the rows + // assert on. + await provider.providerSettingsManager["_lock"] await provider.resolveWebviewView(view) return provider } - async function waitForRounds(rounds: number, condition: () => boolean): Promise { for (let round = 0; round < rounds; round++) { if (condition()) { @@ -400,52 +507,78 @@ describe("ClineProvider - provider profile mutation exclusion", () => { store = undefined }) + it("stores the seeded profiles through the real manager read and write paths", async () => { + // The premise every row below rests on, and the claim review thread 4748668057 (printed at + // line 242 with original_line 242) asked the fixture to hold: these are the manager own + // paths. Its load() parses the seeded blob, its profile lookup and selection read go through + // the mocked context.secrets boundary, and a write lands through its store(), so a regression + // inside the manager fails these rows instead of hiding behind a replaced method. + store = createSharedProfileStore() + const view = await createView(store, "first") + views = [view] + + await expect(view.providerSettingsManager.getProfile({ name: SEED_PROFILE_NAME })).resolves.toStrictEqual({ + name: SEED_PROFILE_NAME, + id: storedIdFor(SEED_PROFILE_NAME), + apiProvider: providerIdentifiers.anthropic, + apiModelId: MODEL_SEED, + }) + await expect(view.providerSettingsManager.getCurrentProfileName()).resolves.toBe("default") + await expect(view.providerSettingsManager.listConfig()).resolves.toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: SEED_PROFILE_NAME, id: storedIdFor(SEED_PROFILE_NAME) }), + ]), + ) + + // The write half runs the same way: the id the manager generated is the id the shared blob + // ends up holding, through the settings-schema parse and store(). + const writtenId = await view.providerSettingsManager.saveConfig(PARKED_NAME, SETTINGS_B) + expect(writtenId).toBeTruthy() + expect(store.record(PARKED_NAME)).toStrictEqual({ ...SETTINGS_B, id: writtenId }) + expect(store.enteredStoreOf("first", PARKED_NAME, MODEL_B)).toBe(true) + expect(store.writersOf(PARKED_NAME)).toEqual(["first"]) + }) + it("keeps the record of the writer that succeeded when two views create the same new name", async () => { store = createSharedProfileStore() const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) views = [first, second] - store.deferSaveOf(SETTINGS_A) + store.deferStoreOf(MODEL_A) const firstSave = first.upsertProviderProfile(PROFILE_NAME, SETTINGS_A, false) - const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredCall("first", "saveConfig", PROFILE_NAME)) + const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredStoreOf("first", PROFILE_NAME, MODEL_A)) expect(parked).toBe(true) - store.deferSaveOf(SETTINGS_B) + store.deferStoreOf(MODEL_B) const secondSave = second.upsertProviderProfile(PROFILE_NAME, SETTINGS_B, false) - // The interleaving the row names is two snapshots taken before the first write lands. - // Waiting for the second writer to finish its two store reads before opening the first - // gate makes that ordering a fact rather than a hope; when the writers are serialized the - // second one parks on the shared exclusion instead, so this wait is capped by design. - await waitForRounds(STORE_ROUNDS, () => store!.returnedCallCount("second") >= 2) - store.releaseSave(SETTINGS_A) + // The interleaving the row names is two snapshots taken before the first write lands. Waiting + // for the second writer to finish its two profile reads before opening the first gate makes + // that ordering a fact rather than a hope; on these bytes the writers are serialized on the + // shared section, so the second one parks there and this wait runs its full length by design. + await waitForRounds(STORE_ROUNDS, () => store!.getCount("second") >= 2) + store.releaseStore(MODEL_A) const firstResult = await firstSave - expect(firstResult).toBe(storedIdFor(PROFILE_NAME)) - store.armReadBackFailureAfter(PROFILE_NAME, SETTINGS_B) - store.releaseSave(SETTINGS_B) + store.armRecordUnreadableAfter(PROFILE_NAME, MODEL_B) + store.releaseStore(MODEL_B) const secondResult = await secondSave expect(secondResult).toBeUndefined() // The stored record is the successful writer record, not the settings the failed writer - // rejected, and not a record some compensation deleted out from under it. - expect(store.record(PROFILE_NAME)?.apiModelId).toBe(SETTINGS_A.apiModelId) - expect(store.record(PROFILE_NAME)).toStrictEqual({ ...SETTINGS_A, id: storedIdFor(PROFILE_NAME) }) + // rejected, and not a record some compensation deleted out from under it - including the id + // the successful writer was handed, which the failed writer own rewrite has to preserve. + expect(firstResult).toBe(store.record(PROFILE_NAME)?.id) + expect(store.record(PROFILE_NAME)?.apiModelId).toBe(MODEL_A) + expect(store.record(PROFILE_NAME)).toStrictEqual({ ...SETTINGS_A, id: firstResult }) expect(store.has(PROFILE_NAME)).toBe(true) // Carriers: both writers really reached the store, in that order, and the failed writer // compensated by restoring rather than by deleting. - const writerOrder = Array.from( - new Set( - store - .calls() - .filter((call) => call.method === "saveConfig" && call.name === PROFILE_NAME) - .map((call) => call.tag), - ), - ) + const writerOrder = Array.from(new Set(store.writersOf(PROFILE_NAME))) expect(writerOrder).toEqual(["first", "second"]) - expect(store.calls().some((call) => call.method === "deleteConfig")).toBe(false) + expect(store.hadRecordDelete()).toBe(false) }) it("waits for the stored-record section another view is parked inside before applying a model patch", async () => { @@ -453,9 +586,9 @@ describe("ClineProvider - provider profile mutation exclusion", () => { const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) views = [first, second] - store.deferSaveOf(SETTINGS_A) + store.deferStoreOf(MODEL_A) const firstSave = first.upsertProviderProfile(PARKED_NAME, SETTINGS_A, false) - const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredCall("first", "saveConfig", PARKED_NAME)) + const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredStoreOf("first", PARKED_NAME, MODEL_A)) expect(parked).toBe(true) let patchSettled = false @@ -466,73 +599,71 @@ describe("ClineProvider - provider profile mutation exclusion", () => { }) const settledEarly = await waitForRounds(STORE_ROUNDS, () => patchSettled) - // Review thread 4748668063 (printed at ClineProvider.ts line 3250 with original_line - // 3250) moved this expectation. The patch now takes the same stored-record critical - // section the save above holds, so while that save is parked the patch waits with it: the - // mutation queue stays per-view - and its per-view timeout budget is asserted by the - // provider profile mutation rows in ClineProvider.spec.ts - but the record section is - // shared, and a patch that wrote through a parked save had its change undone by the save - // that was still in flight. + // Review thread 4748668063 (printed at ClineProvider.ts line 3250 with original_line 3250) + // moved this expectation. The patch now takes the same stored-record critical section the + // save above holds, so while that save is parked at the storage boundary the patch waits with + // it: the mutation queue stays per-view - and its per-view timeout budget is asserted by the + // provider profile mutation rows in ClineProvider.spec.ts - but the record section is shared, + // and a patch that wrote through a parked save had its change undone by the save that was + // still in flight. expect(settledEarly).toBe(false) - expect(store.enteredCall("second", "saveConfig", SEED_PROFILE_NAME)).toBe(false) + expect(store.enteredStoreOf("second", SEED_PROFILE_NAME, PATCHED_SEED_MODEL_ID)).toBe(false) - store.releaseSave(SETTINGS_A) + store.releaseStore(MODEL_A) await Promise.all([firstSave, patch]) expect(patchSettled).toBe(true) expect(store.record(SEED_PROFILE_NAME)?.apiModelId).toBe(PATCHED_SEED_MODEL_ID) }) - it("applies a model patch after another view compensates its failed write of the same profile", async () => { - // The lost update review thread 4748668063 names, at the pair of steps above: the save - // holds the shared stored-record section, and when its read-back fails its compensation - // re-writes the snapshot it took before that save. A model patch for the same profile from - // another view that wrote inside that window reported success while the record went back to - // the older snapshot, because nothing made the patch wait for the section. + // The lost update review thread 4748668063 names, at the pair of steps above: the save holds + // the shared stored-record section, and when its read-back of the landed write fails its + // compensation re-writes the snapshot it took before that save. A model patch for the same + // profile from another view that wrote inside that window reported success while the record + // went back to the older snapshot, because nothing made the patch wait for the section. store = createSharedProfileStore() const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) views = [first, second] - store.deferSaveOf(SETTINGS_A) + store.deferStoreOf(MODEL_A) const firstSave = first.upsertProviderProfile(SEED_PROFILE_NAME, SETTINGS_A, false) const parked = await waitForRounds(STORE_ROUNDS, () => - store!.enteredCall("first", "saveConfig", SEED_PROFILE_NAME), + store!.enteredStoreOf("first", SEED_PROFILE_NAME, MODEL_A), ) expect(parked).toBe(true) // The patch runs on the other view own queue, which the parked save does not hold, and it // reaches the store only after the save above settles - which is the interleaving the thread - // names: snapshot taken, save in flight, patch queued behind it. + // names: snapshot taken, write in flight, patch queued behind it. const patch = second.updateProfileModel(SEED_PROFILE_NAME, providerIdentifiers.anthropic, { apiModelId: PATCHED_SEED_MODEL_ID, }) - // The wait below is capped by design, exactly as the row above caps its own: on these - // bytes the patch cannot reach the store while the save holds the section, so it runs its - // full length, and on the parent bytes the patch reaches the store inside the window and - // the wait returns early. Either way the save below is released only after the patch had - // its turn, so the interleaving the thread names is a fact rather than a hope. - await waitForRounds(STORE_ROUNDS, () => store!.enteredCall("second", "saveConfig", SEED_PROFILE_NAME)) - store.armReadBackFailureAfter(SEED_PROFILE_NAME, SETTINGS_A) - store.releaseSave(SETTINGS_A) + // The wait below is capped by design, exactly as the row above caps its own: on these bytes + // the patch cannot reach the store while the save holds the section, so the wait runs its full + // length, and on the parent bytes the patch reaches the store inside the window and the wait + // returns early. Either way the save below is released only after the patch had its turn, so + // the interleaving the thread names is a fact rather than a hope. + await waitForRounds(STORE_ROUNDS, () => + store!.enteredStoreOf("second", SEED_PROFILE_NAME, PATCHED_SEED_MODEL_ID), + ) + store.armRecordUnreadableAfter(SEED_PROFILE_NAME, MODEL_A) + store.releaseStore(MODEL_A) await Promise.all([firstSave, patch]) - // The patch is the last writer of the name, so the compensation above cannot have put its - // own older snapshot back over it. - const writersOfSeed = store - .calls() - .filter((call) => call.method === "saveConfig" && call.name === SEED_PROFILE_NAME) - .map((call) => call.tag) + // The patch is the last writer of the name, so the compensation above cannot have put its own + // older snapshot back over it. + const writersOfSeed = store.writersOf(SEED_PROFILE_NAME) expect(writersOfSeed.at(-1)).toBe("second") expect(store.record(SEED_PROFILE_NAME)?.apiModelId).toBe(PATCHED_SEED_MODEL_ID) }) it("declines a patch whose read went stale while it waited for the shared section", async () => { - // The read is part of the section for the same reason the write is, and this row is what - // makes that half load-bearing. The patch is queued while the other view parked save is in - // flight on the same profile. A patch that took only the write half of the section would - // still merge the provider it read before waiting and store that stale provider back over - // the record the other view had just written, because the guard above would have compared - // the patch against a record that no longer exists. Reading inside the section makes the - // guard see the newer provider, so the patch declines to write at all. + // The read is part of the section for the same reason the write is, and this row is what makes + // that half load-bearing. The patch is queued while the other view parked save is in flight on + // the same profile. A patch that took only the write half of the section would still merge the + // provider it read before waiting and store that stale provider back over the record the other + // view had just written, because the guard would have compared the patch against a record that + // no longer exists. Reading inside the section makes the guard see the newer provider, so the + // patch declines to write at all. store = createSharedProfileStore() const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) views = [first, second] @@ -540,12 +671,12 @@ describe("ClineProvider - provider profile mutation exclusion", () => { const movedSettings: ProviderSettings = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "moved-by-the-other-view", - openRouterModelId: "model-moved", + openRouterModelId: MODEL_MOVED, } - store.deferSaveOf(movedSettings) + store.deferStoreOf(MODEL_MOVED) const firstSave = first.upsertProviderProfile(SEED_PROFILE_NAME, movedSettings, false) const parked = await waitForRounds(STORE_ROUNDS, () => - store!.enteredCall("first", "saveConfig", SEED_PROFILE_NAME), + store!.enteredStoreOf("first", SEED_PROFILE_NAME, MODEL_MOVED), ) expect(parked).toBe(true) @@ -558,16 +689,13 @@ describe("ClineProvider - provider profile mutation exclusion", () => { const settledEarly = await waitForRounds(STORE_ROUNDS, () => patchSettled) expect(settledEarly).toBe(false) - store.releaseSave(movedSettings) + store.releaseStore(MODEL_MOVED) await Promise.all([firstSave, patch]) expect(patchSettled).toBe(true) // Only the other view wrote the name: the provider guard saw the newer record and the patch // never reached the store. - const writersOfSeed = store - .calls() - .filter((call) => call.method === "saveConfig" && call.name === SEED_PROFILE_NAME) - .map((call) => call.tag) + const writersOfSeed = store.writersOf(SEED_PROFILE_NAME) expect(writersOfSeed).toEqual(["first"]) expect(store.record(SEED_PROFILE_NAME)?.apiProvider).toBe(providerIdentifiers.openrouter) }) @@ -576,9 +704,9 @@ describe("ClineProvider - provider profile mutation exclusion", () => { // Scope carrier for the section the row above waits on, and the check that the section is // taken only where the record is touched. A patch that grabbed the section before entering // its own view queue would hold it while sitting behind the unrelated task below, and the - // writer below - which needs the section for its own record write - would then wait on a - // lock nobody was using. On these bytes the patch has not reached the section yet, so the - // writer completes while the patch has not settled. + // writer below - which needs the section for its own record write - would then wait on a lock + // nobody was using. On these bytes the patch has not reached the section yet, so the writer + // completes while the patch has not settled. store = createSharedProfileStore() const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) views = [first, second] @@ -598,65 +726,69 @@ describe("ClineProvider - provider profile mutation exclusion", () => { const firstWriterSettings: ProviderSettings = { apiProvider: providerIdentifiers.anthropic, - apiModelId: "model-first-writer", + apiModelId: MODEL_FIRST_WRITER, } const firstSave = first.upsertProviderProfile(PARKED_NAME, firstWriterSettings, false) const sameNamespaceSettled = await waitForRounds(STORE_ROUNDS, () => - store!.enteredCall("first", "saveConfig", PARKED_NAME), + store!.enteredStoreOf("first", PARKED_NAME, MODEL_FIRST_WRITER), ) try { expect(sameNamespaceSettled).toBe(true) expect(patchSettled).toBe(false) - expect(store.record(SEED_PROFILE_NAME)?.apiModelId).toBe("model-seed") + expect(store.record(SEED_PROFILE_NAME)?.apiModelId).toBe(MODEL_SEED) } finally { - // Review thread 4749096381 (printed at line 590 with original_line 590): the release and the - // queue drain used to sit after the assertions above, so a failing assertion left the queued - // task and the patch parked on a gate nothing else opened - the afterEach hook releases only - // the store save gates, never this local one - and the run then sat out the mutation-queue - // timeout, with an unhandled rejection behind the reported failure. Both belong in a finally, - // so the gate opens and the queue drains whichever way the assertions go. + // Review thread 4749096381 (printed at line 590 with original_line 590), carried over from the + // row this one replaces: the release and the drain belong in the finally, so a failing + // assertion above cannot leave the queued task and the patch parked on a gate nothing else + // opens - the afterEach hook releases the stored-profile gates, never this local one. queueGate.release() await Promise.allSettled([queuedTask, patch, firstSave]) } - expect(patchSettled).toBe(true) - expect(store.record(PARKED_NAME)?.apiModelId).toBe("model-first-writer") + expect(store.record(PARKED_NAME)?.apiModelId).toBe(MODEL_FIRST_WRITER) }) it("lets another view read the stored profiles while a view is parked inside its write group", async () => { - // Width guard for the same section. While the writer above is parked inside its save, the - // locked read paths of another view - the profile list and the profile lookup every - // consumer uses - still complete, so the section bounds the record write group rather than - // every use of the stored profiles. A shape that put the section around the manager read - // path, or around every profile entry point, would be wider than the gap the thread names. + // Width guard for the same section. While the writer above is parked inside its save at the + // storage boundary, the locked read paths of another view - the profile list and the profile + // lookup every consumer uses - still complete through their own manager, so the section bounds + // the record write group rather than every use of the stored profiles. A shape that put the + // section around a manager read path, or around every profile entry point, would be wider than + // the gap the thread names - and on the real manager those reads are the manager own methods, + // not callbacks the fixture substituted for them. store = createSharedProfileStore() const [first, second] = await Promise.all([createView(store, "first"), createView(store, "second")]) views = [first, second] - store.deferSaveOf(SETTINGS_A) + store.deferStoreOf(MODEL_A) let firstSettled = false const firstSave = first.upsertProviderProfile(PARKED_NAME, SETTINGS_A, false).then((id) => { firstSettled = true return id }) - const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredCall("first", "saveConfig", PARKED_NAME)) + const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredStoreOf("first", PARKED_NAME, MODEL_A)) expect(parked).toBe(true) let readsDone = false const profileReads = Promise.all([ second.providerSettingsManager.listConfig(), second.providerSettingsManager.getProfile({ name: SEED_PROFILE_NAME }), - ]).then(() => { - readsDone = true - }) + ]).then( + () => { + readsDone = true + }, + // A rejected read is reported by the wait below, not left dangling: an assertion that fails + // here would otherwise strand a rejected read behind it. + () => undefined, + ) const readsCompleted = await waitForRounds(STORE_ROUNDS, () => readsDone) // The reads finished while the writer above was still parked inside its own write group. expect(readsCompleted).toBe(true) expect(firstSettled).toBe(false) - store.releaseSave(SETTINGS_A) + store.releaseStore(MODEL_A) await Promise.all([firstSave, profileReads]) expect(firstSettled).toBe(true) }) From 953ff7cbda78715b25e52cb3bdd5a221d957b643 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:04:20 +0800 Subject: [PATCH 13/34] test the profile selection read through the real manager [cr review 6124404069] Three direct tests for getCurrentProfileName, the method the changed lines added, run against the real manager with no spy on it: a stored selection comes back verbatim, nothing stored answers with the default selection - providerProfilesSchema requires the selection field, so a blob that omits it is the wrapped parse failure asserted in that same row, never an undefined - and a secrets read failure rejects with the wrapped text, the method prefix over the load wrap over the host message: Failed to read the active profile: Failed to read provider profiles from secrets: Error: Storage failed. Each row counts the storage boundary while a same-manager write queues behind the per-instance lock: one secrets read and no store while the selection read is inside its critical section. Production is unchanged. A manager that drops the lock fails all three rows on those counts. A manager that reads the selection from its defaults fails two rows on the returned name; the unset row survives because both answers are the default name and those two bytes cannot separate it, which is reported rather than hidden. A manager that returns nothing fails all three, and one that rethrows without the wrap fails all three on the message. --- .../__tests__/ProviderSettingsManager.spec.ts | 125 ++++++++++++++++++ 1 file changed, 125 insertions(+) diff --git a/src/core/config/__tests__/ProviderSettingsManager.spec.ts b/src/core/config/__tests__/ProviderSettingsManager.spec.ts index 0f8f8d9da1d..bee19c89f97 100644 --- a/src/core/config/__tests__/ProviderSettingsManager.spec.ts +++ b/src/core/config/__tests__/ProviderSettingsManager.spec.ts @@ -1497,6 +1497,131 @@ describe("ProviderSettingsManager", () => { }) }) + describe("GetCurrentProfileName", () => { + // The stored shape every row below reads back: one selectable profile plus the default, with + // every migration flag set so initialize() writes nothing. + const profilesSelecting = (currentApiConfigName: string): ProviderProfiles => ({ + currentApiConfigName, + apiConfigs: { + default: { id: "default" }, + chosen: { apiProvider: providerIdentifiers.anthropic, id: "chosen-id" }, + }, + modeApiConfigs: {}, + migrations: { + rateLimitSecondsMigrated: true, + openAiHeadersMigrated: true, + consecutiveMistakeLimitMigrated: true, + toolRepetitionLimitsMigrated: true, + todoListEnabledMigrated: true, + claudeCodeLegacySettingsMigrated: true, + routerProviderMigrated: true, + }, + }) + + // The text the method produces for a secrets failure: its own prefix over the load wrap over + // the host error. Asserted as a whole so dropping the wrap - or replacing it with a rethrow - + // is a failing assertion rather than a message change. + const wrappedStorageFailure = + "Failed to read the active profile: Failed to read provider profiles from secrets: Error: Storage failed" + + /** + * Drains the manager startup chain, parks this manager next secrets read, and queues a + * same-manager write behind it. The per-instance lock the method takes is what keeps that write + * out of storage while the selection read is inside its critical section: without the lock the + * queued write runs its own read and write while the selection read is still parked, so the + * counts below depend on the lock. They are returned rather than asserted here so each test + * names the assertion that goes red. + */ + async function startReadWithWriteQueuedBehindIt(storedProfiles: string | undefined) { + await providerSettingsManager.initialize() + const readsBefore = mockSecrets.get.mock.calls.length + const storesBefore = mockSecrets.store.mock.calls.length + let settleParkedRead: (settlement: { value?: string; error?: Error }) => void = () => {} + const parkedRead = new Promise((resolve, reject) => { + settleParkedRead = (settlement) => + settlement.error ? reject(settlement.error) : resolve(settlement.value) + }) + mockSecrets.get.mockImplementationOnce(() => parkedRead) + const selection = providerSettingsManager.getCurrentProfileName() + const queuedWrite = providerSettingsManager.saveConfig("chosen", { + apiProvider: providerIdentifiers.anthropic, + apiModelId: "written-after-the-selection-read", + id: "chosen-id", + }) + await new Promise((resolve) => setTimeout(resolve, 0)) + return { + selection, + queuedWrite, + release: () => settleParkedRead({ value: storedProfiles }), + fail: () => settleParkedRead({ error: new Error("Storage failed") }), + readCallsWhileParked: mockSecrets.get.mock.calls.length - readsBefore, + storeCallsWhileParked: mockSecrets.store.mock.calls.length - storesBefore, + } + } + + it("returns the selection the stored profiles carry, after the write queued behind its lock", async () => { + const storedProfiles = JSON.stringify(profilesSelecting("chosen")) + mockSecrets.get.mockResolvedValue(storedProfiles) + + await providerSettingsManager.initialize() + await providerSettingsManager.activateProfile({ name: "chosen" }) + const persistedCalls = mockSecrets.store.mock.calls + const activated = JSON.parse(persistedCalls[persistedCalls.length - 1][1] as string) + expect(activated.currentApiConfigName).toBe("chosen") + + const read = await startReadWithWriteQueuedBehindIt(storedProfiles) + // Lock: the queued write has not reached its own secrets read, let alone storage. + expect(read.readCallsWhileParked).toBe(1) + expect(read.storeCallsWhileParked).toBe(0) + + read.release() + // Field read: the selection the stored profiles carry - not the record the queued write + // stored after it, and not nothing. + await expect(read.selection).resolves.toBe("chosen") + await expect(read.queuedWrite).resolves.toBe("chosen-id") + + // Error wrap: the same read through the same lock, failed at the secrets boundary. + mockSecrets.get.mockRejectedValueOnce(new Error("Storage failed")) + await expect(providerSettingsManager.getCurrentProfileName()).rejects.toThrow(wrappedStorageFailure) + }) + + it("answers with its own default selection when nothing is stored", async () => { + // Nothing stored: the fresh-install default selection is what a consumer reads back. There is + // no stored shape in which this method answers with nothing - providerProfilesSchema requires + // the selection field, so a blob that omits it is the wrapped parse failure asserted below - + // so the unset case reports a default, not an undefined. + const read = await startReadWithWriteQueuedBehindIt(undefined) + expect(read.readCallsWhileParked).toBe(1) + expect(read.storeCallsWhileParked).toBe(0) + + read.release() + await expect(read.selection).resolves.toBe("default") + await expect(read.queuedWrite).resolves.toBe("chosen-id") + + const { currentApiConfigName: _omitted, ...blobWithoutSelection } = profilesSelecting("chosen") + mockSecrets.get.mockResolvedValue(JSON.stringify(blobWithoutSelection)) + await expect(providerSettingsManager.getCurrentProfileName()).rejects.toThrow( + "Failed to read the active profile:", + ) + }) + + it("rejects with its own wrapped message when the secrets read fails, and stays usable", async () => { + const storedProfiles = JSON.stringify(profilesSelecting("chosen")) + mockSecrets.get.mockResolvedValue(storedProfiles) + + const read = await startReadWithWriteQueuedBehindIt(storedProfiles) + expect(read.readCallsWhileParked).toBe(1) + expect(read.storeCallsWhileParked).toBe(0) + + read.fail() + await expect(read.selection).rejects.toThrow(wrappedStorageFailure) + await expect(read.queuedWrite).resolves.toBe("chosen-id") + + // A rejected critical section does not strand the lock: the next read through it still + // answers with the stored selection. + await expect(providerSettingsManager.getCurrentProfileName()).resolves.toBe("chosen") + }) + }) describe("syncCloudProfiles", () => { it("should add new cloud profiles without secret keys", async () => { const existingConfig: ProviderProfiles = { From 79970ffb93b7d12d54fda41dd4a6a4e406f13017 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:47:34 +0800 Subject: [PATCH 14/34] write the launch repair pin and its settings as one mutation [cr 4746979121] [cr 4746979128] Production, src/core/webview/webviewMessageHandler.ts: - L713-722 (parent L713-714): the launch repair wrote the seeded settings and the view pin as two single-key provider.saveViewState calls. Only currentApiConfigName persists durably, so a rejection on the second write left the provider buffer holding the new profile's settings under a pin that still named the deleted profile, with no durable write at all. The repair now issues one provider mutation carrying { apiConfiguration: seedSettings, currentApiConfigName: globalConfigName } - the shape the finding asks for, and the shape this file's deletion re-pin (ClineProvider.ts L4246) and rename re-point (L4315) already use. - L1013-1025 (parent L1005-1010): the updateSettings profile-lookup catch cleared this view's settings overlay and let the pin move anyway, so the view reported the selected profile while it ran the previous profile's settings, and a caller that supplied a requestId got settingsSaveResult { success: true } for a save that had not installed the record. It logs the same [updateSettings] Unable to resolve API profile '' prefix with the new semantics and rethrows (L1024). The rethrow is taken by the branch's own catch (L1046-1049), which records failed/failure; L1060-1067 then posts settingsSaveResult { type, requestId, success: false, error } to the requestId caller and L1069 rejects the message promise. That is the save-failure response the finding names, reached through the path the pin write already used. The promise is awaited by ClineProvider.setWebviewMessageListener's onReceiveMessage (ClineProvider.ts L2728-2757), which records a diagnostics failure and rethrows; no new unhandled rejection is created, the rejection lands on the boundary the existing failure path already lands on. Production, src/core/webview/ClineProvider.ts: - L1280-1310 (parent L1280-1292): public saveViewState gains a second overload taking a values object (declarations L1293-1297, implementation signature L1298-1301). Both shapes delegate to _saveViewLocalStateFromMutation (L1307), so no third public name is added for the same concept and the type system keeps the two shapes apart. The log line is unchanged for single-key calls; for an object it names the keys that one mutation carried. The JSDoc above it (parent L1281-1283) was rewritten because it described only the single-key shape. Clearing a pin still uses the single-key arm, untouched. Spec, src/core/webview/__tests__/webviewMessageHandler.spec.ts: - New assertions naming the single mutation, in equality form (not toMatchObject or toContainEqual): L997-1005, L1050-1058, L1135-1138 and L1139 (one call only), each naming apiConfiguration together with currentApiConfigName. - L1010-1015 asserts the apiConfiguration payload that one call carried (equality on mock.calls[0][0].apiConfiguration); L1015 is the parent invariant kept verbatim, L1018-1021 and L1059-1062 are new negations on the same mutation: a pin never lands with an absent or unreadable overlay, and never names first-listed. - Reviewer-authorized semantic re-derives (parent line -> new line): 991 -> 997, 997 -> 1010, 1029 -> 1050, 1056 -> 1094, 1060 -> 1104, 1075+1076 -> 1135-1138, 2270 -> 2349, 2272 -> 2352. Each replaced a per-key saveViewState assertion that a paired write cannot express; the invariants behind them (which profile the view follows, what the seed carried, nothing written when the save fails) are unchanged or stronger. - Titles rewritten because the behavior they named changed, disclosed because rows are cited by name: parent L1034 -> L1066, "seeds the re-pinned profile's settings before persisting the re-pin so a failed pin stays retryable" -> "writes the re-pinned profile's settings together with the re-pin so a failed write stays retryable"; parent L2253 -> L2316, "clears the overlay instead of serving a stale one when the selected record cannot be read" -> "keeps the pin and its settings on the previous profile when the selected record cannot be read". - Harness retargets the new write shape forces: L983-986 records the fields of the one call in the order log (parent L980-982 recorded args[0], which is an object once a call carries several fields; without the retarget the pre-existing ordering assertion at L1032-1033 would have gone green vacuously). L1078-1084 injects the failure on that one mutation (parent L1038-1045 keyed its throw on args[0] === "currentApiConfigName", which no longer fires) and types the stub parameter unknown, because a two-parameter stub is not assignable to the overloaded method (tsc TS2322 otherwise). L2342-2347 wraps the updateSettings call in await expect(...).rejects.toThrow (L2339-2344) because the save now rejects. L2326-2328 and L2366-2367 snapshot the shared doubles' call counts before the call, and L2349, L2352-2353, L2385-2386 assert none were added: this file shares module-level doubles across rows and restores identities, not histories. - New row L2356-2387, "reports a failed save to the caller when the selected record cannot be read": the requestId caller receives settingsSaveResult { requestId, success: false, error: "secrets read failed" }, and no overlay, pin or shared-selection write happens. - Comments added where the pairing is asserted. No assertion was downgraded to toMatchObject or toContainEqual to make it pass. Evidence (core/webview/__tests__/webviewMessageHandler.spec.ts; 188 rows at parent bytes, 189 at new bytes; --disableConsoleIntercept so the local worker-teardown race does not colour the verdict): - baseline, parent bytes: exit 0, 188 passed. - new production + parent assertions: exit 1, 5 failed; first red per row L991, L1029, L1056, L1075, L2258 - the parent bytes of exactly the re-derived lines, so assertions and behavior changed together. - parent production + new assertions: exit 1, 6 failed; first red L997, L1050, L1094, L1135, L2344, L2375 (new numbering): every re-derived line is red against parent production. - comment-only control (parent production bytes plus this commit's comments, new spec): exit 1, the same 6 rows red at the same lines. - mutants, each named with its red location: M1 parent two single-key writes restored: 4 failed - L997, L1050, L1094, L1135, the four launch rows. M2 mutation carries the pin only (apiConfiguration dropped): 3 failed - L997, L1050, L1094. M3 overload dispatch broken (object treated as a key): 189 passed here - the launch suite stubs the provider, so the implementation is invisible to it; killed in ClineProvider.spec.ts (1 failed, L9686, "should re-pin the view to a valid global selection when ..."). M4 mutation persists the pin only, overlay dropped: 189 passed here for the same reason; killed in ClineProvider.spec.ts (36 failed, first L3886, saveViewState "should update viewLocalState and persist ..."). M5 parent catch restored (clear the overlay, swallow): 2 failed - L2344, L2375, both "promise resolved undefined instead of rejecting". M6 log and swallow (throw error -> void error): 2 failed, same rows. M7 failure injection removed from the L1066 row's stub: 189 passed - that row is a failure-injection test and the injected rejection is what makes it assert anything; reported rather than hidden. M8 the wrapper around the L2316 call removed against parent production: 1 failed at L2347 - "expected [ [ apiConfiguration, undefined ] ] to have a length of +0 but got 1" - so the re-derived no-write assertion catches the parent clear-overlay write on its own. - No survivor among mutants that target behavior this spec observes; M3 and M4 are implementation-level and are covered where that code is tested, as listed. - Gates on the delivered bytes: format:check 0; check-types 0; src tsc 0; root lint 0; src lint 0; test:code-qa-ci 0; test:translations-check 0; knip 0; knip:production 0; test:knip-policy 0 (fail 0); lifecycle:model-check 0; mcp:integration-check 0; test:core 0 (5473 passed, 17 skipped, 224 files); test:misc 0 (2589 passed, 13 skipped); per-file eslint --prune-suppressions --max-warnings=0 on all three files 0. test:services is 1 for the environmental reason it is 1 at HEAD too - fs.symlink EPERM on the broken-rules fixture, 5 failed at HEAD as well - and it is not in the gate list. - src/eslint-suppressions.json unchanged: blob 1fad7b0e65fef2ae0d20cf0f83331da2b6d90012, 2841 counts over 261 files; eslint rewrites its line endings on every run, so it was checked out and re-hashed after each run. --- src/core/webview/ClineProvider.ts | 28 ++- .../__tests__/webviewMessageHandler.spec.ts | 176 +++++++++++++++--- src/core/webview/webviewMessageHandler.ts | 23 ++- 3 files changed, 187 insertions(+), 40 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 78a50dae37e..fc585f55337 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -1278,17 +1278,35 @@ export class ClineProvider } /** - * Saves a single view-local state value. The in-memory buffer is always updated; the - * non-secret subset (mode, currentApiConfigName) is persisted durably under the view - * id active when the change was made, re-keyed to the stable id on registration. + * Saves view-local state: one value at a time, or several values as one mutation. + * The in-memory buffer is always updated; the non-secret subset (mode, + * currentApiConfigName) is persisted durably under the view id active when the + * change was made, re-keyed to the stable id on registration. + * + * The object shape is here for the launch repair reviewed in cid 4746979121: the + * view pin and the settings that belong to it must not be two writes, because only + * the pin persists, and a failure between the two left the view serving one + * profile's settings under a pin that still named the deleted profile. Both shapes + * delegate to the same mutation, which persists the durable subset before touching + * the buffer. */ public async saveViewState( key: K, value: ViewLocalStateValues[K] | undefined, + ): Promise + public async saveViewState(values: ViewLocalStateValues): Promise + public async saveViewState( + keyOrValues: keyof ViewLocalStateValues | ViewLocalStateValues, + value?: unknown, ): Promise { - await this._saveViewLocalStateFromMutation({ [key]: value } as ViewLocalStateValues) + const values = + typeof keyOrValues === "object" && keyOrValues !== null + ? keyOrValues + : ({ [keyOrValues]: value } as ViewLocalStateValues) + + await this._saveViewLocalStateFromMutation(values) - this.log(`[saveViewState] Saved ${String(key)} for viewId ${this.viewId}`) + this.log(`[saveViewState] Saved ${Object.keys(values).join(", ")} for viewId ${this.viewId}`) } /** diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 39f9dce41c2..59b20808beb 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -977,8 +977,12 @@ describe("webviewMessageHandler - webviewDidLaunch", () => { // The order matters more than the individual calls: the re-pin changes what this view // resolves to, and neither write below posts anything by itself. const order: string[] = [] + // Review cid 4746979121: the repair writes pin and settings as one call now, so the + // order log records the fields that single call carried - the ordering the row below + // asserts is the single-key harness's, kept meaningful under the paired write. vi.mocked(mockClineProvider.saveViewState).mockImplementation(async (...args: unknown[]) => { - order.push(`save:${String(args[0])}`) + const values = args[0] as Record + for (const key of Object.keys(values)) order.push(`save:${String(key)}`) }) vi.mocked(mockClineProvider.postStateToWebview).mockImplementation(async () => { order.push("post") @@ -988,18 +992,33 @@ describe("webviewMessageHandler - webviewDidLaunch", () => { await new Promise((resolve) => setImmediate(resolve)) // The view pin is re-pinned to the first available profile, // and the shared global selection is left untouched: no global write, no global activation. - expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("currentApiConfigName", "shared-profile") + // Review cid 4746979121: the repaired pin is one provider mutation that carries the pin + // together with the settings belonging to it. + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith({ + apiConfiguration: { + id: "shared-profile-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }, + currentApiConfigName: "shared-profile", + }) // A re-pin that leaves the overlay empty is half a repair: a view whose overlay carries a // name but no apiConfiguration resolves that field from the shared store, so it would // display its own pin while running whatever profile the shared selection names next. The // seed mirrors loadViewState - the stored record without its name. expect(double.providerSettingsManager.getProfile).toHaveBeenCalledWith({ name: "shared-profile" }) - expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("apiConfiguration", { + expect(vi.mocked(mockClineProvider.saveViewState).mock.calls[0][0].apiConfiguration).toEqual({ id: "shared-profile-id", apiProvider: providerIdentifiers.anthropic, apiKey: "sk-shared-profile", }) expect(mockClineProvider.saveViewState).not.toHaveBeenCalledWith("apiConfiguration", undefined) + // The same invariant on the paired write: a successful record read is never followed by + // a pin that lands with an empty overlay. + expect(mockClineProvider.saveViewState).not.toHaveBeenCalledWith({ + apiConfiguration: undefined, + currentApiConfigName: "shared-profile", + }) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith( "currentApiConfigName", "shared-profile", @@ -1026,22 +1045,42 @@ describe("webviewMessageHandler - webviewDidLaunch", () => { await new Promise((resolve) => setImmediate(resolve)) // The view pin follows the still-valid shared global selection, not the first // profile in the list; the global selection is left untouched. - expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("currentApiConfigName", "shared-profile") + // Review cid 4746979121: the profile this view follows is asserted on the single call + // that carries the pin together with its settings. + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith({ + apiConfiguration: { + id: "shared-profile-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }, + currentApiConfigName: "shared-profile", + }) expect(mockClineProvider.saveViewState).not.toHaveBeenCalledWith("currentApiConfigName", "first-listed") + expect(mockClineProvider.saveViewState).not.toHaveBeenCalledWith({ + apiConfiguration: expect.anything(), + currentApiConfigName: "first-listed", + }) expect(mockClineProvider.activateProviderProfile).not.toHaveBeenCalled() }) - it("seeds the re-pinned profile's settings before persisting the re-pin so a failed pin stays retryable", async () => { + it("writes the re-pinned profile's settings together with the re-pin so a failed write stays retryable", async () => { + // Review cid 4746979121 rewrote this row's title, its harness and its two assertions: + // the repair no longer seeds first and pins after. It writes both fields as one mutation + // whose durable half is the pin, so the failure injected here is that single write, and + // the invariant is that neither field moved when it rejected - the invalid selection + // stays retryable on the next launch instead of a valid pin serving the deleted + // profile's buffered settings. vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation( async (name: string) => name === "shared-profile", ) - const calls: Array<[string, unknown]> = [] + const calls: Array = [] const originalSaveViewState = mockClineProvider.saveViewState - mockClineProvider.saveViewState = vi.fn(async (key: string, value: unknown) => { - calls.push([key, value]) - if (key === "currentApiConfigName") { - throw new Error("pin write failed") - } + // The stub parameter is unknown because the public saveViewState is overloaded (one key, + // or several keys as one mutation) and a stub typed for the single-key shape is not + // assignable to the overloaded method. + mockClineProvider.saveViewState = vi.fn(async (keyOrValues: unknown) => { + calls.push(keyOrValues) + throw new Error("pin write failed") }) try { await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) @@ -1050,14 +1089,32 @@ describe("webviewMessageHandler - webviewDidLaunch", () => { mockClineProvider.saveViewState = originalSaveViewState } - // The seed must land before the pin write: a failed seed leaves the pin unwritten, so the - // merged selection stays invalid and the repair retries on the next launch instead of a - // valid pin serving the deleted profile's buffered settings. - expect(calls[0]).toEqual([ - "apiConfiguration", - { id: "shared-profile-id", apiProvider: providerIdentifiers.anthropic, apiKey: "sk-shared-profile" }, + // The one attempted mutation, named as the call that carries the pin together with the + // settings that belong to it. + expect(calls).toEqual([ + { + apiConfiguration: { + id: "shared-profile-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }, + currentApiConfigName: "shared-profile", + }, ]) - expect(calls).toContainEqual(["currentApiConfigName", "shared-profile"]) + expect(calls).toContainEqual({ + apiConfiguration: { + id: "shared-profile-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }, + currentApiConfigName: "shared-profile", + }) + // The single-key overlay write that used to run ahead of the pin is gone, so a rejected + // repair cannot leave the new profile's settings in this view's buffer at all. + // The exact array above is the whole record of writes: one attempted mutation, and the + // repair never reaches a second write after the durable one failed. The assertion is on + // the recorded calls rather than on the mock because this row swaps in its own stub and + // restores the module-level double before it asserts. }) it("re-pins without a settings snapshot when the profile record vanishes before the seed read", async () => { @@ -1072,8 +1129,14 @@ describe("webviewMessageHandler - webviewDidLaunch", () => { // A seed read that fails must not cost the view the repair: the overlay falls back to empty // and the pin still lands, so the re-pin is not swallowed by the catch around this block. expect(double.providerSettingsManager.getProfile).toHaveBeenCalledWith({ name: "shared-profile" }) - expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("apiConfiguration", undefined) - expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("currentApiConfigName", "shared-profile") + // Review cid 4746979121: a re-pin without a settings snapshot is one mutation that + // carries the pin together with an explicitly absent overlay - the pin still lands, and it + // never lands next to a record that could not be read. + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith({ + apiConfiguration: undefined, + currentApiConfigName: "shared-profile", + }) + expect(mockClineProvider.saveViewState).toHaveBeenCalledTimes(1) expect(mockClineProvider.log).toHaveBeenCalledWith( expect.stringContaining('Seed read failed for "shared-profile"'), ) @@ -2250,7 +2313,7 @@ describe("webviewMessageHandler - updateSettings profile pin", () => { expect(order).toEqual(["seed:apiConfiguration", "write:currentApiConfigName"]) }) - it("clears the overlay instead of serving a stale one when the selected record cannot be read", async () => { + it("keeps the pin and its settings on the previous profile when the selected record cannot be read", async () => { const view = mockClineProvider as unknown as { providerSettingsManager: { getProfile: ReturnType } } @@ -2258,18 +2321,69 @@ describe("webviewMessageHandler - updateSettings profile pin", () => { getProfile: vi.fn().mockRejectedValue(new Error("secrets read failed")), } const logSpy = vi.mocked(mockClineProvider.log) - - await webviewMessageHandler(mockClineProvider, { - type: "updateSettings", - updatedSettings: { currentApiConfigName: "profile-b" }, - }) + // These module-level doubles are shared between rows and their call histories are not + // reset here, so the row snapshots the write counts first and asserts none were added. + const overlayWritesBefore = vi.mocked(mockClineProvider.saveViewState).mock.calls.length + const providerWritesBefore = vi.mocked(mockClineProvider.setValue).mock.calls.length + const globalWritesBefore = vi.mocked(mockClineProvider.contextProxy.setValue).mock.calls.length + + // Review cid 4746979128 rewrote this row's title and its two assertions. An unreadable + // record used to clear this view's overlay and move the pin anyway: the view then reported + // profile B while it ran profile A's settings, and a caller got a successful + // settingsSaveResult for a save that had not installed the record. The save fails now, + // with the pin and the overlay both left on the previous profile. The failure surfaces + // through the path updateSettings already has: the branch rethrows, the surrounding catch + // records it, a caller that supplied a requestId receives + // settingsSaveResult { success: false, error }, and the message promise itself rejects for + // callers that did not - so there is no unhandled rejection on either path. + await expect( + webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { currentApiConfigName: "profile-b" }, + }), + ).rejects.toThrow("secrets read failed") expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Unable to resolve API profile 'profile-b'")) - // An unreadable record must not leave the previous profile's settings under the new name: - // the overlay is cleared, which is what an unresolvable pin already means elsewhere. - expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("apiConfiguration", undefined) - // The pin itself still lands, so the selection is not silently dropped. - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("currentApiConfigName", "profile-b") + // Nothing was written to this view's overlay - no clear, and no seed under a name whose + // record could not be read. + expect(vi.mocked(mockClineProvider.saveViewState).mock.calls).toHaveLength(overlayWritesBefore) + // The pin does not move either: the selection is not rewritten to a profile whose record + // could not be read, so the view keeps its previous pin serving its previous settings. + expect(vi.mocked(mockClineProvider.contextProxy.setValue).mock.calls).toHaveLength(globalWritesBefore) + expect(vi.mocked(mockClineProvider.setValue).mock.calls).toHaveLength(providerWritesBefore) + }) + + it("reports a failed save to the caller when the selected record cannot be read", async () => { + // Review cid 4746979128 asked for the existing save-failure response on this path. The + // caller that supplied a requestId is the one that gets it, and it has to say the save + // failed: the same row above shows the promise rejecting for callers without a requestId. + const view = mockClineProvider as unknown as { + providerSettingsManager: { getProfile: ReturnType } + } + view.providerSettingsManager = { + getProfile: vi.fn().mockRejectedValue(new Error("secrets read failed")), + } + const overlayWritesAtStart = vi.mocked(mockClineProvider.saveViewState).mock.calls.length + const providerWritesAtStart = vi.mocked(mockClineProvider.setValue).mock.calls.length + + await expect( + webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { currentApiConfigName: "profile-b" }, + requestId: "save-unreadable-record", + }), + ).rejects.toThrow("secrets read failed") + + expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ + type: "settingsSaveResult", + requestId: "save-unreadable-record", + success: false, + error: "secrets read failed", + }) + // The response is the only write this failure produces: the pin, the overlay and the + // shared selection all stay where they were, so the caller can retry the same save. + expect(vi.mocked(mockClineProvider.saveViewState).mock.calls).toHaveLength(overlayWritesAtStart) + expect(vi.mocked(mockClineProvider.setValue).mock.calls).toHaveLength(providerWritesAtStart) }) it("restores the view's prior overlay when the pin write fails after the seed", async () => { diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 766a7253c66..f155ab38dc2 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -710,8 +710,16 @@ export const webviewMessageHandler = async ( // The durable view entry carries only mode and currentApiConfigName (see // _persistViewLocalStateFromMutation), so this seed is an in-memory overlay write; the // pin below is what persists. - await provider.saveViewState("apiConfiguration", seedSettings) - await provider.saveViewState("currentApiConfigName", globalConfigName) + // Review cid 4746979121: the pin and its settings move as one provider mutation. + // The two single-key writes this replaced let the seed land first, so a rejected pin + // left the provider holding profile B's settings under a pin that still named the + // deleted profile A: the durable write never happened, but the buffer had moved. + // One mutation persists the pin before either in-memory field changes, so a failed + // repair leaves both prior fields alone and the next launch retries it. + await provider.saveViewState({ + apiConfiguration: seedSettings, + currentApiConfigName: globalConfigName, + }) // The repair changes what this view resolves to, so the state has to be posted: the // two writes above update provider state without posting it, and the listApiConfig // message below carries the profile list only, so without this the webview keeps @@ -1003,10 +1011,17 @@ export const webviewMessageHandler = async ( await provider.providerSettingsManager.getProfile({ name: pinnedName }) await provider.saveViewState("apiConfiguration", seedProfile as ProviderSettings) } catch (error) { + // Review cid 4746979128: an unreadable record must not move this view's pin. Clearing + // the overlay and writing the name anyway left the view reporting profile B while it + // ran profile A's shared settings, and a caller that supplied a requestId got a + // successful settingsSaveResult for a save that had not installed the record. Fail + // the update through the same response the pin write above uses, so the caller can + // retry with the pin and the overlay both still on the previous profile. Clearing a + // pin is the separate arm below, where the caller asked for it. provider.log( - `[updateSettings] Unable to resolve API profile '${pinnedName}'; cleared this view's settings overlay instead of keeping the previous profile's: ${error instanceof Error ? error.message : String(error)}`, + `[updateSettings] Unable to resolve API profile '${pinnedName}'; this view's pin and settings overlay stay on the previous profile and the save failed: ${error instanceof Error ? error.message : String(error)}`, ) - await provider.saveViewState("apiConfiguration", undefined) + throw error } } else { // The pin is being cleared, so nothing should keep serving settings under no name. From e427154547cc520a18a5eafd6b1194c8e95cf4e0 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:08:29 +0800 Subject: [PATCH 15/34] queue the rename's shared-selection repair behind activation [cr 4746979132] Production, src/core/webview/ClineProvider.ts L495-515: a new public method enqueueSharedProfileSelectionRepair(name) queues the write of the shared profile selection onto the provider profile mutation queue with runToCompletion. A runToCompletion timeout rejects only the caller: the mutation is not aborted, its rollback - which restores the selection that mutation overwrote - is still ahead in the queue, and the queue advances from the mutation itself once it settles. Queuing the repair is therefore what makes the repaired name the last write, whether the rollback arrives late or the mutation settled first. The method is a new concept - one queued repair of the shared setting - and is deliberately not another shape of the view-local saveViewState mutation added in the previous commit: the shared setting and the view-local pin travel on different paths. Production, src/core/webview/webviewMessageHandler.ts L2779-2786 (parent L2778-2780): the rename's post-commit repair wrote updateGlobalState("currentApiConfigName", committedNewName), i.e. provider.contextProxy.setValue directly, outside that queue. The rename then awaits provider.activateProviderProfile, which enqueues with runToCompletion; when its 30 s timeout rejected this caller the rename committed and deleted the old name already, and the activation's late rollback put the shared selection back onto that deleted name. The repair now asks the provider to queue it, so the restored name is overwritten instead of doing the overwriting. Clearing a pin and the failure responses are untouched. Spec, src/core/webview/__tests__/webviewMessageHandler.spec.ts: - L142-148 (harness addition, not an assertion): the shared provider double gains enqueueSharedProfileSelectionRepair, delegating to the same contextProxy.setValue write its setValue double above already uses, so the rename rows that read the surviving selection off that write keep their existing observation channel instead of a storage of their own. - L3279 and L3293 (harness additions): the rename suite's structural widening and its member-restore list carry the new member, so the row below cannot leak its double into later suites. - L3510-3556 new row "repairs the shared selection through the profile mutation queue when activation fails after the rename commits": order equality ["activation:new-profile", "repair:new-profile"], the repair requested exactly once, and no direct contextProxy write of the shared selection. This row replaces nothing; the committed row above it (parent L3443, now L3452) keeps its title, its doubles and both of its assertions unchanged. Spec, src/core/webview/__tests__/ClineProvider.spec.ts: - L6379-6441 new row "lands the queued shared-selection repair after a timed-out mutation's late rollback": a gated mutation on the private queue (bracket access, like the committed mode-switch row at L6334 that this row follows), timed out for its caller, then the repair. The row asserts the repair wrote nothing while the mutation was still running, then asserts both selection writes in order - the restore of the deleted name, then the repair - and that the selection ends on the surviving name. The caller-side rejection is the timeout text, which is what runToCompletion gives a caller; the run's own failure is observable only through the restore write, which the order assertion reads. - L6443-6471 new row "lands the queued shared-selection repair behind a mutation that settled first": the reviewer's other order - the mutation and its restore settle before the repair is asked for, and the repair is still the last write. Evidence (logs in the lane gate directory; --disableConsoleIntercept on the column harness so the local worker-teardown race cannot colour a verdict): - new bytes: webviewMessageHandler.spec.ts 190 passed; ClineProvider.spec.ts 523 passed, no unhandled rejection. - parent production + new spec: handler spec 1 failed (first red L3546, the new row's order equality); provider spec 2 failed (L6425, L6469 - the two new rows call a method the parent production does not have). - new production + parent spec: handler spec 1 failed, first red L3481 in the committed row "leaves the shared selection on a name that still exists when activation fails after the rename commits": at parent spec bytes the double has no queue hop, so the repair has nowhere to land. That is why the delegation above is required, and it is the same row the mutant below reddens independently. - comment-only control (parent production plus this commit's comments, new spec): 1 failed at the same L3546. - mutants, each named with its red location: M1 repair removed entirely (the queue hop skipped): 2 failed - L3507 in the committed row ("expected ['new-profile'] to include 'old-profile'") and L3546 in the new row. The committed row is load-bearing on the repair, not on the double's own plumbing. M2 repair restored to the parent direct write: 1 failed - L3546 only. The committed row stays green because it reads the surviving value, which the direct write also produces; the queue hop is what the new row sees. M3 the repair's own enqueue loses runToCompletion: 523 passed - a survivor, reported rather than hidden. The rows above never let the repair itself time out, which is the only state where that flag changes an outcome; the flag's queue effect on an in-flight mutation is pinned by the committed row at L6334 ("keeps the mutation queue owned by a mode switch past its timeout"), which M3 does not touch. M4 the method writes the selection without the queue: 1 failed - L6429 ("expected ['new-profile'] to deeply equal []"), the assertion that the repair waits behind the running mutation. - Gates on the delivered bytes: format:check, root check-types, src tsc, root lint, src lint, test:code-qa-ci, test:translations-check, knip, knip:production, test:knip-policy, lifecycle:model-check, mcp:integration-check, test:misc and test:core results are reported per run in the lane log set; per-file eslint --prune-suppressions --max-warnings=0 on all four files exits 0, and src/eslint-suppressions.json is unchanged at blob 1fad7b0e65fef2ae0d20cf0f83331da2b6d90012 (2841 counts, 261 files) - eslint rewrites its line endings on every run, so it was checked out and re-hashed after each run. test:services stays red here for the same environmental fs.symlink EPERM it is red for at HEAD, and it is not in the gate list. --- src/core/webview/ClineProvider.ts | 22 +++++ .../webview/__tests__/ClineProvider.spec.ts | 96 +++++++++++++++++++ .../__tests__/webviewMessageHandler.spec.ts | 50 ++++++++++ src/core/webview/webviewMessageHandler.ts | 9 +- 4 files changed, 176 insertions(+), 1 deletion(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index fc585f55337..9b183acd45c 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -492,6 +492,28 @@ export class ClineProvider }) } + /** + * Queue the repair of the shared profile selection behind the profile mutation + * that is still running. A `runToCompletion` timeout only rejects the caller: the + * mutation is not aborted, and its rollback - which restores the selection this + * mutation overwrote - is still ahead of the queue. A direct write lands first, so + * that late rollback restores the pre-mutation name and the repair is lost: review + * cid 4746979132, where a committed rename had deleted the old name and the shared + * selection was put back onto it. The queue advances from the mutation itself once + * it settles (see the tail assignment in enqueueProviderProfileMutation), so this + * write lands after that rollback whether the caller timed out or activation + * settled first. The write is the shared setting only - the view-local pin and + * overlay travel on their own mutation paths. + */ + public async enqueueSharedProfileSelectionRepair(name: string): Promise { + return this.enqueueProviderProfileMutation( + async () => { + await this.contextProxy.setValue("currentApiConfigName", name) + }, + { runToCompletion: true }, + ) + } + private readonly pendingEditOperations: PendingEditOperationStore private cloudOrganizationsCache: CloudOrganizationMembership[] | null = null diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 801662e7041..2783ed4db24 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6376,6 +6376,102 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("lands the queued shared-selection repair after a timed-out mutation's late rollback", async () => { + // Review cid 4746979132, the order the finding names: the rename transaction + // committed and deleted the old name, the activation that followed it timed out + // for its caller while runToCompletion kept the queue busy with it, and the caller + // repaired the shared selection. The activation's own rollback - the write that + // restores the selection it overwrote, which is the deleted old name - is still + // ahead in that queue, so a repair written directly lands first and is then + // undone. Bracket access drives the private queue: the gated body stands where + // the profile-list read stood, and its restore line where the rollback restores + // the selection. + vi.useFakeTimers() + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + const writes: string[] = [] + const originalSetValue = provider.contextProxy.setValue.bind(provider.contextProxy) + vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key, value) => { + if (key === "currentApiConfigName") { + writes.push(String(value)) + } + return originalSetValue(key, value) + }) + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + // What the caller sees is the timeout, not the run's failure: runToCompletion + // rejects the caller and leaves the run to settle on its own - the run's observable + // is the restore write the assertions below read out. + const activationTimedOut = expect( + provider["enqueueProviderProfileMutation"]( + async () => { + await gate + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + throw new Error("profile list read failed") + }, + { runToCompletion: true }, + ), + ).rejects.toThrow("Provider profile mutation timed out") + await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) + + const repair = provider.enqueueSharedProfileSelectionRepair("new-profile") + await vi.advanceTimersByTimeAsync(0) + // The repair waits behind the mutation that is still running: nothing it wrote has + // landed, so it cannot get ahead of the restore it has to follow. + expect(writes).toEqual([]) + + release() + await activationTimedOut + await repair + // Both writes in the order the world sees them: the late restore of the deleted + // name, then the repair. The repaired name is last, so the shared selection + // names the profile that survived the rename. + expect(writes).toEqual(["old-profile", "new-profile"]) + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("new-profile") + vi.useRealTimers() + await provider.dispose() + }) + + it("lands the queued shared-selection repair behind a mutation that settled first", async () => { + // The other order the reviewer asks the fix to hold: the mutation settled, and its + // restore landed, before the caller asked for the repair. The repair is then + // simply the later write, and the surviving name still ends up last. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + const writes: string[] = [] + const originalSetValue = provider.contextProxy.setValue.bind(provider.contextProxy) + vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key, value) => { + if (key === "currentApiConfigName") { + writes.push(String(value)) + } + return originalSetValue(key, value) + }) + await provider["enqueueProviderProfileMutation"]( + async () => { + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + }, + { runToCompletion: true }, + ) + await provider.enqueueSharedProfileSelectionRepair("new-profile") + expect(writes).toEqual(["old-profile", "new-profile"]) + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("new-profile") + await provider.dispose() + }) + it("does not resurrect a pruned sibling entry that the sibling cleared mid-window", async () => { const provider = new ClineProvider( mockContext, diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 59b20808beb..53b8a05d604 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -139,6 +139,13 @@ const mockClineProvider = { value as RooCodeSettings[keyof RooCodeSettings], ), ), + // The rename's queued selection repair delegates to the same contextProxy write the + // setValue double above uses, because the rename rows read the surviving selection + // off that write: the queue hop has to land on the channel those rows already + // observe rather than on a storage of its own. + enqueueSharedProfileSelectionRepair: vi.fn(async (name: string) => { + await mockClineProvider.contextProxy.setValue("currentApiConfigName", name) + }), log: vi.fn(), postStateToWebview: vi.fn(), resolveWebviewThemeFixtureProbe: vi.fn(), @@ -3269,6 +3276,7 @@ describe("webviewMessageHandler - renameApiConfiguration", () => { } repointViewLocalStateAfterProfileRename: ReturnType activateProviderProfile: ReturnType + enqueueSharedProfileSelectionRepair: ReturnType } // The rename runs its name check, save, and compensation inside the manager's // cross-instance critical section; this double runs the callback inline. @@ -3282,6 +3290,7 @@ describe("webviewMessageHandler - renameApiConfiguration", () => { providerSettingsManager: provider.providerSettingsManager, repointViewLocalStateAfterProfileRename: provider.repointViewLocalStateAfterProfileRename, activateProviderProfile: provider.activateProviderProfile, + enqueueSharedProfileSelectionRepair: provider.enqueueSharedProfileSelectionRepair, } afterEach(() => { @@ -3498,6 +3507,47 @@ describe("webviewMessageHandler - renameApiConfiguration", () => { expect(stored).toContain(finalSelection) }) + it("repairs the shared selection through the profile mutation queue when activation fails after the rename commits", async () => { + // Review cid 4746979132: the row above pins the state the run leaves behind. This row + // pins the mechanism that produces it. The activation runs with runToCompletion, so + // its caller sees a timeout while that mutation - and the rollback restoring the + // selection it overwrote - is still running. A direct write here lands first and the + // late rollback puts the deleted name back, so the repair has to be queued behind the + // mutation: the queue advances from the mutation once it settles, which makes the + // repaired name the last write. The double above delegates to contextProxy.setValue; + // this row replaces it with a recorder so the row sees the request to queue, not the + // delegated write. + const order: string[] = [] + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi.fn().mockResolvedValue({ id: "profile-id", apiProvider: providerIdentifiers.anthropic }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn().mockResolvedValue(undefined), + } + provider.repointViewLocalStateAfterProfileRename = vi.fn().mockResolvedValue(undefined) + provider.activateProviderProfile = vi.fn(async ({ name }: { name?: string }) => { + order.push(`activation:${String(name)}`) + throw new Error("activation timed out") + }) + const repair = vi.fn(async (name: string) => { + order.push(`repair:${name}`) + }) + provider.enqueueSharedProfileSelectionRepair = repair + + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + + // The repair is requested by name, once, and only after the activation rejected: the + // handler never writes the shared selection itself. + expect(order).toEqual(["activation:new-profile", "repair:new-profile"]) + expect(repair).toHaveBeenCalledTimes(1) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("currentApiConfigName", "new-profile") + }) + it("re-points views with the stored record instead of the raw webview payload", async () => { provider.providerSettingsManager = { runExclusiveAcrossInstances, diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index f155ab38dc2..76fb160e067 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -2776,7 +2776,14 @@ export const webviewMessageHandler = async ( // re-pointed - so this branch takes the second shape: the rename stands and the // shared selection is moved onto the stored name instead of left on the deleted one. if (renameCommitted && committedNewName) { - await updateGlobalState("currentApiConfigName", committedNewName) + // Review cid 4746979132: the activation above runs with runToCompletion, so a + // timeout rejects this caller while that mutation - and its rollback, which + // restores the selection it overwrote - is still running. The old name is gone + // by then, so restoring it would leave the shared selection naming a deleted + // profile. The repair is queued behind that mutation instead: the queue + // advances from the mutation once it settles, so the repaired name is the + // last write whether the rollback arrives late or activation settled first. + await provider.enqueueSharedProfileSelectionRepair(committedNewName) } provider.log( `Error rename api configuration: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, From d2d079560dc4d0c855cf87d64c3887c4f15dc3cc Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:26:34 +0800 Subject: [PATCH 16/34] pin the queued repair against overtaking its mutation [cr 4746979132] Test bytes only - no production line changed in this commit. It closes the gap lead ruled on after the previous commit: the runToCompletion flag on the repair's own enqueue had no test, because no row ever let the repair time out. That is the only state where the flag changes an outcome. src/core/webview/__tests__/ClineProvider.spec.ts L6475-6557 (row body incl. its two assertions on the following mutation at L6540 and L6548), new row "keeps a timed-out queued shared-selection repair from writing at all": - A gated mutation owns the queue and times out for its caller (bracket access on the private enqueueProviderProfileMutation, the pattern of the committed mode-switch row at L6334). A contextProxy.setValue spy records every shared selection write in order; the spy is harness, not an assertion. - The repair is enqueued next and times out while still queued behind that mutation, then asserts writes == [] : a repair whose caller already saw a timeout has written nothing. - A third mutation is enqueued behind the repair and only records that it started. Its assertion (followingStarted is false) is what makes the flag observable: the repair method never reads its AbortSignal, so the flag shows up only in what the queue waits for next. With runToCompletion the queue advances from the running mutation, so nothing behind the repair may overtake it; without the flag the queue advances on the repair's caller-bounded result the moment the repair times out, and the following mutation starts mid-mutation. - The gate opens, the queue is drained by awaiting the following mutation (which runs only after everything before it settles), and the row asserts the repair still never wrote: the only standing selection write is the mutation's restore of the deleted name, so the shared selection stays on a name that exists rather than on one a timed-out write invented. Evidence (logs in the lane gate directory; --disableConsoleIntercept on the column harness only): - new spec + current production: 524 passed, no unhandled rejection, tsc 0. - new spec + production at 79970ffb93b7d12d54fda41dd4a6a4e406f13017 (the commit before the queue hop): 3 failed - first red L6425 and L6469 (the two rows of that commit, unchanged here) and first red L6520 for this row, a TypeError on the method the parent production does not have. - comment-only controls: current production + parent spec + this row's comment block alone: 523 passed, so the comments change no verdict; production at 79970ffb + this spec + two further comment lines: 3 failed at L6425, L6469 and L6522 - the same three reds, shifted only by the two comment lines. - M3, the mutant that survived the previous commit (the repair enqueue loses runToCompletion): now 1 failed, first red L6540, the followingStarted assertion ("expected true to be false"). The other 523 rows stay green, which is the point: this row is the one that pins the flag. - M4 re-checked unchanged (the method writes the selection without the queue): 2 failed, first red L6429 and L6526, both on the assertion that a queued repair has written nothing while the mutation runs. That column also reported 4 unhandled errors, which is an artifact of the mutant bypassing the queue, not of the row. - No committed assertion was rewritten, retitled or removed by this commit; the two rows added by the previous commit are byte-identical here. - Per-file eslint --prune-suppressions --max-warnings=0 on core/webview/__tests__/ClineProvider.spec.ts exits 0, and src/eslint-suppressions.json stays at blob 1fad7b0e65fef2ae0d20cf0f83331da2b6d90012 (2841 counts, 261 files). --- .../webview/__tests__/ClineProvider.spec.ts | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 2783ed4db24..5826e55bb83 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6472,6 +6472,90 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("keeps a timed-out queued shared-selection repair from writing at all", async () => { + // Review cid 4746979132, and the one state where the runToCompletion flag on the + // repair enqueue changes an outcome: the repair times out while it is still queued + // behind the mutation it waits for. With the flag the queue advances from the + // mutation itself, so the timed-out repair never starts - a start refuses a caller + // that already saw a timeout - and the only selection write left standing is the + // running mutation's restore of the deleted name. Without the flag the queue + // advances on the caller-bounded result the moment the repair times out, so both + // the repair and whatever follows it overtake the mutation that is still running. + // The third mutation below is what makes that difference visible: the repair method + // does not read its AbortSignal, so the flag is only observable through who the + // queue waits for next. + vi.useFakeTimers() + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + const writes: string[] = [] + const originalSetValue = provider.contextProxy.setValue.bind(provider.contextProxy) + vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key, value) => { + if (key === "currentApiConfigName") { + writes.push(String(value)) + } + return originalSetValue(key, value) + }) + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + const mutationTimedOut = expect( + provider["enqueueProviderProfileMutation"]( + async () => { + await gate + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + throw new Error("profile list read failed") + }, + { runToCompletion: true }, + ), + ).rejects.toThrow("Provider profile mutation timed out") + await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) + + const repairTimedOut = expect(provider.enqueueSharedProfileSelectionRepair("new-profile")).rejects.toThrow( + "Provider profile mutation timed out", + ) + await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) + // The repair has timed out for its caller while the mutation it waits behind is + // still running, and it has written nothing. + expect(writes).toEqual([]) + + // Bracket access drives the private queue, as in the committed mode-switch row this + // one follows. This mutation only records that it started: whether it may start at + // all is the question, because the repair sits between it and the running mutation. + let followingStarted = false + const following = provider["enqueueProviderProfileMutation"]( + async () => { + followingStarted = true + }, + { runToCompletion: true }, + ) + await vi.advanceTimersByTimeAsync(0) + // Nothing behind the repair may overtake the mutation that is still running. + expect(followingStarted).toBe(false) + + release() + await mutationTimedOut + await repairTimedOut + // Awaiting the following mutation drains everything queued before it: the run, the + // repair's refused start, and only then this mutation's own callback. + await following + expect(followingStarted).toBe(true) + // The mutation's restore of the deleted name is the only selection write that ever + // lands: a repair that already reported failure to its caller does not write state + // behind that caller's back, so the shared selection stays on a name that exists + // rather than on one a timed-out write invented. + expect(writes).toEqual(["old-profile"]) + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile") + vi.useRealTimers() + await provider.dispose() + }) + it("does not resurrect a pruned sibling entry that the sibling cleared mid-window", async () => { const provider = new ClineProvider( mockContext, From 926920fc1bc3861f464081102f4ecf80644c8d58 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:46:36 +0800 Subject: [PATCH 17/34] compensate the activation mode mapping with its writes [cr 4746968719] Production, src/core/webview/ClineProvider.ts: - L4077-4085: the mode is read before the compensated group instead of after it (the function's single this.getState() call moved, it is not a second read). The explicit mode mapping needs the mode, and as long as the read sat after the group the mapping could only land after the compensation had already run. - L4086-4094: writesModeConfig = id && persistModeConfig, and the prior mapping id is snapshotted from the settings manager before the group, best-effort: an unreadable prior mapping snapshots as absent and restores as absent. Same shape as upsertProviderProfile's mode-mapping handling (L3497-3534, L3619-3643). - L4108-4113: the mapping write joins the Promise.allSettled group, routed through this.setModeConfig so this provider's cached mapping commits with the activation. A rejected mapping write is now a rejected activation, so it is compensated rather than being the one failure the compensation had already walked past. Callers that do not ask for the mapping (writesModeConfig false) contribute no element to the group, as before. - L4139-4149: the compensation restores the mapping between the manager selection and the shared/per-view state - the manager store is what the profile list and shared settings derive from - through the manager rather than this.setModeConfig, so the cache is not written by a rollback. A failed restore is logged and does not replace the original error, matching the upsertProviderProfile restore. - L4156-4160: the standalone write stays for activations that skip the current-task rebuild: those have no group and nothing to compensate. Spec, src/core/webview/__tests__/ClineProvider.spec.ts: - L6559-6608 new row "compensates the mode mapping when the mapping write is the one that fails": activation rejects, the settings manager's mapping calls are exactly [["code","new-id"], ["code","old-mode-id"]] - the attempt then the restore of the PRIOR id by value - and the shared selection is back on the old profile. - L6610-6651 new row "restores an absent prior mode mapping when the mapping write fails": the prior id is undefined, and the restore leaves the mode unmapped (["code", undefined]) rather than inventing an id. - L6653-6685 new row "writes the mode mapping on its own when the activation skips the current task rebuild": one mapping call, the new id, no restore - the shape of the path that keeps its own write. - No committed assertion was rewritten, retitled or removed; the existing suites that touch activation run green against the new bytes (see below), so nothing had to be rewritten to land this fix. Caller list for persistModeConfig, as the reviewer's "keep implicit callers on persistModeConfig: false" can only be checked against it (current delivered bytes): - explicit false (three): ClineProvider.ts L2278 (reopening a task from history), L2312 (the sibling history path in the same block), L2961 (handleModeSwitch, with skipCurrentTaskRebuild derived from whether a target task exists). - implicit, no options argument at all (six): ClineProvider.ts L6836 (setProviderProfile), webviewMessageHandler.ts L735 (launch validation of a stale pin), L2770 (rename activation), L2799 (activateProviderProfile message by name), L2811 (the same message by id), L2845 (the other rename-ish path). - No caller passes persistModeConfig: true explicitly. This commit changes no caller: the default stays options?.persistModeConfig ?? true (L4073 untouched), so every caller's mapping behavior is exactly what it was; only WHEN the mapping is written and whether it is compensated changed. Flipping the default to false for the six implicit callers would silently stop persisting the mode mapping on those six paths, which is a behavior change beyond this finding; flagged rather than done. Evidence (logs cellO-*.log; --disableConsoleIntercept on the column harness only): - new bytes: ClineProvider.spec 527 passed, no unhandled rejection, tsc 0. - old bytes (ClineProvider.ts at d2d079560dc4d0c855cf87d64c3887c4f15dc3cc) + new rows: 2 failed - first red L6601 and L6645, both "expected [['code','new-id']] to deeply equal [['code','new-id'], ...]": at the parent bytes the mapping is attempted and never restored. That is the finding, reproduced. - new bytes + old assertions: ClineProvider.spec 524 passed, webviewMessageHandler.spec 190 passed, ClineProvider.apiHandlerRebuild.spec 40 passed, sticky-profile.spec 24 passed. No committed assertion turns red - reported plainly: nothing in the suite pinned the compensation gap before, so the red direction comes from the parent bytes and from the mutants. The fifth intended column (ClineProvider.delegation.spec at parent bytes + new production) failed in the column harness before vitest started (no log written); that suite is unchanged by this commit and runs green against the new bytes inside the battery's test:core run, reported in its place. - comment-only controls: new production with this commit's getState rationale comment block deleted: 527 passed (the comments carry no verdict); parent production + the new rows + two further comment lines: 2 failed at L6603 and L6647 - the same two reds, moved only by the two comment lines. - mutants, each named with its red location: M1 mapping taken back out of the group and written standalone (the parent shape with the new snapshot left in place): 2 failed - first red L6601 and L6645: the mapping is attempted once and never restored, so both compensation rows go red. M2 the compensation restores the wrong value (the new id instead of the snapshot): 2 failed - first red L6601 and L6645. The rows assert the restored value, not merely that a write happened. M3 an implicit caller made explicit - webviewMessageHandler.ts L735 passing { persistModeConfig: false }: 1 failed in webviewMessageHandler.spec.ts, first red L977 in the committed row "validates the view-local currentApiConfigName on launch", which pins that activation call. The caller list is therefore not untested. Gates on the delivered bytes are reported per run in the lane log set, and per-file eslint --prune-suppressions --max-warnings=0 on both touched files exits 0, with src/eslint-suppressions.json unchanged at blob 1fad7b0e65fef2ae0d20cf0f83331da2b6d90012 (2841 counts, 261 files); eslint rewrites its line endings on every run, so it was checked out and re-hashed after each run. --- src/core/webview/ClineProvider.ts | 53 +++++++- .../webview/__tests__/ClineProvider.spec.ts | 128 ++++++++++++++++++ 2 files changed, 178 insertions(+), 3 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 9b183acd45c..396f02628fe 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -4074,6 +4074,26 @@ export class ClineProvider const persistTaskHistory = options?.persistTaskHistory ?? true const skipCurrentTaskRebuild = options?.skipCurrentTaskRebuild ?? false + // The mode has to be known before the group below, because the explicit mode mapping + // is one of the writes this activation performs. Read afterwards, the mapping landed + // after the compensation had already run: a rejected mapping write then reported + // failure while the manager selection, the shared settings and this view's pin had + // already changed, and nothing put them back. Review cid 4746968719 restores the + // mapping inside the same compensation as those writes, so the read moves ahead of + // the group. The single getState call is the group's own - the paths below read the + // mode from here rather than asking again. + const { mode } = await this.getState() + const writesModeConfig = id && persistModeConfig + let priorModeConfigId: string | undefined + if (writesModeConfig) { + try { + priorModeConfigId = await this.providerSettingsManager.getModeConfigId(mode) + } catch { + // Best-effort snapshot, as in upsertProviderProfile: when the prior mapping + // cannot be read the compensation restores the mapping as absent. + } + } + if (!skipCurrentTaskRebuild) { // See `upsertProviderProfile` for a description of what this is doing. const activationSnapshot = this._snapshotProfileActivationState() @@ -4085,6 +4105,12 @@ export class ClineProvider // activated profile: a plain ContextProxy write would leave a stale loaded // currentApiConfigName shadowing the new value in getValues(). this.setValue("currentApiConfigName", name), + // The explicit mode mapping joins the group: a rejected mapping write is now a + // rejected activation, so the compensation above runs over it together with the + // selection, the settings and the pin rather than being skipped because the + // mapping was still to come. Route through this.setModeConfig so this provider's + // cached mapping commits with the activation, as in upsertProviderProfile. + ...(writesModeConfig ? [this.setModeConfig(mode, id)] : []), this.contextProxy.setProviderSettings(providerSettings), // setProviderSettings writes the shared store directly, bypassing the // view-local mutation path: clear this view's buffered apiConfiguration @@ -4101,14 +4127,35 @@ export class ClineProvider // Compensate every write that may have landed before the failure, // including the manager selection written by activateProfile. await this._restoreProviderManagerSelection(managerSelectionSnapshot) + // The mode mapping is compensated here, between the manager selection and the + // shared and per-view state: the manager store is what the profile list and the + // shared settings are derived from, and the mapping belongs with them rather than + // after them. Restoring it through the manager rather than this.setModeConfig + // keeps the cache out of the rollback - the cache is rebuilt by the state restore + // below - and an absent prior mapping restores as absent. A failed restore is + // logged, not thrown, so it can neither strand the rest of the compensation nor + // replace the original failure. Same shape as upsertProviderProfile's mode-mapping + // restore. + if (writesModeConfig) { + try { + await this.providerSettingsManager.setModeConfig(mode, priorModeConfigId as string) + } catch (restoreError) { + this.log( + `[ClineProvider] profile-activation rollback failed for the mode mapping: ${ + restoreError instanceof Error ? restoreError.message : String(restoreError) + }`, + ) + } + } await this._restoreProfileActivationState(activationSnapshot) throw error } } - const { mode } = await this.getState() - - if (id && persistModeConfig) { + // The group above owns the mapping write for every activation that rebuilds the + // current task. Without that group - a restoration-style activation that skips the + // rebuild - there is nothing to compensate, so the mapping is written on its own. + if (writesModeConfig && skipCurrentTaskRebuild) { await this.setModeConfig(mode, id) } diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 5826e55bb83..afefa9f6eb4 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6556,6 +6556,134 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("compensates the mode mapping when the mapping write is the one that fails", async () => { + // Review cid 4746968719. The explicit mapping used to be written after the group, + // so a rejected mapping reported a failed activation while the manager selection, + // the shared settings and this view's pin had already moved - and the compensation + // had already run past them, so nothing put them back. The mapping is one of the + // group's writes now, so this failure compensates the mapping along with the rest. + // The prior mapping is a real id: the row checks the restored VALUE, not merely that + // something was written back. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "new-profile", + id: "new-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "new-profile", + id: "new-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("old-profile") + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("old-mode-id") + const mappingWrites = vi + .spyOn(provider.providerSettingsManager, "setModeConfig") + .mockRejectedValue(new Error("mode mapping write failed")) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await expect(provider.activateProviderProfile({ name: "new-profile" })).rejects.toThrow( + "mode mapping write failed", + ) + + // The attempt, then the restore of the id the activation overwrote: two calls, and + // the second one names the prior mapping rather than the new one. + expect(mappingWrites.mock.calls).toEqual([ + ["code", "new-id"], + ["code", "old-mode-id"], + ]) + // The writes that used to survive this failure are compensated with it. + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile") + await provider.dispose() + }) + + it("restores an absent prior mode mapping when the mapping write fails", async () => { + // The other shape of the same compensation: a mode with no mapping yet. Restoring + // "the prior value" here means leaving the mode unmapped, not inventing an id. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "new-profile", + id: "new-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "new-profile", + id: "new-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) + vi.spyOn(provider.providerSettingsManager, "getCurrentProfileName").mockResolvedValue("old-profile") + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + const mappingWrites = vi + .spyOn(provider.providerSettingsManager, "setModeConfig") + .mockRejectedValue(new Error("mode mapping write failed")) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await expect(provider.activateProviderProfile({ name: "new-profile" })).rejects.toThrow( + "mode mapping write failed", + ) + + expect(mappingWrites.mock.calls).toEqual([ + ["code", "new-id"], + ["code", undefined], + ]) + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile") + await provider.dispose() + }) + + it("writes the mode mapping on its own when the activation skips the current task rebuild", async () => { + // The one path that still writes the mapping outside the group: an activation that + // skips the rebuild has no group and nothing to compensate, so the mapping is a + // single write and no restore follows it. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + name: "new-profile", + id: "new-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "new-profile", + id: "new-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("old-mode-id") + const mappingWrites = vi + .spyOn(provider.providerSettingsManager, "setModeConfig") + .mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await provider.activateProviderProfile({ name: "new-profile" }, { skipCurrentTaskRebuild: true }) + + expect(mappingWrites.mock.calls).toEqual([["code", "new-id"]]) + await provider.dispose() + }) + it("does not resurrect a pruned sibling entry that the sibling cleared mid-window", async () => { const provider = new ClineProvider( mockContext, From db9b7fa08333e1cab3d5e8ee9f1e5882bd670970 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:59:38 +0800 Subject: [PATCH 18/34] bound the profile repair by its execution, not by its queue wait [cr 4750230092] Reviewer (cid 4750230092, anchored at ClineProvider.ts line 509): "Keep the repair executable after its own queue timeout." / "At 60 seconds, the repair also times out while waiting. enqueueProviderProfileMutation sets callerTimedOut, so start later rejects without executing the repair." / "The handler also skips its error notification." / "Use a repair continuation that remains executable after caller timeout. Keep the timeout guard for ordinary user mutations. Add a test that holds activation beyond both timeout periods." What this does, and what it costs, in the open: - The repair's wait phase is now unbounded. A repair queued behind a mutation that is still running no longer rejects for its caller at 30 s, so the 61 s activation the reviewer describes no longer refuses the repair outright. At the parent bytes the repair was rejected at the first bound: it never ran, and the name the mutation's rollback had just restored - a name the committed rename had deleted - stood. - The repair's execution phase stays bounded. The bound is re-anchored onto the callback, and a run that overruns 30 s still aborts the mutation and still rejects its caller, so the guard the reviewer asks to keep is kept for the work itself and awaiting one of these enqueues is not open-ended once its own work has begun. - Ordinary user mutations are unchanged in effect: they pass armAfter = undefined (ClineProvider.ts L483), so their timer still arms synchronously at the enqueue and their caller still times out 30 s later. The committed rows in ClineProvider.apiHandlerRebuild.spec.ts L995-1035 pin both timeout log strings and the abort flag; mutant M7 below turns exactly those rows red. - No parameter was added to hand the outcome into the repair: the outcome - which name the mutation left standing - is not available at the execution point, and the repair is idempotent (writing the same name twice is the same value), so the extra argument would carry nothing the execution point can act on. Production, src/core/webview/ClineProvider.ts: - L425-433: doc paragraph for boundExecutionOnly, including the cost above. - L437: the options argument gains boundExecutionOnly?: boolean; runToCompletion untouched. - L440-445: the callerTimedOut comment records why the guard keeps its meaning: under boundExecutionOnly no caller timeout can precede the callback. - L447-453: beginExecution / executionBegun, resolved by start() when this mutation's own callback begins. - L459-460: start() resolves it immediately before returning fn(controller.signal), so the bound is armed on the tick the callback starts. - L466-473: new onTimeout branch for boundExecutionOnly - controller.abort() plus the "aborting in-flight mutation" log, then return - placed before the unchanged runToCompletion branch (L474-478) and the unchanged default abort path (L480-481). - L483: options.boundExecutionOnly ? executionBegun : undefined - the third argument to withProviderProfileMutationTimeout; every ordinary mutation passes undefined and arms exactly as before. - L503-508: the queue tail is byte-identical (options.runToCompletion ? run : callerResult), so advancement for existing callers does not change. - L512-544: withProviderProfileMutationTimeout gains armAfter?: Promise (L515). settled (L518) gates arm() (L520-525): an operation that settled before the bound was armed needs no bound, because arming on it afterwards would fire a timeout for work that already finished. L531-535 arms after armAfter when given and synchronously when not; the race's finally (L538-543) sets settled and clears the timer. Without armAfter the code path is the old one, one assignment apart. - L558-563: enqueueSharedProfileSelectionRepair's doc says why the bound moves for this repair and only for this repair. - L570: the repair enqueues with { runToCompletion: true, boundExecutionOnly: true }. Production, src/core/webview/webviewMessageHandler.ts - the notification half of the same finding ("The handler also skips its error notification"), landed here rather than in a separate commit because it is one finding: - L2784: the repair's failure is recorded (selectionRepairFailure) instead of being allowed to skip the notification block that follows. - L2799-2810: try/catch around the awaited repair; the failure is logged with the same JSON.stringify(error, Object.getOwnPropertyNames(error), 2) shape this case already uses for the rename error. - L2812-2816 unchanged: the rename error log and showErrorMessage still run - that is the notification the parent bytes skipped. - L2817-2822: the recorded failure is rethrown only after both channels ran, so the message dispatch keeps seeing repairs that never landed (the wrapper records diagnostics and rethrows at ClineProvider.ts L2834). A silent catch would have bought the user's notification with the caller's silence. - L2778-2783 and L2793-2798: comments stating both halves and the line the rethrow goes through. Cross-references were re-measured against the delivered bytes: the dispatch wrapper is ClineProvider.ts L2807-2835, call L2819, rethrow L2834. Spec, src/core/webview/__tests__/ClineProvider.spec.ts - one committed row restated, four rows delivered: - Removed: HEAD L6475-6557 "keeps a timed-out queued shared-selection repair from writing at all" (d2d079560dc4, cid 4746979132). Its assertions as they stood: L6508-6517 the mutation's caller sees "Provider profile mutation timed out"; L6520-6522 the repair's own caller sees the same rejection at 30 s; L6526 writes == []; L6540 the mutation queued behind the repair had not started; L6548 it had after the drain; L6553-6554 the rollback's restore of the deleted name is the only standing write and the selection stays on it. - L6520-6522 is the sentence this design cannot keep: the repair no longer rejects while it waits, so "a repair that already reported failure to its caller" is not a state that exists at 61 s. The row is restated rather than kept weakened, and the rest of its scenario is preserved in rows 1 and 4 below. - Row 1 L6475-6554 "lands a queued shared-selection repair whose wait behind the mutation outlasted the bound": the recorded settle state is "running" after the second 30 s (L6532) with nothing written (L6533), the next mutation has not started (L6542), and once the gate opens the write order is ["old-profile","new-profile"] (L6548) ending on "new-profile" (L6551). That is the reviewer's 61 s case: the repair runs, after the rollback, and it is the last write. - Row 2 L6556-6614 "aborts the shared-selection repair whose own execution runs past the bound": rejected (L6602), the abort log line (L6603), no settled write (L6604) while the selection still names the old profile (L6605), then the aborted write settles as "new-profile" (L6610-6611). - Row 3 L6616-6660 "aborts a mutation bounded from its own execution when the run overruns the bound": started (L6652), rejected (L6654), its own signal aborted (L6655) - the bound bites the run, not only the wait. - Row 4 L6662-6720 "keeps the queue owned by a repair whose execution timed out until its write settles": rejected (L6701) and still the queue does not advance past it (L6712), the following mutation runs only after the write settles (L6715) behind ["new-profile"] (L6716). M3's kill moved here: at HEAD the runToCompletion flag was pinned by L6540 of the removed row; the same observable is L6712 now, and the flag-dropped mutant goes red exactly there. - Rows 1-4 are the "test that holds activation beyond both timeout periods": 30 s of mutation, then 30 s more (a second bound length) on the repair's wait, and rows 2 and 4 push the repair's own execution past the bound. Spec, src/core/webview/__tests__/webviewMessageHandler.spec.ts: - L3551-3587 "notifies the user when the queued shared-selection repair itself rejects": activation and the repair both reject; the rejection still escapes (L3581), the rename error was logged (L3582), showErrorMessage got common:errors.rename_api_config (L3583), and the repair failure was logged under its own prefix (L3584-3586). - L3589-3612 "keeps the repair failure visible to the message dispatch after notifying the user": the handler call rejects with "repair write rejected". The notification is not bought by swallowing the rejection. - No committed assertion was rewritten, retitled or removed except the one row restated above; the rename rows of e427154547 (L3452-3508, L3510-3549) are byte-identical here. - probeB - a probe column that kept the repair rejection silent and asserted only the dispatch escape - was run as evidence and is NOT committed: its assertion is the dispatch behavior this commit keeps, not a new claim. Evidence (column harness, per-column logs written by Node fs; no numbers here passed through a PowerShell pipe): - Delivered bytes: ClineProvider.spec 530 passed (cP20); webviewMessageHandler.spec 192 passed (cP44); ClineProvider.apiHandlerRebuild.spec 40 passed. - Parent bytes + new rows (red first): ClineProvider.spec 3 failed - first red L6532 (expected "running", received "rejected": the repair was refused at 30 s instead of running), then L6603 (the abort log never emitted) and L6655 (signal not aborted); webviewMessageHandler.spec 1 failed - first red L3582 (the rename log had 0 calls because the notification block was skipped). With both production files at HEAD the handler red is the same L3582 (cP49), and with only ClineProvider.ts at HEAD the handler suite stays green (cP50): the handler rows do not lean on the provider side. - Comment-only controls: new bytes with the four new-row comment blocks replaced by one control line each: 530 passed (cP22); same spec against parent production: 3 failed at L6526, L6592, L6642 - the same three reds, shifted only by the removed comment lines (cP23). Handler: new bytes with the two comment blocks stripped: 192 passed (cP46); stripped + parent production: 1 failed at L3578, the L3582 red moved by exactly the four removed comment lines (cP47). The comments carry no verdict. - Mutants, each with its first red location: M1 timer still armed at the enqueue (armAfter dropped at L483): 1 failed, first red L6532 - the queue-wait row, i.e. exactly the old behavior. M2 no bound at all (arm() never armed): 3 failed - L6602, L6654, L6701 (all expected "rejected", received "running") - the unbounded-execution reading is not what was shipped. M3 expiry does not abort (controller.abort() removed from the new branch): 1 failed, first red L6655 (signal.aborted false). M4 the repair loses runToCompletion: 1 failed, first red L6712 - row 4 holds the flag pin that HEAD's removed row L6540 carried. M5 the repair writes the wrong name - the mutant that checks the restated rows, a wrong value rather than a missing write: 5 failed - L6437 and L6470 (the two committed rename rows of e427154547), L6548 (row 1's write order), L6610 (row 2's settled write), L6716 (row 4's). The restated rows assert values, not merely that something happened. M6 queue advances on the caller-bounded result always: 6 failed - L6367, L6429, L6532 (expected "running", received "settled"), L6712, L8146, L10969 - committed rows outside this cell go red too, so the tail rule is not free to change. M7 queue advances from the run always: ClineProvider.spec stays green (530 passed, cP30) but ClineProvider.apiHandlerRebuild.spec 1 failed, first red L1005 - the committed ordinary-mutation row pins the other half of the tail. Ordinary mutation semantics are therefore tested, not asserted by comment. M8 the notification guard removed (plain await, no catch): 1 failed, first red L3582 (cP48) - the finding, reproduced. Gates and hygiene are reported in the lane log set for tag cellP-final; per-file eslint --prune-suppressions --max-warnings=0 exits 0 for all four touched files and src/eslint-suppressions.json is unchanged in substance (2841 counts across 261 files; ClineProvider.ts 7, ClineProvider.spec.ts 193, webviewMessageHandler.ts 5, webviewMessageHandler.spec.ts 35), checked out and re-hashed after the runs to blob 1fad7b0e65fef2ae0d20cf0f83331da2b6d90012: eslint rewrites its own line endings every run, so the file is verified by hash rather than trusted. CI self-check for these six rows (the 1918 Windows lesson): every row drives the real queue or the real handler through in-memory doubles and vi.useFakeTimers - no fs, no symlink, no permission or path-case assumptions, no Date.now / performance.now, no real setTimeout, no vitest test-timeout dependence (each settle state is recorded and asserted by value). The diff adds no it.skip, describe.skip, skipIf or process.platform predicate, so nothing here is a "red only where the machine can do it" test in either direction. The lane's one recurring local red is unrelated: services/rules/__tests__/rules.spec.ts fails 5 rows with EPERM on fs.symlink here (identical in all 18 gate runs in this directory, including runs of the parent commit), which is a capability of this Windows box, not a property of this commit. --- src/core/webview/ClineProvider.ts | 91 +++++-- .../webview/__tests__/ClineProvider.spec.ts | 229 +++++++++++++++--- .../__tests__/webviewMessageHandler.spec.ts | 63 +++++ src/core/webview/webviewMessageHandler.ts | 32 ++- 4 files changed, 364 insertions(+), 51 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 396f02628fe..5b32c89cd75 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -421,34 +421,67 @@ export class ClineProvider * With `runToCompletion`, a timeout only rejects the caller: the mutation is not aborted and the * queue advances once it settles. Use it for multi-write mutations that must not stop halfway * (storage saved but not activated) or overlap with the next mutation. + * + * `boundExecutionOnly` moves where the 30 s is measured from: the bound is armed when this + * mutation's own callback begins, so time spent queued behind an earlier mutation does not + * consume it, and an expiry aborts the mutation the way every other in-flight timeout does. + * Use it for a repair whose job is to follow the mutation ahead of it (review cid 4750230092): + * waiting the bound out while queued used to report failure to the caller without the repair + * ever running, so the name the mutation's rollback had just restored stood. The bound is + * re-anchored, not removed: an execution that runs past it still aborts and still rejects its + * caller, so awaiting one of these enqueues is not open-ended once its own work has begun. + * `runToCompletion` still keeps the queue owned until the mutation settles. */ private enqueueProviderProfileMutation( fn: (signal: AbortSignal) => Promise, - options: { runToCompletion?: boolean } = {}, + options: { runToCompletion?: boolean; boundExecutionOnly?: boolean } = {}, ): Promise { const controller = new AbortController() // Set when the caller's timeout fires while this mutation is still queued behind a // longer-running one: the callback must not start after its caller already saw a - // timeout, or the mutation would change state while reporting failure. + // timeout, or the mutation would change state while reporting failure. Under + // `boundExecutionOnly` no caller timeout can precede the callback - the bound is not + // armed until start() below runs - so this guard keeps its meaning for every mutation + // that bounds its wait. let callerTimedOut = false + // Resolved by start() when this mutation's own callback begins. Handed to + // withProviderProfileMutationTimeout under `boundExecutionOnly` so the bound is armed on + // the callback rather than on the enqueue. + let beginExecution: () => void = () => {} + const executionBegun = new Promise((resolve) => { + beginExecution = resolve + }) // Run fn after either outcome so a rejected mutation never poisons the queue. const start = () => { if (callerTimedOut) { return Promise.reject(new Error("Provider profile mutation timed out while queued")) } + beginExecution() return fn(controller.signal) } const run = this.providerProfileMutationQueue.then(start, start) - const callerResult = this.withProviderProfileMutationTimeout(run, () => { - if (options.runToCompletion) { - callerTimedOut = true - this.log("Provider profile mutation timed out; waiting for it to finish before the next mutation") - return - } + const callerResult = this.withProviderProfileMutationTimeout( + run, + () => { + if (options.boundExecutionOnly) { + // The bound was armed when the callback started, so this is a run that overran + // its own bound, not a wait in the queue: cancel the in-flight mutation and + // release the caller, as for any other timeout. + controller.abort() + this.log("Provider profile mutation timed out; aborting in-flight mutation") + return + } + if (options.runToCompletion) { + callerTimedOut = true + this.log("Provider profile mutation timed out; waiting for it to finish before the next mutation") + return + } - controller.abort() - this.log("Provider profile mutation timed out; aborting in-flight mutation") - }) + controller.abort() + this.log("Provider profile mutation timed out; aborting in-flight mutation") + }, + options.boundExecutionOnly ? executionBegun : undefined, + ) void run.then( () => { @@ -476,16 +509,34 @@ export class ClineProvider return callerResult } - private withProviderProfileMutationTimeout(operation: Promise, onTimeout: () => void): Promise { + private withProviderProfileMutationTimeout( + operation: Promise, + onTimeout: () => void, + armAfter?: Promise, + ): Promise { let timeoutId: ReturnType | undefined + let settled = false const timeout = new Promise((_, reject) => { - timeoutId = setTimeout(() => { - onTimeout() - reject(new Error("Provider profile mutation timed out")) - }, ClineProvider.PENDING_OPERATION_TIMEOUT_MS) + const arm = () => { + // An operation that settled before the bound was armed needs no bound: arming + // on it afterwards would fire a timeout for work that already finished. + if (settled) { + return + } + timeoutId = setTimeout(() => { + onTimeout() + reject(new Error("Provider profile mutation timed out")) + }, ClineProvider.PENDING_OPERATION_TIMEOUT_MS) + } + if (armAfter) { + void armAfter.then(arm) + } else { + arm() + } }) return Promise.race([operation, timeout]).finally(() => { + settled = true if (timeoutId) { clearTimeout(timeoutId) } @@ -504,13 +555,19 @@ export class ClineProvider * write lands after that rollback whether the caller timed out or activation * settled first. The write is the shared setting only - the view-local pin and * overlay travel on their own mutation paths. + * + * The bound is armed on the write, not on the enqueue (`boundExecutionOnly`): review + * cid 4750230092. This repair exists to follow the mutation ahead of it, so the time + * it spends queued is not its own time to run, and burning the 30 s on that wait used + * to refuse the repair outright: the caller saw a timeout, the repair never wrote, and + * the name the rollback restored - a name the committed rename had deleted - stood. */ public async enqueueSharedProfileSelectionRepair(name: string): Promise { return this.enqueueProviderProfileMutation( async () => { await this.contextProxy.setValue("currentApiConfigName", name) }, - { runToCompletion: true }, + { runToCompletion: true, boundExecutionOnly: true }, ) } diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index afefa9f6eb4..1cbc8b4b145 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6472,18 +6472,14 @@ describe("ClineProvider", () => { await provider.dispose() }) - it("keeps a timed-out queued shared-selection repair from writing at all", async () => { - // Review cid 4746979132, and the one state where the runToCompletion flag on the - // repair enqueue changes an outcome: the repair times out while it is still queued - // behind the mutation it waits for. With the flag the queue advances from the - // mutation itself, so the timed-out repair never starts - a start refuses a caller - // that already saw a timeout - and the only selection write left standing is the - // running mutation's restore of the deleted name. Without the flag the queue - // advances on the caller-bounded result the moment the repair times out, so both - // the repair and whatever follows it overtake the mutation that is still running. - // The third mutation below is what makes that difference visible: the repair method - // does not read its AbortSignal, so the flag is only observable through who the - // queue waits for next. + it("lands a queued shared-selection repair whose wait behind the mutation outlasted the bound", async () => { + // Review cid 4750230092 restates what this row used to claim about the same state. The + // row below once asserted that a repair whose 30 s ran out while it was still queued + // writes nothing at all; the finding is that the wait was never the repair's own time + // to run, so a repair that waited out the bound is still owed its write. Same state, new + // verdict: the mutation's restore of the deleted name lands first and the repaired name + // lands after it. The third mutation records the queue order the repair keeps - nothing + // queued behind it overtakes the mutation it is waiting for. vi.useFakeTimers() const provider = new ClineProvider( mockContext, @@ -6505,7 +6501,9 @@ describe("ClineProvider", () => { const gate = new Promise((resolve) => { release = resolve }) - const mutationTimedOut = expect( + // What its caller sees is the mutation timeout, as in the row above: runToCompletion + // rejects the caller and leaves the gated run ahead of the repair. + const mutation = expect( provider["enqueueProviderProfileMutation"]( async () => { await gate @@ -6516,18 +6514,23 @@ describe("ClineProvider", () => { ), ).rejects.toThrow("Provider profile mutation timed out") await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) - - const repairTimedOut = expect(provider.enqueueSharedProfileSelectionRepair("new-profile")).rejects.toThrow( - "Provider profile mutation timed out", + let repairState = "running" + const repair = provider.enqueueSharedProfileSelectionRepair("new-profile") + void repair.then( + () => { + repairState = "settled" + }, + () => { + repairState = "rejected" + }, ) + // The repair has sat behind the mutation for longer than the mutation timeout without + // running once. Its bound measures its own write, so the wait has not spent it: the + // repair is neither rejected nor written, and it is not the second timer to fire - + // this advance is the second 30 s since the repair was queued. await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) - // The repair has timed out for its caller while the mutation it waits behind is - // still running, and it has written nothing. + expect(repairState).toBe("running") expect(writes).toEqual([]) - - // Bracket access drives the private queue, as in the committed mode-switch row this - // one follows. This mutation only records that it started: whether it may start at - // all is the question, because the repair sits between it and the running mutation. let followingStarted = false const following = provider["enqueueProviderProfileMutation"]( async () => { @@ -6536,22 +6539,182 @@ describe("ClineProvider", () => { { runToCompletion: true }, ) await vi.advanceTimersByTimeAsync(0) - // Nothing behind the repair may overtake the mutation that is still running. expect(followingStarted).toBe(false) - release() - await mutationTimedOut - await repairTimedOut - // Awaiting the following mutation drains everything queued before it: the run, the - // repair's refused start, and only then this mutation's own callback. + await mutation + await repair + // The restore of the deleted name, then the repair that follows it through the queue: + // the repaired name is the last write the shared selection sees. + expect(writes).toEqual(["old-profile", "new-profile"]) await following expect(followingStarted).toBe(true) - // The mutation's restore of the deleted name is the only selection write that ever - // lands: a repair that already reported failure to its caller does not write state - // behind that caller's back, so the shared selection stays on a name that exists - // rather than on one a timed-out write invented. - expect(writes).toEqual(["old-profile"]) + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("new-profile") + vi.useRealTimers() + await provider.dispose() + }) + + it("aborts the shared-selection repair whose own execution runs past the bound", async () => { + // Review cid 4750230092, the bound half of the ask. Moving where the 30 s starts must not + // remove it: the rename awaits this repair inside its catch (webviewMessageHandler.ts + // line 2786), and without a bound that await has no ceiling once the write began. Nothing + // is queued ahead here, so this is the execution running past its bound. The settle state + // is recorded rather than awaited, so a missing bound reads as a wrong recorded state + // instead of a hung test. + vi.useFakeTimers() + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + let releaseWrite!: () => void + const writeGate = new Promise((resolve) => { + releaseWrite = resolve + }) + // Records the write only once it settles, so the row can tell a bound that cancelled the + // mutation from a write that landed after the caller was already released. + const settledWrites: string[] = [] + const originalSetValue = provider.contextProxy.setValue.bind(provider.contextProxy) + vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key, value) => { + if (key === "currentApiConfigName") { + await writeGate + settledWrites.push(String(value)) + } + return originalSetValue(key, value) + }) + const logSpy = vi.spyOn(provider, "log") + let repairState = "running" + const repair = provider.enqueueSharedProfileSelectionRepair("new-profile") + void repair.then( + () => { + repairState = "settled" + }, + () => { + repairState = "rejected" + }, + ) + await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) + // The execution passed its bound: the caller is released with the timeout instead of + // waiting on a write that has not settled, and the mutation is cancelled the way every + // other in-flight timeout cancels. + expect(repairState).toBe("rejected") + expect(logSpy).toHaveBeenCalledWith("Provider profile mutation timed out; aborting in-flight mutation") + expect(settledWrites).toEqual([]) expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile") + releaseWrite() + await vi.advanceTimersByTimeAsync(0) + // Aborting cannot un-write a ContextProxy write that is already in flight, so the write + // does land after the caller was released - and the queue is still owned until it does. + expect(settledWrites).toEqual(["new-profile"]) + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("new-profile") + vi.useRealTimers() + await provider.dispose() + }) + + it("aborts a mutation bounded from its own execution when the run overruns the bound", async () => { + // The same bound read where its effect is visible to the callback itself. Bound from + // execution, the timer is armed when the callback starts, so an overrun cancels the + // mutation that is still in flight instead of only releasing its caller. + vi.useFakeTimers() + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + let mutationSignal: AbortSignal | undefined + let started = false + let mutationState = "running" + const mutation = provider["enqueueProviderProfileMutation"]( + async (signal) => { + mutationSignal = signal + started = true + await gate + }, + { runToCompletion: true, boundExecutionOnly: true }, + ) + void mutation.then( + () => { + mutationState = "settled" + }, + () => { + mutationState = "rejected" + }, + ) + await vi.advanceTimersByTimeAsync(0) + expect(started).toBe(true) + await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) + expect(mutationState).toBe("rejected") + expect(mutationSignal?.aborted).toBe(true) + release() + await vi.advanceTimersByTimeAsync(0) + vi.useRealTimers() + await provider.dispose() + }) + + it("keeps the queue owned by a repair whose execution timed out until its write settles", async () => { + // The state where runToCompletion on the repair enqueue changes an outcome: the repair + // passed its bound while its write was still outstanding. Advancing the queue on the + // rejected caller instead of on the write would let the mutation behind the repair start + // under that write, so its own selection could land first and the late repair would then + // overwrite it with the name the rename committed. + vi.useFakeTimers() + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("currentApiConfigName", "old-profile") + let releaseWrite!: () => void + const writeGate = new Promise((resolve) => { + releaseWrite = resolve + }) + const settledWrites: string[] = [] + const originalSetValue = provider.contextProxy.setValue.bind(provider.contextProxy) + vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key, value) => { + if (key === "currentApiConfigName") { + await writeGate + settledWrites.push(String(value)) + } + return originalSetValue(key, value) + }) + let repairState = "running" + const repair = provider.enqueueSharedProfileSelectionRepair("new-profile") + void repair.then( + () => { + repairState = "settled" + }, + () => { + repairState = "rejected" + }, + ) + await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) + expect(repairState).toBe("rejected") + let followingStarted = false + const following = provider["enqueueProviderProfileMutation"]( + async () => { + followingStarted = true + }, + { runToCompletion: true }, + ) + await vi.advanceTimersByTimeAsync(0) + // The repair already reported failure to its caller, but its write is still outstanding + // and the queue is still owned by it: nothing behind it may start under that write. + expect(followingStarted).toBe(false) + releaseWrite() + await following + expect(followingStarted).toBe(true) + expect(settledWrites).toEqual(["new-profile"]) + expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("new-profile") vi.useRealTimers() await provider.dispose() }) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 53b8a05d604..dc85880e3c5 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -3548,6 +3548,69 @@ describe("webviewMessageHandler - renameApiConfiguration", () => { expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("currentApiConfigName", "new-profile") }) + it("notifies the user when the queued shared-selection repair itself rejects", async () => { + // Review cid 4750230092: the repair is awaited inside this catch, so the rejection + // below used to skip the log and the notification that follows it, and the user was + // left with the old name deleted and the shared selection still naming it. Both + // channels now report it: the repair's own failure, and the rename failure the + // handler reports for the activation. + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi.fn().mockResolvedValue({ id: "profile-id", apiProvider: providerIdentifiers.anthropic }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn().mockResolvedValue(undefined), + } + provider.repointViewLocalStateAfterProfileRename = vi.fn().mockResolvedValue(undefined) + provider.activateProviderProfile = vi.fn().mockRejectedValue(new Error("activation timed out")) + provider.enqueueSharedProfileSelectionRepair = vi.fn().mockRejectedValue(new Error("repair write rejected")) + + let escaped: string | undefined + try { + // The rejection still reaches the dispatch - the row below pins that. This row is + // about what the user is told before it does. + await webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + } catch (error) { + escaped = error instanceof Error ? error.message : String(error) + } + + expect(escaped).toBe("repair write rejected") + expect(mockClineProvider.log).toHaveBeenCalledWith(expect.stringContaining("Error rename api configuration:")) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("common:errors.rename_api_config") + expect(mockClineProvider.log).toHaveBeenCalledWith( + expect.stringContaining("Shared profile selection repair failed after rename:"), + ) + }) + + it("keeps the repair failure visible to the message dispatch after notifying the user", async () => { + // The notification must not be bought by swallowing the rejection: the dispatch + // wrapper records the diagnostics and rethrows (ClineProvider.ts line 2777), and that + // is how a caller learns the repair never landed. Rethrowing after the notification + // keeps that channel open. + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi.fn().mockResolvedValue({ id: "profile-id", apiProvider: providerIdentifiers.anthropic }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn().mockResolvedValue(undefined), + } + provider.repointViewLocalStateAfterProfileRename = vi.fn().mockResolvedValue(undefined) + provider.activateProviderProfile = vi.fn().mockRejectedValue(new Error("activation timed out")) + provider.enqueueSharedProfileSelectionRepair = vi.fn().mockRejectedValue(new Error("repair write rejected")) + + await expect( + webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }), + ).rejects.toThrow("repair write rejected") + }) + it("re-points views with the stored record instead of the raw webview payload", async () => { provider.providerSettingsManager = { runExclusiveAcrossInstances, diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 76fb160e067..609b3225f18 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -2775,6 +2775,13 @@ export const webviewMessageHandler = async ( // transaction committed - oldName already deleted, views and tasks already // re-pointed - so this branch takes the second shape: the rename stands and the // shared selection is moved onto the stored name instead of left on the deleted one. + // The repair has a failure of its own to report, and reporting it must not cost the + // user the rename notification: the failure is recorded here, the log and the + // notification below still run, and the rejection is rethrown once they have. A + // silent catch would leave the message dispatch (ClineProvider.ts line 2834) never + // seeing a repair that did not land - review cid 4750230092 asks that this stays + // visible to the caller as well as to the user. + let selectionRepairFailure: { error: unknown } | undefined if (renameCommitted && committedNewName) { // Review cid 4746979132: the activation above runs with runToCompletion, so a // timeout rejects this caller while that mutation - and its rollback, which @@ -2783,13 +2790,36 @@ export const webviewMessageHandler = async ( // profile. The repair is queued behind that mutation instead: the queue // advances from the mutation once it settles, so the repaired name is the // last write whether the rollback arrives late or activation settled first. - await provider.enqueueSharedProfileSelectionRepair(committedNewName) + // + // Review cid 4750230092 moved where that repair's 30 s is measured from: the + // bound is armed on the write, not on the enqueue. That takes the queue wait + // out as a source of rejection here, but not every source - the write itself + // can still reject, and a rename whose repair never landed is not a rename + // that quietly succeeded. + try { + await provider.enqueueSharedProfileSelectionRepair(committedNewName) + } catch (repairFailure) { + selectionRepairFailure = { error: repairFailure } + provider.log( + `Shared profile selection repair failed after rename: ${JSON.stringify( + repairFailure, + Object.getOwnPropertyNames(repairFailure), + 2, + )}`, + ) + } } provider.log( `Error rename api configuration: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, ) vscode.window.showErrorMessage(t("common:errors.rename_api_config")) + // The repair failure is rethrown only after the user has been told: the dispatch + // wrapper still sees the rejection (it rethrows at ClineProvider.ts line 2834), + // and the log plus the notification above are what the user gets either way. + if (selectionRepairFailure) { + throw selectionRepairFailure.error + } } } break From 01ea0ffdaacf785622bb4087e31c1cc578abfb26 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:45:17 +0800 Subject: [PATCH 19/34] restore the tombstone a rejected view-state write made [cr review 6126668924] Review 6126668924 asked for the tombstone a rejected view-state write leaves behind to be undone, naming clearPersistedViewState as the pattern: "record wasCleared before changing clearedViewStateIds and restore it on a failed write". That half already exists for clearPersistedViewState (ClineProvider.ts L1027-1036): it records the membership, drops only the claim this call added, and keeps a claim an earlier landed clear set. The two sibling writes had no such undo: savePersistedViewState deletes the entry and claims the id when a view stops pinning anything (L957-959), and drops the claim when a view re-pins (L960-964); rekeyPersistedViewStateEntry claims the temporary id (L1169-1170) and un-claims the stable id it moves the entry onto (L1172-1175). All three then restored the durable map when their write rejected, but left the claim standing, so the map said "the entry is there" while the claim set said "it is not". What changed - savePersistedViewState records the membership before either branch touches it (L951-955) and, in the rejected-write path, restores it to the recorded value (L976-985): the clear branch's add comes off, the re-pin branch's delete goes back on. One restore covers both branches because it is written against the recorded value, not the branch. - rekeyPersistedViewStateEntry records both claims before touching them (L1162-1168) and restores them on rejection (L1187-1201). The stable id is only re-claimed when this call was the one that removed it (movedToNext), so a rejection never invents a claim for a slot this write never moved into. - The claim is restored before the durable-map snapshot restore, so the two statements about the same map are made in one order. Measured, not assumed: moving it after the snapshot restore changes nothing while that restore succeeds (column cT-o0: 4 passed), and turns both write rows red once the restore itself rejects and aborts the catch (cT-o1: first reds at ClineProvider.spec.ts:8694 and :8769), so the placement matters only in that second case. - No assertion relies on pruning keeping entries: prunePersistedViewStates (L1117-1127) and MAX_PERSISTED_VIEW_STATES (L319) are untouched, and every assertion below targets the entry that pruning evicted, not one it kept. Tests (src/core/webview/__tests__/ClineProvider.spec.ts) - L8627 restores an entry an evicting activation pruned when the save that un-pinned it was rejected: a sibling's un-pin rejects, this view snapshots, its own pin write evicts the pin, and the rollback runs. The load-bearing assertion is L8694 - the claim a rejected write must not leave, which the rollback gate at ClineProvider.ts L3253 reads before restoring a pruned entry. Disclosure, measured: in this construction the pin is present in the restored map (L8689) in every byte version and under every mutant below, so that assertion is not the half that fails - the claim assertion is. The reviewer's stated consequence (the rollback losing the entry) did not reproduce in this scenario, and this row does not claim it does. - L8698 keeps the tombstone an earlier landed clear set when a later clear write rejects: green at the parent bytes as well - it is the guard for "undo only what this call did", and it is the row that dies when the undo becomes unconditional (cT-m3, red at L8729). - L8735 restores the tombstone a re-pin write removed when that write rejects: the other branch, red at the parent bytes (L8769). - L8775 restores both tombstone claims a rejected re-key touched: red at the parent bytes (L8802 for the temporary id, L8803 for the stable id under the re-key mutants). - Isolation, measured: clearedViewStateIds is a process-level static (L329) and this suite has no reset helper for it - the only test-side reference in the tree is the committed row's own membership assertion (L8465). Rows below therefore normalize the ids they use to a known membership before asserting, so a claim checked after the row belongs to this row's calls and not to an earlier row. Evidence (all runs on the bytes above, logs written by Node, no shell pipe in the way) - New bytes: ClineProvider.spec.ts 534 passed (530 committed rows + the 4 above). Parent bytes with the new rows: 3 failed, 531 passed - the three rows above, first reds L8694 / L8769 / L8802, and no committed row changed verdict. - Comment-only control: stripping the 16 new spec comment lines of row one and the 4 of each other row (28 in all, plus 16 new production comment lines) keeps all four green, and at the parent bytes moves the three first reds to L8678 / L8746 / L8774 - exactly the number of comment lines removed above each one. The verdicts come from the assertions. - Mutants, each named for the half-claim it kills: no save-side restore (rows one and three red, L8694 / L8769); no re-key restore (row four, L8802); unconditional claim removal in the clear path (row two, L8729); unconditional add in save (row one, L8694); unconditional delete in save (row three, L8769); re-key restoring only the temporary id (row four, L8803); re-key adding the temporary claim regardless (row four, L8802); re-key deleting the stable claim regardless (row four, L8803). - The four rows use in-memory doubles only: no file system, no symlink, no permissions, no Date.now, no real timers and no vitest timeout dependence, and no platform or skip predicate was added. --- src/core/webview/ClineProvider.ts | 38 ++++ .../webview/__tests__/ClineProvider.spec.ts | 183 ++++++++++++++++++ 2 files changed, 221 insertions(+) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 5b32c89cd75..93bebffd977 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -948,6 +948,11 @@ export class ClineProvider } } + // A tombstone is a claim that the entry is gone. A write whose durable store + // rejected may not leave behind a claim this call made, and may not drop a claim + // it found already made, so the membership is recorded here - before either branch + // touches it - and restored to exactly that if the write below rejects. + const wasCleared = ClineProvider.clearedViewStateIds.has(viewStateId) let wroteEntry = false if (!next.mode && !next.currentApiConfigName) { delete states[viewStateId] @@ -968,6 +973,16 @@ export class ClineProvider try { await this.contextProxy.setValue("viewStates", pruned) } catch (error) { + // The durable map still holds what this write tried to change, so the tombstone + // has to say what it said before the attempt: the clear branch's add comes off, + // the re-pin branch's delete goes back on. It is restored before the snapshot + // restore so the two claims about the same map stay in step even when that + // restore itself fails. + if (wasCleared) { + ClineProvider.clearedViewStateIds.add(viewStateId) + } else { + ClineProvider.clearedViewStateIds.delete(viewStateId) + } // A rejected write leaves the in-memory map holding the attempted value, so the // compensation must come from the snapshot taken before this write mutated // anything: re-reading the map here would persist the change whose write failed @@ -1144,12 +1159,20 @@ export class ClineProvider return } + // The re-key touches two tombstones: it claims the temporary id is gone, and it + // un-claims the stable id it moves the entry onto. Both are claims about durable + // storage, so each is recorded before the attempt and restored to the recorded + // value if the write below rejects. + const wasClearedPrevious = ClineProvider.clearedViewStateIds.has(previousViewStateId) + const wasClearedNext = ClineProvider.clearedViewStateIds.has(nextViewStateId) + let movedToNext = false delete states[previousViewStateId] ClineProvider.clearedViewStateIds.add(previousViewStateId) if (!states[nextViewStateId]) { states[nextViewStateId] = previous ClineProvider.clearedViewStateIds.delete(nextViewStateId) + movedToNext = true } const pruned = this.prunePersistedViewStates(states) @@ -1161,6 +1184,21 @@ export class ClineProvider try { await this.contextProxy.setValue("viewStates", pruned) } catch (error) { + // Neither tombstone claim survives a write that never landed: the temporary id + // goes back to whatever it claimed before this call, and the stable id only comes + // back onto the list if this call was the one that took it off. + if (wasClearedPrevious) { + ClineProvider.clearedViewStateIds.add(previousViewStateId) + } else { + ClineProvider.clearedViewStateIds.delete(previousViewStateId) + } + if (movedToNext) { + if (wasClearedNext) { + ClineProvider.clearedViewStateIds.add(nextViewStateId) + } else { + ClineProvider.clearedViewStateIds.delete(nextViewStateId) + } + } // A rejected write leaves the in-memory map holding the attempted value, so the // compensation must come from the snapshot taken before this write mutated // anything: re-reading the map here would persist the change whose write failed diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 1cbc8b4b145..799200eec21 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -8624,6 +8624,189 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("restores an entry an evicting activation pruned when the save that un-pinned it was rejected", async () => { + // Review cid 4751099424 family (persistence tombstone on the save/re-key pair): a + // tombstone claims the durable map holds no entry under that id, and the rollback + // gate at ClineProvider.ts L3253 reads it before restoring a pruned entry, so a + // write whose durable store rejected - it changed nothing there - may not leave one + // behind for a pin no user removed. clearedViewStateIds is process-level + // (ClineProvider.ts L329) and this suite has no reset helper for it, so the ids + // here are normalized to a known membership: the assertions are about this row. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-tomb-a-view") + const seeded: Record = { + // The sibling view's pin, and the oldest entry: the row's pin write prunes it. + "tomb-a-view": { mode: "architect", currentApiConfigName: "tomb-a-profile", updatedAt: 0 }, + } + for (let i = 1; i <= 50; i++) { + seeded["tomb-fill-" + i] = { mode: "code", updatedAt: i } + } + await provider.contextProxy.setValue("viewStates", seeded) + ClineProvider["clearedViewStateIds"].delete("tomb-a-view") + + // A second provider owns the sibling view and un-pins it: nothing persistable is + // left, so the write deletes the entry and claims the id, and the durable store + // rejects that change - the entry stays stored. + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await sibling["setViewStateId"]("tomb-a-view") + const unpinFailure = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { + throw new Error("durable un-pin failed") + }) + await expect( + sibling["savePersistedViewState"]({ mode: undefined, currentApiConfigName: undefined }), + ).rejects.toThrow("durable un-pin failed") + unpinFailure.mockRestore() + + // The activation snapshot is taken now, while the pin is still stored. + const snapshot = provider["_snapshotProfileActivationState"]() + // This view's own pin write lands and evicts the two oldest entries; only the + // pin matters below, the filler is the control that the rollback itself ran. + await provider["savePersistedViewState"]({ + mode: "code", + currentApiConfigName: "new-profile", + updatedAt: 9001, + }) + + // The group then fails, so the rollback is what has to bring the pin back. + await provider["_restoreProfileActivationState"](snapshot) + + const restored = provider.contextProxy.getValue("viewStates") as Record + expect(restored["tomb-fill-1"]).toEqual({ mode: "code", updatedAt: 1 }) + // The evicted pin is back in the restored map with its own metadata - the row's + // claim assertion below is the half that the rollback gate actually reads. + expect(restored["tomb-a-view"]).toEqual({ + mode: "architect", + currentApiConfigName: "tomb-a-profile", + updatedAt: 0, + }) + expect(ClineProvider["clearedViewStateIds"].has("tomb-a-view")).toBe(false) + await provider.dispose() + await sibling.dispose() + }) + it("keeps the tombstone an earlier landed clear set when a later clear write rejects", async () => { + // The undo removes only the claim this call made. A claim an earlier clear that + // landed put there stands: that clear really did remove the entry when it ran. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("stable-tomb-b-view") + await provider.contextProxy.setValue("viewStates", { + "tomb-b-view": { currentApiConfigName: "tomb-b-profile", updatedAt: 1 }, + }) + ClineProvider["clearedViewStateIds"].delete("tomb-b-view") + await provider["clearPersistedViewState"]("tomb-b-view") + expect(ClineProvider["clearedViewStateIds"].has("tomb-b-view")).toBe(true) + + // The entry is written back into storage without going through a clear, so the + // claim that predates the next call is still there when that call runs. + await provider.contextProxy.setValue("viewStates", { + ...(provider.contextProxy.getValue("viewStates") as Record), + "tomb-b-view": { currentApiConfigName: "tomb-b-profile", updatedAt: 2 }, + }) + + const clearFailure = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { + throw new Error("durable clear failed") + }) + await expect(provider["clearPersistedViewState"]("tomb-b-view")).rejects.toThrow("durable clear failed") + clearFailure.mockRestore() + + expect(ClineProvider["clearedViewStateIds"].has("tomb-b-view")).toBe(true) + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + "tomb-b-view": { currentApiConfigName: "tomb-b-profile" }, + }) + await provider.dispose() + }) + it("restores the tombstone a re-pin write removed when that write rejects", async () => { + // The other half of the same rule: the re-pin branch drops the claim because the + // entry is being written back. When the durable write rejects, nothing was written + // back, so the claim has to be put back where it was found. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("tomb-c-view") + ClineProvider["clearedViewStateIds"].delete("tomb-c-view") + await provider["savePersistedViewState"]({ + mode: "architect", + currentApiConfigName: "tomb-c-profile", + updatedAt: 1, + }) + expect(ClineProvider["clearedViewStateIds"].has("tomb-c-view")).toBe(false) + await provider["clearPersistedViewState"]() + expect(ClineProvider["clearedViewStateIds"].has("tomb-c-view")).toBe(true) + + const writeFailure = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { + throw new Error("durable re-pin failed") + }) + await expect( + provider["savePersistedViewState"]({ + mode: "architect", + currentApiConfigName: "tomb-c-profile", + updatedAt: 2, + }), + ).rejects.toThrow("durable re-pin failed") + writeFailure.mockRestore() + + expect(ClineProvider["clearedViewStateIds"].has("tomb-c-view")).toBe(true) + // And the entry the rejected write tried to recreate stayed out of storage. + const after = provider.contextProxy.getValue("viewStates") as Record + expect(after["tomb-c-view"]).toBeUndefined() + await provider.dispose() + }) + it("restores both tombstone claims a rejected re-key touched", async () => { + // The re-key claims the temporary id is gone and un-claims the stable id it moves + // the entry onto. A rejected write landed neither half, so neither claim may stay. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + ClineProvider["clearedViewStateIds"].delete(provider.viewId) + ClineProvider["clearedViewStateIds"].delete("tomb-d-stable") + // Author the temporary entry through the real write path so this instance owns it. + await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) + // The stable slot is claimed and empty, exactly the state a re-key moves into. + await provider["clearPersistedViewState"]("tomb-d-stable") + expect(ClineProvider["clearedViewStateIds"].has(provider.viewId)).toBe(false) + expect(ClineProvider["clearedViewStateIds"].has("tomb-d-stable")).toBe(true) + + const writeFailure = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { + throw new Error("durable re-key failed") + }) + await expect(provider["rekeyPersistedViewStateEntry"]("tomb-d-stable")).rejects.toThrow( + "durable re-key failed", + ) + writeFailure.mockRestore() + + expect(ClineProvider["clearedViewStateIds"].has(provider.viewId)).toBe(false) + expect(ClineProvider["clearedViewStateIds"].has("tomb-d-stable")).toBe(true) + const after = provider.contextProxy.getValue("viewStates") as Record + expect(after[provider.viewId]).toMatchObject({ mode: "architect" }) + expect(after["tomb-d-stable"]).toBeUndefined() + await provider.dispose() + }) + it("does not resurrect a sibling pin cleared after the activation snapshot", async () => { const provider = new ClineProvider( mockContext, From d26b39fd06ea41cb721e86a884c6acd81d12866b Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:08:54 +0800 Subject: [PATCH 20/34] state the repair bound as a caller deadline and pin its edge [cr 4751099424] [cr 4751099434] Review 4751099424: "A repair that times out after 1 ms still passes this test. Keep the write pending. Assert that the caller is still pending at 29,999 ms. Advance one more millisecond and assert the timeout error." Review 4751099434: "The repair callback ignores the abort signal. ... If storage cannot cancel this write, document the limit as a caller deadline and log that the write is still pending. Keep queue ownership until settlement." What changed - The timeout the shared-selection repair can hit is a deadline on its caller, not a cancellation of its write. enqueueSharedProfileMutation arms that bound when the callback begins, aborts its controller when it expires, and the repair's callback never consults that controller - so the abort changes nothing for that mutation and the write can still land after the caller saw the timeout. The log said "aborting in-flight mutation"; it now says what the code did: "Provider profile mutation timed out; aborting in-flight mutation" "Provider profile mutation timed out for its caller; the write is still pending" Only the branch that bounds execution changed. The default branch (no runToCompletion, no boundExecutionOnly) still logs the abort sentence, because for that path an abort really is delivered to a callback that reads it - the committed row in ClineProvider.apiHandlerRebuild.spec.ts asserts mutationSignal?.aborted alongside that sentence. - Queue ownership was already what 4751099434 asks to keep: the tail is assigned from `run`, not from the timeout-bounded caller result, whenever `runToCompletion` is set, so the next mutation waits for the repair's write whether or not its caller was released. No line of that changed; the queue-advancing comment now states where the order safety comes from instead of crediting signal checks the repair callback does not perform. - Test side (ClineProvider.spec.ts, row "aborts the shared-selection repair whose own execution runs past the bound"): the single step past the bound is replaced by a step to one millisecond short and a step across it. At the edge the caller is still waiting and the write has not settled; one millisecond later the caller holds the timeout error and the write is still outstanding. The write stays gated throughout, so nothing in the row depends on real timers, the file system, or Date.now. - Comment citations that had drifted were corrected, and the corrected ones carry the byte version they were measured against: - webviewMessageHandler.ts rename catch: the ask that "offers two shapes" is now cited as review cid 4746979132 anchored at that review's bytes, naming both shapes, instead of "this file's line 2690" - which pointed at an unrelated comment in every version measured. - the dispatch-wrapper cites moved from "ClineProvider.ts line 2834" to the wrapper function plus ClineProvider.ts:2872 at 01ea0ffdaa. - this row's cite of the rename await now reads webviewMessageHandler.ts: 2800 at db9b7fa083, and records that the sentence read 2786 when it was committed - the parent's numbering, so it was stale on arrival. These are comment-only. Measured on the notification path: the repair await moved 2800 to 2802, the rename notification 2816 to 2818, and the rethrow 2821 to 2823, because two comment lines were added above them. Evidence (Node-run columns, logs written by Node, no shell pipe in the way) - New bytes: ClineProvider.spec.ts 534 passed (534). At 01ea0ffdaa with the new rows and the parent's production bytes: 1 failed, 533 passed - only this row, first red at ClineProvider.spec.ts:6611, and the failure is the log sentence itself, which is the half that changed. No committed row changed verdict. - Comment-only control: deleting the 22 new production comment lines, the 11 new spec comment lines and the 16 new handler comment lines leaves the whole file at 534 passed; at the parent's production bytes it moves the first red from 6611 to 6600 - the 11 comment lines deleted above it. The verdict comes from the assertions, not the prose. - Named mutants, predictions written before the runs, readings reported as measured: bound armed one millisecond early - predicted one red at 6603, read one red at 6603 (expected 'rejected' to be 'running'): the edge assertion is what dies. No bound armed at all - predicted two red, read three: 6610 in this row and 6664 in "aborts a mutation bounded from its own execution when the run overruns the bound" as predicted, plus 6711 in "keeps the queue owned by a repair whose execution timed out until its write settles", which the prediction named as possible and did not count. Log sentence reverted while the code stays - predicted one red at 6611, read one red at 6611 with the edge and timeout assertions green. - Review 4751099434 cites "the test at Lines 6606-6611" as confirming that the write can still commit while the queue stays blocked. Measured at db9b7fa083 - the bytes that review saw - those lines are this row's releaseWrite() block and its two assertions that the write landed; the same content sits at 6616-6621 in the bytes above. The reviewer's reading of the row is right, which is why this change is wording plus a boundary and not a new mechanism. - This commit does not address review 4751099445 (presenting the rename error before awaiting the repair). That is a separate change. --- src/core/webview/ClineProvider.ts | 30 +++++++++++++------ .../webview/__tests__/ClineProvider.spec.ts | 28 +++++++++++------ src/core/webview/webviewMessageHandler.ts | 14 +++++---- 3 files changed, 48 insertions(+), 24 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 93bebffd977..f5b1fa5191b 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -424,13 +424,16 @@ export class ClineProvider * * `boundExecutionOnly` moves where the 30 s is measured from: the bound is armed when this * mutation's own callback begins, so time spent queued behind an earlier mutation does not - * consume it, and an expiry aborts the mutation the way every other in-flight timeout does. + * consume it, and an expiry aborts the controller the way every other in-flight timeout does. * Use it for a repair whose job is to follow the mutation ahead of it (review cid 4750230092): * waiting the bound out while queued used to report failure to the caller without the repair * ever running, so the name the mutation's rollback had just restored stood. The bound is - * re-anchored, not removed: an execution that runs past it still aborts and still rejects its - * caller, so awaiting one of these enqueues is not open-ended once its own work has begun. - * `runToCompletion` still keeps the queue owned until the mutation settles. + * re-anchored, not removed: an execution that runs past it still aborts its signal and still + * rejects its caller, so awaiting one of these enqueues is not open-ended once its own work + * has begun. Whether that abort does anything is the callback's call: a callback that never + * consults the signal keeps running and its write can still land, so for that mutation the + * 30 s is a deadline on the caller and not a cancellation of the write - review cid 4751099434. + * `runToCompletion` still keeps the queue owned until that write settles. */ private enqueueProviderProfileMutation( fn: (signal: AbortSignal) => Promise, @@ -465,10 +468,13 @@ export class ClineProvider () => { if (options.boundExecutionOnly) { // The bound was armed when the callback started, so this is a run that overran - // its own bound, not a wait in the queue: cancel the in-flight mutation and - // release the caller, as for any other timeout. + // its own bound, not a wait in the queue. The signal is aborted for contract + // uniformity, because that is what every other expiry here does; a callback that + // never consults it - the shared-selection repair does not - keeps running and its + // write can still land, so what expired is the caller's deadline, not the write + // (review cid 4751099434). controller.abort() - this.log("Provider profile mutation timed out; aborting in-flight mutation") + this.log("Provider profile mutation timed out for its caller; the write is still pending") return } if (options.runToCompletion) { @@ -500,8 +506,10 @@ export class ClineProvider }, ) - // Advance from the timeout-bounded result. Each fn checks its AbortSignal before - // writing state, so advancing the queue on timeout cannot produce stale overwrites. + // Advance from the timeout-bounded result. On the default path order safety comes from each + // fn checking its signal before writing state. A callback that ignores the signal is safe + // here for a different reason: `runToCompletion` below advances the queue from `run`, so + // the next mutation waits for that write instead of racing it (review cid 4751099434). this.providerProfileMutationQueue = (options.runToCompletion ? run : callerResult).then( () => undefined, () => undefined, @@ -561,6 +569,10 @@ export class ClineProvider * it spends queued is not its own time to run, and burning the 30 s on that wait used * to refuse the repair outright: the caller saw a timeout, the repair never wrote, and * the name the rollback restored - a name the committed rename had deleted - stood. + * + * The 30 s on this path is a deadline for the caller, not a cancellation of the write: the + * callback never consults the signal, so a write already in flight lands anyway - review cid + * 4751099434. Queue ownership is untouched: the tail advances from the write itself. */ public async enqueueSharedProfileSelectionRepair(name: string): Promise { return this.enqueueProviderProfileMutation( diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 799200eec21..9fa8c775405 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6555,11 +6555,11 @@ describe("ClineProvider", () => { it("aborts the shared-selection repair whose own execution runs past the bound", async () => { // Review cid 4750230092, the bound half of the ask. Moving where the 30 s starts must not - // remove it: the rename awaits this repair inside its catch (webviewMessageHandler.ts - // line 2786), and without a bound that await has no ceiling once the write began. Nothing - // is queued ahead here, so this is the execution running past its bound. The settle state - // is recorded rather than awaited, so a missing bound reads as a wrong recorded state - // instead of a hung test. + // remove it: the rename awaits this repair inside its catch (webviewMessageHandler.ts:2800 + // at db9b7fa083 - this cite read 2786 when the row was committed, which was the parent's + // numbering, not this commit's). Nothing is queued ahead here, so this is the execution + // running past its bound. The settle state is recorded rather than awaited, so a missing + // bound reads as a wrong recorded state instead of a hung test. vi.useFakeTimers() const provider = new ClineProvider( mockContext, @@ -6595,12 +6595,22 @@ describe("ClineProvider", () => { repairState = "rejected" }, ) - await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) + // Review cid 4751099424 asks for both sides of the bound. One step past the bound could not + // tell an expiry at 30 s from one a millisecond early, so the row now walks up to the edge + // and crosses it: still pending one millisecond short, the timeout error on that millisecond. + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS - 1) + expect(repairState).toBe("running") + expect(settledWrites).toEqual([]) + await vi.advanceTimersByTimeAsync(1) // The execution passed its bound: the caller is released with the timeout instead of - // waiting on a write that has not settled, and the mutation is cancelled the way every - // other in-flight timeout cancels. + // waiting on a write that has not settled. Its signal is aborted, and for this callback + // that is a contract gesture rather than a cancellation - the write is still outstanding + // (review cid 4751099434, the log below says so). expect(repairState).toBe("rejected") - expect(logSpy).toHaveBeenCalledWith("Provider profile mutation timed out; aborting in-flight mutation") + expect(logSpy).toHaveBeenCalledWith( + "Provider profile mutation timed out for its caller; the write is still pending", + ) expect(settledWrites).toEqual([]) expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile") releaseWrite() diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 609b3225f18..6ef4db80d83 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -2769,17 +2769,19 @@ export const webviewMessageHandler = async ( // currently activated provider profile. await provider.activateProviderProfile({ name: newName }) } catch (error) { - // The ask at this file's line 2690 offers two shapes for a failed rename: - // roll it back, or treat it as committed and make the shared selection name a - // profile that exists. A rejection from the activation above arrives after the + // Review cid 4746979132 (anchored at webviewMessageHandler.ts:2764 in the bytes that + // review saw) offered two shapes for a failed rename: run the repair inside the + // provider profile mutation queue after activation settles, or keep the committed + // name in the rollback. A rejection from the activation above arrives after the // transaction committed - oldName already deleted, views and tasks already // re-pointed - so this branch takes the second shape: the rename stands and the // shared selection is moved onto the stored name instead of left on the deleted one. // The repair has a failure of its own to report, and reporting it must not cost the // user the rename notification: the failure is recorded here, the log and the // notification below still run, and the rejection is rethrown once they have. A - // silent catch would leave the message dispatch (ClineProvider.ts line 2834) never - // seeing a repair that did not land - review cid 4750230092 asks that this stays + // silent catch would leave the message dispatch (ClineProvider.ts onReceiveMessage, + // at rethrowing its failure; ClineProvider.ts:2872 at 01ea0ffdaa) never seeing a repair + // that did not land - review cid 4750230092 asks that this stays // visible to the caller as well as to the user. let selectionRepairFailure: { error: unknown } | undefined if (renameCommitted && committedNewName) { @@ -2815,7 +2817,7 @@ export const webviewMessageHandler = async ( vscode.window.showErrorMessage(t("common:errors.rename_api_config")) // The repair failure is rethrown only after the user has been told: the dispatch - // wrapper still sees the rejection (it rethrows at ClineProvider.ts line 2834), + // wrapper still sees the rejection (it rethrows at ClineProvider.ts:2872 at 01ea0ffdaa), // and the log plus the notification above are what the user gets either way. if (selectionRepairFailure) { throw selectionRepairFailure.error From 633bc039c3be47c0866091cd006b6995536c3271 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:35:24 +0800 Subject: [PATCH 21/34] show the rename error before awaiting its queued repair [cr 4751099445] Review 4751099445: "If activation times out but never settles, the repair waits behind it without a deadline. Line 2816 never shows the rename error. Show the error before awaiting the repair. Keep the repair queued and report its result separately." What changed - The rename's log line and its error notification were the last things the catch wrote, after the awaited repair. Measured at d26b39fd06 they sat at webviewMessageHandler.ts:2814-2818, below the await at 2810; at the bytes this review saw (01ea0ffdaa) the notification was line 2816. The repair is queued behind the mutation that timed out, so that await has no ceiling until the repair's own write begins: a repair that never reaches its turn leaves the catch parked and the user shown nothing. Both statements now run before the repair is asked for. The rethrow, the repair request, and the queue that carries it are untouched, so the repair is still queued and its failure is still reported on its own log line and to the dispatch. - The three timeout log sentences from the previous commit were not touched: the caller-deadline sentence, the abort sentence on the default path, and the runToCompletion sentence each still appear exactly once. - New row in webviewMessageHandler.spec.ts, "shows the rename error before awaiting a repair that has not begun": activation rejects, the repair is asked for and never answers (no resolution, no rejection), and the row asserts the notification and the rename's log line while the dispatch is recorded as still pending. Then the repair rejects, and the row asserts the dispatch rejection plus the repair's own failure line. The settle state is recorded rather than awaited, so a missing notification reads as a wrong recorded value instead of a hung test. Evidence (Node-run columns; predictions written in the gate scratch before each pass and reported against the readings, with no retrofit) - Move alone, committed rows only (the new row absent): 192 passed, 0 failed. No committed row pins the notification/repair order, so this is the control that shows any red below comes from the new row and not from the move. - New row against the previous production bytes: 1 failed, first red at webviewMessageHandler.spec.ts:3674 - the notification assertion. Predicted 1 failed at 3674 before the run; read the same. The filtered form (this row only) reads 1 failed | 192 skipped at the same line, and with the new production bytes it reads 1 passed | 192 skipped: the row is the only carrier, and it is red exactly where the reviewer's symptom lives. - Whole file at the new bytes: 193 passed, 0 failed. - Comment-only control: deleting the 14 new production comment lines and the 22 new spec comment lines still reads 193 passed. With the order reverted as well, the same control moves the first red from 3674 to 3655 - the 19 new comment lines it deleted above the assertion. Predicted and read the same. - Named mutants: revert-to-await-first (move the two statements back below the await) - predicted 1 failed at 3674, read 1 failed at 3674. drop-the- await (await becomes void) - predicted 3 failed, read 3 failed: 3676 in this row (expected 'settled' to be 'pending'), 3582 in "notifies the user when the queued shared-selection repair itself rejects" (escaped stays undefined) and 3612 in "keeps the repair failure visible to the message dispatch after notifying the user" (promise resolved instead of rejecting). The latter two are committed rows: they pin the await and the rethrow, and they go red only when those are removed. - No row depends on a platform, a skip predicate, the file system, symlinks, permissions, Date.now, a real setTimeout, or vitest's default timeout. - Gates (14 steps): format-check, check-types, src-tsc, root-lint, src-lint, code-qa-ci, translations-check, knip, knip-production, lifecycle:model-check and mcp:integration-check all exit 0. test:core: 224 files, 5490 passed and 17 skipped (5507) - one more test than the previous commit, which is this row, so CI's own suite count confirms the row runs there; test:misc: 122 files, 2589 passed and 13 skipped, unchanged. EnvironmentTeardownError and "Closing rpc while" appear 0 times in both logs, and 0 times in every column log above. test:services remains red exactly as before this commit: 5 failed and 5872 passed over 84 files, one file red (services/rules/__tests__/ rules.spec.ts, symlink EPERM on Windows), which is the standing failure this chain has carried since before the first cell. - The filtered form alongside it: this row alone reads 1 passed and 192 skipped at the new bytes and 1 failed and 192 skipped at the previous production bytes; the whole spec file reads 193 passed. - eslint --prune-suppressions on both touched files exits 0 and rewrites only the JSON's indentation (tabs to two spaces); all 261 entries and the total of 2841 suppressed counts are identical, with no increase and none removed. The file was restored to the committed blob and verified at 1fad7b0e65fe. Disclosures - The first pass of the battery ran this row with vitest fake timers, and when the row went red before reaching vi.useRealTimers() it left fake timers installed for the two kimiCodeSignIn rows that follow it in the same file, which then failed with "Test timed out in 20000ms". Predicted collateral: none. Read: 2. The filtered form of the same run showed no collateral, which identified the cause as timer state rather than the assertion. The row now drains with the shared setImmediate helper already used across src tests (src/test-utils/timers.ts, flushMacrotasks) and installs no timers at all; pass 2 re-ran the whole battery, with its predictions written before that pass, and every prediction above is a pass-2 reading. Pass 1 is reported as run and is not revised here. - Pass 1 also mis-predicted one line number: for "keeps the repair failure visible to the message dispatch" it named the statement's opening line (3605) while vitest reports the rejection assertion on the ").rejects. toThrow(...)" line (3611 then, 3612 now). Reported as measured. - Not addressed here: review 4751099445's note that the repair waits without a deadline. The bound on that path is the subject of the previous commit; this commit changes only what the user is told and when. --- .../__tests__/webviewMessageHandler.spec.ts | 75 +++++++++++++++++++ src/core/webview/webviewMessageHandler.ts | 32 ++++---- 2 files changed, 93 insertions(+), 14 deletions(-) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index dc85880e3c5..38008ab5343 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -90,6 +90,7 @@ import { flushModels, getModels } from "../../../api/providers/fetchers/modelCac import { getLMStudioModels } from "../../../api/providers/fetchers/lmstudio" import { getCommands } from "../../../services/command/commands" import { ensureDcgInstalled } from "../../../services/destructive-command-guard" +import { flushMacrotasks } from "../../../test-utils/timers" import { handleCreateRule, handleDeleteRule, @@ -3611,6 +3612,80 @@ describe("webviewMessageHandler - renameApiConfiguration", () => { ).rejects.toThrow("repair write rejected") }) + it("shows the rename error before awaiting a repair that has not begun", async () => { + // Review cid 4751099445: "If activation times out but never settles, the repair waits + // behind it without a deadline. Line 2816 never shows the rename error. Show the error + // before awaiting the repair. Keep the repair queued and report its result separately." + // The quoted line is webviewMessageHandler.ts:2816 at 01ea0ffdaa - the notification, which + // sat below the repair await. The repair is asked for behind the mutation that timed out, + // so this await has no ceiling until that write begins: a repair that never reaches its + // turn leaves the handler parked, and everything written after the await - the rename log + // and the notification with it - is never reached. The double below never settles, so the + // row sees that state directly instead of inferring it from a timeout. The drains below + // use the shared setImmediate helper, so the row touches no timer state: a failed + // assertion here cannot leave fake timers installed for the rows that run after it, and + // nothing here depends on the wall clock, the file system, or vitest's default timeout. + provider.providerSettingsManager = { + runExclusiveAcrossInstances, + hasConfig: vi.fn().mockResolvedValue(false), + getProfile: vi.fn().mockResolvedValue({ id: "profile-id", apiProvider: providerIdentifiers.anthropic }), + saveConfig: vi.fn().mockResolvedValue(undefined), + deleteConfig: vi.fn().mockResolvedValue(undefined), + } + provider.repointViewLocalStateAfterProfileRename = vi.fn().mockResolvedValue(undefined) + provider.activateProviderProfile = vi.fn().mockRejectedValue(new Error("activation timed out")) + // Asked for and never answered: no resolution, no rejection. That is what a repair still + // queued behind an unsettled mutation looks like from the caller's side. + let settleRepair!: (outcome: "settled" | "rejected") => void + const repair = vi.fn( + () => + new Promise((resolve, reject) => { + settleRepair = (outcome) => { + if (outcome === "settled") { + resolve() + return + } + reject(new Error("repair write rejected")) + } + }), + ) + provider.enqueueSharedProfileSelectionRepair = repair + const dispatch = webviewMessageHandler(mockClineProvider, { + type: "renameApiConfiguration", + values: { oldName: "old-profile", newName: "new-profile" }, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + }) + // The settle state is recorded rather than awaited, so a notification that never arrived + // reads as a failed assertion here instead of a hung test. + let dispatchState = "pending" + void dispatch.then( + () => { + dispatchState = "settled" + }, + () => { + dispatchState = "rejected" + }, + ) + await flushMacrotasks() + // The handler has reached its await: the repair was requested once, the user has already + // been told the rename failed, and the rename's own error line is already in the log - + // while the dispatch is still parked on a repair that has not begun. + expect(repair).toHaveBeenCalledTimes(1) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("common:errors.rename_api_config") + expect(mockClineProvider.log).toHaveBeenCalledWith(expect.stringContaining("Error rename api configuration:")) + expect(dispatchState).toBe("pending") + // The repair answers late, and badly. The user was told already, so the rejection is free + // to travel on its own channel: that is where the message dispatch learns the shared + // selection never landed, and the repair's own failure line is logged next to it. + settleRepair("rejected") + await flushMacrotasks() + await expect(dispatch).rejects.toThrow("repair write rejected") + expect(dispatchState).toBe("rejected") + expect(mockClineProvider.log).toHaveBeenCalledWith( + expect.stringContaining("Shared profile selection repair failed after rename:"), + ) + }) + it("re-points views with the stored record instead of the raw webview payload", async () => { provider.providerSettingsManager = { runExclusiveAcrossInstances, diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6ef4db80d83..c9cc10f770a 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -2776,13 +2776,21 @@ export const webviewMessageHandler = async ( // transaction committed - oldName already deleted, views and tasks already // re-pointed - so this branch takes the second shape: the rename stands and the // shared selection is moved onto the stored name instead of left on the deleted one. + // The rename is reported before anything else in this catch is awaited - review cid + // 4751099445. The repair below is queued behind the mutation that timed out, so this + // catch cannot assume that await returns: a repair that never reaches its turn leaves + // the handler parked, and a notification written after that await is never shown. + provider.log( + `Error rename api configuration: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, + ) + vscode.window.showErrorMessage(t("common:errors.rename_api_config")) // The repair has a failure of its own to report, and reporting it must not cost the - // user the rename notification: the failure is recorded here, the log and the - // notification below still run, and the rejection is rethrown once they have. A - // silent catch would leave the message dispatch (ClineProvider.ts onReceiveMessage, - // at rethrowing its failure; ClineProvider.ts:2872 at 01ea0ffdaa) never seeing a repair - // that did not land - review cid 4750230092 asks that this stays - // visible to the caller as well as to the user. + // user the notification above: the failure is recorded here, logged on its own line, + // and rethrown once the user has been told. A silent catch would leave the message + // dispatch (ClineProvider.ts onReceiveMessage, at rethrowing its failure; + // ClineProvider.ts:2872 at 01ea0ffdaa) never seeing a repair that did not land - + // review cid 4750230092 asks that this stays visible to the caller as well as to the + // user. let selectionRepairFailure: { error: unknown } | undefined if (renameCommitted && committedNewName) { // Review cid 4746979132: the activation above runs with runToCompletion, so a @@ -2811,14 +2819,10 @@ export const webviewMessageHandler = async ( ) } } - provider.log( - `Error rename api configuration: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, - ) - - vscode.window.showErrorMessage(t("common:errors.rename_api_config")) - // The repair failure is rethrown only after the user has been told: the dispatch - // wrapper still sees the rejection (it rethrows at ClineProvider.ts:2872 at 01ea0ffdaa), - // and the log plus the notification above are what the user gets either way. + // Rethrown because the notification is not the whole report: the dispatch wrapper + // rethrows its own failure (ClineProvider.ts:2872 at 01ea0ffdaa) and that is how a + // caller learns the shared selection never landed. The user was told above, so + // rethrowing here cannot cost them that notification. if (selectionRepairFailure) { throw selectionRepairFailure.error } From d6edcc76f2f998a13ee493769ca0cb657c769a59 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:00:05 +0800 Subject: [PATCH 22/34] webview: record view-state evictions only after the write lands The retention prune now runs inside the write's protection in the pin, re-pin and re-key paths, and the eviction list is appended only after setValue("viewStates", kept) resolves, so the rollback list can only name entries that a landed write really dropped. The tombstone cell established the same ordering for the clear claims; this applies it to the eviction list that an activation rollback reads. Review 4751662055 asked for the record to follow the write. The row that pins it asserts provider["prunedViewIdsDuringActivation"] directly as well as the end-to-end rollback, and the reason for that switch belongs in the record: the rollback gate skips a view id that is still present in the map, so after a rejected write the entry is back in the map and the rollback path cannot tell a recorded eviction from an unrecorded one (measured, not inferred). The rollback story is asserted too, in its own row; the two assertions are reported side by side rather than one standing in for the other. Review 4751662046 asked for mixed input plus an assertion on the whole output: the corrupt-entry rows assert the complete stored map after the failure, not only the entry that failed to read, and the re-point row compares the rollback list against every key the store actually lost rather than against a hand-written id. Review 4751662065 asked what a corrupt stored entry should do. It keeps throwing out of the prune, and now leaves the tombstone claim restored instead of half-applied over a store that never changed. The consequence is stated rather than softened: such an entry still fails every later write, exactly as before - only the stray claim is gone. A null row written through contextProxy.setValue never reaches the prune, because that write itself resolves; seeding it that way would not represent an entry that was already stored (measured), so the row mutates the same map object in place and puts the entry back afterwards. Moving the re-point prune inside its try was measured as equivalent - no tombstone claim and no durable write precede the throw - so only the record moved there, and the hoisted-prune variant was run as a probe: it came back with zero reds, which is reported as a null result rather than as coverage. This commit also strengthens the tombstone cell's row ("restores an entry an evicting activation pruned when the save that un-pinned it was rejected", spec 8637-8723): the seed now stops one entry below the cap so the pin write is the growth that has to evict exactly one, that pin write no longer carries a mode (a rolled-back mode would have let the whole-map assertion pass on state no user asked for), and the row asserts the stored length right after the landed write and the complete restored map after the rollback instead of two fragments of it. The eight tombstone mutants were re-run against these bytes and all eight still turn a tombstone row red. Four new rows, that one strengthened row, and no other existing row. Named mutants (record before the write, prune outside the try, cap off by one, save never records) each turn the matching row red at the position recorded in the run log. Removing only the added comment lines changes no verdict, and with the record-before-write mutant the first red sits exactly as many lines lower as there are added comment lines above it (30 lines), which is the arithmetic check on the comment-only control. [cr 4751662046] [cr 4751662055] [cr 4751662065] --- src/core/webview/ClineProvider.ts | 58 +++-- .../webview/__tests__/ClineProvider.spec.ts | 209 +++++++++++++++++- 2 files changed, 241 insertions(+), 26 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index f5b1fa5191b..e5d76600670 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -623,8 +623,10 @@ export class ClineProvider /** * View ids evicted from the durable viewStates map by this instance's writes - * since the last activation snapshot: the rollback restores exactly these - * entries, so a sibling's intentional pin clear is never resurrected. + * since the last activation snapshot, recorded only once the write that dropped + * them has landed: the rollback restores exactly these entries, so a sibling's + * intentional pin clear is never resurrected, and neither is an eviction whose + * store rejected. */ private prunedViewIdsDuringActivation: string[] = [] @@ -976,14 +978,22 @@ export class ClineProvider wroteEntry = true } - const pruned = this.prunePersistedViewStates(states) - const evicted = Object.keys(states).filter((viewId) => !Object.hasOwn(pruned, viewId)) - if (evicted.length > 0) { - this.prunedViewIdsDuringActivation.push(...evicted) - } - try { - await this.contextProxy.setValue("viewStates", pruned) + // The retention prune reads every entry it is about to hand to the store, so a + // stored entry the sort cannot read (a null value) throws here rather than + // reaching the write. Computing the pruned map inside this try is what keeps the + // tombstone claim above and the snapshot restore below in step with a store that + // such a throw leaves untouched. + const kept = this.prunePersistedViewStates(states) + const evicted = Object.keys(states).filter((viewId) => !Object.hasOwn(kept, viewId)) + await this.contextProxy.setValue("viewStates", kept) + // Retention is recorded for the map the store actually took. The catch below + // undoes the tombstone claim this call made, so an eviction that never committed + // must not join the list either: this instance's rollback then restores only what + // one of its landed writes really evicted. + if (evicted.length > 0) { + this.prunedViewIdsDuringActivation.push(...evicted) + } } catch (error) { // The durable map still holds what this write tried to change, so the tombstone // has to say what it said before the attempt: the clear branch's add comes off, @@ -1100,12 +1110,16 @@ export class ClineProvider if (changed) { const pruned = this.prunePersistedViewStates(states) const evicted = Object.keys(states).filter((viewId) => !Object.hasOwn(pruned, viewId)) - if (evicted.length > 0) { - this.prunedViewIdsDuringActivation.push(...evicted) - } - try { await this.contextProxy.setValue("viewStates", pruned) + // Same rule as the pin write and the re-key: an eviction joins the list only + // with the write that dropped it, so a re-point whose store rejected leaves this + // activation's rollback nothing it did not really do. The prune stays where it + // is - this site makes no tombstone claim and no write precedes the throw, so + // moving it inside would be provably equivalent. + if (evicted.length > 0) { + this.prunedViewIdsDuringActivation.push(...evicted) + } } catch (error) { // A rejected write leaves the in-memory map holding the attempted value, so the // compensation must come from the snapshot taken before this write mutated @@ -1187,14 +1201,18 @@ export class ClineProvider movedToNext = true } - const pruned = this.prunePersistedViewStates(states) - const evicted = Object.keys(states).filter((viewId) => !Object.hasOwn(pruned, viewId)) - if (evicted.length > 0) { - this.prunedViewIdsDuringActivation.push(...evicted) - } - try { - await this.contextProxy.setValue("viewStates", pruned) + // As in the pin write: the prune runs inside the protection, so a stored entry + // the sort cannot read leaves the two tombstone claims below restored instead + // of half-applied over a store that never changed. + const kept = this.prunePersistedViewStates(states) + const evicted = Object.keys(states).filter((viewId) => !Object.hasOwn(kept, viewId)) + await this.contextProxy.setValue("viewStates", kept) + // The catch below puts both tombstone claims back, so an eviction this write + // only attempted stays out of the list too. + if (evicted.length > 0) { + this.prunedViewIdsDuringActivation.push(...evicted) + } } catch (error) { // Neither tombstone claim survives a write that never landed: the temporary id // goes back to whatever it claimed before this call, and the stable id only comes diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 9fa8c775405..5373ca1890e 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -8654,7 +8654,11 @@ describe("ClineProvider", () => { // The sibling view's pin, and the oldest entry: the row's pin write prunes it. "tomb-a-view": { mode: "architect", currentApiConfigName: "tomb-a-profile", updatedAt: 0 }, } - for (let i = 1; i <= 50; i++) { + // The cap is 50 entries (ClineProvider.ts:MAX_PERSISTED_VIEW_STATES at 633bc039c3), and + // a save never leaves the map over it, so this fixture starts exactly at the cap: + // the pin write below is then the growth that has to evict one entry, and an entry + // that survives that eviction is a store that stopped pruning one entry late. + for (let i = 1; i <= 49; i++) { seeded["tomb-fill-" + i] = { mode: "code", updatedAt: i } } await provider.contextProxy.setValue("viewStates", seeded) @@ -8681,21 +8685,33 @@ describe("ClineProvider", () => { // The activation snapshot is taken now, while the pin is still stored. const snapshot = provider["_snapshotProfileActivationState"]() - // This view's own pin write lands and evicts the two oldest entries; only the - // pin matters below, the filler is the control that the rollback itself ran. + // Only the profile pin is written: an activation that also carried a mode would + // bring that mode back through the rollback, and the whole-map assertion below + // could then match a map holding state no user asked for. await provider["savePersistedViewState"]({ - mode: "code", currentApiConfigName: "new-profile", updatedAt: 9001, }) + // The write lands, so the growth has to evict exactly the oldest entry - the + // sibling pin - and hold the map at the cap. + const prunedAfterWrite = provider.contextProxy.getValue("viewStates") as Record + expect(Object.keys(prunedAfterWrite)).toHaveLength(50) + expect(prunedAfterWrite["tomb-a-view"]).toBeUndefined() + // The group then fails, so the rollback is what has to bring the pin back. await provider["_restoreProfileActivationState"](snapshot) const restored = provider.contextProxy.getValue("viewStates") as Record + // The whole map, not a fragment of it: the 49 fillers untouched, the sibling pin + // back with its own metadata, and this view's own entry gone again because the + // rollback restores the pin this view did not have before the group. Anything the + // rollback leaves behind - a stale mode, a second pin, an entry that outlived the + // cap - fails this assertion instead of passing unnoticed. + expect(restored).toEqual(seeded) + // The filler a cap of 51 would have spared is the control that the eviction really + // ran; the claim assertion below is the half the rollback gate reads. expect(restored["tomb-fill-1"]).toEqual({ mode: "code", updatedAt: 1 }) - // The evicted pin is back in the restored map with its own metadata - the row's - // claim assertion below is the half that the rollback gate actually reads. expect(restored["tomb-a-view"]).toEqual({ mode: "architect", currentApiConfigName: "tomb-a-profile", @@ -8874,6 +8890,187 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("records an eviction only after the write that made it has landed", async () => { + // Review cid 4751662055: prunedViewIdsDuringActivation is the list this instance's + // profile-activation rollback restores from, so an id may join it only once a store + // has taken the map that dropped it. The rollback path itself cannot show the + // difference - the gate at ClineProvider.ts skips an id that is still in the map, so a + // claim made by a write whose store rejected is skipped either way (measured) - and the + // assertion is therefore about the list itself, read through bracket notation. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("u1-stable") + const seeded: Record = { + // The oldest entry: the pin write below is the growth that has to evict it. + "u1-old": { mode: "code", currentApiConfigName: "u1-old-profile", updatedAt: 1 }, + } + // The cap is 50 entries (ClineProvider.ts:MAX_PERSISTED_VIEW_STATES at 633bc039c3), so + // this fixture starts exactly at it and the write below is the growth that evicts one. + for (let i = 2; i <= 50; i++) { + seeded["u1-fill-" + i] = { mode: "code", updatedAt: i } + } + await provider.contextProxy.setValue("viewStates", seeded) + const storeFailure = vi.spyOn(mockContext.globalState, "update").mockImplementation(async () => { + throw new Error("durable pin write failed") + }) + await expect( + provider["savePersistedViewState"]({ currentApiConfigName: "u1-profile", updatedAt: 9001 }), + ).rejects.toThrow("durable pin write failed") + storeFailure.mockRestore() + // The rejected attempt is read from the durable store, not from this instance's cache: + // what a rejection leaves in that cache is the Memento's business, while the list below + // is about whether an eviction that never landed got recorded. + const afterReject = mockContext.globalState.get("viewStates") as Record + // The rejected write changed nothing stored: the map is still at the cap and still + // holds the entry its prune had already dropped, so there is no eviction on record. + expect(Object.keys(afterReject)).toHaveLength(50) + expect(afterReject["u1-old"]).toEqual(seeded["u1-old"]) + expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) + // The control: once a write really lands, the eviction it made does join the list, so + // the empty list above is the rejected write and not a list that never records. + await provider["savePersistedViewState"]({ currentApiConfigName: "u1-profile-2", updatedAt: 9002 }) + const afterLand = provider.contextProxy.getValue("viewStates") as Record + expect(Object.keys(afterLand)).toHaveLength(50) + expect(afterLand["u1-old"]).toBeUndefined() + expect(provider["prunedViewIdsDuringActivation"]).toEqual(["u1-old"]) + await provider.dispose() + }) + + it("restores the tombstone claim when the retention prune itself throws", async () => { + // Review cid 4751662065: the retention prune reads every stored entry it is about to + // hand over, so an entry the sort cannot read throws before anything reaches the + // store. Running it inside the same protection as the write is what keeps the + // tombstone this call made from surviving a throw that changed nothing stored. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("u2-view") + const seeded: Record = { + "u2-view": { mode: "code", currentApiConfigName: "u2-profile", updatedAt: 1 }, + "u2-fill": { mode: "code", updatedAt: 2 }, + } + await provider.contextProxy.setValue("viewStates", seeded) + // The corrupt entry is put into the very map object the next fresh read returns: one + // seeded through contextProxy.setValue would be dropped on the way in, so it would not + // stand for an entry that is already stored (measured before writing this row). + const stored = mockContext.globalState.get("viewStates") as Record + stored["u2-broken"] = null + ClineProvider["clearedViewStateIds"].delete("u2-view") + await expect( + provider["savePersistedViewState"]({ mode: undefined, currentApiConfigName: undefined }), + ).rejects.toThrow(TypeError) + // The tombstone this call added is undone, because no store ever took the change it + // came from; a kept claim would tell the rollback gate the entry is gone while it is + // still in the map below. + expect(ClineProvider["clearedViewStateIds"].has("u2-view")).toBe(false) + const restored = mockContext.globalState.get("viewStates") as Record + expect(restored).toEqual({ ...seeded, "u2-broken": null }) + await provider.dispose() + }) + + it("restores both tombstone claims when the retention prune throws during a re-key", async () => { + // The same throw class, this time on the re-key, which moves two tombstones at once: + // it claims the temporary id is gone and un-claims the stable id the entry moves onto. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const temporaryViewStateId = provider["viewId"] + const seeded: Record = { + [temporaryViewStateId]: { mode: "code", currentApiConfigName: "u2b-profile", updatedAt: 1 }, + "u2b-fill": { mode: "code", updatedAt: 2 }, + } + await provider.contextProxy.setValue("viewStates", seeded) + const stored = mockContext.globalState.get("viewStates") as Record + stored["u2b-broken"] = null + // clearedViewStateIds is process-level and this suite has no reset helper for it, so + // both ids are normalized to a known membership: the assertions are about this row. + ClineProvider["clearedViewStateIds"].delete(temporaryViewStateId) + ClineProvider["clearedViewStateIds"].delete("u2b-stable") + provider["wroteUnderTemporaryViewStateId"] = true + await expect(provider["rekeyPersistedViewStateEntry"]("u2b-stable")).rejects.toThrow(TypeError) + expect(ClineProvider["clearedViewStateIds"].has(temporaryViewStateId)).toBe(false) + expect(ClineProvider["clearedViewStateIds"].has("u2b-stable")).toBe(false) + const restored = mockContext.globalState.get("viewStates") as Record + expect(restored).toEqual({ ...seeded, "u2b-broken": null }) + await provider.dispose() + }) + + it("records a re-point eviction only after the re-point write has landed", async () => { + // Review cid 4751662055 on the profile re-point, which re-stamps every entry that + // carried the removed profile name. The map here is stored one entry over the cap - + // the state a write whose store rejected leaves behind - so the prune that answers this + // re-point drops the oldest filler, and only a landed re-point may record that. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("u4-stable") + const seeded: Record = { + // The two entries the re-point re-stamps, so both move above every filler. + "u4-view-a": { mode: "code", currentApiConfigName: "u4-removed", updatedAt: 7 }, + "u4-view-b": { mode: "code", currentApiConfigName: "u4-removed", updatedAt: 8 }, + } + for (let i = 2; i <= 51; i++) { + seeded["u4-fill-" + i] = { mode: "code", updatedAt: i } + } + await provider.contextProxy.setValue("viewStates", seeded) + // Registering the view persists this view's own entry, so the length this row compares against is + // the stored length taken here, not a hand-counted constant. + const keysBefore = Object.keys(mockContext.globalState.get("viewStates") as object).length + const storeFailure = vi.spyOn(mockContext.globalState, "update").mockImplementation(async () => { + throw new Error("durable re-point failed") + }) + await expect(provider["repointPersistedViewStates"]("u4-removed", "u4-replacement")).rejects.toThrow( + "durable re-point failed", + ) + storeFailure.mockRestore() + // Read from the store, not from this instance's cache: the cache carries what the + // Memento applied to it, and a rejection there says nothing about which entries storage + // ever lost, so it is the eviction list below that this row is checking. + const afterReject = mockContext.globalState.get("viewStates") as Record + // Nothing moved: the rejected re-point left the over-cap map exactly as stored, so the + // attempt has no eviction to have recorded. + expect(Object.keys(afterReject)).toHaveLength(keysBefore) + expect(afterReject["u4-view-a"]).toEqual(seeded["u4-view-a"]) + expect(afterReject["u4-fill-2"]).toEqual(seeded["u4-fill-2"]) + expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) + await provider["repointPersistedViewStates"]("u4-removed", "u4-replacement") + const afterLand = provider.contextProxy.getValue("viewStates") as Record< + string, + { currentApiConfigName?: string } + > + // The landed re-point is the growth that takes the stored map over the cap, and the cap + // then answers by dropping u4-fill-2: the map comes back to the cap of 50 and that eviction + // is what joins the rollback list - and only that one. + expect(Object.keys(afterLand)).toHaveLength(50) + expect(afterLand["u4-fill-2"]).toBeUndefined() + expect(afterLand["u4-view-a"].currentApiConfigName).toBe("u4-replacement") + // The rollback list has to hold exactly the entries storage actually lost in this write - the + // oldest fillers are the ones the cap drops here, and naming them by hand would hide a prune that + // dropped something else. + const droppedKeys = Object.keys(afterReject).filter((viewId) => !Object.hasOwn(afterLand, viewId)) + expect(droppedKeys.length).toBeGreaterThan(0) + expect(droppedKeys).toContain("u4-fill-2") + expect(provider["prunedViewIdsDuringActivation"]).toEqual(droppedKeys) + await provider.dispose() + }) + it("re-points live views pinned to a renamed profile onto the new name", async () => { const provider = new ClineProvider( mockContext, From 007ba09a95e1d910f69fa36b6d84f9f189192c25 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:27:35 +0800 Subject: [PATCH 23/34] task: build the api handler before the new settings take effect Task.updateApiConfiguration assigned the new settings before building the handler, so a handler constructor that rejects those settings left the task reporting a profile it was not running: the assignment had already happened, the handler had not changed, and nothing was queued for release. Construction now runs first, and the settings, the handler and the hand-off of the previous handler all move only after it returns. Review 4747813720 describes the rename case. An Azure AI Inference base URL together with openAiUseResponsesApi is accepted by the settings schema and rejected by the handler constructor (src/api/providers/openai.ts:101-105; _isAzureAiInference at :786 treats a services.ai.azure.com host that is not an /openai/v1 base URL as Azure AI Inference). Renaming the profile then fails inside the rebuild that updateTaskApiHandlerIfNeeded does for a task bound to the renamed profile (ClineProvider.ts:4528), before that task's sticky profile name is written at :4530, and the rename's reverse pass re-points tasks through that sticky name (webviewMessageHandler.ts:2734 and :2755 into ClineProvider.ts:4495-4498), so a task whose rebuild threw is skipped there and nothing downstream repairs the mismatch. Each part was checked against the current code rather than taken from the comment: the assignment order was as described (Task.ts:2571-2572 at the parent), the constructor does reject that combination, and the sticky-name skip is real. The comment's own coordinates are stale - ClineProvider.ts:4229 in its base sits inside the activation write block, not at the code it describes - and the behavior lives in Task.ts, so the fix is there and no caller was touched. updateTaskApiHandlerIfNeeded's no-rebuild branch only assigns settings, which is the half that cannot fail construction, and stays as it was. The new row also pins the halves that must survive a failed switch. The handler identity and the release queue are observed while API work is leased, because an idle task disposes a replaced handler at once and there the queue cannot be told apart from never having been queued. The companion row pins the other half - after a construction that succeeds, handler and settings both move - because without it a change that built the handler and installed neither half would pass as well. Reported rather than smoothed over: no existing row pinned this consequence, and no provider-level row was added - the divergence is decided inside Task.updateApiConfiguration, and at the provider layer the same fact is only reachable through a handler constructor that the rename tests mock. Five named mutants were run: order restored, rejected settings left installed on failure, previous handler queued for release before construction, settings installed without the handler, and handler installed without the settings. The first two turn the failed-switch row red at the settings-preservation assertion, the third turns the release-queue assertion red in both new rows plus the pre-existing idle-dispose row, and the last two turn the success row red - the handler mutant additionally kills twelve pre-existing handler-lifecycle rows. [cr 4747813720] --- src/core/task/Task.ts | 12 ++++- src/core/task/__tests__/Task.spec.ts | 76 ++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 1 deletion(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index e2e25ef93da..4400ea582ff 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -2568,8 +2568,18 @@ export class Task extends EventEmitter implements TaskLike { // released — immediately when idle, or when the last request, retry, // background drain, or condense that leased it settles. const previousApi = this.api + // Construction first. A handler constructor can reject settings the profile schema + // accepts - an Azure AI Inference base URL together with openAiUseResponsesApi is + // one - and a task that keeps running on its old handler must not end up reporting + // settings that no handler was ever built for. The profile-mutation rollback + // re-points a renamed task through its sticky profile name, and a task whose rebuild + // threw before that name was written is skipped by that reverse pass, so nothing + // downstream would undo a settings half this call had already assigned. Until + // construction returns this method touches neither the settings, nor the handler, + // nor the release queue. + const nextApi = buildApiHandler(newApiConfiguration) this.apiConfiguration = newApiConfiguration - this.api = buildApiHandler(this.apiConfiguration) + this.api = nextApi this.retireApi(previousApi) // Refresh only the soft tool-repetition limit from the new profile so an diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 5438453c2cf..7eae3385478 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -1789,6 +1789,82 @@ describe("Cline", () => { }) describe("updateApiConfiguration", () => { + it("keeps the previous handler and settings when a profile switch fails at handler construction", async () => { + // Review cid 4747813720: the profile schema accepts an Azure AI Inference base URL + // together with the responses API, while the openai handler constructor rejects that + // combination. The reviewer's rename case is this failure followed by a rollback + // whose reverse pass skips the task, because the sticky profile name never moved to + // the new name - so the only thing that can leave the task consistent is this method + // not having touched anything yet. + const initialSettings: ProviderSettings = { + ...mockApiConfig, + apiProvider: providerIdentifiers.openai, + openAiModelId: "gpt-4o-mini", + openAiBaseUrl: "https://example.services.ai.azure.com", + openAiApiKey: "azure-key", + openAiUseResponsesApi: false, + } + const cline = new Task({ + provider: mockProvider, + apiConfiguration: { ...initialSettings }, + task: "test task", + startTask: false, + }) + const handlerBefore = cline["api"] + const settingsBefore = cline.apiConfiguration + const softLimitBefore = cline.toolRepetitionSoftLimit + // Premise: as stored the profile builds, and it says no responses api. + expect(cline.apiConfiguration.openAiUseResponsesApi).toBe(false) + const rejectedSettings: ProviderSettings = { ...settingsBefore, openAiUseResponsesApi: true } + // In-flight work is what makes the release queue observable: an idle task + // disposes a replaced handler at once, so only while work is leased can a handler + // queued for release be told apart from one that was never queued at all. + const endOfApiWork = cline["beginApiWork"]() + expect(() => cline.updateApiConfiguration(rejectedSettings)).toThrow(/\/openai\/v1 base URL/) + expect([...cline["retiredApis"]]).toEqual([]) + endOfApiWork() + // The whole settings object, not the flag: a task that keeps the handler that + // rejected this profile must not report the switched profile's settings at all. + expect(cline.apiConfiguration).toEqual(settingsBefore) + expect(cline["api"]).toBe(handlerBefore) + // The soft tool-repetition limit is refreshed only by a switch that took effect, + // so it stays where the stored profile put it. + expect(cline.toolRepetitionSoftLimit).toBe(softLimitBefore) + await cline.dispose() + }) + + it("installs the new handler and the new settings together when construction succeeds", async () => { + // The other half of the same rule: once construction returns, both halves move. + // Without this row the change would also pass for a variant that builds the handler + // first and then installs neither half. + const initialSettings: ProviderSettings = { + ...mockApiConfig, + apiProvider: providerIdentifiers.openai, + openAiModelId: "gpt-4o-mini", + openAiBaseUrl: "https://example.services.ai.azure.com", + openAiApiKey: "azure-key", + openAiUseResponsesApi: false, + } + const cline = new Task({ + provider: mockProvider, + apiConfiguration: { ...initialSettings }, + task: "test task", + startTask: false, + }) + const handlerBefore = cline["api"] + const settingsBefore = cline.apiConfiguration + const softLimitBefore = cline.toolRepetitionSoftLimit + const nextSettings: ProviderSettings = { ...settingsBefore, openAiModelId: "gpt-4o" } + cline.updateApiConfiguration(nextSettings) + expect(cline["api"]).not.toBe(handlerBefore) + expect(cline.apiConfiguration).toEqual(nextSettings) + expect(cline.apiConfiguration.openAiModelId).toBe("gpt-4o") + // With no work leased, the replaced handler is released at once, so nothing is left + // queued behind it. + expect([...cline["retiredApis"]]).toEqual([]) + expect(cline.toolRepetitionSoftLimit).toBe(softLimitBefore) + await cline.dispose() + }) it("refreshes the soft limit but preserves the task-level hard limit when the provider profile changes", () => { const cline = new Task({ provider: mockProvider, From 775eb413cef0ad2672435c55c3fecda9e3ab058a Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:54:54 +0800 Subject: [PATCH 24/34] webview: restore evicted view entries with their last value Review 4751662076 asks that the profile-activation rollback restore each entry the retention prune evicted with the value it held immediately before the eviction, not the value the activation snapshot captured, and that the existing skip for an entry with a clear tombstone stay as it is. Both halves were checked against the current code before anything was changed. The restore used to read snapshot.viewStates[viewId]. That map was a copy taken when activation started, while the durable viewStates map is shared: the viewStates write queue is per instance (ClineProvider.ts:321 at 007ba09a95), so another view keeps writing into the same map while an activation group is in flight. When this view's own pin write then took the stored map over the retention cap and the group failed, the rollback put the entry back as it had been before activation and dropped the write the other view had already committed. An eviction now carries the entry it dropped. prunedViewEntriesDuringActivation holds, per view id, the entry exactly as the prune saw it in the map it handed to the store, and the same landed write that records the id records the value. The rollback restores that value. The activation snapshot no longer copies the durable map at all, because a copy taken at the start can only ever be older than the eviction it is meant to undo. This is not Cell U's finding and the two must not be read as one answer. Cell U (4751662055, landed in d6edcc76f2) is about WHEN an eviction may be recorded: only after the store took the map that dropped it. This cell is about WHICH value the record carries once the eviction is on record. Neither answer implies the other, and each was measured against the other: the new rows keep Cell U's id-list assertions green, and Cell U's rows stay green under this change (whole file 540 passed). The record-after-landing boundary was probed once more from this side, and it still belongs to Cell U: recording the eviction before the store write turns the existing pin-write row at ClineProvider.spec.ts:8933 red and leaves the re-point row green, because that mutant only moved the pin-write site. The tombstone skip is preserved, and pinned through the new path rather than only next to it. The second row lets the cap evict an entry, records the value that eviction dropped, lets the owning view clear its own view for real, and then checks that the rollback still leaves the entry out of the map. Dropping the tombstone guard turns that row red by itself (ClineProvider.spec.ts:9192), so the guard is not riding along on the new value source. Reported rather than smoothed over: - Two probes were equivalent and are reported as null results rather than as kills: dropping the guard that skips an id which is present in the map again (a sibling wrote it back inside the window), and not clearing the value record when a new activation snapshot is taken. No row here re-creates an evicted id inside the window, and no row takes a second snapshot after an eviction, so neither difference is observable from a test. - A third null result: the value is recorded at all three prune sites (pin write ClineProvider.ts:1003, re-point :1127, re-key :1235), but only the pin-write site's record is load-bearing for any row that exists today. A probe that records values only at the pin-write site leaves the whole file green (540 passed), because the re-point and re-key sites stamp updatedAt on every entry they touch, which makes those entries the newest in the map, so the retention cap drops other entries instead - and for the entries those sites do drop, the value before the eviction equals the value the snapshot held. The records are kept at those sites because it is the same rule, not because a row forces them. - Predictions that missed, with the reason. For the two value-source mutants I predicted one red each and measured two: the older row at ClineProvider.spec.ts:8582, which asserts the restored entry with its original metadata, goes red as well, so the value source is load-bearing for an expectation that predates this cell. For the record-before-the-write probe I predicted two reds and measured one: the patch moved only the pin-write site, so the re-point row it never touched stayed green. The comment-shift arithmetic did land: with the added test comments removed the new row's red moved from 9133 to 9110, exactly the 23 comment lines above it. - One process slip: the last probe's prediction was reasoned out before launching it but was only appended to the predictions file after it ran, so it does not count as pre-registered. The six named mutants' predictions were all written before the run. Verification, in that order: the new rows against the parent bytes give one red, at the restored-entry assertion (ClineProvider.spec.ts:9133); with the rows removed the parent file is green; the candidate file is green (540 passed). Both comment-only controls - the 15 added production comment lines and the 43 added test comment lines removed together, and each set alone - are green, so none of this is a comment effect. Filtered runs: each new row passes at the candidate, the first fails at the parent bytes at 9133, and the second passes at both versions, because the tombstone skip is a preservation control and not the change under test. The gate matrix ran green on the candidate, and the core suite ran red with exactly this one new failure at the same coordinate against the parent production bytes. Teardown, closing-rpc and unhandled counts were 0 in every column. [cr 4751662076] --- src/core/webview/ClineProvider.ts | 69 +++++++--- .../webview/__tests__/ClineProvider.spec.ts | 130 ++++++++++++++++++ 2 files changed, 177 insertions(+), 22 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index e5d76600670..7b2a9696ab5 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -287,7 +287,6 @@ type ProfileActivationSnapshot = { viewCurrentApiConfigName: string | undefined providerSettings: RooCodeSettings viewApiConfiguration: ProviderSettings | undefined - viewStates: Record } type ProviderManagerSnapshot = { @@ -630,6 +629,16 @@ export class ClineProvider */ private prunedViewIdsDuringActivation: string[] = [] + /** + * The value each tracked eviction dropped, keyed by view id: the entry as the + * retention prune saw it in the map it handed to the store, recorded with the same + * landed write that records the id above. A sibling view writes to the same durable + * map while an activation group is in flight, so the entry the activation evicted can + * hold a value newer than the one the activation snapshot captured. The rollback + * restores this value, because that is the value eviction actually removed. + */ + private prunedViewEntriesDuringActivation = new Map() + /** * This view's pinned profile name from the view-local buffer. Exposed for * sibling-instance inspection (getAllInstances() filtering): `viewLocalState` @@ -991,9 +1000,7 @@ export class ClineProvider // undoes the tombstone claim this call made, so an eviction that never committed // must not join the list either: this instance's rollback then restores only what // one of its landed writes really evicted. - if (evicted.length > 0) { - this.prunedViewIdsDuringActivation.push(...evicted) - } + this._recordActivationEvictions(evicted, states) } catch (error) { // The durable map still holds what this write tried to change, so the tombstone // has to say what it said before the attempt: the clear branch's add comes off, @@ -1117,9 +1124,7 @@ export class ClineProvider // activation's rollback nothing it did not really do. The prune stays where it // is - this site makes no tombstone claim and no write precedes the throw, so // moving it inside would be provably equivalent. - if (evicted.length > 0) { - this.prunedViewIdsDuringActivation.push(...evicted) - } + this._recordActivationEvictions(evicted, states) } catch (error) { // A rejected write leaves the in-memory map holding the attempted value, so the // compensation must come from the snapshot taken before this write mutated @@ -1152,6 +1157,23 @@ export class ClineProvider ) } + /** + * Record an eviction together with the value it dropped. Called only after the store + * took the pruned map, so both records describe writes that really landed. The value + * comes from the map the prune ran on, not from the activation snapshot: an entry a + * sibling rewrote between the snapshot and the eviction has to come back with that + * newer value, or the rollback undoes a write the sibling already committed. + */ + private _recordActivationEvictions(evicted: string[], statesBeforePrune: Record): void { + if (evicted.length === 0) { + return + } + this.prunedViewIdsDuringActivation.push(...evicted) + for (const viewId of evicted) { + this.prunedViewEntriesDuringActivation.set(viewId, statesBeforePrune[viewId]) + } + } + /** * Re-keys this provider's temporary pre-launch viewStates entry to the newly * registered stable id so pre-launch writes become durable under the stable key @@ -1210,9 +1232,7 @@ export class ClineProvider await this.contextProxy.setValue("viewStates", kept) // The catch below puts both tombstone claims back, so an eviction this write // only attempted stays out of the list too. - if (evicted.length > 0) { - this.prunedViewIdsDuringActivation.push(...evicted) - } + this._recordActivationEvictions(evicted, states) } catch (error) { // Neither tombstone claim survives a write that never landed: the temporary id // goes back to whatever it claimed before this call, and the stable id only comes @@ -3197,8 +3217,10 @@ export class ClineProvider * concurrent write group so a failure can compensate the writes that landed. */ private _snapshotProfileActivationState(): ProfileActivationSnapshot { - // The rollback may only restore entries this activation's own writes evict. + // The rollback may only restore entries this activation's own writes evict, and only + // with the values those writes dropped: both records start empty here. this.prunedViewIdsDuringActivation = [] + this.prunedViewEntriesDuringActivation.clear() // Capture only the provider-settings keys. getValues() returns the whole // global state, and restoring that copy would write unrelated keys // (viewStates, mode, taskHistory, ...) back over changes that legitimately @@ -3215,10 +3237,10 @@ export class ClineProvider viewCurrentApiConfigName: this.viewLocalState?.currentApiConfigName, providerSettings, viewApiConfiguration: this.viewLocalState?.apiConfiguration, - // The activation's pin write merges into and prunes the durable map: the - // rollback needs the exact pre-activation map to bring back any sibling the - // pruning evicted, entry metadata included. - viewStates: this.getPersistedViewStates({ fresh: true }), + // The durable viewStates map is not captured here: the entries the activation's + // writes evict are restored from the eviction record, which holds what each one + // held when the prune dropped it - possibly a value a sibling wrote after this + // snapshot, which a copy taken here would only restore the older value over. } } @@ -3269,17 +3291,20 @@ export class ClineProvider try { // Restore the siblings the activation's pruning evicted, last, so it // lands after the overlay restore's own pin write, with their original - // entry metadata. Only tracked evictions are restored: an entry a - // sibling deleted on purpose after the snapshot is newer than the - // snapshot too, and resurrecting it would undo the sibling's clear on - // reload. The mutation queue is per-instance, so sibling views keep - // writing to the durable map while an activation group is in flight; - // merge, never replace, to leave those newer writes alone. + // entry metadata - the metadata they had when the eviction dropped them, + // not the metadata the activation started with: a sibling can rewrite an + // entry between the snapshot and the eviction, and the value it committed + // is the value this restore has to put back. Only tracked evictions are + // restored: an entry a sibling deleted on purpose after the snapshot is + // newer than the snapshot too, and resurrecting it would undo the + // sibling's clear on reload. The mutation queue is per-instance, so + // sibling views keep writing to the durable map while an activation group + // is in flight; merge, never replace, to leave those newer writes alone. const restore = ClineProvider.persistedViewStateWriteQueue.then(async () => { const current = this.getPersistedViewStates({ fresh: true }) const merged = { ...current } for (const viewId of this.prunedViewIdsDuringActivation) { - const entry = snapshot.viewStates[viewId] + const entry = this.prunedViewEntriesDuringActivation.get(viewId) if (entry && !Object.hasOwn(merged, viewId) && !ClineProvider.clearedViewStateIds.has(viewId)) { merged[viewId] = entry } diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 5373ca1890e..f435838ddab 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -9071,6 +9071,136 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("restores an evicted sibling entry with the value it held just before the eviction", async () => { + // Review cid 4751662076: the activation rollback re-inserts every entry the retention + // prune dropped. It read the value the entry had when activation started, so a sibling + // that rewrote that entry inside the activation group had its committed write rolled + // back out by a rollback that never made it. The restored value has to be the one the + // eviction actually removed. + // Cell U's finding was about when an eviction is recorded - only after the store took the + // map. This row is about a different thing: which value the record carries. A row that + // only checked the id list, or only checked that the entry came back, passes for both. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("w1-stable-view") + const seeded: Record = { + // The sibling's pinned entry, and the oldest one: the activation's pin write below is + // the growth that has to evict it. + "w1-sibling-view": { mode: "code", currentApiConfigName: "w1-old-profile", updatedAt: 0 }, + } + // The cap is 50 entries (ClineProvider.ts:MAX_PERSISTED_VIEW_STATES at 007ba09a95), so + // this fixture starts exactly at it. + for (let i = 1; i <= 49; i++) { + seeded["w1-fill-" + i] = { mode: "code", updatedAt: i } + } + await provider.contextProxy.setValue("viewStates", seeded) + ClineProvider["clearedViewStateIds"].delete("w1-sibling-view") + // A second provider owns the sibling view and can write to the same durable map while + // this view's activation group is in flight. + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await sibling["setViewStateId"]("w1-sibling-view") + // The activation snapshot is taken now: at this moment the entry still says code. + const snapshot = provider["_snapshotProfileActivationState"]() + const siblingWrite = { mode: "architect", currentApiConfigName: "w1-old-profile", updatedAt: 0 } + await sibling["savePersistedViewState"](siblingWrite) + // Premise: the sibling's rewrite really landed, and keeping its older updatedAt is what + // makes this entry the one the activation's growth evicts. Read it from the durable store: + // the write was made through the other instance's ContextProxy, so this view's proxy cache + // only ever holds its own writes, while the activation's prune reads the stored map. + expect(mockContext.globalState.get("viewStates")).toMatchObject({ "w1-sibling-view": siblingWrite }) + // The activation's own pin write is the growth the cap has to answer. + await provider["savePersistedViewState"]({ currentApiConfigName: "w1-new-profile", updatedAt: 9001 }) + const afterEviction = provider.contextProxy.getValue("viewStates") as Record + expect(Object.keys(afterEviction)).toHaveLength(50) + expect(afterEviction["w1-sibling-view"]).toBeUndefined() + expect(provider["prunedViewIdsDuringActivation"]).toEqual(["w1-sibling-view"]) + // The activation group then fails, so the rollback is what has to put the entry back. + await provider["_restoreProfileActivationState"](snapshot) + const restored = provider.contextProxy.getValue("viewStates") as Record + // The entry comes back with the mode the sibling committed after the snapshot, not the + // one activation started with. + expect(restored["w1-sibling-view"]).toEqual(siblingWrite) + // The whole map: the 49 fillers untouched, the entry back with its full post-eviction + // metadata, and this view's own entry gone again because the rollback restores the pin + // this view did not have before the group. + expect(restored).toEqual({ ...seeded, "w1-sibling-view": siblingWrite }) + expect(restored["w1-stable-view"]).toBeUndefined() + expect(ClineProvider["clearedViewStateIds"].has("w1-sibling-view")).toBe(false) + await provider.dispose() + await sibling.dispose() + }) + + it("keeps the clear tombstone ahead of the eviction record when the sibling cleared after the eviction", async () => { + // The other half of the rollback rule, which the new value source must not disturb: a + // tracked eviction whose id a sibling has since cleared on purpose is not resurrected, + // even though the eviction record now holds a real value for it. The clear is a later + // committed decision about the same map, so the tombstone outranks the record. + // A mutant that reads the recorded value and writes it back without consulting the + // tombstone passes every other assertion in this row. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("w2-stable-view") + const seeded: Record = { + // The oldest entry: the pin write below is the growth that evicts it. + "w2-clear-view": { mode: "code", currentApiConfigName: "w2-old-profile", updatedAt: 0 }, + } + // Same cap fixture as the row above: exactly at 50 entries. + for (let i = 1; i <= 49; i++) { + seeded["w2-fill-" + i] = { mode: "code", updatedAt: i } + } + await provider.contextProxy.setValue("viewStates", seeded) + ClineProvider["clearedViewStateIds"].delete("w2-clear-view") + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await sibling["setViewStateId"]("w2-clear-view") + const snapshot = provider["_snapshotProfileActivationState"]() + await provider["savePersistedViewState"]({ currentApiConfigName: "w2-new-profile", updatedAt: 9001 }) + const afterEviction = provider.contextProxy.getValue("viewStates") as Record + // Premise: the eviction is tracked, so the restore loop really does hold a value for it + // by the time the rollback runs; without this the skip below could pass for an id that + // was never recorded at all. + expect(afterEviction["w2-clear-view"]).toBeUndefined() + expect(provider["prunedViewIdsDuringActivation"]).toEqual(["w2-clear-view"]) + // The sibling then un-pins its own view, and that write lands: the id carries a + // tombstone by the time the rollback reaches it. + await sibling["savePersistedViewState"]({ mode: undefined, currentApiConfigName: undefined }) + expect(ClineProvider["clearedViewStateIds"].has("w2-clear-view")).toBe(true) + await provider["_restoreProfileActivationState"](snapshot) + const restored = provider.contextProxy.getValue("viewStates") as Record + // The tombstone wins: the cleared entry stays out of the map. + expect(restored["w2-clear-view"]).toBeUndefined() + // The whole map after the two decisions the user actually made: every filler still + // there, the cleared pin gone, and the map one entry below the cap because the clear + // committed after the eviction that dropped it. + const expectedMap = { ...seeded } + delete expectedMap["w2-clear-view"] + expect(restored).toEqual(expectedMap) + expect(Object.keys(restored)).toHaveLength(49) + await provider.dispose() + await sibling.dispose() + }) + it("re-points live views pinned to a renamed profile onto the new name", async () => { const provider = new ClineProvider( mockContext, From 360f534b2d8a99b07e715f7d85810a786821a4df Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:32:59 +0800 Subject: [PATCH 25/34] webview: assert view-state evictions against the write, not the result Review 6130276577 leaves three asks on the view-state eviction rows, all of them about when a record is read rather than about what the code does: cid 4753366448 wants the rollback list read while the durable write is still in flight, cid 4753366461 wants the destination tombstone to come from clearPersistedViewState rather than from a hand delete, and to stay dropped when the write is rejected, and cid 4753366472 wants the rejected map compared with the seed, the whole landed map asserted, and the eviction ids derived from the input instead of from the map the write produced. All three were checked against the current code before anything was rewritten. Anchors first, because all three quote bytes that are no longer the head. The cited lines (8923, 9001 and 9005, 9061-9070) are at d6edcc76f2; the review landed at 11:25:47Z, before Cell V was pushed. Cell V touched only Task.ts and Task.spec.ts, and Cell W added its 130 spec lines at 9074, below the last cited line, so between those two commits the cited rows did not move at all - the diff of this file from d6edcc76f2 to 775eb413ce is one pure insertion. Coordinates below are against the bytes this commit leaves behind. The pin-write row holds the store open. The mocked globalState.update parks the write, the row reads prunedViewIdsDuringActivation while that write is in flight and requires it to be empty (8940), then settles the write with an error and keeps every outcome check it had. An implementation that records the eviction as soon as it computes it and takes it back when the store rejects reads identically once the write has settled, so the mid-write read is the only thing that separates them [cr 4753366448]. The re-key row stops deleting the destination tombstone by hand. It calls clearPersistedViewState for the stable id, asserts the claim that made, injects the corrupt entry, and after the rejection asserts both that the destination tombstone is still claimed (9036) and that the id invented for the temporary write is not claimed - which is the half the reviewer asked for and the half the old row only asserted for a storage rejection at 8829 [cr 4753366461]. The re-point row compares the rejected map with the seed as a whole map (9106), derives the eviction ids from the map it seeded (9077, cross-checked against the literal list) rather than reading them back out of the map the write produced, asserts the whole landed map (9140: both pins renamed with their mode kept, the two oldest fillers gone, every other entry exactly as seeded), asserts the re-stamped timestamps separately (9142-9143) because the re-point stamps them from the clock, and asserts the rollback list against the ids derived from the input (9146). It also asserts the seed itself is untouched before comparing storage with it, so the comparison cannot be seed-mutated data against itself [cr 4753366472]. One measured fact decided where the landed map is read from. While the spy over globalState.update is installed the fake store persists - the seed write and the rejected attempt's compensation both reach it - but once that spy is restored the mock stores nothing again: the probe run recorded one spy call with a 50-key map, 52 keys still in the store with both pins under the removed name, and 50 keys in the instance's proxy with both pins renamed. The store therefore keeps what the compensation wrote back and only the proxy carries what the landed write produced, so the landed read goes through the proxy - which is where the previous version of this very row read it - while the rejected-phase reads stay on the store, where the mock is still persisting. This cell adds no production behaviour, so there is no parent-side red for its rows: run against ClineProvider.ts at HEAD~1 the whole suite fails only in Cell W's row at 9209. The red here is mutant-directional: each mutant is run against the rewritten row and against the previous version of the same row (spec reverted to 775eb413ce, same production patch). Pin site records early and undoes on rejection: rewritten row red at 8940, previous version of the row green. Re-point site in the same shape: red at 9093, previous version green. Re-key compensation never restores the destination tombstone: red at 9036 here and at 8829 in the row that already pinned that restore - a second detection point, not the only one. Re-point renames only the first match: red at 9140 here and at 9403 in the row that pins the re-point itself. Rename drops the mode: red at 9140 and nowhere else in the file. Re-key claims the temporary id only after the prune succeeds: green in both directions - an equivalent mutant, reported as the null result it is. Comment-only control: deleting exactly the 41 comment lines this cell adds, with no mutant, leaves 540 passed. With a mutant on the same patch the red moves up by precisely the number of deleted comment lines above it - 8934 for the pin-site mutant (6 lines above), 9067 for the re-point-site mutant (26), 9101 for the first-match mutant (39). Whole-file runs of the two record-timing mutants do not finish inside 300 s; capped at two failures they show the rewritten row first and then a pre-existing row timing out - restores the tombstone claim when the retention prune itself throws under the pin-site mutant, Cell W's sibling-value row under the re-point-site mutant - so those two are broad kills rather than kills of this cell's rows alone. Things this cell got wrong on the way and is not smoothing over. The first column battery passed each patch name with a second .json suffix, so 15 of its 21 columns failed before vitest started. Its candidate then read the landed map from the fake store and failed its own whole-map assertion at 9133; the probe above is what that turned out to be, and the row now reads it where the previous version read it. Two predictions were wrong and are left standing rather than rewritten: the first-match mutant was predicted to be killed only by the new whole-map assertion and is also caught by the row at 9403, and the two record-timing mutants were predicted to be lone kills and turn out to reach pre-existing rows as well. The earlier predictions also named 8818 for the pre-existing rejected-re-key row; 8818 is that row's claim check, the assertion a rejection breaks is 8829. Gates were run twice, against these bytes and against the parent production bytes. On these bytes: format-check, check-types, src tsc, root and src lint, code-qa, translations, both knip jobs, lifecycle:model-check and the MCP integration check all pass; test:core 5498 passed | 17 skipped (5515) across 224 files, test:misc 2589 passed | 13 skipped, test:services keeps its standing 5 failures in services/rules/__tests__/rules.spec.ts (symlink EPERM, unrelated to this file). Against ClineProvider.ts at HEAD~1 the same test:core gives 1 failed | 5497 passed | 17 skipped, and that failure is Cell W's sibling-value row at 9209, which is what a parent-side run is expected to show. Both calibers end with a vitest worker teardown artifact - Closing rpc while "onUserConsoleLog" was pending: 5 lines on these bytes, 3 on the parent bytes, and 2/2/0 across three earlier runs of the same caliber - reported as a caliber property, not as evidence about behaviour. Production is untouched: ClineProvider.ts stays at blob 7b2a9696ab and everything else in the diff is this one spec file, 108 added and 32 deleted lines. eslint --prune-suppressions on the touched file keeps its count at 193 explicit-any suppressions and rewrites only the formatting of src/eslint-suppressions.json - tabs to two spaces, no count changes anywhere in it - which was restored byte-identically at blob 1fad7b0e65. --- .../webview/__tests__/ClineProvider.spec.ts | 140 ++++++++++++++---- 1 file changed, 108 insertions(+), 32 deletions(-) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index f435838ddab..8ab317d06ac 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -8897,6 +8897,10 @@ describe("ClineProvider", () => { // difference - the gate at ClineProvider.ts skips an id that is still in the map, so a // claim made by a write whose store rejected is skipped either way (measured) - and the // assertion is therefore about the list itself, read through bracket notation. + // Review cid 4753366448 is about when the list is read, so the check is made while the + // durable store is still holding the map. An implementation that records the eviction as + // soon as it computes it and takes it back when the store rejects reads exactly like this + // one once the write has settled: only a mid-write read tells them apart. const provider = new ClineProvider( mockContext, mockOutputChannel, @@ -8915,12 +8919,27 @@ describe("ClineProvider", () => { seeded["u1-fill-" + i] = { mode: "code", updatedAt: i } } await provider.contextProxy.setValue("viewStates", seeded) - const storeFailure = vi.spyOn(mockContext.globalState, "update").mockImplementation(async () => { - throw new Error("durable pin write failed") + let markStoreReached = () => {} + const storeReached = new Promise((resolve) => { + markStoreReached = () => resolve() + }) + let settleStore: (error: Error) => void = () => {} + const storeFailure = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(() => { + markStoreReached() + return new Promise((_, reject) => { + settleStore = (error) => reject(error) + }) }) - await expect( - provider["savePersistedViewState"]({ currentApiConfigName: "u1-profile", updatedAt: 9001 }), - ).rejects.toThrow("durable pin write failed") + const rejectedAttempt = provider["savePersistedViewState"]({ + currentApiConfigName: "u1-profile", + updatedAt: 9001, + }) + await storeReached + // Mid-write: the store has been handed the pruned map and has not answered yet, so the + // eviction this write computed is not on record. + expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) + settleStore(new Error("durable pin write failed")) + await expect(rejectedAttempt).rejects.toThrow("durable pin write failed") storeFailure.mockRestore() // The rejected attempt is read from the durable store, not from this instance's cache: // what a rejection leaves in that cache is the Memento's business, while the list below @@ -8980,6 +8999,10 @@ describe("ClineProvider", () => { it("restores both tombstone claims when the retention prune throws during a re-key", async () => { // The same throw class, this time on the re-key, which moves two tombstones at once: // it claims the temporary id is gone and un-claims the stable id the entry moves onto. + // Review cid 4753366461: the destination tombstone used to be made by editing + // clearedViewStateIds directly, which can only ever show that a claim is absent. Here a + // real clear puts it in place first, so this row reaches the half of the compensation + // that puts a tombstone back and not only the half that takes one off. const provider = new ClineProvider( mockContext, mockOutputChannel, @@ -8993,16 +9016,24 @@ describe("ClineProvider", () => { "u2b-fill": { mode: "code", updatedAt: 2 }, } await provider.contextProxy.setValue("viewStates", seeded) + // clearedViewStateIds is process-level and this suite has no reset helper for it, so the + // one id this row invented is normalized by deleting it, and the assertion below states + // the starting point of the id the row named. + ClineProvider["clearedViewStateIds"].delete(temporaryViewStateId) + expect(ClineProvider["clearedViewStateIds"].has("u2b-stable")).toBe(false) + // A clear is what puts a stable id onto the tombstone list in production, and it leaves + // the slot claimed and empty - the exact state a re-key moves an entry into. + await provider["clearPersistedViewState"]("u2b-stable") + expect(ClineProvider["clearedViewStateIds"].has("u2b-stable")).toBe(true) const stored = mockContext.globalState.get("viewStates") as Record stored["u2b-broken"] = null - // clearedViewStateIds is process-level and this suite has no reset helper for it, so - // both ids are normalized to a known membership: the assertions are about this row. - ClineProvider["clearedViewStateIds"].delete(temporaryViewStateId) - ClineProvider["clearedViewStateIds"].delete("u2b-stable") provider["wroteUnderTemporaryViewStateId"] = true await expect(provider["rekeyPersistedViewStateEntry"]("u2b-stable")).rejects.toThrow(TypeError) expect(ClineProvider["clearedViewStateIds"].has(temporaryViewStateId)).toBe(false) - expect(ClineProvider["clearedViewStateIds"].has("u2b-stable")).toBe(false) + // The claim the clear put in place is back: the re-key took it off in order to move the + // entry onto the stable id, its write never landed, and a claim about storage may not + // stay dropped by an attempt that never stored anything either. + expect(ClineProvider["clearedViewStateIds"].has("u2b-stable")).toBe(true) const restored = mockContext.globalState.get("viewStates") as Record expect(restored).toEqual({ ...seeded, "u2b-broken": null }) await provider.dispose() @@ -9013,6 +9044,9 @@ describe("ClineProvider", () => { // carried the removed profile name. The map here is stored one entry over the cap - // the state a write whose store rejected leaves behind - so the prune that answers this // re-point drops the oldest filler, and only a landed re-point may record that. + // Review cid 4753366472 asks for the whole map and for an eviction list derived from the + // input rather than from the map the write produced; cid 4753366448 asks for the record + // to be read while the write is still in flight. const provider = new ClineProvider( mockContext, mockOutputChannel, @@ -9033,41 +9067,83 @@ describe("ClineProvider", () => { // Registering the view persists this view's own entry, so the length this row compares against is // the stored length taken here, not a hand-counted constant. const keysBefore = Object.keys(mockContext.globalState.get("viewStates") as object).length - const storeFailure = vi.spyOn(mockContext.globalState, "update").mockImplementation(async () => { - throw new Error("durable re-point failed") + // The entries the cap has to answer with, derived from the map this row seeded: its lowest + // updatedAt values, as many of them as the map is over the cap of 50. Nothing here is read + // back out of the map the write produced. + const evictedByThisWrite = Object.entries(seeded) + .sort(([, a], [, b]) => a.updatedAt - b.updatedAt) + .slice(0, Object.keys(seeded).length - 50) + .map(([viewId]) => viewId) + expect(evictedByThisWrite).toEqual(["u4-fill-2", "u4-fill-3"]) + let markStoreReached = () => {} + const storeReached = new Promise((resolve) => { + markStoreReached = () => resolve() + }) + let settleStore: (error: Error) => void = () => {} + const storeFailure = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(() => { + markStoreReached() + return new Promise((_, reject) => { + settleStore = (error) => reject(error) + }) }) - await expect(provider["repointPersistedViewStates"]("u4-removed", "u4-replacement")).rejects.toThrow( - "durable re-point failed", - ) + const rejectedAttempt = provider["repointPersistedViewStates"]("u4-removed", "u4-replacement") + await storeReached + // Mid-write: the store is holding the pruned map and has not answered, so the eviction + // this re-point computed is not on record yet. + expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) + settleStore(new Error("durable re-point failed")) + await expect(rejectedAttempt).rejects.toThrow("durable re-point failed") storeFailure.mockRestore() // Read from the store, not from this instance's cache: the cache carries what the // Memento applied to it, and a rejection there says nothing about which entries storage // ever lost, so it is the eviction list below that this row is checking. const afterReject = mockContext.globalState.get("viewStates") as Record - // Nothing moved: the rejected re-point left the over-cap map exactly as stored, so the - // attempt has no eviction to have recorded. + // Nothing moved: the stored map is still exactly what this row seeded, so the attempt has no + // eviction to have recorded. The seed is checked first - without it the comparison below could + // be comparing data the attempt already mutated against itself. + expect(seeded["u4-view-a"].currentApiConfigName).toBe("u4-removed") expect(Object.keys(afterReject)).toHaveLength(keysBefore) - expect(afterReject["u4-view-a"]).toEqual(seeded["u4-view-a"]) - expect(afterReject["u4-fill-2"]).toEqual(seeded["u4-fill-2"]) + expect(afterReject).toEqual(seeded) expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) await provider["repointPersistedViewStates"]("u4-removed", "u4-replacement") + // The landing map is read through this instance's proxy. Measured in this row: while the + // spy is installed the fake store persists, the seeding and the rejected attempt's + // compensation both reached it, but once the spy is restored the fake update no longer + // stores anything, so the store keeps the map the compensation wrote back while the proxy + // holds the map the landed write produced. The reads above stay on the store, where the + // mock was still persisting. const afterLand = provider.contextProxy.getValue("viewStates") as Record< string, - { currentApiConfigName?: string } + { mode?: string; currentApiConfigName?: string; updatedAt: number } > - // The landed re-point is the growth that takes the stored map over the cap, and the cap - // then answers by dropping u4-fill-2: the map comes back to the cap of 50 and that eviction - // is what joins the rollback list - and only that one. + // The whole map storage took, not a sample of it: both pins back under the replacement + // name with their mode kept, the oldest fillers gone, every other entry exactly as seeded. + // Timestamps are left out of the comparison because the re-point stamps them from the + // clock, and are asserted separately instead. + const withoutTimestamps = (map: Record) => + Object.fromEntries( + Object.entries(map).map(([viewId, entry]) => [ + viewId, + { mode: entry.mode, currentApiConfigName: entry.currentApiConfigName }, + ]), + ) + const expectedAfterLand: Record = {} + for (const [viewId, entry] of Object.entries(seeded)) { + if (evictedByThisWrite.includes(viewId)) { + continue + } + expectedAfterLand[viewId] = + entry.currentApiConfigName === "u4-removed" + ? { mode: entry.mode, currentApiConfigName: "u4-replacement" } + : { mode: entry.mode, currentApiConfigName: entry.currentApiConfigName } + } + expect(withoutTimestamps(afterLand)).toEqual(withoutTimestamps(expectedAfterLand)) expect(Object.keys(afterLand)).toHaveLength(50) - expect(afterLand["u4-fill-2"]).toBeUndefined() - expect(afterLand["u4-view-a"].currentApiConfigName).toBe("u4-replacement") - // The rollback list has to hold exactly the entries storage actually lost in this write - the - // oldest fillers are the ones the cap drops here, and naming them by hand would hide a prune that - // dropped something else. - const droppedKeys = Object.keys(afterReject).filter((viewId) => !Object.hasOwn(afterLand, viewId)) - expect(droppedKeys.length).toBeGreaterThan(0) - expect(droppedKeys).toContain("u4-fill-2") - expect(provider["prunedViewIdsDuringActivation"]).toEqual(droppedKeys) + expect(afterLand["u4-view-a"].updatedAt).toBeGreaterThan(seeded["u4-view-a"].updatedAt) + expect(afterLand["u4-view-b"].updatedAt).toBeGreaterThan(seeded["u4-view-b"].updatedAt) + // The rollback list holds exactly the ids derived from the input above - the entries + // storage really lost in this write - and nothing else. + expect(provider["prunedViewIdsDuringActivation"]).toEqual(evictedByThisWrite) await provider.dispose() }) From 2e8db66019530dd90d71cef8425a16481a1d5b57 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:15:16 +0800 Subject: [PATCH 26/34] test(webview): harden the four new view-state eviction rows Addresses review cids 4755114517, 4755114535, 4755114566 and 4755114571. Test-side only: production bytes are unchanged in this commit. Row 4755114517: the two pinned-write rows now race the write against the store answer and settle the mock in a finally. Measured before this change, a rejected pin left an unhandled rejection, and every later row that writes viewStates timed out because the abandoned store reply blocked the static write queue forever. A control that forces the row to fail confirms both halves: with the finally the neighbor passes, without it the same neighbor times out at 20 s. Row 4755114535: the re-key row normalizes the process-level tombstone set for "u2b-stable" at its start, like its neighbors already do for theirs. The set has no reset helper, and the row's own rejected re-key re-claims the id, so a second run in the same module instance would otherwise fail its starting assertion. A control seeds the id from the preceding row in both directions: with the delete the row passes, without it the assertion fails true against false. Row 4755114566: the success control now compares the complete map storage took - pins renamed with their mode kept, stamps taken at a clock fixed for the landing write, every other entry byte-for-byte as seeded - instead of a proxy-cache sample with the stamps stripped. The landing write is read back from the mock store: measured, vi.spyOn reuses the mock already on the property and leaves a non-storing spy behind after mockRestore, so the row captures the persisting implementation before installing the spy and re-installs it in the finally. Row 4755114571: the tombstone row now asserts the recorded entry carries the evicted view's stored value before the clear - an ids-only recorder would leave the rollback nothing to restore and passed the old row - and reads the map back from the durable store rather than this instance's cache. --- .../webview/__tests__/ClineProvider.spec.ts | 151 +++++++++++++----- 1 file changed, 107 insertions(+), 44 deletions(-) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 8ab317d06ac..73440cfdea1 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -8934,13 +8934,34 @@ describe("ClineProvider", () => { currentApiConfigName: "u1-profile", updatedAt: 9001, }) - await storeReached - // Mid-write: the store has been handed the pruned map and has not answered yet, so the - // eviction this write computed is not on record. - expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) - settleStore(new Error("durable pin write failed")) - await expect(rejectedAttempt).rejects.toThrow("durable pin write failed") - storeFailure.mockRestore() + // The rejection is handled from the moment the attempt exists, and the storage gate is + // raced against the operation itself: an attempt that answers before the store was + // reached fails this row by name instead of hanging, and an assertion that throws + // below never leaves the rejection unowned. + const opSettled = rejectedAttempt.then( + () => "resolved", + () => "rejected", + ) + try { + await Promise.race([ + storeReached, + opSettled.then((outcome) => { + throw new Error(`the pin write ${outcome} before the store was reached`) + }), + ]) + // Mid-write: the store has been handed the pruned map and has not answered yet, so the + // eviction this write computed is not on record. + expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) + settleStore(new Error("durable pin write failed")) + await expect(rejectedAttempt).rejects.toThrow("durable pin write failed") + } finally { + // Whatever happened above, the store gets an answer and the attempt drains to the + // end: an unsettled answer would leave the static write queue blocked for every + // later row in this file. + settleStore(new Error("the pin write was abandoned before the store answered")) + await rejectedAttempt.catch(() => {}) + storeFailure.mockRestore() + } // The rejected attempt is read from the durable store, not from this instance's cache: // what a rejection leaves in that cache is the Memento's business, while the list below // is about whether an eviction that never landed got recorded. @@ -9016,10 +9037,13 @@ describe("ClineProvider", () => { "u2b-fill": { mode: "code", updatedAt: 2 }, } await provider.contextProxy.setValue("viewStates", seeded) - // clearedViewStateIds is process-level and this suite has no reset helper for it, so the - // one id this row invented is normalized by deleting it, and the assertion below states - // the starting point of the id the row named. + // clearedViewStateIds is process-level and this suite has no reset helper for it, so + // both ids this row touches are normalized at the start, as the neighboring rows do: + // the temporary id it invented, and the stable id it leaves on the tombstone list when + // the rejected re-key restores its claim - a second run of this row in the same module + // instance would otherwise fail the starting assertion below. ClineProvider["clearedViewStateIds"].delete(temporaryViewStateId) + ClineProvider["clearedViewStateIds"].delete("u2b-stable") expect(ClineProvider["clearedViewStateIds"].has("u2b-stable")).toBe(false) // A clear is what puts a stable id onto the tombstone list in production, and it leaves // the slot claimed and empty - the exact state a re-key moves an entry into. @@ -9080,6 +9104,19 @@ describe("ClineProvider", () => { markStoreReached = () => resolve() }) let settleStore: (error: Error) => void = () => {} + // Measured in this row: vi.spyOn reuses the mock that already sits on globalState.update, + // so once its once implementation is consumed the writes past it resolve without storing, + // and mockRestore does not put the persisting implementation back. This row captures the + // persisting implementation before the spy is installed and re-installs it in the finally + // below, so storage writes stay enabled for the success control. + const originalUpdate = ( + mockContext.globalState.update as unknown as { + getMockImplementation: () => ((key: string, value: unknown) => unknown) | undefined + } + ).getMockImplementation() + if (typeof originalUpdate !== "function") { + throw new Error("the storage mock no longer carries its persisting implementation") + } const storeFailure = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(() => { markStoreReached() return new Promise((_, reject) => { @@ -9087,13 +9124,38 @@ describe("ClineProvider", () => { }) }) const rejectedAttempt = provider["repointPersistedViewStates"]("u4-removed", "u4-replacement") - await storeReached - // Mid-write: the store is holding the pruned map and has not answered, so the eviction - // this re-point computed is not on record yet. - expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) - settleStore(new Error("durable re-point failed")) - await expect(rejectedAttempt).rejects.toThrow("durable re-point failed") - storeFailure.mockRestore() + // Same rule as the pin write above: handle the rejection at creation, race the storage + // gate against the operation, and let the finally below close the gate and drain the + // attempt whichever assertion throws. + const opSettled = rejectedAttempt.then( + () => "resolved", + () => "rejected", + ) + try { + await Promise.race([ + storeReached, + opSettled.then((outcome) => { + throw new Error(`the re-point write ${outcome} before the store was reached`) + }), + ]) + // Mid-write: the store is holding the pruned map and has not answered, so the eviction + // this re-point computed is not on record yet. + expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) + settleStore(new Error("durable re-point failed")) + await expect(rejectedAttempt).rejects.toThrow("durable re-point failed") + } finally { + // Close the gate and drain the attempt whatever failed above: an answer the test + // never gave the store would block the static write queue for every later row. + settleStore(new Error("the re-point write was abandoned before the store answered")) + await rejectedAttempt.catch(() => {}) + // Keep storage writes enabled for the rest of this row: re-install the persisting + // implementation on the mock, so the success control reads the map storage really took + // rather than a cache-only copy. + storeFailure.mockImplementation((key, value) => { + originalUpdate(key, value) + return Promise.resolve() + }) + } // Read from the store, not from this instance's cache: the cache carries what the // Memento applied to it, and a rejection there says nothing about which entries storage // ever lost, so it is the eviction list below that this row is checking. @@ -9105,42 +9167,36 @@ describe("ClineProvider", () => { expect(Object.keys(afterReject)).toHaveLength(keysBefore) expect(afterReject).toEqual(seeded) expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) - await provider["repointPersistedViewStates"]("u4-removed", "u4-replacement") - // The landing map is read through this instance's proxy. Measured in this row: while the - // spy is installed the fake store persists, the seeding and the rejected attempt's - // compensation both reached it, but once the spy is restored the fake update no longer - // stores anything, so the store keeps the map the compensation wrote back while the proxy - // holds the map the landed write produced. The reads above stay on the store, where the - // mock was still persisting. - const afterLand = provider.contextProxy.getValue("viewStates") as Record< + // The re-point stamps both entries from the clock, so the clock is fixed for the landing + // write and the comparison below is the complete stored map, timestamps included: + // an unrelated entry - value or stamp - cannot change unnoticed, and the control does + // not rely on proxy-only state. + const FIXED_NOW = 1_780_000_000_000 + const realNow = Date.now + Date.now = () => FIXED_NOW + try { + await provider["repointPersistedViewStates"]("u4-removed", "u4-replacement") + } finally { + Date.now = realNow + } + const afterLand = mockContext.globalState.get("viewStates") as Record< string, { mode?: string; currentApiConfigName?: string; updatedAt: number } > // The whole map storage took, not a sample of it: both pins back under the replacement - // name with their mode kept, the oldest fillers gone, every other entry exactly as seeded. - // Timestamps are left out of the comparison because the re-point stamps them from the - // clock, and are asserted separately instead. - const withoutTimestamps = (map: Record) => - Object.fromEntries( - Object.entries(map).map(([viewId, entry]) => [ - viewId, - { mode: entry.mode, currentApiConfigName: entry.currentApiConfigName }, - ]), - ) - const expectedAfterLand: Record = {} + // name with their mode kept and stamped at the fixed clock, the oldest fillers gone, + // every other entry exactly as seeded. + const expectedAfterLand: Record = {} for (const [viewId, entry] of Object.entries(seeded)) { if (evictedByThisWrite.includes(viewId)) { continue } expectedAfterLand[viewId] = entry.currentApiConfigName === "u4-removed" - ? { mode: entry.mode, currentApiConfigName: "u4-replacement" } - : { mode: entry.mode, currentApiConfigName: entry.currentApiConfigName } + ? { mode: entry.mode, currentApiConfigName: "u4-replacement", updatedAt: FIXED_NOW } + : { ...entry } } - expect(withoutTimestamps(afterLand)).toEqual(withoutTimestamps(expectedAfterLand)) - expect(Object.keys(afterLand)).toHaveLength(50) - expect(afterLand["u4-view-a"].updatedAt).toBeGreaterThan(seeded["u4-view-a"].updatedAt) - expect(afterLand["u4-view-b"].updatedAt).toBeGreaterThan(seeded["u4-view-b"].updatedAt) + expect(afterLand).toEqual(expectedAfterLand) // The rollback list holds exactly the ids derived from the input above - the entries // storage really lost in this write - and nothing else. expect(provider["prunedViewIdsDuringActivation"]).toEqual(evictedByThisWrite) @@ -9255,15 +9311,22 @@ describe("ClineProvider", () => { const afterEviction = provider.contextProxy.getValue("viewStates") as Record // Premise: the eviction is tracked, so the restore loop really does hold a value for it // by the time the rollback runs; without this the skip below could pass for an id that - // was never recorded at all. + // was never recorded at all. The id list alone does not prove that: a recorder that only + // saved ids would pass it while leaving the rollback nothing to restore, so the recorded + // entry itself is checked for the stored value here - this view seeded it and no sibling + // rewrote it between the eviction and this read. expect(afterEviction["w2-clear-view"]).toBeUndefined() expect(provider["prunedViewIdsDuringActivation"]).toEqual(["w2-clear-view"]) + expect(provider["prunedViewEntriesDuringActivation"].get("w2-clear-view")).toEqual(seeded["w2-clear-view"]) // The sibling then un-pins its own view, and that write lands: the id carries a // tombstone by the time the rollback reaches it. await sibling["savePersistedViewState"]({ mode: undefined, currentApiConfigName: undefined }) expect(ClineProvider["clearedViewStateIds"].has("w2-clear-view")).toBe(true) await provider["_restoreProfileActivationState"](snapshot) - const restored = provider.contextProxy.getValue("viewStates") as Record + // Read the durable backing map, not this instance's proxy cache: the decision this row + // checks is what storage ends up holding after both writes, and a cache that only kept + // the shape in memory would say nothing about what a reload would see. + const restored = mockContext.globalState.get("viewStates") as Record // The tombstone wins: the cleared entry stays out of the map. expect(restored["w2-clear-view"]).toBeUndefined() // The whole map after the two decisions the user actually made: every filler still From 0bba2197957b1b6fc21e1b7f4cc590fe2428d1c4 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:15:26 +0800 Subject: [PATCH 27/34] webview: pay the store only for writes it actually received Addresses review cid 4753366481 and its second site, the re-key prune call the row flags as also applying (line 1208 of the reviewed bytes). The pin write and the re-key run their retention prune inside the same protection as the store write, so a corrupt stored entry makes the prune throw before any write is dispatched. Both catches used to answer that throw - and a store rejection alike - by awaiting a rewrite of the map captured before the write. For a throw that dispatched nothing, storage already holds exactly that map: the rewrite posts a change nobody made and makes the caller wait on a write no failure produced. Each catch now marks whether the store was called, restores the tombstone claims unconditionally - a claim is a claim about storage either way - and runs the snapshot compensation only when a write really started. A rejected write keeps its compensation exactly as before: the split is only about throws that dispatched nothing. The re-point needs no change: its prune already runs outside the protected region, so its catch can never see an undispatched write. Test side: both prune-throw rows count the durable viewStates writes and require the failed call to have added none - red against the unsplit catch, 2 against 1 and 3 against 2, before this commit. One new row models the Memento's own order, applying the update to the map before answering with a rejection, and checks the gated catch still writes the pre-write snapshot back: that is the half the split could swallow, and a gate turned the wrong way fails there as well as in the two count rows. --- src/core/webview/ClineProvider.ts | 64 +++++++++++----- .../webview/__tests__/ClineProvider.spec.ts | 75 +++++++++++++++++++ 2 files changed, 119 insertions(+), 20 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 7b2a9696ab5..c71a04d1fa7 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -987,6 +987,11 @@ export class ClineProvider wroteEntry = true } + // Whether the store call was dispatched at all. A throw from the preparation + // below leaves this false - that failure is about a corrupt entry in the map, + // not about a write the store refused - and the snapshot compensation in the + // catch has nothing to undo in that case. + let storeAttempted = false try { // The retention prune reads every entry it is about to hand to the store, so a // stored entry the sort cannot read (a null value) throws here rather than @@ -995,7 +1000,11 @@ export class ClineProvider // such a throw leaves untouched. const kept = this.prunePersistedViewStates(states) const evicted = Object.keys(states).filter((viewId) => !Object.hasOwn(kept, viewId)) - await this.contextProxy.setValue("viewStates", kept) + // The attempt exists from the moment the store is called; that is exactly + // what the catch below compensates, and nothing else. + const attempt = this.contextProxy.setValue("viewStates", kept) + storeAttempted = true + await attempt // Retention is recorded for the map the store actually took. The catch below // undoes the tombstone claim this call made, so an eviction that never committed // must not join the list either: this instance's rollback then restores only what @@ -1012,15 +1021,21 @@ export class ClineProvider } else { ClineProvider.clearedViewStateIds.delete(viewStateId) } - // A rejected write leaves the in-memory map holding the attempted value, so the - // compensation must come from the snapshot taken before this write mutated - // anything: re-reading the map here would persist the change whose write failed - // (a rejected pin would become durable on the next write). - try { - await this.contextProxy.setValue("viewStates", durableBeforeWrite) - } catch { - // The snapshot is what storage held when this write started: the restore is - // correct whether or not this compensating write itself landed. + // Compensation is for a store rejection only. A preparation throw (the prune + // above failing on a corrupt entry) dispatched no write at all, so storage + // still holds what it held before this call: re-writing the snapshot there + // would post a change nobody made and wait on a write no failure produced. + if (storeAttempted) { + // A rejected write leaves the in-memory map holding the attempted value, so the + // compensation must come from the snapshot taken before this write mutated + // anything: re-reading the map here would persist the change whose write failed + // (a rejected pin would become durable on the next write). + try { + await this.contextProxy.setValue("viewStates", durableBeforeWrite) + } catch { + // The snapshot is what storage held when this write started: the restore is + // correct whether or not this compensating write itself landed. + } } throw error } @@ -1223,13 +1238,19 @@ export class ClineProvider movedToNext = true } + // Whether the store call was dispatched: the catch below compensates a store + // rejection, and a throw from the preparation - the prune on a corrupt entry + // - needs no compensation because no write ever started. + let storeAttempted = false try { // As in the pin write: the prune runs inside the protection, so a stored entry // the sort cannot read leaves the two tombstone claims below restored instead // of half-applied over a store that never changed. const kept = this.prunePersistedViewStates(states) const evicted = Object.keys(states).filter((viewId) => !Object.hasOwn(kept, viewId)) - await this.contextProxy.setValue("viewStates", kept) + const attempt = this.contextProxy.setValue("viewStates", kept) + storeAttempted = true + await attempt // The catch below puts both tombstone claims back, so an eviction this write // only attempted stays out of the list too. this._recordActivationEvictions(evicted, states) @@ -1249,15 +1270,18 @@ export class ClineProvider ClineProvider.clearedViewStateIds.delete(nextViewStateId) } } - // A rejected write leaves the in-memory map holding the attempted value, so the - // compensation must come from the snapshot taken before this write mutated - // anything: re-reading the map here would persist the change whose write failed - // (a re-key would make the stable id durable while the temporary entry is still the stored one). - try { - await this.contextProxy.setValue("viewStates", durableBeforeWrite) - } catch { - // The snapshot is what storage held when this write started: the restore is - // correct whether or not this compensating write itself landed. + if (storeAttempted) { + // A rejected write leaves the in-memory map holding the attempted value, so the + // compensation must come from the snapshot taken before this write mutated + // anything: re-reading the map here would persist the change whose write failed + // (a re-key would make the stable id durable while the temporary entry is + // still the stored one). + try { + await this.contextProxy.setValue("viewStates", durableBeforeWrite) + } catch { + // The snapshot is what storage held when this write started: the restore is + // correct whether or not this compensating write itself landed. + } } throw error } diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 73440cfdea1..8f00f0c1f4b 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -9014,6 +9014,73 @@ describe("ClineProvider", () => { expect(ClineProvider["clearedViewStateIds"].has("u2-view")).toBe(false) const restored = mockContext.globalState.get("viewStates") as Record expect(restored).toEqual({ ...seeded, "u2-broken": null }) + // A prune that throws owes the store no rewrite: it happened before any write was + // dispatched, so the only viewStates write this row made is the seed it stored. The + // tombstone restore above is the whole repair such a throw needs; compensating an + // attempt that never reached the store is a round trip nobody asked for. The call + // list is reached through the vitest shape because the mock context erases types. + const updateCalls = (mockContext.globalState.update as unknown as { mock: { calls: unknown[][] } }) + .mock.calls + .map((call) => call[0]) + .filter((key) => key === "viewStates") + expect(updateCalls).toEqual(["viewStates"]) + await provider.dispose() + }) + + it("writes the pre-write snapshot back when the store applies the change and then rejects", async () => { + // Review cid 4753366481 splits the catch in two: a preparation throw owes the store + // nothing, a store rejection owes it the snapshot back. This row pins the second + // half so the split cannot swallow it. The mock models the Memento's own order - + // it applies the update to its map and only then answers with a rejection - so a + // failed attempt leaves the attempted value in storage and only the compensation + // can take it back out. Nothing else in this group can see that difference, + // because the rejections there are answered before the mock is ever reached. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("u5-view") + const seeded: Record = { + "u5-view": { mode: "code", currentApiConfigName: "u5-profile", updatedAt: 1 }, + "u5-fill": { mode: "code", updatedAt: 2 }, + } + await provider.contextProxy.setValue("viewStates", seeded) + ClineProvider["clearedViewStateIds"].delete("u5-view") + // Measured in this suite: vi.spyOn reuses the mock already sitting on the property, + // so what the spy does after its own implementation is replaced is not something + // this row may rely on. It captures the persisting implementation and drives it by + // hand: the first write lands in the map and then rejects, every write after it + // persists normally - exactly the order a compensation write needs to succeed in. + const originalUpdate = ( + mockContext.globalState.update as unknown as { + getMockImplementation: () => ((key: string, value: unknown) => unknown) | undefined + } + ).getMockImplementation() + if (typeof originalUpdate !== "function") { + throw new Error("the storage mock no longer carries its persisting implementation") + } + let storeAnswered = false + vi.spyOn(mockContext.globalState, "update").mockImplementation((key: string, value: unknown) => { + originalUpdate(key, value) + if (storeAnswered) { + return Promise.resolve() + } + storeAnswered = true + return Promise.reject(new Error("durable write failed after the value landed")) + }) + await expect( + provider["savePersistedViewState"]({ mode: undefined, currentApiConfigName: undefined }), + ).rejects.toThrow("durable write failed after the value landed") + // The value the store applied before failing is gone again: the durable map holds + // exactly what it held before the attempt, cleared entry and all. + const after = mockContext.globalState.get("viewStates") as Record + expect(after).toEqual(seeded) + // And the tombstone the clear branch added is undone by the same catch: the write + // it described never became durable. + expect(ClineProvider["clearedViewStateIds"].has("u5-view")).toBe(false) await provider.dispose() }) @@ -9060,6 +9127,14 @@ describe("ClineProvider", () => { expect(ClineProvider["clearedViewStateIds"].has("u2b-stable")).toBe(true) const restored = mockContext.globalState.get("viewStates") as Record expect(restored).toEqual({ ...seeded, "u2b-broken": null }) + // The viewStates writes still standing are this row's own decisions - the seed and + // the clear. The re-key's prune threw before dispatching its write, so the store is + // owed no compensation rewrite for it either. + const updateCalls = (mockContext.globalState.update as unknown as { mock: { calls: unknown[][] } }) + .mock.calls + .map((call) => call[0]) + .filter((key) => key === "viewStates") + expect(updateCalls).toEqual(["viewStates", "viewStates"]) await provider.dispose() }) From 5b02fd902852a8027598513a27ef7168012b1066 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:23:43 +0800 Subject: [PATCH 28/34] webview: give each activation group its own eviction record Addresses review cid 4753366490. The reviewed bytes anchored the rule on the save-site push into the shared list; in the current bytes that push sits in _recordActivationEvictions, which all three write paths call. The rollback read the eviction record off the instance: one shared list every landed write pushes, which any new activation snapshot restarts. Tracking shared is not tracking per operation - when a newer activation displaced a group's window, the waiting rollback either consumed the newer group's evictions (resurrecting an entry its own write never dropped) or lost its own record with the restart and restored nothing. Each snapshot now creates its record and carries it in the returned object; the write paths fill the record the group that is currently open opened, alongside the shared lists, and a rollback consumes its snapshot's record. The instance pointer is released when that group's window closes. The shared lists keep the same content while a group's window is open and remain inspectable, but the rollback no longer depends on them. Test side: a new row runs two activation groups on one provider with no rollback between them. The first group's save evicts the oldest entry; a second activation starts - displacing the first group's record from the shared list - and its save evicts the next oldest. The second rollback must restore exactly its own eviction and leave the first group's entry alone; the first rollback, run after the displacement, must still restore what its own write dropped. Red against the shared-list rollback on the second half (undefined against the seeded entry); against a snapshot that reuses the live record, red on the first half; with a record the writes never fill, red together with the two older restore rows. --- src/core/webview/ClineProvider.ts | 101 ++++++++++++++---- .../webview/__tests__/ClineProvider.spec.ts | 66 ++++++++++++ 2 files changed, 146 insertions(+), 21 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index c71a04d1fa7..d5cd84198d1 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -281,12 +281,27 @@ function releaseProfileCreate(name: string): boolean { return false } +/** + * The evictions belonging to one activation group: the ids and dropped values that + * this instance's writes land while the group is in flight. The record is created + * when the group's snapshot starts and travels with that snapshot, so a rollback + * always consumes its own group's content even when a later activation has already + * started on the same instance and restarted the shared tracking list. + */ +type ActivationEvictionRecord = { + viewIds: string[] + entries: Map +} + type ProfileActivationSnapshot = { listApiConfigMeta: ProviderSettingsEntry[] | undefined currentApiConfigName: string | undefined viewCurrentApiConfigName: string | undefined providerSettings: RooCodeSettings viewApiConfiguration: ProviderSettings | undefined + // The evictions this group's writes land; its rollback consumes this record, + // not the instance's shared list. + viewStateEvictions: ActivationEvictionRecord } type ProviderManagerSnapshot = { @@ -621,24 +636,39 @@ export class ClineProvider private viewLocalState: Partial = {} /** - * View ids evicted from the durable viewStates map by this instance's writes - * since the last activation snapshot, recorded only once the write that dropped - * them has landed: the rollback restores exactly these entries, so a sibling's - * intentional pin clear is never resurrected, and neither is an eviction whose - * store rejected. + * View ids evicted from the durable viewStates map by this instance's landed + * writes since the last activation snapshot on this instance, + * _recordActivationEvictions appends only after the write that dropped them + * landed, so a rollback restores exactly these entries: a sibling's intentional + * pin clear is never resurrected, and neither is an eviction whose store + * rejected. While the current activation group's window is open this list holds + * the same content as that group's snapshot record; once a newer snapshot has + * started, the rollback consumes the record - see activationEvictionRecord - and + * this list just tracks the instance's recent writes. */ private prunedViewIdsDuringActivation: string[] = [] /** * The value each tracked eviction dropped, keyed by view id: the entry as the * retention prune saw it in the map it handed to the store, recorded with the same - * landed write that records the id above. A sibling view writes to the same durable - * map while an activation group is in flight, so the entry the activation evicted can - * hold a value newer than the one the activation snapshot captured. The rollback + * landed write that records the id above and in the current activation group's + * snapshot record. A sibling view writes to the same durable map while an + * activation group is in flight, so the entry the activation evicted can hold a + * value newer than the one the activation snapshot captured. The rollback * restores this value, because that is the value eviction actually removed. */ private prunedViewEntriesDuringActivation = new Map() + /** + * The eviction record the instance's writes currently fill: + * _snapshotProfileActivationState points it at a fresh record that travels with + * the snapshot it returns, and _recordActivationEvictions fills it alongside the + * shared lists above. A rollback consumes its own snapshot's record; a later + * activation replaces the pointer but can never reach the earlier record. The + * pointer is released when that snapshot's window closes. + */ + private activationEvictionRecord: ActivationEvictionRecord | null = null + /** * This view's pinned profile name from the view-local buffer. Exposed for * sibling-instance inspection (getAllInstances() filtering): `viewLocalState` @@ -1187,6 +1217,16 @@ export class ClineProvider for (const viewId of evicted) { this.prunedViewEntriesDuringActivation.set(viewId, statesBeforePrune[viewId]) } + const operation = this.activationEvictionRecord + if (operation) { + // Side by side with the shared lists: the record the current activation's + // snapshot carries is what its rollback consumes, and the shared list may + // have been restarted by a newer activation long before that rollback runs. + operation.viewIds.push(...evicted) + for (const viewId of evicted) { + operation.entries.set(viewId, statesBeforePrune[viewId]) + } + } } /** @@ -3242,7 +3282,13 @@ export class ClineProvider */ private _snapshotProfileActivationState(): ProfileActivationSnapshot { // The rollback may only restore entries this activation's own writes evict, and only - // with the values those writes dropped: both records start empty here. + // with the values those writes dropped. The record is created here and travels with + // the snapshot below: a newer activation replaces the instance's pointer but can + // never reach this record, so each rollback consumes exactly its own group's + // evictions. The shared fields carry the window's content for callers that inspect + // this instance's landed writes. + const viewStateEvictions: ActivationEvictionRecord = { viewIds: [], entries: new Map() } + this.activationEvictionRecord = viewStateEvictions this.prunedViewIdsDuringActivation = [] this.prunedViewEntriesDuringActivation.clear() // Capture only the provider-settings keys. getValues() returns the whole @@ -3261,6 +3307,7 @@ export class ClineProvider viewCurrentApiConfigName: this.viewLocalState?.currentApiConfigName, providerSettings, viewApiConfiguration: this.viewLocalState?.apiConfiguration, + viewStateEvictions, // The durable viewStates map is not captured here: the entries the activation's // writes evict are restored from the eviction record, which holds what each one // held when the prune dropped it - possibly a value a sibling wrote after this @@ -3314,21 +3361,27 @@ export class ClineProvider } try { // Restore the siblings the activation's pruning evicted, last, so it - // lands after the overlay restore's own pin write, with their original - // entry metadata - the metadata they had when the eviction dropped them, - // not the metadata the activation started with: a sibling can rewrite an - // entry between the snapshot and the eviction, and the value it committed - // is the value this restore has to put back. Only tracked evictions are - // restored: an entry a sibling deleted on purpose after the snapshot is - // newer than the snapshot too, and resurrecting it would undo the - // sibling's clear on reload. The mutation queue is per-instance, so - // sibling views keep writing to the durable map while an activation group - // is in flight; merge, never replace, to leave those newer writes alone. + // lands after the overlay restore's own pin write. The loop consumes the + // record the snapshot carries: the shared list on this instance restarts + // with every newer activation snapshot, and a rollback that ran after a + // newer activation had started would otherwise consume the newer group's + // content - resurrecting what it should leave alone, or missing its own. + // Entries come back with their original entry metadata - the metadata + // they had when the eviction dropped them, not the metadata the activation + // started with: a sibling can rewrite an entry between the snapshot and + // the eviction, and the value it committed is the value this restore has + // to put back. Only tracked evictions are restored: an entry a sibling + // deleted on purpose after the snapshot is newer than the snapshot too, + // and resurrecting it would undo the sibling's clear on reload. The + // mutation queue is per-instance, so sibling views keep writing to the + // durable map while an activation group is in flight; merge, never + // replace, to leave those newer writes alone. + const viewStateEvictions = snapshot.viewStateEvictions const restore = ClineProvider.persistedViewStateWriteQueue.then(async () => { const current = this.getPersistedViewStates({ fresh: true }) const merged = { ...current } - for (const viewId of this.prunedViewIdsDuringActivation) { - const entry = this.prunedViewEntriesDuringActivation.get(viewId) + for (const viewId of viewStateEvictions.viewIds) { + const entry = viewStateEvictions.entries.get(viewId) if (entry && !Object.hasOwn(merged, viewId) && !ClineProvider.clearedViewStateIds.has(viewId)) { merged[viewId] = entry } @@ -3342,6 +3395,12 @@ export class ClineProvider `[ClineProvider] profile-activation rollback failed for the durable viewStates map: ${error instanceof Error ? error.message : String(error)}`, ) } + if (this.activationEvictionRecord === snapshot.viewStateEvictions) { + // This snapshot's window has closed: later writes belong to no activation + // until a new snapshot starts, and must not keep filling a record that + // no rollback will ever consume. + this.activationEvictionRecord = null + } } /** diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 8f00f0c1f4b..5e4df0f8ce2 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -9415,6 +9415,72 @@ describe("ClineProvider", () => { await sibling.dispose() }) + it("keeps each activation group's rollback to the evictions its own writes made", async () => { + // Review cid 4753366490: the rollback read the eviction record off this instance, + // where every landed write - activation or not - pushes one shared list, and any + // new activation snapshot restarts it. Tracking has to belong to the activation + // whose rollback consumes it. One provider here runs two activation groups + // without a rollback in between: the first group's save evicts the oldest entry, + // a second activation starts (which displaces the first group's record from the + // shared list), and its own save evicts the next oldest. Rolling back the second + // group must restore only its own eviction, and rolling back the first must still + // restore what its own write dropped. A rollback that reads the shared list at + // restore time gets the wrong group's content: it resurrects what it should not, + // or fails to resurrect its own. + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider["setViewStateId"]("g1-stable") + // The durable map sits exactly at the cap: each group's pin write is growth + // that has to evict the oldest entry then standing. + const seeded: Record = { + "g1-evict-view": { mode: "code", currentApiConfigName: "g-old-profile", updatedAt: 0 }, + } + for (let i = 1; i <= 49; i++) { + seeded["g-fill-" + i] = { mode: "code", updatedAt: i } + } + await provider.contextProxy.setValue("viewStates", seeded) + // Tombstone membership is process-level, so the two ids the rollbacks must + // restore are normalized here first: nothing in this row clears them, but a + // leftover claim from another module run could gate the restore on its own. + ClineProvider["clearedViewStateIds"].delete("g1-evict-view") + ClineProvider["clearedViewStateIds"].delete("g-fill-1") + const firstGroup = provider["_snapshotProfileActivationState"]() + await provider["savePersistedViewState"]({ currentApiConfigName: "g1-new-profile", updatedAt: 9101 }) + // The second activation starts on the same instance while the first group has + // been saved but not rolled back. + await provider["setViewStateId"]("g2-stable") + const secondGroup = provider["_snapshotProfileActivationState"]() + await provider["savePersistedViewState"]({ currentApiConfigName: "g2-new-profile", updatedAt: 9202 }) + await provider["_restoreProfileActivationState"](secondGroup) + const afterSecond = mockContext.globalState.get("viewStates") as Record + // The second group's rollback restores its own eviction: the fill its pin write + // dropped is back with the value the eviction removed. And it stops there - the + // entry the first group evicted was not this group's write, so this rollback + // may not resurrect it on the way. + expect(afterSecond["g-fill-1"]).toEqual(seeded["g-fill-1"]) + expect(afterSecond["g1-evict-view"]).toBeUndefined() + await provider["_restoreProfileActivationState"](firstGroup) + const afterFirst = mockContext.globalState.get("viewStates") as Record + // The first group's record has to have survived the second activation starting: + // rolling this group back still restores what its own write evicted, with the + // value that eviction dropped. On the shared list the first group's entry was + // already displaced by the time its rollback ran - that is what this row drives + // red against a rollback that reads the list instead of its group's record. + expect(afterFirst["g1-evict-view"]).toEqual(seeded["g1-evict-view"]) + // The rest of the accounting: the fill the second rollback restored stays + // restored, and the first group's pin stands - neither rollback un-pins it + // (a rollback's overlay restore lands on the view id this instance carries, by + // then the second group's). + expect(afterFirst["g-fill-1"]).toEqual(seeded["g-fill-1"]) + expect((afterFirst["g1-stable"] as Record | undefined)?.currentApiConfigName).toBe("g1-new-profile") + await provider.dispose() + }) + it("re-points live views pinned to a renamed profile onto the new name", async () => { const provider = new ClineProvider( mockContext, From c5b735f1324deefee0453d0a14f956fbec94b066 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:56:14 +0800 Subject: [PATCH 29/34] style(webview): reflow the provider spec to the repository prettier config The formatting drift came from 2e8db66019530dd90d71cef8425a16481a1d5b57: prettier --check passes on 360f534b2d8a99b07e715f7d85810a786821a4df and fails on that commit and on both later cells of this chain, so the rows themselves were written outside the repository prettier config rather than reformatted by a later step. This commit only reformats; it changes no assertion and no production byte. Measured on the reformatted bytes: prettier --check exit 0, eslint --max-warnings=0 exit 0, and vitest run --config vitest.core.config.ts core/webview/__tests__/ClineProvider.spec.ts reproduces the candidate counts of the three cells it stacks on (542 passed at 5b02fd902852a8027598513a27ef7168012b1066 before the reflow). No executable line is added: the mutation gate metric is computed over test-excluded sources, so this file does not enter it. Co-Authored-By: Claude --- .../webview/__tests__/ClineProvider.spec.ts | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 5e4df0f8ce2..2971cd05e8c 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -9019,8 +9019,9 @@ describe("ClineProvider", () => { // tombstone restore above is the whole repair such a throw needs; compensating an // attempt that never reached the store is a round trip nobody asked for. The call // list is reached through the vitest shape because the mock context erases types. - const updateCalls = (mockContext.globalState.update as unknown as { mock: { calls: unknown[][] } }) - .mock.calls + const updateCalls = ( + mockContext.globalState.update as unknown as { mock: { calls: unknown[][] } } + ).mock.calls .map((call) => call[0]) .filter((key) => key === "viewStates") expect(updateCalls).toEqual(["viewStates"]) @@ -9056,7 +9057,7 @@ describe("ClineProvider", () => { // persists normally - exactly the order a compensation write needs to succeed in. const originalUpdate = ( mockContext.globalState.update as unknown as { - getMockImplementation: () => ((key: string, value: unknown) => unknown) | undefined + getMockImplementation: () => ((key: string, value: unknown) => unknown) | undefined } ).getMockImplementation() if (typeof originalUpdate !== "function") { @@ -9130,8 +9131,9 @@ describe("ClineProvider", () => { // The viewStates writes still standing are this row's own decisions - the seed and // the clear. The re-key's prune threw before dispatching its write, so the store is // owed no compensation rewrite for it either. - const updateCalls = (mockContext.globalState.update as unknown as { mock: { calls: unknown[][] } }) - .mock.calls + const updateCalls = ( + mockContext.globalState.update as unknown as { mock: { calls: unknown[][] } } + ).mock.calls .map((call) => call[0]) .filter((key) => key === "viewStates") expect(updateCalls).toEqual(["viewStates", "viewStates"]) @@ -9186,7 +9188,7 @@ describe("ClineProvider", () => { // below, so storage writes stay enabled for the success control. const originalUpdate = ( mockContext.globalState.update as unknown as { - getMockImplementation: () => ((key: string, value: unknown) => unknown) | undefined + getMockImplementation: () => ((key: string, value: unknown) => unknown) | undefined } ).getMockImplementation() if (typeof originalUpdate !== "function") { @@ -9261,7 +9263,10 @@ describe("ClineProvider", () => { // The whole map storage took, not a sample of it: both pins back under the replacement // name with their mode kept and stamped at the fixed clock, the oldest fillers gone, // every other entry exactly as seeded. - const expectedAfterLand: Record = {} + const expectedAfterLand: Record< + string, + { mode?: string; currentApiConfigName?: string; updatedAt: number } + > = {} for (const [viewId, entry] of Object.entries(seeded)) { if (evictedByThisWrite.includes(viewId)) { continue @@ -9477,7 +9482,9 @@ describe("ClineProvider", () => { // (a rollback's overlay restore lands on the view id this instance carries, by // then the second group's). expect(afterFirst["g-fill-1"]).toEqual(seeded["g-fill-1"]) - expect((afterFirst["g1-stable"] as Record | undefined)?.currentApiConfigName).toBe("g1-new-profile") + expect((afterFirst["g1-stable"] as Record | undefined)?.currentApiConfigName).toBe( + "g1-new-profile", + ) await provider.dispose() }) From 9ff9ccc48501590f1047497abc0848b7f2b4ab0f Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:10:55 +0800 Subject: [PATCH 30/34] webview: re-point the retained task when launching repairs the pin Addresses review cid 4506514002. The launch repair wrote this view's pin together with the seed read's settings and posted the state, while the task this view retained kept the API handler and the sticky profile name it was started with - both built from the profile that no longer resolves. The posted state prefers the task's own apiConfiguration, so the sidebar showed the replacement while the conversation still sent the missing profile's configuration, and every later request used it. The repair now re-points the retained task between the pin write and the state post, following the sibling re-pin in ClineProvider (rePinViewLocalStateForDeletedProfile): the handler is rebuilt with the replacement settings - forced, because the profile behind the conversation changed rather than its settings alone - and the sticky name follows the replacement. Two guards keep it narrow. Only a task whose own sticky name is the missing profile is touched, so a conversation that follows another profile is not switched by a repair nobody asked for. And nothing is touched when the seed read produced no settings: there is nothing to hand over, and rebuilding then would serve whatever profile the shared store names next under the replacement's name. The row's own wording - update the task only when the replacement settings are available - is applied to both halves, which is stricter than the sibling path, where the sticky half runs whenever the task follows the deleted profile. Direct private access through bracket notation for both halves: updateTaskApiHandlerIfNeeded and persistStickyProviderProfileToCurrentTask are private on the class, and this handler sits outside it. Test side: three rows on the launch re-pin. One runs a task that follows the missing profile and requires both halves, named in full call order - launch posts an initial state first, so the sequence is asserted end to end: initial post, pin write, handler rebuild, sticky write, repair post. One runs a task that follows a different profile and requires that neither half runs while the view repair itself still lands. One lands the re-pin without a settings snapshot - the record confirmed gone between the lookup and the read - and requires the task to keep the handler it has. Against the parent bytes all three rows fail, the first on the missing rebuild and the other two on the absent doubles. Seven mutants of the new block are each killed by a row: settings half removed from the guard, sticky name compared against the replacement, rebuild not forced, sticky re-pointed to the missing name, sticky call dropped, guard negated, and the whole repair moved after the post. [cr 4506514002] --- .../__tests__/webviewMessageHandler.spec.ts | 184 ++++++++++++++++++ src/core/webview/webviewMessageHandler.ts | 14 ++ 2 files changed, 198 insertions(+) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 38008ab5343..fc958881071 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -1150,6 +1150,190 @@ describe("webviewMessageHandler - webviewDidLaunch", () => { ) }) + it("re-points the retained task onto the replacement settings before posting the repaired state", async () => { + // Review cid 4506514002: this repair re-points the view, and the task the view retained is the + // other half. A task started under the missing profile carries its own API handler and its own + // sticky profile name, and the state posted below prefers the task's own apiConfiguration - so a + // repaired pin with an untouched task posts the missing profile's configuration and every later + // request uses it. + // Double assertion: the spec-wide provider double only declares the members most tests drive; + // this structural widening keeps these rows free of any, and a real Task cannot be constructed + // here, so only the fields this repair reads are modeled. + const taskRepair = mockClineProvider as unknown as { + updateTaskApiHandlerIfNeeded: ReturnType + persistStickyProviderProfileToCurrentTask: ReturnType + } + const originalTaskRepair = { + updateTaskApiHandlerIfNeeded: taskRepair.updateTaskApiHandlerIfNeeded, + persistStickyProviderProfileToCurrentTask: taskRepair.persistStickyProviderProfileToCurrentTask, + } + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation( + async (name: string) => name === "shared-profile", + ) + // The task follows the profile this view was pinned to - the one that no longer resolves. + vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ + taskId: "task-1", + taskApiConfigName: "view-local-profile", + } as unknown as ReturnType) + const order: string[] = [] + // Asserted through the locals: the finally below puts the provider properties back to undefined, + // so the doubles are named before they are installed. + const rebuild = vi.fn(() => { + order.push("handler") + }) + const sticky = vi.fn(async () => { + order.push("sticky") + }) + taskRepair.updateTaskApiHandlerIfNeeded = rebuild + taskRepair.persistStickyProviderProfileToCurrentTask = sticky + vi.mocked(mockClineProvider.saveViewState).mockImplementation(async () => { + order.push("save") + }) + vi.mocked(mockClineProvider.postStateToWebview).mockImplementation(async () => { + order.push("post") + }) + try { + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + } finally { + taskRepair.updateTaskApiHandlerIfNeeded = originalTaskRepair.updateTaskApiHandlerIfNeeded + taskRepair.persistStickyProviderProfileToCurrentTask = + originalTaskRepair.persistStickyProviderProfileToCurrentTask + // The launch suite clears mock calls between rows but not implementations, so the task double + // installed above is put back at the module-level default (no task) here. + vi.mocked(mockClineProvider.getCurrentTask).mockReset() + } + + // The handler is rebuilt with the same record the pin write carried, forced because the profile + // behind the conversation changed rather than its settings alone. + expect(rebuild).toHaveBeenCalledWith( + { + id: "shared-profile-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }, + { forceRebuild: true }, + ) + // The sticky name follows the replacement too, so the conversation persists under it. + expect(sticky).toHaveBeenCalledWith("shared-profile") + // Launch posts an initial state before this repair runs, so the sequence is named in full: the + // task repair sits between the pin write and the state post that carries it. + expect(order).toEqual(["post", "save", "handler", "sticky", "post"]) + }) + + it("leaves a retained task that follows a different profile alone", async () => { + // Review cid 4506514002 negative control: the conversation this view retained may follow another + // profile than the pin being repaired. Forcing the replacement onto that task switches a + // conversation the user never touched and rewrites its persisted profile name, so only the view + // is repaired. + // Double assertion: the spec-wide provider double only declares the members most tests drive; + // this structural widening keeps these rows free of any, and a real Task cannot be constructed + // here, so only the fields this repair reads are modeled. + const taskRepair = mockClineProvider as unknown as { + updateTaskApiHandlerIfNeeded: ReturnType + persistStickyProviderProfileToCurrentTask: ReturnType + } + const originalTaskRepair = { + updateTaskApiHandlerIfNeeded: taskRepair.updateTaskApiHandlerIfNeeded, + persistStickyProviderProfileToCurrentTask: taskRepair.persistStickyProviderProfileToCurrentTask, + } + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation( + async (name: string) => name === "shared-profile", + ) + vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ + taskId: "task-1", + taskApiConfigName: "other-profile", + } as unknown as ReturnType) + // Asserted through the locals: the finally below puts the provider properties back to undefined, + // so the doubles are named before they are installed. + const rebuild = vi.fn() + const sticky = vi.fn(async () => {}) + taskRepair.updateTaskApiHandlerIfNeeded = rebuild + taskRepair.persistStickyProviderProfileToCurrentTask = sticky + try { + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + } finally { + taskRepair.updateTaskApiHandlerIfNeeded = originalTaskRepair.updateTaskApiHandlerIfNeeded + taskRepair.persistStickyProviderProfileToCurrentTask = + originalTaskRepair.persistStickyProviderProfileToCurrentTask + // The launch suite clears mock calls between rows but not implementations, so the task double + // installed above is put back at the module-level default (no task) here. + vi.mocked(mockClineProvider.getCurrentTask).mockReset() + } + + expect(rebuild).not.toHaveBeenCalled() + expect(sticky).not.toHaveBeenCalled() + // The view repair itself is unchanged: pin and settings land together, and the state is posted + // twice - the launch initial post and this repair's post. + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith({ + apiConfiguration: { + id: "shared-profile-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }, + currentApiConfigName: "shared-profile", + }) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(2) + }) + + it("leaves the retained task alone when the re-pin lands without a settings snapshot", async () => { + // Review cid 4506514002: the rebuild needs settings to hand over. Without them the task keeps + // the handler it has instead of picking up whatever profile the shared store names next under the + // replacement's name. + // Double assertion: the spec-wide provider double only declares the members most tests drive; + // this structural widening keeps these rows free of any, and a real Task cannot be constructed + // here, so only the fields this repair reads are modeled. + const taskRepair = mockClineProvider as unknown as { + updateTaskApiHandlerIfNeeded: ReturnType + persistStickyProviderProfileToCurrentTask: ReturnType + } + const originalTaskRepair = { + updateTaskApiHandlerIfNeeded: taskRepair.updateTaskApiHandlerIfNeeded, + persistStickyProviderProfileToCurrentTask: taskRepair.persistStickyProviderProfileToCurrentTask, + } + let sharedChecks = 0 + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation(async (name: string) => { + if (name !== "shared-profile") { + return false + } + // The record is there for the lookup before the seed read and gone for the re-check after it: + // the deleted-separately case, where the re-pin completes. + return ++sharedChecks === 1 + }) + vi.mocked(double.providerSettingsManager.getProfile).mockRejectedValue(new Error("profile vanished mid-flight")) + vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ + taskId: "task-1", + taskApiConfigName: "view-local-profile", + } as unknown as ReturnType) + // Asserted through the locals: the finally below puts the provider properties back to undefined, + // so the doubles are named before they are installed. + const rebuild = vi.fn() + const sticky = vi.fn(async () => {}) + taskRepair.updateTaskApiHandlerIfNeeded = rebuild + taskRepair.persistStickyProviderProfileToCurrentTask = sticky + try { + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + } finally { + taskRepair.updateTaskApiHandlerIfNeeded = originalTaskRepair.updateTaskApiHandlerIfNeeded + taskRepair.persistStickyProviderProfileToCurrentTask = + originalTaskRepair.persistStickyProviderProfileToCurrentTask + // The launch suite clears mock calls between rows but not implementations, so the task double + // installed above is put back at the module-level default (no task) here. + vi.mocked(mockClineProvider.getCurrentTask).mockReset() + } + + expect(rebuild).not.toHaveBeenCalled() + expect(sticky).not.toHaveBeenCalled() + // The fallback repair still lands, exactly as it did before this change. + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith({ + apiConfiguration: undefined, + currentApiConfigName: "shared-profile", + }) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(2) + }) + it("records the legacy repair without activating a profile when no name is listed", async () => { double.providerSettingsManager.listConfig = vi .fn() diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index c9cc10f770a..7472a12a65f 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -720,6 +720,20 @@ export const webviewMessageHandler = async ( apiConfiguration: seedSettings, currentApiConfigName: globalConfigName, }) + // Review cid 4506514002: the view is not the only thing this repair re-points. The task this + // view retained carries its own API handler and its own sticky profile name, both built from + // the profile that no longer resolves, and the state posted below prefers the task's own + // apiConfiguration - so a repaired pin with an untouched task posts the missing profile's + // configuration and every later request uses it. Same guard as the sibling re-pin in + // ClineProvider (rePinViewLocalStateForDeletedProfile): only a task that really follows the + // missing name is re-pointed, and only once the replacement settings were read. Direct + // private access: both halves mutate this provider's own task and the class keeps them + // private from callers outside it. + const rePinnedTask = provider.getCurrentTask() + if (seedSettings && rePinnedTask?.taskApiConfigName === currentConfigName) { + provider["updateTaskApiHandlerIfNeeded"](seedSettings, { forceRebuild: true }) + await provider["persistStickyProviderProfileToCurrentTask"](globalConfigName) + } // The repair changes what this view resolves to, so the state has to be posted: the // two writes above update provider state without posting it, and the listApiConfig // message below carries the profile list only, so without this the webview keeps From 297e16138089afb68644fc3c94624732951d1e03 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:26:30 +0800 Subject: [PATCH 31/34] webview: re-read the replacement profile once before giving up the seed Addresses review cid 4506513995. The launch repair read the profile it is re-pinning this view to exactly once: a read that threw - the record vanished between the hasConfig check above and the read - ended the repair with an empty overlay, even when the record was readable a moment later. What the row asks for is a retry before the re-pin completes, and its prompt-to-fix is literally retry until the profile is available. What is implemented is a bounded re-read: two attempts, each preceded by a re-check of hasConfig, success leaving the loop at once, and the empty overlay kept as the fallback. The bound is deliberate. The failure this catch handles is a record that was deleted during the launch, and retrying until available on a delete that already happened would hold this launch's listConfig continuation open on a profile nobody is going to restore, while the pin repair never needed the seed to land - it lands with an empty overlay today and the next launch reads the profile again. The re-check is what tells the two cases apart: a record still listed is unreadable-temporarily, so it is read again, and a record no longer listed is gone, so the retry stops there rather than producing the same error a second time. A create or a delete can land between the awaits here, so the answer from the lookup above is not reused. The alternative of rethrowing while the record is still listed was rejected on measured grounds: the surrounding continuation swallows it (the .catch on the listConfig chain posts an error log and nothing else), so the launch would lose the listApiConfig post and the state post that this repair just added - a new regression paid for a literal reading of the row. Test side: five rows on the re-read. One has the first read fail and the second succeed, and requires the seed the re-pin carries to be the record the second attempt read. One keeps the record listed for the first attempt and takes it away for the re-check after it, and requires exactly one read. One takes the record away before the first attempt and requires no read at all and no failure reported, because a record that is gone is not a read that failed. One leaves the record listed and unreadable and requires exactly two reads, then the fallback: the call count is the bound. One is the control on the success path: a profile that reads first try is read once, so the re-read is recovery, not confirmation. Against the parent bytes three of the five fail (the two read-count rows and the no-read row); the other two assert absence and are green at the parent by construction, which is why each is also pinned by a mutant. Mutants (candidate bytes edited, then git hash-object -w; each blob verified with git cat-file -e, which exits 0; each search string measured 1 occurrence before the edit and 0 after): - bound 2 -> 0 attempts, a0f013e42a69389f9598df716dd463ad557ad8d9: 10 failed - bound 2 -> 1 attempt, 420f2cb6d29a6300f9b300f86af22c17d5eeb97e: 2 failed - bound 2 -> 3 attempts, ad951626d8faecfd14047dd62146c6ff3782234f: 1 failed - hasConfig re-check deleted, 586e462f31fbc12673ae7da06969ffd8a09f4add: 2 failed - re-check keyed on the missing name, a1923a990fde9e60c8b61686c4c159ec2586cd2e: 10 failed - success no longer leaves the loop, ba774e4b66db96518d77b16e78ae73ad5522e159: 1 failed - failure report no longer needs an actual failed read, 8fa65a4ad1cf8e6a50a5ea7e8d36382ddd447e40: 1 failed - failure caught but never reported, f8c0667454554c9532f0ceb3eda5ae0bf77912a7: 3 failed [cr 4506513995] --- .../__tests__/webviewMessageHandler.spec.ts | 147 ++++++++++++++++++ src/core/webview/webviewMessageHandler.ts | 37 +++-- 2 files changed, 173 insertions(+), 11 deletions(-) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index fc958881071..a62ddac62f4 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -1150,6 +1150,153 @@ describe("webviewMessageHandler - webviewDidLaunch", () => { ) }) + it("re-reads the replacement profile when the first seed read fails and the record is still listed", async () => { + // Review cid 4506513995: a seed read that fails on a transient miss used to end the repair with an + // empty overlay, even though the record was readable a moment later. The re-read is bounded, and + // it only runs while the record is still listed. + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation( + async (name: string) => name === "shared-profile", + ) + vi.mocked(double.providerSettingsManager.getProfile) + .mockRejectedValueOnce(new Error("profile not readable yet")) + .mockResolvedValue({ + id: "shared-profile-id", + name: "shared-profile", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }) + + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + + // Both attempts target the profile this view is being pinned to. + expect(double.providerSettingsManager.getProfile).toHaveBeenCalledTimes(2) + expect(double.providerSettingsManager.getProfile).toHaveBeenCalledWith({ name: "shared-profile" }) + // The settings the re-pin carries are the record the second attempt read, not an empty + // overlay: the retry is what kept the snapshot. + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith({ + apiConfiguration: { + id: "shared-profile-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }, + currentApiConfigName: "shared-profile", + }) + // A read that succeeded on the second attempt is not reported as a failed seed read. + expect(mockClineProvider.log).not.toHaveBeenCalledWith( + expect.stringContaining('Seed read failed for "shared-profile"'), + ) + }) + + it("stops the re-read when the record is gone at the re-check before the second attempt", async () => { + // Review cid 4506513995 negative control: the re-read is for a record that is still there. + // Once the re-check says it is gone, a second read only produces the same error again, and + // the empty overlay is already the answer for that case. + // The counter is keyed on the profile this view is pinned to: the lookup above and the first + // attempt see the record, the re-check before the second attempt does not. + let sharedLookups = 0 + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation(async (name: string) => { + if (name !== "shared-profile") { + return false + } + sharedLookups += 1 + return sharedLookups <= 2 + }) + vi.mocked(double.providerSettingsManager.getProfile).mockRejectedValue(new Error("profile vanished mid-flight")) + + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + + // One read, not two: the re-check stopped the retry, which is what keeps the launch from + // chasing a delete that already happened. + expect(double.providerSettingsManager.getProfile).toHaveBeenCalledTimes(1) + // The repair still lands, with the empty overlay a re-pin had before the seed existed. + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith({ + apiConfiguration: undefined, + currentApiConfigName: "shared-profile", + }) + expect(mockClineProvider.log).toHaveBeenCalledWith( + expect.stringContaining('Seed read failed for "shared-profile"'), + ) + }) + + it("does not read or report a failure when the record is gone at the re-check before the first attempt", async () => { + // Review cid 4506513995: the re-check is also the guard against chasing a delete that already + // happened before any read ran. A record that is gone is not a read that failed, so the repair + // lands with the empty overlay and nothing is reported as a failed seed read. + // Keyed on the profile this view is pinned to: the lookup above sees the record, the re-check + // before the first attempt does not. + let sharedLookups = 0 + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation(async (name: string) => { + if (name !== "shared-profile") { + return false + } + sharedLookups += 1 + return sharedLookups <= 1 + }) + + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + + expect(double.providerSettingsManager.getProfile).toHaveBeenCalledTimes(0) + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith({ + apiConfiguration: undefined, + currentApiConfigName: "shared-profile", + }) + expect(mockClineProvider.log).not.toHaveBeenCalledWith( + expect.stringContaining('Seed read failed for "shared-profile"'), + ) + }) + it("gives up after the second attempt instead of retrying while the record stays unreadable", async () => { + // Review cid 4506513995: the bound is the design. The prompt-to-fix says retry until the + // profile is available, and a record that stays listed but unreadable is exactly the case + // where that never stops. The launch gives up after the second attempt and lands the repair + // with an empty overlay rather than holding the launch open. + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation( + async (name: string) => name === "shared-profile", + ) + vi.mocked(double.providerSettingsManager.getProfile).mockImplementation(async () => { + throw new Error("profile listed but not readable") + }) + + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + + // The call count is the assertion: two attempts, then the launch moves on. + expect(double.providerSettingsManager.getProfile).toHaveBeenCalledTimes(2) + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith({ + apiConfiguration: undefined, + currentApiConfigName: "shared-profile", + }) + expect(mockClineProvider.saveViewState).toHaveBeenCalledTimes(1) + // One report of the failed seed read, not one per attempt: the retry is internal to the repair. + const seedReadFailures = vi + .mocked(mockClineProvider.log) + .mock.calls.filter((call) => String(call[0]).includes('Seed read failed for "shared-profile"')) + expect(seedReadFailures).toHaveLength(1) + }) + + it("does not re-read the replacement profile when the first seed read succeeds", async () => { + // Review cid 4506513995 control on the success path: the re-read recovers from a failed + // attempt, it does not confirm a good one, so a working profile is not read twice on every + // webview open. + vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation( + async (name: string) => name === "shared-profile", + ) + + await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" }) + await new Promise((resolve) => setImmediate(resolve)) + + expect(double.providerSettingsManager.getProfile).toHaveBeenCalledTimes(1) + expect(mockClineProvider.saveViewState).toHaveBeenCalledWith({ + apiConfiguration: { + id: "shared-profile-id", + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-shared-profile", + }, + currentApiConfigName: "shared-profile", + }) + }) it("re-points the retained task onto the replacement settings before posting the repaired state", async () => { // Review cid 4506514002: this repair re-points the view, and the task the view retained is the // other half. A task started under the missing profile carries its own API handler and its own diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 7472a12a65f..1051d59a346 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -693,18 +693,33 @@ export const webviewMessageHandler = async ( // pin write fails leaves the view holding the settings of the profile it is about to be // pinned to rather than the missing profile's stale buffer. let seedSettings: ProviderSettings | undefined - try { - const { name: _seedProfileName, ...seedProfile } = - await provider.providerSettingsManager.getProfile({ - name: globalConfigName, - }) - seedSettings = seedProfile as ProviderSettings - } catch (error) { - // The record can vanish between the hasConfig check above and this read. Fall back to - // an empty overlay - what a re-pin left before the seed existed - so the pin write - // still lands instead of the whole repair being lost to this error. + // Review cid 4506513995 asks for this read to be retried before the re-pin completes. The + // prompt-to-fix is literally "retry until the profile is available"; what is implemented is + // a bounded re-read - two attempts - because the failure handled here is a record deleted + // during the launch, and an unbounded retry would hold the launch open on a delete nobody + // is going to undo. Each attempt re-checks hasConfig first rather than trusting the lookup + // above, since a create or a delete can land between two awaits: a record that came back is + // read, a record that is gone is stopped at instead of read again. The empty overlay below + // stays the fallback for every path that ends without a record. + let seedReadFailure: string | undefined + for (let seedAttempt = 1; seedAttempt <= 2; seedAttempt++) { + if (!(await provider.providerSettingsManager.hasConfig(globalConfigName))) { + break + } + try { + const { name: _seedProfileName, ...seedProfile } = + await provider.providerSettingsManager.getProfile({ + name: globalConfigName, + }) + seedSettings = seedProfile as ProviderSettings + break + } catch (error) { + seedReadFailure = String(error) + } + } + if (!seedSettings && seedReadFailure) { provider.log( - `[webviewDidLaunch] Seed read failed for "${globalConfigName}"; re-pinning without a settings snapshot: ${String(error)}`, + `[webviewDidLaunch] Seed read failed for "${globalConfigName}"; re-pinning without a settings snapshot: ${seedReadFailure}`, ) } // The durable view entry carries only mode and currentApiConfigName (see From 6001e8d07fcd609aa6f48fdbb5d5ad6cf6d10483 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:15:04 +0800 Subject: [PATCH 32/34] [cr 4506513941] carry the activated settings into the activating view Review row 4506513941 (Major, Functional Correctness, created 2026-11-08T14:14:30Z against 446a89921fd7) sits on original_line 4989, whose text is the ": providerSettings" fallback now at ClineProvider.ts:5721. Every activation group wrote the shared provider store and then cleared this view's apiConfiguration overlay, so the acting view kept its pin with no settings of its own and every later read - the state posted to the webview and the apiConfiguration a new task takes - answered from the shared store. When a sibling view activated another profile, this view served that profile's settings under its own name. Both activation sites now carry the activated record into the view's buffer: persistProviderProfile writes normalizedSettings (line 3781) and activateProviderProfileUnlocked writes providerSettings (line 4365). The cleared overlay was there so that no previously loaded profile could shadow the new settings in getState(); carrying the record this activation just stored gives that guarantee directly instead. Explicit shared-setting overrides keep working: the save-without-activation refresh, the delete survivor swap and the rename pass still rewrite pinned overlays, and the delete fallback that clears the overlay when no survivor settings could be resolved is untouched. Not fixed here, stated plainly: a view whose pinned record could not be read at load time still holds a pin without settings and still takes the shared store (loadViewState logs it at ClineProvider.ts:1448-1461, and a later save of that profile refreshes the overlay). This cell closes the sibling-activation half of the review row, not that residue. The pin half of the pair was already isolated, so the pin assertion inside the sibling row is green at the parent by construction. Verification. Test caliber: cmd.exe /c "\src\node_modules\.bin\vitest.CMD" run --config vitest.core.config.ts , cwd \src. - Red first (parent 297e16138089 production file, new rows only): 3 failed | 542 passed (545). First failing assertion src/core/webview/__tests__/ClineProvider.spec.ts:5260:56 - "expected undefined to deeply equal { apiProvider: openrouter, apiKey: sk-activated }". The other two rows fail at 5299:56 and 5368:58; the last one received the sibling's openrouter/sk-b settings object, which is the reported symptom itself. - Candidate: 545 passed (545). Each new row alone: 1 passed | 544 skipped (545), repeated clean. - Affected group core/webview: 38 test files, 1271 passed (1271); the parent baseline for the same group is 38 files, 1268 passed. - Mutants, each written with git hash-object -w and proven present with git cat-file -e (exit 0) before and after the run: m1 site 1 argument back to undefined e762c3bf0f1707ac6d83efe5b2cebee15d2f41de -> 1 failed | 2 passed | 542 skipped; m2 site 2 argument back to undefined 897bf26a626df41771913b6173f802e5f166a149 -> 2 failed | 1 passed | 542 skipped; m3 site 1 raw caller payload instead of the read-back record dd8d6011e6774ab367372aec1d65c9585daa4931 -> 1 failed | 2 passed | 542 skipped; m4 site 2 write deleted a6de83adf04da99e611ae5a3ce0736ee66baeb1f -> 2 failed | 1 passed | 542 skipped; m5 site 1 write deleted fc14324d087043860b4a9bbcb01988c974a8fae8 -> 1 failed | 2 passed | 542 skipped. - Comment-only controls, green in both directions: +3 comments inside the Promise.allSettled array span e9ecffd3e6d95fdfebbfd2867d7235e4d433b720 and +3 comments above the group statement 7ab8c552616b74820ef2667a5589d820c1eaf96d both keep 545 passed while adding 3 file lines each; the executable-line count shows why the cell's notes sit outside the array: 2 -> 5 for the in-span control and 2 -> 2 for the out-of-span control. Removing all 19 comment lines this cell added 51d6e5704b1acae1320dcf2677cd26967d6701a7 removes 19 lines, 0 executable, and stays green. - Gates on the candidate and on the parent, named calibers: prettier --check on both files exit 0 in both states; tsc --noEmit -p tsconfig.json (cwd \src) exit 0 in both; eslint --max-warnings=0 exit 0 in both; eslint --prune-suppressions --max-warnings=0 exit 0 in both with core/webview/ClineProvider.ts no-explicit-any 7 -> 7 and core/webview/__tests__/ClineProvider.spec.ts 193 -> 193 (the suppressions file is rewritten wholesale 1306/1306 by --prune-suppressions and restored with git checkout every time, never hand-edited). - Host load at run time: 8 node.exe processes, 68770 MB free of 193956 MB total; os.loadavg() reports 0,0,0 on this platform, so it is not evidence. Per-cell executable changed lines (scripts/stryker-diff.mjs executableChangedLines over a -U0 diff of the production file): 2 - lines 3781 and 4365. The two in-array notes the writes replace were deleted, and the replacement notes were placed above the group statement on purpose. --- src/core/webview/ClineProvider.ts | 33 ++-- .../webview/__tests__/ClineProvider.spec.ts | 161 ++++++++++++++++++ 2 files changed, 184 insertions(+), 10 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index d5cd84198d1..98cc27aeaf9 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3749,6 +3749,18 @@ export class ClineProvider // Best-effort snapshot: when the prior mapping cannot be read the // compensation restores the mapping as absent. } + // setProviderSettings below writes the shared store directly, bypassing the view-local + // mutation path, so the buffer write that closes this group is what keeps this view's own + // settings in step with the shared store. It used to clear them - the note that sat inside + // the group said a stale loaded profile must not keep shadowing the new settings in + // getState() - and that half of the contract still holds: the write below carries the + // record this activation just stored, so nothing stale can shadow it. Review row + // 4506513941 (Major, created 2026-11-08T14:14:30Z, printed at line 4989 of the anchor + // blob 446a89921fd7, whose text is the ": providerSettings" fallback now at line 5721) + // reports the other half: with an emptied overlay the acting view kept its pin but lost + // its settings, so every later read took whatever the shared store held - and a sibling + // view's activation writes its own profile there, which left this view displaying and + // starting tasks on another profile's settings under its own name. // `allSettled` so the compensation below never races a write still in flight. const activationResults = await Promise.allSettled([ this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()), @@ -3766,11 +3778,7 @@ export class ClineProvider // this head. this.setModeConfig(mode, id), this.contextProxy.setProviderSettings(normalizedSettings), - // setProviderSettings writes the shared store directly, bypassing the - // view-local mutation path: clear this view's buffered apiConfiguration - // overlay (if any) so a stale loaded profile cannot keep shadowing the - // new settings in getState(). - this._saveViewLocalStateFromMutation({ apiConfiguration: undefined }), + this._saveViewLocalStateFromMutation({ apiConfiguration: normalizedSettings }), ]) const failedActivation = activationResults.find( (result): result is PromiseRejectedResult => result.status === "rejected", @@ -4331,6 +4339,15 @@ export class ClineProvider // See `upsertProviderProfile` for a description of what this is doing. const activationSnapshot = this._snapshotProfileActivationState() try { + // The buffer write that closes this group carries the activated record instead of clearing + // this view's apiConfiguration overlay. Clearing it kept the promise the removed in-array + // note made - no previously loaded profile shadows the newly activated settings in + // getState() - but review row 4506513941 (Major, created 2026-11-08T14:14:30Z, printed at + // line 4989 of the anchor blob 446a89921fd7, the ": providerSettings" fallback now at + // line 5721) names the other half: the empty overlay left this view holding a pin with no + // settings of its own, so every later read took the shared store, and a sibling view's + // activation replaces that with its own profile. The rollback restores the overlay this + // activation replaced, so a rejected group still leaves the view on its own settings. // `allSettled` so the compensation below never races a write still in flight. const activationResults = await Promise.allSettled([ this.contextProxy.setValue("listApiConfigMeta", await this.providerSettingsManager.listConfig()), @@ -4345,11 +4362,7 @@ export class ClineProvider // cached mapping commits with the activation, as in upsertProviderProfile. ...(writesModeConfig ? [this.setModeConfig(mode, id)] : []), this.contextProxy.setProviderSettings(providerSettings), - // setProviderSettings writes the shared store directly, bypassing the - // view-local mutation path: clear this view's buffered apiConfiguration - // overlay (if any) so a stale loaded profile cannot keep shadowing the - // new settings in getState(). - this._saveViewLocalStateFromMutation({ apiConfiguration: undefined }), + this._saveViewLocalStateFromMutation({ apiConfiguration: providerSettings }), ]) const failedActivation = activationResults.find( (result): result is PromiseRejectedResult => result.status === `rejected`, diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 2971cd05e8c..723843f9282 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -5219,6 +5219,167 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("carries the activated record into the acting view instead of clearing its overlay", async () => { + // Review row 4506513941 (Major, created 2026-11-08T14:14:30Z, printed at + // ClineProvider.ts line 4989 with original_line 4989): the activation group cleared + // this view's apiConfiguration overlay, so the view kept its pin but lost its own + // settings, and every later read answered from the shared store. The overlay must + // carry the profile this save activated. + // Defensive: the doubles in this suite can leave console writes pending at + // worker teardown. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + vi.spyOn(console, "info").mockImplementation(() => {}) + const profile: ProviderSettingsEntry = { + name: "activated-profile", + id: "activated-id", + apiProvider: providerIdentifiers.openrouter, + } + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("activated-id") + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([profile]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "activated-profile", + id: "activated-id", + apiProvider: providerIdentifiers.openrouter, + apiKey: "sk-activated", + }) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + // The caller payload carries a padded key: the profile record is normalized + // by the manager and read back before any activation write (ClineProvider.ts + // 3703-3718), so the buffer must carry the stored record, not this payload. + await provider.upsertProviderProfile("activated-profile", { + apiProvider: providerIdentifiers.openrouter, + apiKey: " sk-activated ", + }) + + expect(provider["viewLocalState"].currentApiConfigName).toBe("activated-profile") + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.openrouter, + apiKey: "sk-activated", + }) + expect((await provider.getState()).apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.openrouter, + apiKey: "sk-activated", + }) + await ClineProvider["persistedViewStateWriteQueue"] + }) + + it("carries the activated record into the acting view when a profile is switched", async () => { + // The switch path is the second activation site: activateProviderProfile writes the + // shared store from the manager's record and must write the same record into this + // view's buffer, or the view keeps a pin with no settings and the shared fallback in + // getState() decides which profile it serves next. Review row 4506513941. + // Defensive: the doubles in this suite can leave console writes pending at + // worker teardown. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + vi.spyOn(console, "info").mockImplementation(() => {}) + const profile: ProviderSettingsEntry = { + name: "switched-profile", + id: "switched-id", + apiProvider: providerIdentifiers.anthropic, + } + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + ...profile, + apiKey: "sk-switched", + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([profile]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + await provider.activateProviderProfile({ name: "switched-profile" }) + + expect(provider["viewLocalState"].currentApiConfigName).toBe("switched-profile") + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-switched", + }) + expect((await provider.getState()).apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-switched", + }) + await ClineProvider["persistedViewStateWriteQueue"] + }) + + it("keeps a view on its own profile settings when a sibling view activates another profile", async () => { + // Review row 4506513941: view A activates profile A, view B then activates profile B. + // Both views read the one ContextProxy the extension host hands every view, so the + // second activation overwrites the shared provider settings. View A must keep serving + // profile A - its pin and the settings of the profile it activated - instead of + // inheriting the sibling's later activation when it next reads state or starts a task. + // Defensive: the doubles in this suite can leave console writes pending at + // worker teardown. + vi.spyOn(console, "log").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) + vi.spyOn(console, "info").mockImplementation(() => {}) + const sibling = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + provider.contextProxy, + new WebviewFocusTracker(), + ) + // The sibling reads custom modes through its own manager, exactly as a second + // view does: this row does not replace it, so no read-only property is assigned. + try { + const profileA: ProviderSettingsEntry = { + name: "profile-a", + id: "id-a", + apiProvider: providerIdentifiers.anthropic, + } + const profileB: ProviderSettingsEntry = { + name: "profile-b", + id: "id-b", + apiProvider: providerIdentifiers.openrouter, + } + vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ + ...profileA, + apiKey: "sk-a", + }) + vi.spyOn(sibling.providerSettingsManager, "activateProfile").mockResolvedValue({ + ...profileB, + apiKey: "sk-b", + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([profileA, profileB]) + vi.spyOn(sibling.providerSettingsManager, "listConfig").mockResolvedValue([profileA, profileB]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(sibling.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + vi.spyOn(sibling.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) + + await provider.activateProviderProfile({ name: "profile-a" }) + await sibling.activateProviderProfile({ name: "profile-b" }) + + // The pin half was never shared, so this assertion is green at the parent by + // construction; it is here to show which half of the pair the fix changes. + expect(provider["viewLocalState"].currentApiConfigName).toBe("profile-a") + expect((await provider.getState()).apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-a", + }) + expect(provider["viewLocalState"].apiConfiguration).toEqual({ + apiProvider: providerIdentifiers.anthropic, + apiKey: "sk-a", + }) + } finally { + await sibling.dispose() + // Wait on the serialized view-state write queue that every + // viewStates mutation goes through, so queued persistence finishes + // while the console spies are still installed and teardown has no + // pending writes. + await ClineProvider["persistedViewStateWriteQueue"] + } + }) + it("should sync the view-local buffer when creating and activating a profile", async () => { const provider = new ClineProvider( mockContext, From 9823952a3ce50af10e9291c8be72b42cfeba6074 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 04:07:08 +0800 Subject: [PATCH 33/34] [cr 4593787862] clear profiles renamed after sign-out took its scan Review row 4593787862 (Major, Data Integrity & Integration, Quick win, created 2026-11-17T00:50:41Z) sits on original_line 3417 of the anchor blob d17e7ad060cae4d93aad6715156a8ebdbff47836 (line null, side RIGHT, review head 4128c45cef0301554823b541b6680205d91dc956), whose text is "await provider.providerSettingsManager.saveConfig(entry.name, cleanedProfile)". At the current head that exact line is gone; context maps +136 (anchor 3398 -> 3534, 3412 -> 3548, and the exclusion call at 3416 -> 3557), and the write the row reviewed is now line 3568 of webviewMessageHandler.ts. Half of what the row asks was already in this PR: the persisted-only branch re-reads the record while it holds the shared exclusion, skips a name that was renamed away, skips a record whose token is already gone, and writes the re-read record (webviewMessageHandler.ts 3548-3569). That half came in with the bulk commit 253a7b09ad, which never cites this row - nothing here claims it. The row names the remaining half itself: "Clearing the token from a profile renamed after the scan also needs the profile list to be read inside the same exclusion. The fix above does not cover that case." This commit adds only that half. After the entry write, while the exclusion is still held, the handler re-lists the profiles and clears a zoo-gateway profile the earlier scan never iterated (3569-3587). Names the scan already covered keep their own iteration, and the token check doubles as the idempotence guard: a record that was already cleared is read, found tokenless, and left alone. Not covered, stated plainly: - The sweep runs only when this pass actually performed a persisted-only write. A sign-out whose scan found no zoo-gateway profile, or whose every zoo profile went through the active/upsert branch, never reaches the sweep and can still leave a late rename holding its token. - A rename that commits after the sweep re-listed the profiles still survives: no finite re-scan closes that window. - The sweep clears the persisted record only. The in-memory API handler for a late name keeps its token until that profile is saved or activated again: pushing through upsertProviderProfile here would reacquire the exclusion this callback already holds (runExclusiveAcrossInstances is a promise-chain queue keyed by secrets key, ProviderSettingsManager.ts 123-146) and deadlock. - deleteConfig does not join that exclusion, so a delete issued by another view can remove a name between the sweep's list and its read; the read then rejects, the per-profile catch reports it, and the names after it are missed for that pass. Line-cost caliber. scripts/stryker-diff.mjs counts changed executable lines, and in this file the whole handler body lies inside one ArrowFunction expression span (checked against the TypeScript 5.9.3 AST: span 138-4847), so every line added inside the handler counts, comments included - a comment-only control at this place measures 5 changed / 5 executable. Comments cannot be parked outside an expression span in this file, so they were kept to five lines. Per-cell executable changed lines: 19 (lines 3569-3587). Verification. Test caliber: cmd.exe /c "\src\node_modules\.bin\vitest.CMD" run --config vitest.core.config.ts , cwd \src. - Red first (parent 6001e8d07fcd production file, new row only): 1 failed | 201 skipped (202), exit 1. First failing assertion src/core/webview/__tests__/webviewMessageHandler.spec.ts:3680:55 - expected "vi.fn()" to be called with arguments: [ 'Renamed Zoo', ...(1) ], Number of calls: 1, the single call being ["Backup Zoo", ... "model-after"]. - Candidate: new row alone 1 passed | 201 skipped (202); whole file 202 passed (202); group core/webview 38 files / 1272 passed (1272). Parent with the new row: whole file 1 failed | 201 passed, group 1 failed | 1271 passed - no existing row moved. - Mutants, each built from the candidate production bytes, written with git hash-object -w and proven present with git cat-file -e (exit 0); after every run the candidate bytes were restored and re-hashed to 4d436272cfbd1d1d5dc4273efe9231e0d3f97702 (equal every time): m1 sweep code deleted, its note left behind c60c3c3ccfe93f7343f66585970f833e23b38eea - 1 failed | 201 skipped, 3680:55; m2 scanned-name skip deleted d8c69c23b49eabfcb76fd4f534511d36d162b0fd - 1 failed, 3688:17, 11 recorded events against 9; m3 provider filter deleted 2dcabefc68129e95bb2a935c26e3ee6d507058d2 - 1 failed, 3688:17, 11 events against 9; m4 token guard deleted 5b4e121377cb99dfb3cb637dea4f5b3b896c5907 - 1 failed, 3688:17, 10 events against 9; m5 sweep writes the scanned entry instead of the re-read record ae7423b5234b4b49ce71404ab0aee87504769d4f - 1 failed, 3688:17, the sweep write recorded as write:Renamed Zoo:undefined; m6 sweep writes the record with zooSessionToken put back e34d524e2525b8c20313c7f60391c0db11faa22d - 1 failed | 201 skipped, 3680:55. - Comment-only control: the five notes alone, 5 added lines and 5 executable, group core/webview with the parent spec 38 files / 1271 passed, exit 0 - behaviourally inert. - Gates on the candidate and on the parent, named calibers: prettier --check on both files exit 0 in both states; tsc --noEmit -p tsconfig.json (cwd \src) exit 0 in both; eslint --max-warnings=0 exit 0 in both; eslint --prune-suppressions --max-warnings=0 exit 0 in both with core/webview/webviewMessageHandler.ts no-explicit-any 5 -> 5 and core/webview/__tests__/webviewMessageHandler.spec.ts 35 -> 35 (that caliber rewrites src/eslint-suppressions.json wholesale, 1306/1306 both times, and the file was restored with git checkout every time, never hand-edited). - Host load at run time: 4 node.exe processes, 71982 MB free of 193956 MB total; os.loadavg() reports 0,0,0 on this platform, so it is not evidence. --- .../__tests__/webviewMessageHandler.spec.ts | 106 ++++++++++++++++++ src/core/webview/webviewMessageHandler.ts | 19 ++++ 2 files changed, 125 insertions(+) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index a62ddac62f4..e3e0d040846 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -3593,6 +3593,112 @@ describe("webviewMessageHandler - zooCodeSignOut persisted-only write", () => { expect(order).toEqual(["exclusionEntered", "hasConfig", "readInsideExclusion"]) expect(provider.providerSettingsManager.saveConfig).not.toHaveBeenCalled() }) + // A separate fixture from wire(): that one models one name read before and after the + // exclusion is taken. This one models the other half of the same race - a rename on + // another view that commits after the handler listed the profiles, so the token ends + // up under a name the scan never iterated. listConfig is called twice by the handler: + // the first call is the scan taken outside the exclusion, the second is the re-list + // the sweep takes while the exclusion is held. The re-list carries one profile the + // scan never saw but which now carries the token (Renamed Zoo), one that never used + // this provider (Other Model), and one whose token is already gone (Cleaned Zoo). + const wireLateRename = () => { + const order: string[] = [] + const scannedProfile = { + apiProvider: providerIdentifiers.zooGateway, + zooSessionToken: "token-backup", + zooGatewayModelId: "model-before", + } + const renamedProfile = { + apiProvider: providerIdentifiers.zooGateway, + zooSessionToken: "token-renamed", + zooGatewayModelId: "model-renamed", + } + const cleanedProfile = { apiProvider: providerIdentifiers.zooGateway, zooGatewayModelId: "model-cleaned" } + let scanCalls = 0 + let backupReads = 0 + provider.upsertProviderProfile = vi.fn().mockResolvedValue(undefined) + provider.contextProxy = { + getProviderSettings: vi.fn().mockReturnValue({ apiProvider: providerIdentifiers.anthropic }), + getValues: vi.fn().mockReturnValue({ currentApiConfigName: "some-other-profile" }), + } + provider.providerSettingsManager = { + listConfig: vi.fn(async () => { + scanCalls += 1 + order.push(scanCalls === 1 ? "scanList" : "sweepList") + return scanCalls === 1 + ? [{ name: "Backup Zoo", apiProvider: providerIdentifiers.zooGateway }] + : [ + { name: "Backup Zoo", apiProvider: providerIdentifiers.zooGateway }, + { name: "Other Model", apiProvider: providerIdentifiers.anthropic }, + { name: "Renamed Zoo", apiProvider: providerIdentifiers.zooGateway }, + { name: "Cleaned Zoo", apiProvider: providerIdentifiers.zooGateway }, + ] + }), + getProfile: vi.fn(async ({ name }: { name: string }) => { + if (name === "Backup Zoo") { + backupReads += 1 + if (backupReads === 1) { + order.push("read:Backup Zoo:outside") + return scannedProfile + } + if (backupReads === 2) { + order.push("read:Backup Zoo:inside") + return { ...scannedProfile, zooGatewayModelId: "model-after" } + } + order.push("read:Backup Zoo:resweep") + return scannedProfile + } + if (name === "Cleaned Zoo") { + order.push("read:Cleaned Zoo") + return cleanedProfile + } + order.push(`read:${name}`) + return renamedProfile + }), + hasConfig: vi.fn(async (name: string) => { + order.push(`hasConfig:${name}`) + return true + }), + runExclusiveAcrossInstances: vi.fn(async (callback: () => Promise) => { + order.push("exclusionEntered") + return callback() + }), + saveConfig: vi.fn(async (name: string, value: Record) => { + order.push(`write:${name}:${String(value.zooGatewayModelId)}`) + }), + } + return order + } + + it("clears a zoo-gateway profile renamed after the handler listed the profiles", async () => { + const order = wireLateRename() + + await webviewMessageHandler(mockClineProvider, { type: "zooCodeSignOut" }) + + // The symptom first: the late name is a zoo-gateway profile that still carries a + // token, and clearing it is the whole point of this pass. + expect(provider.providerSettingsManager.saveConfig).toHaveBeenCalledWith( + "Renamed Zoo", + expect.not.objectContaining({ zooSessionToken: expect.anything() }), + ) + // The re-list is taken after the first write and while the exclusion is held, so no + // rename can slip between reading the list and writing to it; names the scan already + // iterated keep their own iteration, a profile that never used this provider is left + // alone, and a record whose token is already gone is not rewritten. + expect(order).toEqual([ + "scanList", + "read:Backup Zoo:outside", + "exclusionEntered", + "hasConfig:Backup Zoo", + "read:Backup Zoo:inside", + "write:Backup Zoo:model-after", + "sweepList", + "read:Renamed Zoo", + "write:Renamed Zoo:model-renamed", + "read:Cleaned Zoo", + ]) + expect(provider.providerSettingsManager.saveConfig).toHaveBeenCalledTimes(2) + }) }) describe("webviewMessageHandler - renameApiConfiguration", () => { diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 1051d59a346..4d436272cfb 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -3566,6 +3566,25 @@ export const webviewMessageHandler = async ( } const { zooSessionToken: _supersededToken, ...currentCleaned } = currentProfile await provider.providerSettingsManager.saveConfig(entry.name, currentCleaned) + // A rename on another view can commit after the scan above was taken, which lands the + // token under a name this pass never iterated. While the exclusion is held no rename + // can slip in, so re-list here and clear the zoo-gateway profiles the scan missed; + // names the scan already covers keep their own iteration, and the token check keeps + // this pass from rewriting a record that was already cleared. + for (const late of await provider.providerSettingsManager.listConfig()) { + if (late.apiProvider !== providerIdentifiers.zooGateway) { + continue + } + if (allProfiles.some((seen) => seen.name === late.name)) { + continue + } + const { zooSessionToken: lateToken, ...lateCurrent } = + await provider.providerSettingsManager.getProfile({ name: late.name }) + if (!lateToken) { + continue + } + await provider.providerSettingsManager.saveConfig(late.name, lateCurrent) + } }) provider.log(`[zooCodeSignOut] Cleared zooSessionToken from "${entry.name}" profile`) } From c2892ca61523afc2ea60c76ea528f7750901c0df Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 05:27:05 +0800 Subject: [PATCH 34/34] [cr 4774950127] follow an explicit API provider change in the serving view Review row 4774950127 (CodeRabbit, src/core/webview/ClineProvider.ts line 3781, original_line 3781, position 1858, side RIGHT, created 2026-12-02T19:39:52Z, Major - Data Integrity & Integration - Heavy lift, "Keep explicit API settings effective after profile activation", "Also applies to: 4365-4365", commit_id 9823952a3ce50af10e9291c8be72b42cfeba6074, original_commit_id 6001e8d07fcd609aa6f48fdbb5d5ad6cf6d10483) reports that api.setConfiguration (src/extension/api.ts:661-675) writes provider settings into the shared store only, while getState() now prefers the view-local pair - the pin plus its settings snapshot - over the shared store, so "a task started with configuration: {} still uses the old provider". Its ask: "Update or invalidate the affected overlay when the API explicitly changes provider settings. Keep the overlay when a sibling activates another profile." Verified at the parent commit rather than inferred. getValues() (ClineProvider.ts :6009) merges { ...contextProxy.getValues(), ...viewLocalState }; getState() (5641, 5646, 5729-5734) answers apiConfiguration from the view copy whenever one exists; _updateViewLocalStateFromMutation (6066-6098) mirrors only mode, currentApiConfigName and apiConfiguration and deliberately does not merge the flat provider keys (6094-6097). A run against the parent bytes showed the buffer unchanged ({"apiConfiguration":{"apiProvider":"anthropic"}, "currentApiConfigName":"activated-profile"}) after the shared-only write, and getState() answering anthropic where the new settings said openrouter. The row is right about the existing test too: the shared-write row passed with no getProfile stub, so the read-back that activation performs rejected, upsertProviderProfile (3526-3533) swallowed it and returned undefined, and the row went green over a view whose buffer was never filled - "The saveConfig stub alone does not establish that the saved record was read back." That row is now strengthened in place: it stubs the read, asserts expect(activatedId).toBe("activated-id") before anything is written on top of the activation, and keeps its apiProvider assertion. This thread carries a second finding as well (Minor - Quick win, "Activation can expose a mixed profile pair before the pin write settles", for lines 3765-3782), so this commit does two things: 1. The API hands the payload to the view it just changed settings for (src/extension/api.ts), and ClineProvider .invalidateViewLocalProfileForSettingsChange drops that view profile pair through the existing invalidation path (_saveViewLocalStateFromMutation with both halves undefined) so the view follows the change instead of serving what it served before. The call is guarded on the payload naming a provider setting or a profile selection, so a display-only write - which api.setConfiguration also performs - cannot silently un-pin a view. Sibling activations are untouched: refreshViewLocalStateForUpdatedProfile still refreshes pinned and task-bound views with the profile they name, which is what row 4506513941 asked for. 2. The activating group stops publishing its two halves at different times. The pin write goes through the plain durable global path (updateGlobalState) instead of setValue, and the pair enters this view buffer as one _updateViewLocalStateFromMutation once every write of the group has settled. Before this change a read taken while the group was in flight paired the new settings, which reached the buffer at once, with the old pin, which was still waiting on its own viewStates write. Alternatives measured before choosing (executable changed lines counted with scripts/stryker-diff.mjs against 9823952a3ce50af10e9291c8be72b42cfeba6074): refreshing the buffer with the shared record instead of dropping it cost the same 5 lines but left a pinned name carrying the shared settings, which is the mismatch row 4506513941 was about; routing the whole payload through ClineProvider.setValues cost 3 lines but flipped two existing ClineProvider rows and all nine api-configuration rows, and made every flat shared write a per-view override, which is the behaviour the comment at ClineProvider.ts:6094-6097 says must not happen. Not covered, stated plainly: - The 4365 half of the row is not a changed line: the write at 4365, inside activateProviderProfile, still enters the buffer the way it did. The invalidation covers it because it clears whatever an activation stored, but no row exercises activateProviderProfile followed by an API write. - The guard sits in the callee, so any future caller of the new method relies on the same check; api.setConfiguration itself does not filter the payload. - The pairing row proves the ordering at the provider seam with a held mode mapping and a held durable viewStates queue. It does not use a real vscode Memento or a real webview post, so a different durable-write ordering in the host is not covered. - Dropping the pair makes the view follow the shared selection; it does not re-resolve the profile the API just saved, so a view that had a pin reports the shared currentApiConfigName afterwards. The row asks for the change to be effective, not for the pin to be re-derived. Tests added in src/core/webview/__tests__/ClineProvider.spec.ts (all three inside "getState merging", run red against the parent bytes first, then green): - "drops the view profile pair when the API names provider settings" - "keeps the view profile pair for a payload that names no provider setting" - "keeps the prior profile pair visible while the durable pin write is pending" plus one row in src/extension/__tests__/api-configuration.spec.ts, "hands an explicit provider-settings change to the view that serves it", and the mechanical warming of the three provider doubles there (one member each, no assertion changed). At the parent the new rows fail: TypeError for the method that does not exist yet (7994, 8042, 8085), and for the pairing row the mixed pair itself - "AssertionError: expected { apiProvider: 'anthropic' } to deeply equal { apiProvider: 'openrouter', ...(1) }" at 8148:43 - while all 544 other ClineProvider rows, all 1271 other core/webview rows and all 9 other api-configuration rows keep passing. Typecheck at the parent reports exactly the three TS2339 uses of the new method; typecheck, prettier and eslint are clean on the candidate. Changed-line cost, the caliber scripts/stryker-diff.mjs uses for the mutation gate: src/extension/api.ts 8 added / 1 executable line; src/core/webview/ ClineProvider.ts 30 added, 5 removed / 9 executable lines; total 10. Comments in this file are free only outside expression spans: the same eight comment lines inside the Promise.allSettled([...]) span measured 13 executable lines, and 5 once they were moved outside it. Whole-range gate numbers against the branch base 6df256602d19502028ce9a2f744555b53973cf90, extension package only (specs carry no cost because the tool finds no mutation package for a *.spec.ts): BEFORE 2147 executable changed lines, AFTER 2152, net +5. The gap to the 10 lines above is exact, not rounding: the range already counted three comment lines that sat inside the Promise.allSettled([...]) span (this commit moves them out) and the two group writes this commit replaces, so five counted lines stop being counted while nine new ClineProvider.ts lines and one api.ts line start being counted. Gates, candidate side: prettier --check 0, tsc --noEmit -p tsconfig.json 0 errors, eslint --max-warnings=0 clean on all four touched files, eslint --prune-suppressions --max-warnings=0 left src/eslint-suppressions.json unchanged at 261 files / 2841 suppressed occurrences with no entry for any touched file (0 before, 0 after), and the file was restored to blob 1fad7b0e65fef2ae0d20cf0f83331da2b6d90012 afterwards. Parent side: prettier and eslint clean, prune left the same 261 / 2841, tsc as described above. Mutation checks, each built from the candidate bytes and stored with git hash-object -w before running it. All ten were killed: - api.ts stops forwarding the payload to the view; killed by the api-configuration row. Blob d1b9a99969c159e8a7b27c4e6fb24ce9bf9ef776 - api.ts forwards an empty payload instead of the values; killed by the api-configuration row. Blob 765cff5736e52f00b90218f9981ce9761089cf4e - guard condition replaced with true, so nothing is ever dropped; killed by the provider-settings row and by the strengthened shared-write row. Blob 952a92a0bd7ebc978db372de41b31bc4cd505de2 - guard condition replaced with false, so a display-only write un-pins the view; killed by the display-only row. Blob d9e001f6b41fd5bf4600b6927222d92b39481632 - drop statement removed from the new method; killed by the provider-settings row and by the strengthened shared-write row. Blob 813a400b004c991684d0d0870dff69eeedb09f46 - combined update omitting the pin; killed by the display-only row and the pairing row. Blob 5799608035a4eff111390a99b87e53c15e4d0234 - combined update omitting the settings; killed by all three new rows. Blob 56a240e6ac24b34e15a1aab1341dba232b707b6c - combined update removed entirely; killed by all three new rows. Blob e8ad07acd9ec5edcb86b714084a7908710cb40b1 - group durable pin write removed; survived the three new rows and killed by two pre-existing rows, "handles successful upsertApiConfiguration" and "handles buildApiHandler error in updateApiConfiguration". Blob b548c89206271dad2d061fbe6ffc2e42d14e2be5 - activation failure propagation inverted; killed by all four rows. This one sits on a context line, outside the changed-line gate. Blob 9e3b8fb0e1d301a6a82e55e5e8fcc2f93e7dae07 Attribution: both anchor lines the row points at, 3781 and 4365, were introduced by 6001e8d07fcd609aa6f48fdbb5d5ad6cf6d10483 ([cr 4506513941] carry the activated settings into the activating view), and the row is a new row on that pushed content: its commit_id is 9823952a3ce50af10e9291c8be72b42cfeba6074 and its original_commit_id is 6001e8d07fcd609aa6f48fdbb5d5ad6cf6d10483. The write the API makes, src/extension/api.ts:665, is upstream content from 8cb5c4e9e3 ("Restore profile management work + fix #3434 (#3449)"). No commit in 41cf71a72c45..HEAD cites 4774950127, so nothing here re-walks a row an earlier commit already answered. --- src/core/webview/ClineProvider.ts | 35 +++- .../webview/__tests__/ClineProvider.spec.ts | 191 +++++++++++++++++- .../__tests__/api-configuration.spec.ts | 35 +++- src/extension/api.ts | 8 + 4 files changed, 260 insertions(+), 9 deletions(-) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 98cc27aeaf9..705f7514e2f 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3764,10 +3764,7 @@ export class ClineProvider // `allSettled` so the compensation below never races a write still in flight. const activationResults = await Promise.allSettled([ this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()), - // Route through setValue so the in-memory viewLocalState buffer tracks the - // activated profile: a plain global write would leave a stale loaded - // currentApiConfigName shadowing the new value in getValues(). - this.setValue("currentApiConfigName", name), + this.updateGlobalState("currentApiConfigName", name), // Route through this.setModeConfig rather than the manager call so // this provider's own mode mapping commits with the activation: an // activation that updates only the manager leaves a stale cached id @@ -3778,7 +3775,6 @@ export class ClineProvider // this head. this.setModeConfig(mode, id), this.contextProxy.setProviderSettings(normalizedSettings), - this._saveViewLocalStateFromMutation({ apiConfiguration: normalizedSettings }), ]) const failedActivation = activationResults.find( (result): result is PromiseRejectedResult => result.status === "rejected", @@ -3786,6 +3782,19 @@ export class ClineProvider if (failedActivation) throw failedActivation.reason + // The pin and the settings enter this view buffer as one update, once every durable + // write of the group has settled. While the group was in flight a read of this view + // saw the prior pair: the pin used to reach the buffer only after its own + // viewStates write had landed, while a settings buffer write landed at once, so a + // state post or a new task started inside that window ran on the old pin with the + // new settings (review row 4774950127, the Minor half of this thread). Routing the + // pin through setValue was what kept this view buffer tracking the activated + // profile, and the update below covers that too, so the durable write above can go + // through the plain global path. + this._updateViewLocalStateFromMutation({ + apiConfiguration: normalizedSettings, + currentApiConfigName: name, + }) // Change the provider for the current task. // TODO: We should rename `buildApiHandler` for clarity (e.g. `getProviderClient`). // Captured at the point this branch starts changing the task: the rebuild and the @@ -6058,6 +6067,22 @@ export class ClineProvider this._updateViewLocalStateFromMutation(values) } + /** + * Drop this view profile pair after provider settings changed without a profile + * activation. The pair is the buffer getState() prefers over the shared store, so + * a shared-only write leaves this view serving what it served before the change; + * dropping both halves makes the view follow the change instead of holding a pin + * whose settings snapshot came from somewhere else. Only a payload that names + * provider settings or a profile selection counts: a display-only write must not + * silently un-pin the view. + */ + async invalidateViewLocalProfileForSettingsChange(values: RooCodeSettings): Promise { + if (!("currentApiConfigName" in values) && !PROVIDER_SETTINGS_KEYS.some((key) => key in values)) { + return + } + await this._saveViewLocalStateFromMutation({ apiConfiguration: undefined, currentApiConfigName: undefined }) + } + /** * Update or invalidate viewLocalState when ContextProxy is mutated via setValues, setValue, * profile upsert/activation/deletion, or resetState. This ensures the local cache stays in diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 723843f9282..946b105cbc2 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -7949,25 +7949,53 @@ describe("ClineProvider", () => { new WebviewFocusTracker(), ) vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("activated-id") + + // The read-back that the activation performs is part of this scenario: with no + // stored record to read, activation fails inside upsertProviderProfile, which + // swallows the error and returns undefined, so this row used to pass over a view + // whose overlay was never filled at all. Review row 4774950127 names that hole, + // and stubbing the read is what makes the assertion below mean anything. + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "activated-profile", + id: "activated-id", + apiProvider: providerIdentifiers.anthropic, + }) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "activated-profile", id: "activated-id", apiProvider: providerIdentifiers.anthropic }, ]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) - await provider.upsertProviderProfile( + // Activation must have succeeded before anything is written on top of it. + const activatedId = await provider.upsertProviderProfile( "activated-profile", { apiProvider: providerIdentifiers.anthropic }, true, ) + expect(activatedId).toBe("activated-id") - // Simulate api.setConfiguration (src/extension/api.ts): a global-only - // write that does not refresh the view-local buffer. + // The two calls api.setConfiguration makes for this payload: the shared store + // first, then the instruction that this view stop serving the profile pair it + // had been serving (src/extension/api.ts). await provider.contextProxy.setValues({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", }) + // The two calls api.setConfiguration (src/extension/api.ts) makes for this + // payload: the shared store first, then the instruction that this view stop + // serving the profile pair it had been serving. The API surface itself is + // covered in extension/__tests__/api-configuration.spec.ts, which is where + // an API instance belongs - this file is the core layer. + await provider.contextProxy.setValues({ + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "mock-key", + }) + await provider.invalidateViewLocalProfileForSettingsChange({ + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "mock-key", + }) + const state = await provider.getState({ includeTaskHistory: false }) // The fresh global selection must win: the activation's buffer write must @@ -7977,6 +8005,163 @@ describe("ClineProvider", () => { await provider.dispose() }) + it("drops the view profile pair when the API names provider settings", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("activated-id") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "activated-profile", + id: "activated-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "activated-profile", id: "activated-id", apiProvider: providerIdentifiers.anthropic }, + ]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + const activatedId = await provider.upsertProviderProfile( + "activated-profile", + { apiProvider: providerIdentifiers.anthropic }, + true, + ) + expect(activatedId).toBe("activated-id") + expect(provider["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic }) + + // The two calls api.setConfiguration (src/extension/api.ts) makes; the API + // surface itself is asserted in extension/__tests__/api-configuration.spec.ts. + await provider.contextProxy.setValues({ + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "mock-key", + }) + await provider.invalidateViewLocalProfileForSettingsChange({ + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "mock-key", + }) + + // The pair is what getState() prefers over the shared store, so it has to go: a + // view that kept it would keep starting tasks on the provider it had before the + // API call. + expect(provider["viewLocalState"].apiConfiguration).toBeUndefined() + expect(provider["viewLocalState"].currentApiConfigName).toBeUndefined() + const state = await provider.getState({ includeTaskHistory: false }) + expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.openrouter) + await provider.dispose() + }) + it("keeps the view profile pair for a payload that names no provider setting", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("activated-id") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "activated-profile", + id: "activated-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "activated-profile", id: "activated-id", apiProvider: providerIdentifiers.anthropic }, + ]) + vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + const activatedId = await provider.upsertProviderProfile( + "activated-profile", + { apiProvider: providerIdentifiers.anthropic }, + true, + ) + expect(activatedId).toBe("activated-id") + + // The display-only payload api.setConfiguration would forward for a settings + // write that names no provider setting. + await provider.invalidateViewLocalProfileForSettingsChange({ timeFormat: "24h" }) + + // The API call named no provider setting and no profile, so this view keeps the + // pair it was given by the activation: un-pinning it here would switch the view + // onto the shared selection without anyone asking. + expect(provider["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic }) + expect(provider["viewLocalState"].currentApiConfigName).toBe("activated-profile") + const state = await provider.getState({ includeTaskHistory: false }) + expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) + await provider.dispose() + }) + it("keeps the prior profile pair visible while the durable pin write is pending", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const priorSettings = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "pinned-key" } + // The view runs a pinned profile and buffers a copy of its settings. + await provider.saveViewState("currentApiConfigName", "pinned-profile") + await provider.saveViewState("apiConfiguration", priorSettings) + vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("late-id") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ + name: "late-profile", + id: "late-id", + apiProvider: providerIdentifiers.anthropic, + }) + vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "pinned-profile", id: "pinned-id", apiProvider: providerIdentifiers.openrouter }, + { name: "late-profile", id: "late-id", apiProvider: providerIdentifiers.anthropic }, + ]) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + // Two gates hold the activation open at the two points this row is about: the + // mode mapping is one of the writes inside the activation group, and the pin + // write is the one that goes through the durable viewStates queue. + let releaseModeConfig = () => {} + const modeConfigGate = new Promise((resolve) => { + releaseModeConfig = resolve + }) + const heldModeConfig = vi.spyOn(provider.providerSettingsManager, "setModeConfig") + heldModeConfig.mockImplementation(() => modeConfigGate) + let releaseWriteQueue = () => {} + const writeQueueGate = new Promise((resolve) => { + releaseWriteQueue = resolve + }) + ClineProvider["persistedViewStateWriteQueue"] = writeQueueGate + + try { + const activation = provider.upsertProviderProfile( + "late-profile", + { apiProvider: providerIdentifiers.anthropic }, + true, + ) + // The group has reached its mode mapping, which this row holds open: the pin + // cannot land because the durable queue is held, and the group cannot settle + // because the mapping is pending. + await vi.waitFor(() => expect(heldModeConfig).toHaveBeenCalled(), { timeout: 5000, interval: 25 }) + const pendingState = await provider.getState({ includeTaskHistory: false }) + // Nothing has reached this view buffer yet, so a read taken now still pairs the + // pinned name with the pinned settings. + expect(pendingState.currentApiConfigName).toBe("pinned-profile") + expect(pendingState.apiConfiguration).toEqual(priorSettings) + releaseModeConfig() + releaseWriteQueue() + expect(await activation).toBe("late-id") + } finally { + releaseModeConfig() + releaseWriteQueue() + ClineProvider["persistedViewStateWriteQueue"] = Promise.resolve() + } + + // Once every write of the group has landed, name and settings arrive together. + const settledState = await provider.getState({ includeTaskHistory: false }) + expect(settledState.currentApiConfigName).toBe("late-profile") + expect(settledState.apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic }) + await provider.dispose() + }) + it("does not fill a pinned profile's omitted keys from the shared profile", async () => { const provider = new ClineProvider( mockContext, diff --git a/src/extension/__tests__/api-configuration.spec.ts b/src/extension/__tests__/api-configuration.spec.ts index 6f263ab9f65..fde0551219c 100644 --- a/src/extension/__tests__/api-configuration.spec.ts +++ b/src/extension/__tests__/api-configuration.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest" import type * as vscode from "vscode" -import type { RooCodeSettings } from "@roo-code/types" +import { providerIdentifiers, type RooCodeSettings } from "@roo-code/types" import { API } from "../api" import type { ClineProvider } from "../../core/webview/ClineProvider" @@ -12,6 +12,36 @@ vi.mock("@roo-code/ipc", () => ({ })) describe("API - configuration", () => { + it("hands an explicit provider-settings change to the view that serves it", async () => { + const setValues = vi.fn().mockResolvedValue(undefined) + const invalidateViewLocalProfile = vi.fn().mockResolvedValue(undefined) + const provider = { + context: {}, + on: vi.fn(), + log: vi.fn(), + contextProxy: { setValues }, + invalidateViewLocalProfileForSettingsChange: invalidateViewLocalProfile, + providerSettingsManager: { saveConfig: vi.fn().mockResolvedValue("default-id") }, + setModeConfig: vi.fn().mockResolvedValue(undefined), + postStateToWebview: vi.fn().mockResolvedValue(undefined), + } as unknown as ClineProvider + const outputChannel = { appendLine: vi.fn() } as unknown as vscode.OutputChannel + const api = new API(outputChannel, provider, makeClineProviderFactory()) + + await api.setConfiguration({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key" }) + + // The shared write alone leaves the sidebar view serving the profile pair it + // already held, which is what getState() prefers over the shared store. The API + // has to hand the payload to that view; whether the payload names a provider + // setting is decided there. + expect(setValues).toHaveBeenCalledWith( + expect.objectContaining({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key" }), + ) + expect(invalidateViewLocalProfile).toHaveBeenCalledWith( + expect.objectContaining({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key" }), + ) + }) + it("persists every supplied mode API config mapping", async () => { const setValues = vi.fn().mockResolvedValue(undefined) const saveConfig = vi.fn().mockResolvedValue("default-id") @@ -22,6 +52,7 @@ describe("API - configuration", () => { on: vi.fn(), log: vi.fn(), contextProxy: { setValues }, + invalidateViewLocalProfileForSettingsChange: vi.fn().mockResolvedValue(undefined), providerSettingsManager: { saveConfig }, setModeConfig, postStateToWebview, @@ -57,6 +88,7 @@ describe("API - configuration", () => { on: vi.fn(), log: vi.fn(), contextProxy: { setValues }, + invalidateViewLocalProfileForSettingsChange: vi.fn().mockResolvedValue(undefined), providerSettingsManager: { saveConfig }, setModeConfig, postStateToWebview, @@ -79,6 +111,7 @@ describe("API - configuration", () => { on: vi.fn(), log, contextProxy: { setValues }, + invalidateViewLocalProfileForSettingsChange: vi.fn().mockResolvedValue(undefined), providerSettingsManager: { saveConfig: vi.fn().mockResolvedValue("default-id"), setModeConfig: vi.fn(), diff --git a/src/extension/api.ts b/src/extension/api.ts index ccb9dce199a..a2b6192cc1a 100644 --- a/src/extension/api.ts +++ b/src/extension/api.ts @@ -663,6 +663,14 @@ export class API extends EventEmitter implements RooCodeAPI { this.sidebarProvider.log(`[setConfiguration] Ignored an invalid value for ${key}`), ) await this.sidebarProvider.contextProxy.setValues(values) + // The write above lands in the shared store only, so this view keeps the profile + // pair it was serving: the pin plus the settings snapshot that getState() prefers + // over the shared store. An API-driven provider change would then keep starting + // every task this view launches with an empty configuration on the previous + // provider. Review row 4774950127 (Major, Data Integrity & Integration, created + // 2026-12-02T19:39:52Z) reports it. A payload that names no provider setting + // leaves the pair alone, which the callee checks. + await this.sidebarProvider.invalidateViewLocalProfileForSettingsChange(values) await this.sidebarProvider.providerSettingsManager.saveConfig(values.currentApiConfigName || "default", values) if (values.modeApiConfigs) { await Promise.all(