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..bee19c89f97 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", ) @@ -1448,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 = { 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/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, diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 32714067fa2..705f7514e2f 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,74 @@ 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 +} + +/** + * 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 = { + 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 +329,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, @@ -344,26 +435,73 @@ 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 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 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, - 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. 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 run = this.providerProfileMutationQueue.then( - () => fn(controller.signal), - () => fn(controller.signal), - ) - const callerResult = this.withProviderProfileMutationTimeout(run, () => { - if (options.runToCompletion) { - this.log("Provider profile mutation timed out; waiting for it to finish before the next mutation") - return + 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.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. 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 for its caller; the write is still pending") + 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( () => { @@ -382,8 +520,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, @@ -391,22 +531,72 @@ 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) } }) } + /** + * 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. + * + * 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. + * + * 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( + async () => { + await this.contextProxy.setValue("currentApiConfigName", name) + }, + { runToCompletion: true, boundExecutionOnly: true }, + ) + } + private readonly pendingEditOperations: PendingEditOperationStore private cloudOrganizationsCache: CloudOrganizationMembership[] | null = null @@ -419,6 +609,85 @@ 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 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 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` + * 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 +717,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 +788,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 +936,610 @@ 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 () => { + // 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 + // 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 + } + } + + // 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] + ClineProvider.clearedViewStateIds.add(viewStateId) + } else { + next.updatedAt = values.updatedAt ?? Date.now() + states[viewStateId] = next + ClineProvider.clearedViewStateIds.delete(viewStateId) + 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 + // 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)) + // 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 + // one of its landed writes really 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, + // 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) + } + // 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 + } + // 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 () => { + // 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 + // 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) + } + // 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", 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 + } + }) + + 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 () => { + // 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 + + 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)) + 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. + 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 + // 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", 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 + } + } + }) + + 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), + ) + } + + /** + * 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]) + } + 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]) + } + } + } + + /** + * 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 + } + + // 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] + + if (!previous) { + 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 + } + + // 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)) + 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) + } 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) + } + } + 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 + } + + // 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 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 { + const values = + typeof keyOrValues === "object" && keyOrValues !== null + ? keyOrValues + : ({ [keyOrValues]: value } as ViewLocalStateValues) + + await this._saveViewLocalStateFromMutation(values) + + this.log(`[saveViewState] Saved ${Object.keys(values).join(", ")} for viewId ${this.viewId}`) + } + /** * Override EventEmitter's on method to match TaskProviderLike interface */ @@ -1052,24 +1933,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 +1972,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 +2451,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, @@ -1772,36 +2673,13 @@ export class ClineProvider const taskId = this.getCurrentTask()?.taskId this.diagnosticsRecorder.record({ boundary: "webview-out", - phase: "start", - type: message.type, - action: message.action, - stateSequence: message.type === "state" ? message.state?.clineMessagesSeq : undefined, - taskId, - }) - if (this._disposed) { - this.diagnosticsRecorder.record({ - boundary: "webview-out", - phase: "failure", - type: message.type, - action: message.action, - elapsedMs: Date.now() - startedAt, - taskId, - }) - 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 { + phase: "start", + type: message.type, + action: message.action, + stateSequence: message.type === "state" ? message.state?.clineMessagesSeq : undefined, + taskId, + }) + if (this._disposed) { this.diagnosticsRecorder.record({ boundary: "webview-out", phase: "failure", @@ -1810,8 +2688,28 @@ export class ClineProvider elapsedMs: Date.now() - startedAt, taskId, }) - // View disposed, drop message silently + return } + + 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 +2998,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 +3014,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 +3077,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 +3178,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 +3276,231 @@ 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, and only + // 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 + // 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, + 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 + // snapshot, which a copy taken here would only restore the older value over. + } + } + + /** + * 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. 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 viewStateEvictions.viewIds) { + const entry = viewStateEvictions.entries.get(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)}`, + ) + } + 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 + } + } + + /** + * 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, @@ -2288,7 +3508,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) { @@ -2312,79 +3544,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 }, ) @@ -2412,77 +3654,600 @@ 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 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) + } 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)}`, ) + } + + 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. + } + // 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()), + 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 + // 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), + ]) + const failedActivation = activationResults.find( + (result): result is PromiseRejectedResult => result.status === "rejected", + ) + + 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 + // 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. + 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. 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, { + 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) + }`, + ) + } + } + 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 + } + } + + async deleteProviderProfile(profileToDelete: ProviderSettingsEntry) { + const globalSettings = this.contextProxy.getValues() + let profileToActivate: string | undefined = globalSettings.currentApiConfigName + + if (profileToDelete.name === profileToActivate) { + profileToActivate = this.getProviderProfileEntries().find(({ name }) => name !== profileToDelete.name)?.name + } + + if (!profileToActivate) { + throw new Error("You cannot delete the last profile") + } + + // 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 + } - if (failedActivation) throw failedActivation.reason + 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`, + ) + } - if (signal.aborted) return id + // 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 - // Change the provider for the current task. - // TODO: We should rename `buildApiHandler` for clarity (e.g. `getProviderClient`). - this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true }) + 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`, + ) + } + } - // 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()) - } + // 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 + // 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 (signal.aborted) return id + 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 }) + } - await this.postStateToWebview() - return id - } + // 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) + } + } - async deleteProviderProfile(profileToDelete: ProviderSettingsEntry) { - const globalSettings = this.contextProxy.getValues() - let profileToActivate: string | undefined = globalSettings.currentApiConfigName + // 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) - if (profileToDelete.name === profileToActivate) { - profileToActivate = this.getProviderProfileEntries().find(({ name }) => name !== profileToDelete.name)?.name - } + await this.postStateToWebview() - if (!profileToActivate) { - throw new Error("You cannot delete the last profile") + // 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)}`, + ) + } + // 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 }) + 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 } - - const entries = this.getProviderProfileEntries().filter(({ name }) => name !== profileToDelete.name) - - await this.contextProxy.setValues({ - ...globalSettings, - currentApiConfigName: profileToActivate, - listApiConfigMeta: entries, - }) - - await this.postStateToWebview() } private async persistStickyProviderProfileToCurrentTask( @@ -2525,8 +4290,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 +4312,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 @@ -2548,18 +4324,93 @@ 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. - 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 { + // 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()), + // 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), + // 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), + this._saveViewLocalStateFromMutation({ apiConfiguration: providerSettings }), + ]) + const failedActivation = activationResults.find( + (result): result is PromiseRejectedResult => result.status === `rejected`, + ) - const { mode } = await this.getState() + 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) + // 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 + } + } - 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) } @@ -2587,6 +4438,229 @@ 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 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 (pinnedViews.length === 0 && taskBoundViews.length === 0) { + return + } + + await Promise.all([ + ...pinnedViews.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() + }), + // 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() + }), + ]) + } + + /** + * 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) + // 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 (pinnedViews.length === 0 && taskBoundViews.length === 0) { + return + } + + 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. + 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() + }), + // 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) { @@ -2724,8 +4798,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 +5644,23 @@ 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 } + // 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() // 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 +5721,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 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, + 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 +5939,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 +6015,140 @@ 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) + } + + /** + * 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 + * 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 +6177,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() @@ -4405,46 +6729,100 @@ 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) { - 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 } + // 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 // 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: 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, @@ -4453,8 +6831,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 +6861,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..3a58126681f 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", @@ -267,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 @@ -853,8 +863,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 +894,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 +977,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.profileMutationExclusion.spec.ts b/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts new file mode 100644 index 00000000000..43f0815b623 --- /dev/null +++ b/src/core/webview/__tests__/ClineProvider.profileMutationExclusion.spec.ts @@ -0,0 +1,795 @@ +// 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 } from "@roo-code/types" +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" + +import { ContextProxy } from "../../config/ContextProxy" +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 + +// 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}` + +/** + * 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 = () => {} + const promise = new Promise((resolve) => { + release = resolve + }) + 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. 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() { + // 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 entered: BoundaryCall[] = [] + const landed: BoundaryCall[] = [] + const storeGates = new Map>() + let unreadable: { name: string; marker: string } | undefined + let poisonNextReadOf: string | undefined + + const readBlob = (): string | undefined => { + const value = blob.value + if (poisonNextReadOf === undefined) { + return value + } + 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) + }), + } + } + + const store = { + /** 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.method === "store" && + call.tag === tag && + recordHoldsMarker(parsedRecordOf(call.payload, name), marker), + ), + /** 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()) + }, + releaseStore: (marker: string) => storeGates.get(marker)?.release(), + releaseAll: () => { + for (const gate of storeGates.values()) { + gate.release() + } + }, + armRecordUnreadableAfter: (name: string, marker: string) => { + unreadable = { name, marker } + }, + createSecrets, + } + + return store +} + +function createMockContext(secrets: ProfilesSecretStorage): vscode.ExtensionContext { + const globalState: Record = { + mode: "code", + currentApiConfigName: "test-config", + listApiConfigMeta: [ + { id: storedIdFor("test-config"), name: "test-config" }, + { id: storedIdFor("default"), name: "default" }, + ], + } + + 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, + 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(store.createSecrets(tag)) + 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({}) + // 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()) { + 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("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.deferStoreOf(MODEL_A) + const firstSave = first.upsertProviderProfile(PROFILE_NAME, SETTINGS_A, false) + const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredStoreOf("first", PROFILE_NAME, MODEL_A)) + expect(parked).toBe(true) + + 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 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 + + 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 - 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.writersOf(PROFILE_NAME))) + expect(writerOrder).toEqual(["first", "second"]) + expect(store.hadRecordDelete()).toBe(false) + }) + + 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] + + store.deferStoreOf(MODEL_A) + const firstSave = first.upsertProviderProfile(PARKED_NAME, SETTINGS_A, false) + const parked = await waitForRounds(STORE_ROUNDS, () => store!.enteredStoreOf("first", PARKED_NAME, MODEL_A)) + 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) + + // 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.enteredStoreOf("second", SEED_PROFILE_NAME, PATCHED_SEED_MODEL_ID)).toBe(false) + + 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 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.deferStoreOf(MODEL_A) + const firstSave = first.upsertProviderProfile(SEED_PROFILE_NAME, SETTINGS_A, false) + const parked = await waitForRounds(STORE_ROUNDS, () => + 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, 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 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.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 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.deferStoreOf(MODEL_MOVED) + const firstSave = first.upsertProviderProfile(SEED_PROFILE_NAME, movedSettings, false) + const parked = await waitForRounds(STORE_ROUNDS, () => + store!.enteredStoreOf("first", SEED_PROFILE_NAME, MODEL_MOVED), + ) + 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.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.writersOf(SEED_PROFILE_NAME) + 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!.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) + } finally { + // 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) + }) + + 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 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.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!.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 + }, + // 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.releaseStore(MODEL_A) + await Promise.all([firstSave, profileReads]) + expect(firstSettled).toBe(true) + }) +}) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index b364b5baa79..946b105cbc2 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,7276 @@ 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("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, + 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("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, + 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("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 + // 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("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("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, + 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 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 + 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) + 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) + expect(repairState).toBe("running") + expect(writes).toEqual([]) + let followingStarted = false + const following = provider["enqueueProviderProfileMutation"]( + async () => { + followingStarted = true + }, + { runToCompletion: true }, + ) + await vi.advanceTimersByTimeAsync(0) + expect(followingStarted).toBe(false) + release() + 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) + 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: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, + 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" + }, + ) + // 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. 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 for its caller; the write is still pending", + ) + 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() + }) + + 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, + 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("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. + 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 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(() => {}) + 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 pinned profile together with the overlay read at the same instant", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + 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", + } + 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, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + 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) + + // 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") + + // 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 + // 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("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, + 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("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 }, + } + // 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) + 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"]() + // 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"]({ + 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 }) + 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, + 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("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. + // 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, + "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) + 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) + }) + }) + const rejectedAttempt = provider["savePersistedViewState"]({ + currentApiConfigName: "u1-profile", + updatedAt: 9001, + }) + // 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. + 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 }) + // 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() + }) + + 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, + "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) + // 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. + 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 + provider["wroteUnderTemporaryViewStateId"] = true + await expect(provider["rekeyPersistedViewStateEntry"]("u2b-stable")).rejects.toThrow(TypeError) + expect(ClineProvider["clearedViewStateIds"].has(temporaryViewStateId)).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 }) + // 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() + }) + + 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. + // 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, + "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 + // 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 = () => {} + // 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) => { + settleStore = (error) => reject(error) + }) + }) + const rejectedAttempt = provider["repointPersistedViewStates"]("u4-removed", "u4-replacement") + // 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. + const afterReject = mockContext.globalState.get("viewStates") as Record + // 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).toEqual(seeded) + expect(provider["prunedViewIdsDuringActivation"]).toEqual([]) + // 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 and stamped at the fixed clock, the oldest fillers gone, + // every other entry exactly as seeded. + const expectedAfterLand: Record< + string, + { mode?: string; currentApiConfigName?: string; updatedAt: number } + > = {} + 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", updatedAt: FIXED_NOW } + : { ...entry } + } + 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) + 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. 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) + // 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 + // 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("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, + 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-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, + 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("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, + 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 +11274,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 +12131,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 +12385,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 +12416,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 +12445,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 +12622,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 +12985,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 +13011,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 +13075,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 +13103,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 +13144,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 +13181,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 +13211,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 +13232,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 +13245,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 +13292,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 +13396,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 +13430,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 +13486,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 +13540,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 +14339,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 +14362,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 +14408,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 +16016,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 +16049,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 +16079,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 +16095,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 +16115,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 +16132,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 +16155,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 +16177,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 +16194,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..e3e0d040846 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" @@ -89,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, @@ -111,6 +113,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 +130,23 @@ 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], + ), + ), + // 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(), @@ -138,6 +158,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 +911,620 @@ 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[] = [] + // 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[]) => { + 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") + }) + + 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. + // 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(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", + ) + 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. + // 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("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 = [] + const originalSaveViewState = mockClineProvider.saveViewState + // 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" }) + await new Promise((resolve) => setImmediate(resolve)) + } finally { + mockClineProvider.saveViewState = originalSaveViewState + } + + // 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({ + 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 () => { + 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" }) + // 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"'), + ) + }) + + 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 + // 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() + .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 +2588,203 @@ 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("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 } + } + view.providerSettingsManager = { + getProfile: vi.fn().mockRejectedValue(new Error("secrets read failed")), + } + const logSpy = vi.mocked(mockClineProvider.log) + // 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'")) + // 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 () => { + // 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 +2853,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 +3413,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 +3478,815 @@ 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() + }) + // 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", () => { + // 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 + 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. + 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, + enqueueSharedProfileSelectionRepair: provider.enqueueSharedProfileSelectionRepair, + } + + 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("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("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("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, + 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 +5015,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..4d436272cfb 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,107 @@ 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 + // 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: ${seedReadFailure}`, + ) + } + // 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. + // 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, + }) + // 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 + // 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 +813,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 +898,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 +1022,55 @@ 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) { + // 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}'; this view's pin and settings overlay stay on the previous profile and the save failed: ${error instanceof Error ? error.message : String(error)}`, + ) + throw error + } + } 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 +1880,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 +2642,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,31 +2685,176 @@ 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`) + } - // Create a new configuration with the new name and old ID. - await provider.providerSettingsManager.saveConfig(newName, { ...message.apiConfiguration, id }) + // 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 + } - // Delete the old configuration. - await provider.providerSettingsManager.deleteConfig(oldName) + // 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. 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) { + // 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 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 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 + // 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. + // + // 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, + )}`, + ) + } + } + // 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 + } } } break @@ -3232,7 +3546,46 @@ 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) + // 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`) } } 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/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( 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 } }