// npx vitest core/webview/__tests__/webviewMessageHandler.spec.ts import type { Mock } from "vitest" // Mock dependencies - must come before imports vi.mock("../../../api/providers/fetchers/modelCache") // The refactor routes model-list fetches through an ApiHandler built by buildApiHandler. // Mock it so the handler is a lightweight double instead of a real provider (which would // require credentials and other un-mocked collaborators). vi.mock("../../../api", () => ({ buildApiHandler: vi.fn().mockReturnValue({ getModel: vi.fn().mockReturnValue({ id: "claude-3-sonnet" }), }), })) vi.mock("../../../services/zoo-code-auth", () => ({ disconnectZooCode: vi.fn().mockResolvedValue(undefined), })) vi.mock("../../../api/providers/fetchers/lmstudio", () => ({ getLMStudioModels: vi.fn(), })) vi.mock("../../../integrations/theme/getTheme", () => ({ getTheme: vi.fn().mockResolvedValue({}), })) vi.mock("../../../integrations/openai-codex/oauth", () => ({ openAiCodexOAuthManager: { getAccessToken: vi.fn(), getAccountId: vi.fn(), }, })) vi.mock("../../../integrations/openai-codex/rate-limits", () => ({ fetchOpenAiCodexRateLimitInfo: vi.fn(), })) vi.mock("../../../services/command/commands", () => ({ getCommands: vi.fn(), })) vi.mock("../../../services/destructive-command-guard", () => ({ ensureDcgInstalled: vi.fn(), })) vi.mock("@anthropic-ai/vertex-sdk", () => ({ AnthropicVertex: vi.fn(), })) vi.mock("google-auth-library", () => ({ GoogleAuth: vi.fn(), })) vi.mock("ollama", () => ({ Ollama: vi.fn(), })) // Mock the diagnosticsHandler module vi.mock("../diagnosticsHandler", () => ({ generateErrorDiagnostics: vi.fn().mockResolvedValue({ success: true, filePath: "/tmp/diagnostics.json" }), })) vi.mock("../rulesMessageHandler", () => ({ handleRequestRules: vi.fn(), handleCreateRule: vi.fn(), handleDeleteRule: vi.fn(), handleOpenRuleFile: vi.fn(), handleOpenRulesDirectory: vi.fn(), })) vi.mock("@roo-code/telemetry", () => ({ TelemetryService: { hasInstance: vi.fn().mockReturnValue(false), instance: { updateTelemetryState: vi.fn(), captureTelemetrySettingsChanged: vi.fn(), }, }, })) 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" import { flushModels, getModels } from "../../../api/providers/fetchers/modelCache" 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, handleOpenRuleFile, handleOpenRulesDirectory, handleRequestRules, } from "../rulesMessageHandler" const { openAiCodexOAuthManager } = await import("../../../integrations/openai-codex/oauth") const { fetchOpenAiCodexRateLimitInfo } = await import("../../../integrations/openai-codex/rate-limits") const mockGetModels = getModels as Mock const mockFlushModels = flushModels as Mock const mockGetLMStudioModels = getLMStudioModels as Mock const mockGetCommands = vi.mocked(getCommands) const mockGetAccessToken = vi.mocked(openAiCodexOAuthManager.getAccessToken) const mockGetAccountId = vi.mocked(openAiCodexOAuthManager.getAccountId) const mockFetchOpenAiCodexRateLimitInfo = vi.mocked(fetchOpenAiCodexRateLimitInfo) // Mock ClineProvider const mockClineProvider = { getState: vi.fn(), postMessageToWebview: vi.fn(), saveViewState: vi.fn(), customModesManager: { getCustomModes: vi.fn(), deleteCustomMode: vi.fn(), }, context: { extensionPath: "/mock/extension/path", globalStorageUri: { fsPath: "/mock/global/storage" }, }, contextProxy: { context: { extensionPath: "/mock/extension/path", globalStorageUri: { fsPath: "/mock/global/storage" }, }, 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(), getCurrentTask: vi.fn(), getTaskWithId: vi.fn(), createTaskWithHistoryItem: vi.fn(), renameTaskWithId: vi.fn(), getSkillsManager: vi.fn(), 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() mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: {} }) }) afterEach(() => vi.restoreAllMocks()) it("reports the account before models finish loading without exposing a token", async () => { vi.spyOn(copilotProvider, "connectGitHubCopilot").mockImplementation( async (onAuthenticated?: (account: string) => Promise) => { await onAuthenticated?.("Test User") return { account: "Test User", models: [] } }, ) await webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) expect(mockClineProvider.postMessageToWebview).toHaveBeenNthCalledWith(1, { type: "githubCopilotModels", githubCopilotAccount: "Test User", }) expect(mockClineProvider.postMessageToWebview).toHaveBeenNthCalledWith(2, { type: "githubCopilotSignInResult", githubCopilotAccount: "Test User", vsCodeLmModels: [], }) expect(JSON.stringify(vi.mocked(mockClineProvider.postMessageToWebview).mock.calls)).not.toContain( "accessToken", ) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() }) it("returns sign-in errors to the requesting control", async () => { vi.spyOn(copilotProvider, "connectGitHubCopilot").mockRejectedValue(new Error("Sign-in cancelled")) await webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "githubCopilotSignInResult", error: "Sign-in cancelled", }) }) it("uses a fresh session for the reconnect command", async () => { const connect = vi .spyOn(copilotProvider, "connectGitHubCopilot") .mockResolvedValue({ account: "New User", models: [] }) await webviewMessageHandler(mockClineProvider, { type: "githubCopilotReconnect" }) expect(connect).toHaveBeenCalledWith(expect.any(Function), true) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "githubCopilotSignInResult", githubCopilotAccount: "New User", vsCodeLmModels: [], }) }) it("drops a stale sign-in that completes after a newer reconnect", async () => { let finishSignIn!: (value: { account: string; models: [] }) => void let finishReconnect!: (value: { account: string; models: [] }) => void vi.spyOn(copilotProvider, "connectGitHubCopilot") .mockImplementationOnce(() => new Promise((resolve) => (finishSignIn = resolve))) .mockImplementationOnce(() => new Promise((resolve) => (finishReconnect = resolve))) const signIn = webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) const reconnect = webviewMessageHandler(mockClineProvider, { type: "githubCopilotReconnect" }) // The newer request finishes first, then the older one arrives late. finishReconnect({ account: "New User", models: [] }) await reconnect finishSignIn({ account: "Old User", models: [] }) await signIn expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledTimes(1) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "githubCopilotSignInResult", githubCopilotAccount: "New User", vsCodeLmModels: [], }) }) it("drops a stale sign-in failure that arrives after a newer success", async () => { let failSignIn!: (reason: Error) => void let finishReconnect!: (value: { account: string; models: [] }) => void vi.spyOn(copilotProvider, "connectGitHubCopilot") .mockImplementationOnce(() => new Promise((_resolve, reject) => (failSignIn = reject))) .mockImplementationOnce(() => new Promise((resolve) => (finishReconnect = resolve))) const signIn = webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) const reconnect = webviewMessageHandler(mockClineProvider, { type: "githubCopilotReconnect" }) finishReconnect({ account: "New User", models: [] }) await reconnect failSignIn(new Error("Sign-in cancelled")) await signIn expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledTimes(1) expect(mockClineProvider.postMessageToWebview).not.toHaveBeenCalledWith( expect.objectContaining({ error: expect.anything() }), ) }) it("answers every view that signs in, since only a view's own newer request makes its older one stale", async () => { const otherView = { ...mockClineProvider, postMessageToWebview: vi.fn(), } as unknown as ClineProvider let finishFirst!: (value: { account: string; models: [] }) => void let finishSecond!: (value: { account: string; models: [] }) => void vi.spyOn(copilotProvider, "connectGitHubCopilot") .mockImplementationOnce(() => new Promise((resolve) => (finishFirst = resolve))) .mockImplementationOnce(() => new Promise((resolve) => (finishSecond = resolve))) const first = webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) const second = webviewMessageHandler(otherView, { type: "githubCopilotSignIn" }) finishSecond({ account: "Second User", models: [] }) finishFirst({ account: "First User", models: [] }) await Promise.all([first, second]) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "githubCopilotSignInResult", githubCopilotAccount: "First User" }), ) expect(otherView.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "githubCopilotSignInResult", githubCopilotAccount: "Second User" }), ) }) it("opens VS Code's account management and never signs out itself", async () => { const open = vi.spyOn(copilotProvider, "openGitHubAccountManagement").mockResolvedValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "githubCopilotManageAccount" }) expect(open).toHaveBeenCalledOnce() expect(mockClineProvider.postMessageToWebview).not.toHaveBeenCalled() }) it("logs, rather than surfacing, a failure to open account management", async () => { vi.spyOn(copilotProvider, "openGitHubAccountManagement").mockRejectedValue(new Error("command missing")) await webviewMessageHandler(mockClineProvider, { type: "githubCopilotManageAccount" }) expect(mockClineProvider.log).toHaveBeenCalledWith(expect.stringContaining("command missing")) }) it("reports a non-Error sign-in failure as text", async () => { vi.spyOn(copilotProvider, "connectGitHubCopilot").mockRejectedValue("denied") await webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "githubCopilotSignInResult", error: "denied", }) }) it("logs a non-Error failure to open account management", async () => { vi.spyOn(copilotProvider, "openGitHubAccountManagement").mockRejectedValue("no such command") await webviewMessageHandler(mockClineProvider, { type: "githubCopilotManageAccount" }) expect(mockClineProvider.log).toHaveBeenCalledWith(expect.stringContaining("no such command")) }) describe("legacy VS Code LM model requests", () => { it("lists the host's models as before and never looks up a GitHub account", async () => { const account = vi.spyOn(copilotProvider, "getGitHubCopilotAccount") const copilotModels = vi.spyOn(copilotProvider, "getGitHubCopilotModels") const models = vi.spyOn(vsCodeLmProvider, "getVsCodeLmModels").mockResolvedValue([]) await webviewMessageHandler(mockClineProvider, { type: "requestVsCodeLmModels" }) expect(models).toHaveBeenCalledWith() expect(account).not.toHaveBeenCalled() expect(copilotModels).not.toHaveBeenCalled() expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledExactlyOnceWith({ type: "vsCodeLmModels", vsCodeLmModels: [], }) }) }) it("restores a signed-in account during passive model refresh", async () => { vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue("Test User") vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockResolvedValue([]) await webviewMessageHandler(mockClineProvider, { type: "requestVsCodeLmModels", apiConfiguration: { apiProvider: providerIdentifiers.githubCopilot }, }) expect(copilotProvider.getGitHubCopilotModels).toHaveBeenCalled() expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "githubCopilotModels", githubCopilotAccount: "Test User", vsCodeLmModels: [], }) }) it("drops the early account update of a sign-in that a newer one has superseded", async () => { let supersededCallback!: (account: string) => Promise let finishSupersededSignIn!: (value: { account: string; models: [] }) => void vi.spyOn(copilotProvider, "connectGitHubCopilot") .mockImplementationOnce((onAuthenticated) => { supersededCallback = onAuthenticated! return new Promise((resolve) => (finishSupersededSignIn = resolve)) }) .mockResolvedValueOnce({ account: "New User", models: [] }) const superseded = webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) await webviewMessageHandler(mockClineProvider, { type: "githubCopilotReconnect" }) await supersededCallback("Old User") finishSupersededSignIn({ account: "Old User", models: [] }) await superseded expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledExactlyOnceWith({ type: "githubCopilotSignInResult", githubCopilotAccount: "New User", vsCodeLmModels: [], }) }) it("publishes the early account update of a sign-in that is still the newest", async () => { let callback!: (account: string) => Promise let finish!: (value: { account: string; models: [] }) => void vi.spyOn(copilotProvider, "connectGitHubCopilot").mockImplementation((onAuthenticated) => { callback = onAuthenticated! return new Promise((resolve) => (finish = resolve)) }) const signIn = webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) await callback("Test User") expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "githubCopilotModels", githubCopilotAccount: "Test User", }) finish({ account: "Test User", models: [] }) await signIn }) it("reports no account as null, so the webview clears a stale sign-in rather than keeping it", async () => { vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue(undefined) vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockResolvedValue([]) await webviewMessageHandler(mockClineProvider, { type: "requestVsCodeLmModels", apiConfiguration: { apiProvider: providerIdentifiers.githubCopilot }, }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "githubCopilotModels", githubCopilotAccount: null, vsCodeLmModels: [], }) }) describe("passive refresh racing a sign-in", () => { const passiveRequest = () => webviewMessageHandler(mockClineProvider, { type: "requestVsCodeLmModels", apiConfiguration: { apiProvider: providerIdentifiers.githubCopilot }, }) const signedInResult = { type: "githubCopilotSignInResult", githubCopilotAccount: "New User", vsCodeLmModels: [], } it("discards a refresh that began before a sign-in which finished first", async () => { let finishModels!: (models: []) => void vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue(undefined) vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockImplementation( () => new Promise((resolve) => (finishModels = resolve)), ) vi.spyOn(copilotProvider, "connectGitHubCopilot").mockResolvedValue({ account: "New User", models: [] }) const refresh = passiveRequest() await webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) finishModels([]) await refresh expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledTimes(1) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith(signedInResult) }) it("discards a refresh whose model lookup fails after a newer sign-in", async () => { let failModels!: (reason: Error) => void vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue(undefined) vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockImplementation( () => new Promise((_resolve, reject) => (failModels = reject)), ) vi.spyOn(copilotProvider, "connectGitHubCopilot").mockResolvedValue({ account: "New User", models: [] }) const refresh = passiveRequest() await webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) failModels(new Error("host busy")) await refresh expect(mockClineProvider.postMessageToWebview).not.toHaveBeenCalledWith( expect.objectContaining({ error: expect.anything() }), ) }) it("discards a refresh that began during a sign-in and ended after it", async () => { let finishSignIn!: (value: { account: string; models: [] }) => void let finishModels!: (models: []) => void vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue(undefined) vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockImplementation( () => new Promise((resolve) => (finishModels = resolve)), ) vi.spyOn(copilotProvider, "connectGitHubCopilot").mockImplementation( () => new Promise((resolve) => (finishSignIn = resolve)), ) const signIn = webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) const refresh = passiveRequest() finishSignIn({ account: "New User", models: [] }) await signIn finishModels([]) await refresh expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledTimes(1) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith(signedInResult) }) it("does not make a pending sign-in stale by starting a refresh", async () => { let finishSignIn!: (value: { account: string; models: [] }) => void vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue(undefined) vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockResolvedValue([]) vi.spyOn(copilotProvider, "connectGitHubCopilot").mockImplementation( () => new Promise((resolve) => (finishSignIn = resolve)), ) const signIn = webviewMessageHandler(mockClineProvider, { type: "githubCopilotSignIn" }) await passiveRequest() finishSignIn({ account: "New User", models: [] }) await signIn expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith(signedInResult) }) it("still answers a refresh when no sign-in happened meanwhile", async () => { vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue("Test User") vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockResolvedValue([]) await passiveRequest() expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "githubCopilotModels", githubCopilotAccount: "Test User", vsCodeLmModels: [], }) }) it("discards an older refresh that finishes after a newer one, even with no sign-in", async () => { const finishers: Array<(models: Array<{ id: string }>) => void> = [] vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue("Test User") vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockImplementation( () => new Promise((resolve) => finishers.push(resolve as (models: Array<{ id: string }>) => void)), ) const older = passiveRequest() const newer = passiveRequest() await vi.waitFor(() => expect(finishers).toHaveLength(2)) finishers[1]([{ id: "newer" }]) await newer finishers[0]([{ id: "older" }]) await older const posted = vi.mocked(mockClineProvider.postMessageToWebview).mock.calls.map(([message]) => message) expect(posted).toEqual([ { type: "githubCopilotModels", githubCopilotAccount: "Test User", vsCodeLmModels: [{ id: "newer" }] }, ]) }) it("discards an older refresh's error that arrives after a newer refresh succeeded", async () => { const settlers: Array<{ resolve: (models: Array<{ id: string }>) => void reject: (error: Error) => void }> = [] vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue("Test User") vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockImplementation( () => new Promise((resolve, reject) => settlers.push({ resolve: resolve as (models: Array<{ id: string }>) => void, reject }), ), ) const older = passiveRequest() const newer = passiveRequest() await vi.waitFor(() => expect(settlers).toHaveLength(2)) settlers[1].resolve([{ id: "newer" }]) await newer settlers[0].reject(new Error("host busy")) await older const posted = vi.mocked(mockClineProvider.postMessageToWebview).mock.calls.map(([message]) => message) expect(posted).toEqual([ { type: "githubCopilotModels", githubCopilotAccount: "Test User", vsCodeLmModels: [{ id: "newer" }] }, ]) }) it("keeps one view's refresh from discarding another view's refresh", async () => { const otherView = { ...mockClineProvider, postMessageToWebview: vi.fn() } as unknown as ClineProvider let finishFirst!: (models: Array<{ id: string }>) => void let calls = 0 vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue("Test User") vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockImplementation(() => ++calls === 1 ? new Promise((resolve) => (finishFirst = resolve as (models: Array<{ id: string }>) => void)) : Promise.resolve([{ id: "other-view" }] as never), ) const refresh = passiveRequest() await vi.waitFor(() => expect(calls).toBe(1)) await webviewMessageHandler(otherView, { type: "requestVsCodeLmModels", apiConfiguration: { apiProvider: providerIdentifiers.githubCopilot }, }) finishFirst([{ id: "first-view" }]) await refresh const posted = vi.mocked(mockClineProvider.postMessageToWebview).mock.calls.map(([message]) => message) expect(posted).toEqual([ { type: "githubCopilotModels", githubCopilotAccount: "Test User", vsCodeLmModels: [{ id: "first-view" }], }, ]) }) it("discards a manual refresh that a host model-change broadcast overtook", async () => { let finishManual!: (models: Array<{ id: string }>) => void vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue("Test User") vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockImplementation( () => new Promise((resolve) => (finishManual = resolve as (models: Array<{ id: string }>) => void)), ) let notifyHost!: () => void const broadcast = registerCopilotModelBroadcast({ getTargets: () => [mockClineProvider], log: vi.fn(), debounceMs: 0, subscribe: (listener: () => void) => { notifyHost = listener return { dispose: () => {} } }, fetchModels: async () => [{ id: "new-from-host" }] as never, fetchAccount: async () => "Test User", }) try { // A manual refresh starts first and is still waiting on the host. const manual = passiveRequest() await vi.waitFor(() => expect(finishManual).toBeDefined()) // The host then reports new models, and the broadcast delivers them. notifyHost() await vi.waitFor(() => expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledTimes(1)) // The manual refresh finishes last, with the older list. finishManual([{ id: "old-from-manual" }]) await manual const posted = vi.mocked(mockClineProvider.postMessageToWebview).mock.calls.map(([message]) => message) expect(posted).toEqual([ { type: "githubCopilotModels", githubCopilotAccount: "Test User", vsCodeLmModels: [{ id: "new-from-host" }], }, ]) } finally { broadcast.dispose() } }) describe("a broadcast that does not deliver", () => { const pendingManual = () => { let finishManual!: (models: Array<{ id: string }>) => void vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue("Test User") vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockImplementation( () => new Promise((resolve) => (finishManual = resolve as (models: Array<{ id: string }>) => void)), ) return { finish: (models: Array<{ id: string }>) => finishManual(models) } } const broadcastWith = (fetchModels: () => Promise) => { let notifyHost!: () => void const registration = registerCopilotModelBroadcast({ getTargets: () => [mockClineProvider], log: vi.fn(), debounceMs: 0, subscribe: (listener: () => void) => { notifyHost = listener return { dispose: () => {} } }, fetchModels, fetchAccount: async () => "Test User", }) return { notify: () => notifyHost(), registration } } const expectManualReplyDelivered = () => expect( vi.mocked(mockClineProvider.postMessageToWebview).mock.calls.map(([message]) => message), ).toEqual([ { type: "githubCopilotModels", githubCopilotAccount: "Test User", vsCodeLmModels: [{ id: "manual" }], }, ]) it("still delivers a manual refresh when the broadcast's lookup fails", async () => { const manualLookup = pendingManual() const { notify, registration } = broadcastWith(() => Promise.reject(new Error("host busy"))) try { const manual = passiveRequest() await vi.waitFor(() => expect(copilotProvider.getGitHubCopilotModels).toHaveBeenCalled()) notify() await new Promise((resolve) => setTimeout(resolve, 0)) manualLookup.finish([{ id: "manual" }]) await manual // Otherwise the view's refresh spinner never clears and its buttons stay disabled. expectManualReplyDelivered() } finally { registration.dispose() } }) it("still delivers a manual refresh when a newer broadcast supersedes the first and both fail", async () => { const manualLookup = pendingManual() const { notify, registration } = broadcastWith(() => Promise.reject(new Error("host busy"))) try { const manual = passiveRequest() await vi.waitFor(() => expect(copilotProvider.getGitHubCopilotModels).toHaveBeenCalled()) notify() notify() await new Promise((resolve) => setTimeout(resolve, 0)) manualLookup.finish([{ id: "manual" }]) await manual expectManualReplyDelivered() } finally { registration.dispose() } }) }) it("reports a thrown account lookup as an error, so the webview keeps its account label", async () => { vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockRejectedValue(new Error("auth unavailable")) vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockResolvedValue([]) await passiveRequest() // No githubCopilotAccount field: the webview leaves its label alone rather than clearing it. expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledExactlyOnceWith({ type: "githubCopilotModels", error: "auth unavailable", }) }) it("keeps one view's sign-in from discarding another view's refresh", async () => { const otherView = { ...mockClineProvider, postMessageToWebview: vi.fn() } as unknown as ClineProvider vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue("Test User") vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockResolvedValue([]) vi.spyOn(copilotProvider, "connectGitHubCopilot").mockResolvedValue({ account: "Other", models: [] }) const refresh = passiveRequest() await webviewMessageHandler(otherView, { type: "githubCopilotSignIn" }) await refresh expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "githubCopilotModels", githubCopilotAccount: "Test User" }), ) }) }) it("reports a model discovery failure that is not an Error as text", async () => { vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue("Test User") vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockRejectedValue("quota exceeded") await webviewMessageHandler(mockClineProvider, { type: "requestVsCodeLmModels", apiConfiguration: { apiProvider: providerIdentifiers.githubCopilot }, }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "githubCopilotModels", error: "quota exceeded", }) }) it("shows model discovery errors instead of silently returning an empty list", async () => { vi.spyOn(copilotProvider, "getGitHubCopilotAccount").mockResolvedValue("Test User") vi.spyOn(copilotProvider, "getGitHubCopilotModels").mockRejectedValue(new Error("Model access denied")) await webviewMessageHandler(mockClineProvider, { type: "requestVsCodeLmModels", apiConfiguration: { apiProvider: providerIdentifiers.githubCopilot }, }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "githubCopilotModels", error: "Model access denied", }) }) }) describe("webviewMessageHandler - theme fixture probes", () => { const originalProbeSetting = process.env.ROO_CODE_THEME_FIXTURE_PROBE const themeFixture = { themeId: "Default Dark Modern", bodyClass: "vscode-dark", variables: { "--vscode-foreground": "#cccccc" }, } beforeEach(() => { vi.clearAllMocks() process.env.ROO_CODE_THEME_FIXTURE_PROBE = "1" }) afterEach(() => { if (originalProbeSetting === undefined) { delete process.env.ROO_CODE_THEME_FIXTURE_PROBE } else { process.env.ROO_CODE_THEME_FIXTURE_PROBE = originalProbeSetting } }) it("resolves a complete response when probing is enabled", async () => { await webviewMessageHandler(mockClineProvider, { type: "themeFixtureProbeResponse", requestId: "request-1", themeFixture, }) expect(mockClineProvider.resolveWebviewThemeFixtureProbe).toHaveBeenCalledWith("request-1", themeFixture) }) it("ignores incomplete or disabled responses", async () => { await webviewMessageHandler(mockClineProvider, { type: "themeFixtureProbeResponse" }) delete process.env.ROO_CODE_THEME_FIXTURE_PROBE await webviewMessageHandler(mockClineProvider, { type: "themeFixtureProbeResponse", requestId: "request-1", themeFixture, }) expect(mockClineProvider.resolveWebviewThemeFixtureProbe).not.toHaveBeenCalled() }) }) import { changeLanguage, t } from "../../../i18n" vi.mock("vscode", () => { const showInformationMessage = vi.fn() const showErrorMessage = vi.fn() const openTextDocument = vi.fn().mockResolvedValue({}) const showTextDocument = vi.fn().mockResolvedValue(undefined) return { window: { showInformationMessage, showErrorMessage, showTextDocument, }, workspace: { workspaceFolders: [{ uri: { fsPath: "/mock/workspace" } }], openTextDocument, getConfiguration: vi.fn(() => ({ get: vi.fn() })), }, commands: { executeCommand: vi.fn().mockResolvedValue(undefined), }, env: { isTelemetryEnabled: true, }, } }) vi.mock("../../../i18n", () => ({ changeLanguage: vi.fn(), t: vi.fn((key: string, args?: Record) => { // For the delete confirmation with rules, we need to return the interpolated string if (key === "common:confirmation.delete_custom_mode_with_rules" && args) { return `Are you sure you want to delete this ${args.scope} mode?\n\nThis will also delete the associated rules folder at:\n${args.rulesFolderPath}` } // Return the translated value for "Yes" if (key === "common:answers.yes") { return "Yes" } // Return the translated value for "Cancel" if (key === "common:answers.cancel") { return "Cancel" } return key }), })) vi.mock("fs/promises", () => { const mockRm = vi.fn().mockResolvedValue(undefined) const mockMkdir = vi.fn().mockResolvedValue(undefined) const mockReadFile = vi.fn().mockResolvedValue("[]") const mockWriteFile = vi.fn().mockResolvedValue(undefined) return { default: { rm: mockRm, mkdir: mockMkdir, readFile: mockReadFile, writeFile: mockWriteFile, }, rm: mockRm, mkdir: mockMkdir, readFile: mockReadFile, writeFile: mockWriteFile, } }) import * as vscode from "vscode" import * as fs from "fs/promises" import * as os from "os" import * as path from "path" import * as fsUtils from "../../../utils/fs" import { getWorkspacePath } from "../../../utils/path" import { ensureSettingsDirectoryExists } from "../../../utils/globalContext" import { generateErrorDiagnostics } from "../diagnosticsHandler" import type { ModeConfig } from "@roo-code/types" vi.mock("../../../utils/fs") vi.mock("../../../utils/path") vi.mock("../../../utils/globalContext") vi.mock("../../mentions/resolveImageMentions", () => ({ resolveImageMentions: vi.fn(async ({ text, images }: { text: string; images?: string[] }) => ({ text, images: [...(images ?? []), "data:image/png;base64,from-mention"], })), })) import { resolveImageMentions } from "../../mentions/resolveImageMentions" 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() mockGetLMStudioModels.mockReset() mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: { lmStudioModelId: "model-1", lmStudioBaseUrl: "http://localhost:1234", }, }) }) it("successfully fetches models from LMStudio", async () => { const mockModels: ModelRecord = { "model-1": { maxTokens: 4096, contextWindow: 8192, supportsPromptCache: false, description: "Test model 1", }, "model-2": { maxTokens: 8192, contextWindow: 16384, supportsPromptCache: false, description: "Test model 2", }, } mockGetModels.mockResolvedValue(mockModels) await webviewMessageHandler(mockClineProvider, { type: "requestLmStudioModels", }) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.lmstudio, baseUrl: "http://localhost:1234", }, expect.anything(), ) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "lmStudioModels", lmStudioModels: mockModels, }) }) it("prefers the request payload base URL over persisted settings", async () => { mockGetLMStudioModels.mockResolvedValue({}) await webviewMessageHandler(mockClineProvider, { type: "requestLmStudioModels", values: { baseUrl: "http://127.0.0.1:4321" }, }) expect(mockGetLMStudioModels).toHaveBeenCalledWith("http://127.0.0.1:4321") expect(mockGetModels).not.toHaveBeenCalled() }) it("treats an empty-string base URL as an explicit preview request", async () => { mockGetLMStudioModels.mockResolvedValue({}) await webviewMessageHandler(mockClineProvider, { type: "requestLmStudioModels", values: { baseUrl: "" }, }) expect(mockGetLMStudioModels).toHaveBeenCalledWith("") expect(mockGetModels).not.toHaveBeenCalled() }) }) describe("webviewMessageHandler - image mentions", () => { beforeEach(() => { vi.clearAllMocks() mockClineProvider.getState = vi.fn().mockResolvedValue({ maxImageFileSize: 5, maxTotalImageSize: 20, }) }) it("should resolve image mentions for askResponse payloads", async () => { const mockHandleWebviewAskResponse = vi.fn() vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ cwd: "/mock/workspace", rooIgnoreController: undefined, handleWebviewAskResponse: mockHandleWebviewAskResponse, } as any) await webviewMessageHandler(mockClineProvider, { type: "askResponse", askResponse: "messageResponse", text: "See @/img.png", images: [], }) expect(vi.mocked(resolveImageMentions)).toHaveBeenCalled() // Omitted segments fail closed, so the text is all generated. expect(mockHandleWebviewAskResponse).toHaveBeenCalledWith( "messageResponse", "See @/img.png", ["data:image/png;base64,from-mention"], [{ text: "See @/img.png", source: "generated" }], ) }) }) describe("webviewMessageHandler - requestOllamaModels", () => { beforeEach(() => { vi.clearAllMocks() mockFlushModels.mockReset() mockFlushModels.mockResolvedValue(undefined) mockGetModels.mockReset() mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: { ollamaModelId: "model-1", ollamaBaseUrl: "http://localhost:1234", }, }) }) it("successfully fetches models from Ollama", async () => { const mockModels: ModelRecord = { "model-1": { maxTokens: 4096, contextWindow: 8192, supportsPromptCache: false, description: "Test model 1", }, "model-2": { maxTokens: 8192, contextWindow: 16384, supportsPromptCache: false, description: "Test model 2", }, } mockGetModels.mockResolvedValue(mockModels) await webviewMessageHandler(mockClineProvider, { type: "requestOllamaModels", }) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.ollama, baseUrl: "http://localhost:1234", }, expect.anything(), ) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "ollamaModels", ollamaModels: mockModels, }) }) it("posts empty models response when no models are found", async () => { mockGetModels.mockResolvedValue({}) await webviewMessageHandler(mockClineProvider, { type: "requestOllamaModels", }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "ollamaModels", ollamaModels: {}, }) }) it("posts empty models response with error message and logs to output on fetch failure", async () => { mockGetModels.mockRejectedValue(new Error("Connection refused")) await webviewMessageHandler(mockClineProvider, { type: "requestOllamaModels", }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "ollamaModels", ollamaModels: {}, error: "Connection refused", }) expect(mockClineProvider.log).toHaveBeenCalledWith( "[requestOllamaModels] Failed to read models for http://localhost:1234: Connection refused", ) }) it("distinguishes a model cache refresh failure from a model read failure", async () => { mockFlushModels.mockRejectedValue(new Error("Cache write failed")) await webviewMessageHandler(mockClineProvider, { type: "requestOllamaModels", values: { baseUrl: "https://ollama.example.com" }, }) expect(mockGetModels).not.toHaveBeenCalled() expect(mockClineProvider.log).toHaveBeenCalledWith( "[requestOllamaModels] Failed to refresh model cache for https://ollama.example.com: Cache write failed", ) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "ollamaModels", ollamaModels: {}, error: "Cache write failed", }) }) it("uses baseUrl from message values over saved state", async () => { const mockModels: ModelRecord = { "remote-model": { maxTokens: 4096, contextWindow: 8192, supportsPromptCache: false, description: "Remote model", }, } mockGetModels.mockResolvedValue(mockModels) await webviewMessageHandler(mockClineProvider, { type: "requestOllamaModels", values: { baseUrl: "https://ollama.example.com", apiKey: "secret-key", }, }) // Should use the URL from message values, not the saved state expect(mockFlushModels).toHaveBeenCalledWith( { provider: providerIdentifiers.ollama, baseUrl: "https://ollama.example.com", apiKey: "secret-key", }, expect.anything(), true, ) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.ollama, baseUrl: "https://ollama.example.com", apiKey: "secret-key", }, expect.anything(), ) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "ollamaModels", ollamaModels: mockModels, }) }) }) describe("webviewMessageHandler - requestRouterModels", () => { beforeEach(() => { vi.clearAllMocks() mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: { openRouterApiKey: "openrouter-key", requestyApiKey: "requesty-key", litellmApiKey: "litellm-key", litellmBaseUrl: "http://localhost:4000", }, }) }) it("successfully fetches models from all providers", async () => { const mockModels: ModelRecord = { "model-1": { maxTokens: 4096, contextWindow: 8192, supportsPromptCache: false, description: "Test model 1", }, "model-2": { maxTokens: 8192, contextWindow: 16384, supportsPromptCache: false, description: "Test model 2", }, } mockGetModels.mockResolvedValue(mockModels) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", }) // Verify getModels was called for each provider expect(mockGetModels).toHaveBeenCalledWith({ provider: providerIdentifiers.openrouter }, expect.anything()) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.requesty, apiKey: "requesty-key" }, expect.anything(), ) expect(mockGetModels).toHaveBeenCalledWith( expect.objectContaining({ provider: providerIdentifiers.unbound, }), expect.anything(), ) expect(mockGetModels).toHaveBeenCalledWith({ provider: providerIdentifiers.vercelAiGateway }, expect.anything()) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.litellm, apiKey: "litellm-key", baseUrl: "http://localhost:4000", }, expect.anything(), ) // Opencode Go's /models endpoint is public, so it is fetched like the other no-auth routers. expect(mockGetModels).toHaveBeenCalledWith( expect.objectContaining({ provider: providerIdentifiers.opencodeGo }), expect.anything(), ) // Kenari's /models endpoint is public, so it is fetched like the other no-auth routers. expect(mockGetModels).toHaveBeenCalledWith( expect.objectContaining({ provider: providerIdentifiers.kenari }), expect.anything(), ) // NanoGPT's detailed catalog is public and may optionally be scoped by a key. expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.nanogpt, apiKey: undefined }, expect.anything(), ) // Verify response was sent expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "routerModels", routerModels: { openrouter: mockModels, requesty: mockModels, unbound: mockModels, "vercel-ai-gateway": mockModels, "zoo-gateway": mockModels, litellm: mockModels, ollama: {}, lmstudio: {}, poe: {}, deepseek: {}, moonshot: {}, "opencode-go": mockModels, kenari: mockModels, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, }, values: undefined, }) }) it("fetches Opencode Go models without an API key (public /models endpoint, regression for empty picker)", async () => { mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: { openRouterApiKey: "openrouter-key", // Deliberately no opencodeGoApiKey — the endpoint is public. }, }) const mockModels: ModelRecord = { "glm-5.1": { maxTokens: 4096, contextWindow: 8192, supportsPromptCache: false, description: "GLM 5.1", }, } mockGetModels.mockResolvedValue(mockModels) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels" }) // Must be fetched despite no configured key, forwarding apiKey: undefined. expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.opencodeGo, apiKey: undefined }, expect.anything(), ) const routerModelsCall = (mockClineProvider.postMessageToWebview as any).mock.calls.find( ([msg]: [{ type: string }]) => msg.type === "routerModels", ) expect(routerModelsCall?.[0].routerModels["opencode-go"]).toEqual(mockModels) }) it("flushes and fetches Opencode Go models when an explicit API key is supplied", async () => { mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: {}, }) mockGetModels.mockResolvedValue({ "opencode/model": { maxTokens: 4096, contextWindow: 8192, supportsPromptCache: false, description: "Opencode model", }, }) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", values: { provider: providerIdentifiers.opencodeGo, opencodeGoApiKey: "fresh-key", }, }) expect(mockFlushModels).toHaveBeenCalledWith( { provider: providerIdentifiers.opencodeGo, apiKey: "fresh-key" }, expect.anything(), true, ) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.opencodeGo, apiKey: "fresh-key" }, expect.anything(), ) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "routerModels", routerModels: { "opencode-go": { "opencode/model": expect.objectContaining({ description: "Opencode model" }), }, }, values: { provider: providerIdentifiers.opencodeGo }, }) }) it("flushes and fetches Kenari models when an explicit API key is supplied", async () => { mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: {}, }) mockGetModels.mockResolvedValue({ "glm-5-2": { maxTokens: 32768, contextWindow: 1048576, supportsPromptCache: false, description: "Kenari model", }, }) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", values: { provider: providerIdentifiers.kenari, kenariApiKey: "fresh-kenari-key", }, }) expect(mockFlushModels).toHaveBeenCalledWith( { provider: providerIdentifiers.kenari, apiKey: "fresh-kenari-key" }, expect.anything(), true, ) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.kenari, apiKey: "fresh-kenari-key" }, expect.anything(), ) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "routerModels", routerModels: { kenari: { "glm-5-2": expect.objectContaining({ description: "Kenari model" }), }, }, values: { provider: providerIdentifiers.kenari }, }) }) it("fetches NanoGPT publicly without an API key", async () => { mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: {} }) mockGetModels.mockResolvedValue({ "openai/gpt-5.6-sol": { maxTokens: 128000, contextWindow: 1050000, supportsPromptCache: false }, }) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", values: { provider: providerIdentifiers.nanogpt }, }) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.nanogpt, apiKey: undefined }, expect.anything(), ) expect(mockFlushModels).not.toHaveBeenCalled() }) it("fetches only Friendli when the provider filter is friendli", async () => { mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: {} }) mockGetModels.mockResolvedValue({ "zai-org/GLM-5.2": { maxTokens: 131072, contextWindow: 1000000, supportsPromptCache: true }, }) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", values: { provider: providerIdentifiers.friendli }, }) expect(mockGetModels).toHaveBeenCalledTimes(1) expect(mockGetModels).toHaveBeenCalledWith({ provider: providerIdentifiers.friendli }, expect.anything()) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "routerModels", routerModels: { friendli: { "zai-org/GLM-5.2": expect.objectContaining({ contextWindow: 1000000 }), }, }, values: { provider: providerIdentifiers.friendli }, }) }) it("prefers an unsaved NanoGPT key and refreshes the matching key-scoped cache", async () => { mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: { nanoGptApiKey: "saved-key" }, }) mockGetModels.mockResolvedValue({ "openai/gpt-5.6-sol": { maxTokens: 128000, contextWindow: 1050000, supportsPromptCache: false }, }) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", values: { provider: providerIdentifiers.nanogpt, nanoGptApiKey: "unsaved-key" }, }) expect(mockFlushModels).toHaveBeenCalledWith( { provider: providerIdentifiers.nanogpt, apiKey: "unsaved-key" }, expect.anything(), true, ) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.nanogpt, apiKey: "unsaved-key" }, expect.anything(), ) }) it("uses the saved NanoGPT key for manual refresh", async () => { mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: { nanoGptApiKey: "saved-key" }, }) mockGetModels.mockResolvedValue({}) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", values: { provider: providerIdentifiers.nanogpt, refresh: true }, }) expect(mockFlushModels).toHaveBeenCalledWith( { provider: providerIdentifiers.nanogpt, apiKey: "saved-key" }, expect.anything(), true, ) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.nanogpt, apiKey: "saved-key" }, expect.anything(), ) }) it("handles LiteLLM models with values from message when config is missing", async () => { mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: { openRouterApiKey: "openrouter-key", requestyApiKey: "requesty-key", // Missing litellm config }, }) const mockModels: ModelRecord = { "model-1": { maxTokens: 4096, contextWindow: 8192, supportsPromptCache: false, description: "Test model 1", }, } mockGetModels.mockResolvedValue(mockModels) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", values: { litellmApiKey: "message-litellm-key", litellmBaseUrl: "http://message-url:4000", }, }) // Verify LiteLLM was called with values from message expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.litellm, apiKey: "message-litellm-key", baseUrl: "http://message-url:4000", }, expect.anything(), ) }) it("skips LiteLLM when both config and message values are missing", async () => { mockClineProvider.getState = vi.fn().mockResolvedValue({ apiConfiguration: { openRouterApiKey: "openrouter-key", requestyApiKey: "requesty-key", // Missing litellm config }, }) const mockModels: ModelRecord = { "model-1": { maxTokens: 4096, contextWindow: 8192, supportsPromptCache: false, description: "Test model 1", }, } mockGetModels.mockResolvedValue(mockModels) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", // No values provided }) // Verify LiteLLM was NOT called expect(mockGetModels).not.toHaveBeenCalledWith( expect.objectContaining({ provider: providerIdentifiers.litellm, }), expect.anything(), ) // Verify response includes empty object for LiteLLM expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "routerModels", routerModels: { openrouter: mockModels, requesty: mockModels, unbound: mockModels, "vercel-ai-gateway": mockModels, "zoo-gateway": mockModels, litellm: {}, ollama: {}, lmstudio: {}, poe: {}, deepseek: {}, moonshot: {}, "opencode-go": mockModels, kenari: mockModels, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, }, values: undefined, }) }) it("handles individual provider failures gracefully", async () => { const mockModels: ModelRecord = { "model-1": { maxTokens: 4096, contextWindow: 8192, supportsPromptCache: false, description: "Test model 1", }, } // Mock some providers to succeed and others to fail mockGetModels .mockResolvedValueOnce(mockModels) // openrouter .mockRejectedValueOnce(new Error("Requesty API error")) // requesty .mockResolvedValueOnce(mockModels) // unbound .mockResolvedValueOnce(mockModels) // vercel-ai-gateway .mockResolvedValueOnce(mockModels) // zoo-gateway .mockRejectedValueOnce(new Error("LiteLLM connection failed")) // litellm .mockResolvedValueOnce(mockModels) // opencode-go .mockResolvedValueOnce(mockModels) // kenari .mockResolvedValueOnce(mockModels) // nanogpt await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", }) // Verify error messages were sent for failed providers (these come first) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "singleRouterModelFetchResponse", success: false, error: "Requesty API error", values: { provider: providerIdentifiers.requesty }, }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "singleRouterModelFetchResponse", success: false, error: "LiteLLM connection failed", values: { provider: providerIdentifiers.litellm }, }) // Verify final routerModels response includes successful providers and empty objects for failed ones expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "routerModels", routerModels: { openrouter: mockModels, requesty: {}, unbound: mockModels, "vercel-ai-gateway": mockModels, "zoo-gateway": mockModels, litellm: {}, ollama: {}, lmstudio: {}, poe: {}, deepseek: {}, moonshot: {}, "opencode-go": mockModels, kenari: mockModels, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, }, values: undefined, }) }) it("handles Error objects and string errors correctly", async () => { // Mock providers to fail with different error types mockGetModels .mockRejectedValueOnce(new Error("Structured error message")) // openrouter .mockRejectedValueOnce(new Error("Requesty API error")) // requesty .mockRejectedValueOnce(new Error("Unbound error")) // unbound .mockRejectedValueOnce(new Error("Vercel AI Gateway error")) // vercel-ai-gateway .mockRejectedValueOnce(new Error("Zoo Gateway error")) // zoo-gateway .mockRejectedValueOnce(new Error("LiteLLM connection failed")) // litellm await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", }) // Verify error handling for different error types expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "singleRouterModelFetchResponse", success: false, error: "Structured error message", values: { provider: providerIdentifiers.openrouter }, }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "singleRouterModelFetchResponse", success: false, error: "Requesty API error", values: { provider: providerIdentifiers.requesty }, }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "singleRouterModelFetchResponse", success: false, error: "Unbound error", values: { provider: providerIdentifiers.unbound }, }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "singleRouterModelFetchResponse", success: false, error: "Vercel AI Gateway error", values: { provider: providerIdentifiers.vercelAiGateway }, }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "singleRouterModelFetchResponse", success: false, error: "LiteLLM connection failed", values: { provider: providerIdentifiers.litellm }, }) }) it("returns an explicit removal error for requestRooModels", async () => { await webviewMessageHandler(mockClineProvider, { type: "requestRooModels", }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "singleRouterModelFetchResponse", success: false, error: "Roo Code Router has been removed. Please select and configure a different provider.", values: { provider: retiredProviderIdentifiers.roo }, }) }) it("prefers message values over config values for LiteLLM", async () => { const mockModels: ModelRecord = {} mockGetModels.mockResolvedValue(mockModels) await webviewMessageHandler(mockClineProvider, { type: "requestRouterModels", values: { litellmApiKey: "message-key", litellmBaseUrl: "http://message-url", }, }) // Verify message values take precedence over saved config (current unsaved field state wins) expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.litellm, apiKey: "message-key", // From message.values baseUrl: "http://message-url", // From message.values }, expect.anything(), ) }) }) describe("webviewMessageHandler - requestOpenAiCodexRateLimits", () => { beforeEach(() => { vi.clearAllMocks() mockGetAccessToken.mockResolvedValue(null) mockGetAccountId.mockResolvedValue(null) }) it("posts error when not authenticated", async () => { await webviewMessageHandler(mockClineProvider, { type: "requestOpenAiCodexRateLimits" } as any) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "openAiCodexRateLimits", error: "Not authenticated with OpenAI Codex", }) }) it("posts values when authenticated", async () => { mockGetAccessToken.mockResolvedValue("token") mockGetAccountId.mockResolvedValue("acct_123") mockFetchOpenAiCodexRateLimitInfo.mockResolvedValue({ primary: { usedPercent: 10, resetsAt: 1700000000000 }, fetchedAt: 1700000000000, }) await webviewMessageHandler(mockClineProvider, { type: "requestOpenAiCodexRateLimits" } as any) expect(mockFetchOpenAiCodexRateLimitInfo).toHaveBeenCalledWith("token", { accountId: "acct_123" }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "openAiCodexRateLimits", values: { primary: { usedPercent: 10, resetsAt: 1700000000000 }, fetchedAt: 1700000000000, }, }) }) }) describe("webviewMessageHandler - deleteCustomMode", () => { beforeEach(() => { vi.clearAllMocks() vi.mocked(getWorkspacePath).mockReturnValue("/mock/workspace") vi.mocked(vscode.window.showErrorMessage).mockResolvedValue(undefined) vi.mocked(ensureSettingsDirectoryExists).mockResolvedValue("/mock/global/storage/.roo") }) it("should delete a project mode and its rules folder", async () => { const slug = "test-project-mode" const rulesFolderPath = path.join("/mock/workspace", ".roo", `rules-${slug}`) vi.mocked(mockClineProvider.customModesManager.getCustomModes).mockResolvedValue([ { name: "Test Project Mode", slug, roleDefinition: "Test Role", groups: [], source: "project", } as ModeConfig, ]) vi.mocked(fsUtils.fileExistsAtPath).mockResolvedValue(true) vi.mocked(mockClineProvider.customModesManager.deleteCustomMode).mockResolvedValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "deleteCustomMode", slug }) // The confirmation dialog is now handled in the webview, so we don't expect showInformationMessage to be called expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() expect(mockClineProvider.customModesManager.deleteCustomMode).toHaveBeenCalledWith(slug) expect(fs.rm).toHaveBeenCalledWith(rulesFolderPath, { recursive: true, force: true }) }) it("should delete a global mode and its rules folder", async () => { const slug = "test-global-mode" const homeDir = os.homedir() const rulesFolderPath = path.join(homeDir, ".roo", `rules-${slug}`) vi.mocked(mockClineProvider.customModesManager.getCustomModes).mockResolvedValue([ { name: "Test Global Mode", slug, roleDefinition: "Test Role", groups: [], source: "global", } as ModeConfig, ]) vi.mocked(fsUtils.fileExistsAtPath).mockResolvedValue(true) vi.mocked(mockClineProvider.customModesManager.deleteCustomMode).mockResolvedValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "deleteCustomMode", slug }) // The confirmation dialog is now handled in the webview, so we don't expect showInformationMessage to be called expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() expect(mockClineProvider.customModesManager.deleteCustomMode).toHaveBeenCalledWith(slug) expect(fs.rm).toHaveBeenCalledWith(rulesFolderPath, { recursive: true, force: true }) }) it("should only delete the mode when rules folder does not exist", async () => { const slug = "test-mode-no-rules" vi.mocked(mockClineProvider.customModesManager.getCustomModes).mockResolvedValue([ { name: "Test Mode No Rules", slug, roleDefinition: "Test Role", groups: [], source: "project", } as ModeConfig, ]) vi.mocked(fsUtils.fileExistsAtPath).mockResolvedValue(false) vi.mocked(mockClineProvider.customModesManager.deleteCustomMode).mockResolvedValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "deleteCustomMode", slug }) // The confirmation dialog is now handled in the webview, so we don't expect showInformationMessage to be called expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() expect(mockClineProvider.customModesManager.deleteCustomMode).toHaveBeenCalledWith(slug) expect(fs.rm).not.toHaveBeenCalled() }) it("should handle errors when deleting rules folder", async () => { const slug = "test-mode-error" const rulesFolderPath = path.join("/mock/workspace", ".roo", `rules-${slug}`) const error = new Error("Permission denied") vi.mocked(mockClineProvider.customModesManager.getCustomModes).mockResolvedValue([ { name: "Test Mode Error", slug, roleDefinition: "Test Role", groups: [], source: "project", } as ModeConfig, ]) vi.mocked(fsUtils.fileExistsAtPath).mockResolvedValue(true) vi.mocked(mockClineProvider.customModesManager.deleteCustomMode).mockResolvedValue(undefined) vi.mocked(fs.rm).mockRejectedValue(error) await webviewMessageHandler(mockClineProvider, { type: "deleteCustomMode", slug }) expect(mockClineProvider.customModesManager.deleteCustomMode).toHaveBeenCalledWith(slug) expect(fs.rm).toHaveBeenCalledWith(rulesFolderPath, { recursive: true, force: true }) // Verify error message is shown to the user expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( t("common:errors.delete_rules_folder_failed", { rulesFolderPath, error: error.message, }), ) // No error response is sent anymore - we just continue with deletion expect(mockClineProvider.postMessageToWebview).not.toHaveBeenCalled() }) }) describe("webviewMessageHandler - message dialog preferences", () => { beforeEach(() => { vi.clearAllMocks() // Mock a current Cline instance vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ taskId: "test-task-id", apiConversationHistory: [], clineMessages: [], } as any) // Reset getValue mock vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(false) }) describe("deleteMessage", () => { it("should always show dialog for delete confirmation", async () => { vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ clineMessages: [], apiConversationHistory: [], } as any) // Mock current cline with proper structure await webviewMessageHandler(mockClineProvider, { type: "deleteMessage", value: 123456789, // Changed from messageTs to value }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "showDeleteMessageDialog", messageTs: 123456789, hasCheckpoint: false, }) }) }) describe("submitEditedMessage", () => { it("should always show dialog for edit confirmation", async () => { vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ clineMessages: [], apiConversationHistory: [], } as any) // Mock current cline with proper structure await webviewMessageHandler(mockClineProvider, { type: "submitEditedMessage", value: 123456789, editedMessageContent: "edited content", }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 123456789, text: "edited content", hasCheckpoint: false, images: undefined, }) }) }) }) describe("webviewMessageHandler - mcpEnabled", () => { let mockMcpHub: any beforeEach(() => { vi.clearAllMocks() // Create a mock McpHub instance mockMcpHub = { handleMcpEnabledChange: vi.fn().mockResolvedValue(undefined), } // Ensure provider exposes getMcpHub and returns our mock ;(mockClineProvider as any).getMcpHub = vi.fn().mockReturnValue(mockMcpHub) }) it("delegates enable=true to McpHub and posts updated state", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { mcpEnabled: true }, }) expect((mockClineProvider as any).getMcpHub).toHaveBeenCalledTimes(1) expect(mockMcpHub.handleMcpEnabledChange).toHaveBeenCalledTimes(1) expect(mockMcpHub.handleMcpEnabledChange).toHaveBeenCalledWith(true) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) it("delegates enable=false to McpHub and posts updated state", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { mcpEnabled: false }, }) expect((mockClineProvider as any).getMcpHub).toHaveBeenCalledTimes(1) expect(mockMcpHub.handleMcpEnabledChange).toHaveBeenCalledTimes(1) expect(mockMcpHub.handleMcpEnabledChange).toHaveBeenCalledWith(false) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) it("handles missing McpHub instance gracefully and still posts state", async () => { ;(mockClineProvider as any).getMcpHub = vi.fn().mockReturnValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { mcpEnabled: true }, }) expect((mockClineProvider as any).getMcpHub).toHaveBeenCalledTimes(1) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) }) 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() vi.mocked(ensureDcgInstalled).mockResolvedValue("/mock/global/storage/dcg") }) it("installs and persists destructive command guard when enabled", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { destructiveCommandGuardEnabled: true }, }) expect(ensureDcgInstalled).toHaveBeenCalledWith("/mock/global/storage") expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("destructiveCommandGuardEnabled", true) expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() }) it("disables the setting and reports an installation failure", async () => { vi.mocked(ensureDcgInstalled).mockRejectedValue(new Error("checksum mismatch")) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { destructiveCommandGuardEnabled: true }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("destructiveCommandGuardEnabled", false) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( "common:errors.destructiveCommandGuard.enableFailed", ) }) it("disables the setting when DCG is unavailable for the current platform", async () => { vi.mocked(ensureDcgInstalled).mockResolvedValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { destructiveCommandGuardEnabled: true }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("destructiveCommandGuardEnabled", false) expect(t).toHaveBeenCalledWith("common:errors.destructiveCommandGuard.unavailable") expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("common:errors.destructiveCommandGuard.unavailable") expect(t).not.toHaveBeenCalledWith("common:errors.destructiveCommandGuard.enableFailed", expect.anything()) }) it("reports non-Error installation failures", async () => { vi.mocked(ensureDcgInstalled).mockRejectedValue("download unavailable") await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { destructiveCommandGuardEnabled: true }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("destructiveCommandGuardEnabled", false) expect(t).toHaveBeenCalledWith("common:errors.destructiveCommandGuard.enableFailed", { error: "download unavailable", }) }) it("persists disabled state without trying to install", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { destructiveCommandGuardEnabled: false }, }) 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, // so this pins the generic persistence path: every polarity, including an // explicit unset (undefined), must reach ContextProxy verbatim rather than // being defaulted away. it("persists alwaysDenyUnapprovedCommands through the generic updateSettings loop", async () => { vi.clearAllMocks() await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { alwaysDenyUnapprovedCommands: true }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) vi.clearAllMocks() await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { alwaysDenyUnapprovedCommands: false }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", false) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) vi.clearAllMocks() await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { alwaysDenyUnapprovedCommands: undefined }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", undefined) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) // Both allowlists are normalized by the same branch, so both are held to the // same contract. describe.each(["allowedReadFiles", "allowedWriteFiles"] as const)("webviewMessageHandler - %s", (key) => { beforeEach(() => { vi.clearAllMocks() }) it("persists the configured patterns", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { [key]: ["notes.md", "docs/scratch/**"] }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith(key, ["notes.md", "docs/scratch/**"]) }) it("drops entries that cannot name a file", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // The double assertion stands in for an untyped payload: the message // arrives as JSON from the webview, so a non-string can reach the // handler even though the type says otherwise. That is what the // handler's `typeof` filter is there to catch, so the test has to be // able to express it. updatedSettings: { [key]: ["notes.md", "", " ", 42 as unknown as string] }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith(key, ["notes.md"]) }) // Whitespace is significant in gitignore syntax, so it must survive saving. it("keeps whitespace within a pattern", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { [key]: [" notes.md", "my notes.md", "notes.md\\ "] }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith(key, [ " notes.md", "my notes.md", "notes.md\\ ", ]) }) it("persists an empty list when the setting is cleared", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { [key]: [] }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith(key, []) }) // Unlike allowed/denied commands, these settings have no // workspace-configuration counterpart, so nothing should be written to VS // Code settings. it("does not write to the VS Code workspace configuration", async () => { const update = vi.fn() vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ update } as never) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { [key]: ["notes.md"] }, }) expect(update).not.toHaveBeenCalled() }) }) describe("webviewMessageHandler - allowlists together", () => { beforeEach(() => { vi.clearAllMocks() }) it("persists both allowlists from one save", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedReadFiles: ["read.md"], allowedWriteFiles: ["write.md"] }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedReadFiles", ["read.md"]) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedWriteFiles", ["write.md"]) }) }) describe("webviewMessageHandler - terminalProfile", () => { beforeEach(() => { vi.clearAllMocks() Terminal.setTerminalProfile(undefined) }) afterEach(() => { Terminal.setTerminalProfile(undefined) vi.restoreAllMocks() }) it("normalizes and persists a saved terminalProfile, then closes stale idle terminals", async () => { const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { terminalProfile: " Git Bash " }, }) expect(Terminal.getTerminalProfile()).toBe("Git Bash") expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", "Git Bash") expect(closeIdleTerminalsSpy).toHaveBeenCalledTimes(1) }) it("does not close idle terminals when hydration sends the unchanged profile", async () => { Terminal.setTerminalProfile("Git Bash") const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { terminalProfile: " Git Bash " }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", "Git Bash") expect(closeIdleTerminalsSpy).not.toHaveBeenCalled() }) it("clears the persisted profile when SettingsView sends the empty-string sentinel", async () => { Terminal.setTerminalProfile("Git Bash") const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { terminalProfile: "" }, }) expect(Terminal.getTerminalProfile()).toBeUndefined() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", undefined) expect(closeIdleTerminalsSpy).toHaveBeenCalledTimes(1) }) it("does not close idle terminals when the empty-string sentinel leaves the profile unset", async () => { const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { terminalProfile: "" }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", undefined) expect(closeIdleTerminalsSpy).not.toHaveBeenCalled() }) it("treats non-string terminalProfile values as unset", async () => { Terminal.setTerminalProfile("Git Bash") const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { terminalProfile: 42 as any }, }) expect(Terminal.getTerminalProfile()).toBeUndefined() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", undefined) expect(closeIdleTerminalsSpy).toHaveBeenCalledTimes(1) }) }) describe("webviewMessageHandler - requestTerminalProfiles", () => { beforeEach(() => { vi.clearAllMocks() }) afterEach(() => { vi.restoreAllMocks() }) it("posts available profile names", async () => { vi.spyOn(Terminal, "getAvailableProfileNames").mockReturnValue(["Git Bash", "bash"]) await webviewMessageHandler(mockClineProvider, { type: "requestTerminalProfiles" }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "terminalProfiles", profiles: ["Git Bash", "bash"], }) }) it("posts an empty array when profile discovery throws", async () => { vi.spyOn(Terminal, "getAvailableProfileNames").mockImplementation(() => { throw new Error("config error") }) await webviewMessageHandler(mockClineProvider, { type: "requestTerminalProfiles" }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "terminalProfiles", profiles: [], }) }) }) describe("webviewMessageHandler - openTerminalProfilePicker", () => { beforeEach(() => { vi.clearAllMocks() }) it("executes the VS Code selectDefaultShell command", async () => { await webviewMessageHandler(mockClineProvider, { type: "openTerminalProfilePicker" }) expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.terminal.selectDefaultShell") }) }) describe("webviewMessageHandler - requestCommands", () => { beforeEach(() => { vi.clearAllMocks() }) it("includes skill slug commands and dedupes duplicate skill names while preserving first skill entry", async () => { mockGetCommands.mockResolvedValue([]) const getTaskMode = vi.fn().mockResolvedValue("code") vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ cwd: "/mock/workspace", getTaskMode, } as unknown as ReturnType) const getSkillsForMode = vi.fn().mockReturnValue([ { name: "skill-slug-entry", description: "Primary skill slug", path: "/mock/.roo/skills/skill-slug-entry/SKILL.md", source: "project", modeSlugs: ["code"], }, { name: "skill-slug-entry", description: "Duplicate skill slug", path: "/mock/.roo/skills/duplicate-skill/SKILL.md", source: "global", modeSlugs: ["code"], }, { name: "another-skill-slug", description: "Another skill-generated command", path: "/mock/.roo/skills/another-skill-slug/SKILL.md", source: "global", modeSlugs: ["code"], }, ]) vi.mocked(mockClineProvider.getSkillsManager).mockReturnValue({ getSkillsForMode, } as unknown as ReturnType) await webviewMessageHandler(mockClineProvider, { type: "requestCommands" }) const commandMessageCall = vi .mocked(mockClineProvider.postMessageToWebview) .mock.calls.find(([postedMessage]) => postedMessage.type === "commands") expect(commandMessageCall).toBeDefined() const commandMessage = commandMessageCall?.[0] expect(commandMessage?.commands).toEqual( expect.arrayContaining([ { name: "skill-slug-entry", source: "project", filePath: "/mock/.roo/skills/skill-slug-entry/SKILL.md", description: "Primary skill slug", }, { name: "another-skill-slug", source: "global", filePath: "/mock/.roo/skills/another-skill-slug/SKILL.md", description: "Another skill-generated command", }, ]), ) expect(commandMessage?.commands?.filter((command) => command.name === "skill-slug-entry")).toHaveLength(1) }) it("adds skill-backed command entries without overriding existing command names", async () => { mockGetCommands.mockResolvedValue([ { name: "deploy", content: "existing command", source: "project", filePath: "/mock/workspace/.roo/commands/deploy.md", description: "Deploy command", argumentHint: "staging | production", }, ]) const getTaskMode = vi.fn().mockResolvedValue("code") vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ cwd: "/mock/workspace", getTaskMode, } as unknown as ReturnType) const getSkillsForMode = vi.fn().mockReturnValue([ { name: "deploy", description: "Deploy skill", path: "/mock/.roo/skills/deploy/SKILL.md", source: "global", modeSlugs: ["code"], }, { name: "skill-only", description: "Skill-generated command", path: "/mock/.roo/skills/skill-only/SKILL.md", source: "project", modeSlugs: ["code"], }, ]) vi.mocked(mockClineProvider.getSkillsManager).mockReturnValue({ getSkillsForMode, } as unknown as ReturnType) await webviewMessageHandler(mockClineProvider, { type: "requestCommands" }) expect(getSkillsForMode).toHaveBeenCalledWith("code") expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "commands", commands: expect.arrayContaining([ { name: "deploy", source: "project", filePath: "/mock/workspace/.roo/commands/deploy.md", description: "Deploy command", argumentHint: "staging | production", }, { name: "skill-only", source: "project", filePath: "/mock/.roo/skills/skill-only/SKILL.md", description: "Skill-generated command", }, ]), }) const commandMessageCall = vi .mocked(mockClineProvider.postMessageToWebview) .mock.calls.find(([postedMessage]) => postedMessage.type === "commands") expect(commandMessageCall).toBeDefined() const commandMessage = commandMessageCall?.[0] expect(commandMessage?.commands?.filter((command) => command.name === "deploy")).toHaveLength(1) }) it("preserves existing behavior when skills manager is unavailable", async () => { mockGetCommands.mockResolvedValue([ { name: "build", content: "build command", source: "built-in", filePath: "", description: "Build command", argumentHint: "target", }, ]) vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ cwd: "/mock/workspace", } as unknown as ReturnType) vi.mocked(mockClineProvider.getSkillsManager).mockReturnValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "requestCommands" }) expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "commands", commands: [ { name: "build", source: "built-in", filePath: "", description: "Build command", argumentHint: "target", }, ], }) }) }) describe("webviewMessageHandler - rules", () => { beforeEach(() => { vi.clearAllMocks() vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue(undefined) ;(mockClineProvider as any).cwd = "/mock/workspace" }) it("routes rules management messages with the current workspace", async () => { const messages = [ { type: "requestRules" }, { type: "createRule", values: { scope: "project", kind: "generic", fileName: "new.md" } }, { type: "deleteRule", values: { scope: "project", kind: "generic", relativePath: "old.md" } }, { type: "openRuleFile", values: { scope: "global", kind: "generic", relativePath: "global.md" } }, { type: "openRulesDirectory", values: { scope: "project", kind: "mode", modeSlug: "code" } }, ] as const for (const message of messages) { await webviewMessageHandler(mockClineProvider, message as any) } expect(handleRequestRules).toHaveBeenCalledWith(mockClineProvider, "/mock/workspace") expect(handleCreateRule).toHaveBeenCalledWith(mockClineProvider, "/mock/workspace", messages[1]) expect(handleDeleteRule).toHaveBeenCalledWith(mockClineProvider, "/mock/workspace", messages[2]) expect(handleOpenRuleFile).toHaveBeenCalledWith(mockClineProvider, "/mock/workspace", messages[3]) expect(handleOpenRulesDirectory).toHaveBeenCalledWith(mockClineProvider, "/mock/workspace", messages[4]) }) it("uses the active task cwd when routing rule messages", async () => { vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ cwd: "/mock/task-workspace", } as unknown as ReturnType) const message = { type: "requestRules" } as const await webviewMessageHandler(mockClineProvider, message as any) expect(handleRequestRules).toHaveBeenCalledWith(mockClineProvider, "/mock/task-workspace") }) }) describe("webviewMessageHandler - downloadErrorDiagnostics", () => { beforeEach(() => { vi.clearAllMocks() // Ensure contextProxy has a globalStorageUri for the handler ;(mockClineProvider as any).contextProxy.globalStorageUri = { fsPath: "/mock/global/storage" } // Provide a current task with a stable ID vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ taskId: "test-task-id", } as any) }) it("calls generateErrorDiagnostics with correct parameters", async () => { await webviewMessageHandler(mockClineProvider, { type: "downloadErrorDiagnostics", values: { timestamp: "2025-01-01T00:00:00.000Z", version: "1.2.3", provider: "test-provider", model: "test-model", details: "Sample error details", }, } as any) // Verify generateErrorDiagnostics was called with the correct parameters expect(generateErrorDiagnostics).toHaveBeenCalledTimes(1) expect(generateErrorDiagnostics).toHaveBeenCalledWith({ taskId: "test-task-id", globalStoragePath: "/mock/global/storage", values: { timestamp: "2025-01-01T00:00:00.000Z", version: "1.2.3", provider: "test-provider", model: "test-model", details: "Sample error details", }, log: expect.any(Function), }) }) it("shows error when no active task", async () => { vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue(null as any) await webviewMessageHandler(mockClineProvider, { type: "downloadErrorDiagnostics", values: {}, } as any) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("No active task to generate diagnostics for") expect(generateErrorDiagnostics).not.toHaveBeenCalled() }) }) describe("zooCodeSignOut", () => { beforeEach(() => { vi.clearAllMocks() }) it("disconnects Zoo Code and clears tokens from all Zoo Gateway profiles", async () => { const { disconnectZooCode } = await import("../../../services/zoo-code-auth") const upsertProviderProfile = vi.fn().mockResolvedValue(undefined) const saveConfig = vi.fn().mockResolvedValue(undefined) ;(mockClineProvider as any).contextProxy = { ...mockClineProvider.contextProxy, getProviderSettings: vi.fn().mockReturnValue({ apiProvider: providerIdentifiers.zooGateway }), 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(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 await webviewMessageHandler(mockClineProvider, { type: "zooCodeSignOut" }) expect(disconnectZooCode).toHaveBeenCalled() expect(upsertProviderProfile).toHaveBeenCalledWith( "Zoo Gateway", expect.not.objectContaining({ zooSessionToken: expect.anything() }), true, ) expect(saveConfig).toHaveBeenCalledWith( "Backup Zoo", expect.not.objectContaining({ zooSessionToken: expect.anything() }), ) expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("still clears the in-memory handler when the active profile token is already empty on disk", async () => { const upsertProviderProfile = vi.fn().mockResolvedValue(undefined) ;(mockClineProvider as any).contextProxy = { ...mockClineProvider.contextProxy, getProviderSettings: vi.fn().mockReturnValue({ apiProvider: providerIdentifiers.zooGateway }), getValues: vi.fn().mockReturnValue({ currentApiConfigName: "Zoo Gateway" }), } ;(mockClineProvider as any).providerSettingsManager = { listConfig: vi .fn() .mockResolvedValue([{ name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }]), getProfile: vi.fn().mockResolvedValue({ apiProvider: providerIdentifiers.zooGateway, zooGatewayModelId: "anthropic/claude-sonnet-4", }), saveConfig: vi.fn(), } ;(mockClineProvider as any).upsertProviderProfile = upsertProviderProfile await webviewMessageHandler(mockClineProvider, { type: "zooCodeSignOut" }) expect(upsertProviderProfile).toHaveBeenCalledWith( "Zoo Gateway", expect.not.objectContaining({ zooSessionToken: expect.anything() }), true, ) }) }) // Own describe for the persisted-only sign-out write and the cross-instance // exclusion it takes. Typed widening rather than a cast: the spec-wide provider // double declares only the members most tests drive, and these tests drive the // manager surface. The doubles are installed wholesale and put back after each // test so no implementation leaks into a later suite. describe("webviewMessageHandler - zooCodeSignOut persisted-only write", () => { const provider = mockClineProvider as unknown as { providerSettingsManager: { listConfig: ReturnType getProfile: ReturnType saveConfig: ReturnType hasConfig: ReturnType runExclusiveAcrossInstances: ReturnType } contextProxy: { getProviderSettings: ReturnType getValues: ReturnType } upsertProviderProfile: ReturnType } const originals = { providerSettingsManager: provider.providerSettingsManager, contextProxy: provider.contextProxy, upsertProviderProfile: provider.upsertProviderProfile, } afterEach(() => { provider.providerSettingsManager = originals.providerSettingsManager provider.contextProxy = originals.contextProxy provider.upsertProviderProfile = originals.upsertProviderProfile }) // The record the handler reads outside the exclusion, and the one the store // holds once the exclusion is held: a rename on another view is modelled by the // second read returning a different record under the same name. const readOutsideExclusion = { apiProvider: providerIdentifiers.zooGateway, zooSessionToken: "token-backup", zooGatewayModelId: "model-before", } const wire = (readInsideExclusion: () => Promise, nameStillPresent: boolean) => { const order: string[] = [] provider.upsertProviderProfile = vi.fn().mockResolvedValue(undefined) provider.contextProxy = { getProviderSettings: vi.fn().mockReturnValue({ apiProvider: providerIdentifiers.anthropic }), getValues: vi.fn().mockReturnValue({ currentApiConfigName: "some-other-profile" }), } provider.providerSettingsManager = { listConfig: vi .fn() .mockResolvedValue([{ name: "Backup Zoo", apiProvider: providerIdentifiers.zooGateway }]), getProfile: vi .fn() .mockResolvedValueOnce(readOutsideExclusion) .mockImplementation(async () => { order.push("readInsideExclusion") return readInsideExclusion() }), hasConfig: vi.fn(async () => { order.push("hasConfig") return nameStillPresent }), runExclusiveAcrossInstances: vi.fn(async (callback: () => Promise) => { order.push("exclusionEntered") return callback() }), saveConfig: vi.fn(async (_name: string, value: Record) => { order.push(`write:${String(value.zooGatewayModelId)}`) }), } return order } it("re-reads the persisted-only profile inside the exclusion so the write carries the current record", async () => { const order = wire( async () => ({ apiProvider: providerIdentifiers.zooGateway, zooSessionToken: "token-backup", zooGatewayModelId: "model-after", }), true, ) await webviewMessageHandler(mockClineProvider, { type: "zooCodeSignOut" }) expect(order).toEqual(["exclusionEntered", "hasConfig", "readInsideExclusion", "write:model-after"]) expect(provider.providerSettingsManager.saveConfig).toHaveBeenCalledWith( "Backup Zoo", expect.not.objectContaining({ zooSessionToken: expect.anything() }), ) }) it("skips the persisted-only write when the name is renamed away before the exclusion is held", async () => { const order = wire( async () => ({ apiProvider: providerIdentifiers.zooGateway, zooSessionToken: "token-backup", zooGatewayModelId: "model-after", }), false, ) await webviewMessageHandler(mockClineProvider, { type: "zooCodeSignOut" }) expect(order).toEqual(["exclusionEntered", "hasConfig"]) expect(provider.providerSettingsManager.hasConfig).toHaveBeenCalledWith("Backup Zoo") expect(provider.providerSettingsManager.saveConfig).not.toHaveBeenCalled() }) it("skips the persisted-only write when the re-read shows the token was already cleared", async () => { const order = wire( async () => ({ apiProvider: providerIdentifiers.zooGateway, zooGatewayModelId: "model-after", }), true, ) await webviewMessageHandler(mockClineProvider, { type: "zooCodeSignOut" }) expect(order).toEqual(["exclusionEntered", "hasConfig", "readInsideExclusion"]) expect(provider.providerSettingsManager.saveConfig).not.toHaveBeenCalled() }) }) describe("webviewMessageHandler - renameApiConfiguration", () => { // Double assertion: the spec-wide provider double only declares the members // most tests drive; this structural widening keeps these tests free of any. const provider = mockClineProvider as unknown as { providerSettingsManager: { getProfile: ReturnType saveConfig: ReturnType deleteConfig: ReturnType hasConfig: ReturnType runExclusiveAcrossInstances: (cb: () => Promise) => Promise } repointViewLocalStateAfterProfileRename: ReturnType activateProviderProfile: ReturnType 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() vi.resetModules() }) it("starts OAuth authorization and opens browser", async () => { const mockStartAuthorization = vi.fn().mockResolvedValue({ userCode: "TEST-CODE", verificationUri: "https://auth.kimi.com/device", expiresAt: Date.now() + 600000, }) const mockWaitForAuthorization = vi.fn().mockResolvedValue({ type: "kimi-code", accessToken: "token", refreshToken: "refresh", expiresAt: Date.now() + 3600000, }) vi.doMock("../../../integrations/kimi-code/oauth", () => ({ kimiCodeOAuthManager: { startAuthorization: mockStartAuthorization, waitForAuthorization: mockWaitForAuthorization, }, })) const mockOpenExternal = vi.fn().mockResolvedValue(true) ;(vscode as any).env = { openExternal: mockOpenExternal } ;(vscode as any).Uri = { parse: vi.fn((url: string) => url) } await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignIn" }) expect(mockStartAuthorization).toHaveBeenCalled() expect(mockOpenExternal).toHaveBeenCalled() expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("shows success message after successful authorization", async () => { const mockStartAuthorization = vi.fn().mockResolvedValue({ userCode: "TEST-CODE", verificationUri: "https://auth.kimi.com/device", expiresAt: Date.now() + 600000, }) const mockWaitForAuthorization = vi.fn().mockResolvedValue({ type: "kimi-code", accessToken: "token", refreshToken: "refresh", expiresAt: Date.now() + 3600000, }) vi.doMock("../../../integrations/kimi-code/oauth", () => ({ kimiCodeOAuthManager: { startAuthorization: mockStartAuthorization, waitForAuthorization: mockWaitForAuthorization, }, })) const mockOpenExternal = vi.fn().mockResolvedValue(true) ;(vscode as any).env = { openExternal: mockOpenExternal } ;(vscode as any).Uri = { parse: vi.fn((url: string) => url) } await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignIn" }) await new Promise((resolve) => setTimeout(resolve, 10)) expect(vscode.window.showInformationMessage).toHaveBeenCalledWith("Successfully signed in to Kimi Code") }) it("handles authorization failure", async () => { const mockStartAuthorization = vi.fn().mockResolvedValue({ userCode: "TEST-CODE", verificationUri: "https://auth.kimi.com/device", expiresAt: Date.now() + 600000, }) const mockWaitForAuthorization = vi.fn().mockRejectedValue(new Error("Authorization cancelled")) vi.doMock("../../../integrations/kimi-code/oauth", () => ({ kimiCodeOAuthManager: { startAuthorization: mockStartAuthorization, waitForAuthorization: mockWaitForAuthorization, }, })) const mockOpenExternal = vi.fn().mockResolvedValue(true) ;(vscode as any).env = { openExternal: mockOpenExternal } ;(vscode as any).Uri = { parse: vi.fn((url: string) => url) } await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignIn" }) await new Promise((resolve) => setTimeout(resolve, 10)) expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("handles startAuthorization error", async () => { const mockStartAuthorization = vi.fn().mockRejectedValue(new Error("Network error")) vi.doMock("../../../integrations/kimi-code/oauth", () => ({ kimiCodeOAuthManager: { startAuthorization: mockStartAuthorization, }, })) await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignIn" }) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.stringContaining("Kimi Code sign in failed")) expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) }) describe("webviewMessageHandler - kimiCodeSignOut", () => { beforeEach(() => { vi.clearAllMocks() vi.resetModules() }) it("clears credentials and shows success message", async () => { const mockClearCredentials = vi.fn().mockResolvedValue(undefined) vi.doMock("../../../integrations/kimi-code/oauth", () => ({ kimiCodeOAuthManager: { clearCredentials: mockClearCredentials, }, })) await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignOut" }) expect(mockClearCredentials).toHaveBeenCalled() expect(vscode.window.showInformationMessage).toHaveBeenCalledWith("Signed out from Kimi Code") expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("handles sign out error", async () => { const mockClearCredentials = vi.fn().mockRejectedValue(new Error("Clear failed")) vi.doMock("../../../integrations/kimi-code/oauth", () => ({ kimiCodeOAuthManager: { clearCredentials: mockClearCredentials, }, })) await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignOut" }) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Kimi Code sign out failed.") }) }) describe("webviewMessageHandler - telemetrySetting", () => { beforeEach(() => { vi.clearAllMocks() vi.mocked(vscode.env).isTelemetryEnabled = true }) // Regression test: TelemetryService.updateTelemetryState must be gated on // vscode.env.isTelemetryEnabled in addition to the stored setting, matching // extension.ts's onDidChangeTelemetryEnabled listener. Without this AND, a user // clicking Accept in the webview could re-enable telemetry even while VS Code's // global telemetry toggle is off. it("does not enable telemetry when the user accepts but VS Code's global telemetry toggle is off", async () => { const { TelemetryService } = await import("@roo-code/telemetry") vi.mocked(TelemetryService.hasInstance).mockReturnValue(true) vi.mocked(vscode.env).isTelemetryEnabled = false vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "telemetrySetting", text: "enabled" }) expect(TelemetryService.instance.updateTelemetryState).toHaveBeenCalledWith(false) }) it("enables telemetry when the user accepts and VS Code's global telemetry toggle is on", async () => { const { TelemetryService } = await import("@roo-code/telemetry") vi.mocked(TelemetryService.hasInstance).mockReturnValue(true) vi.mocked(vscode.env).isTelemetryEnabled = true vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "telemetrySetting", text: "enabled" }) expect(TelemetryService.instance.updateTelemetryState).toHaveBeenCalledWith(true) }) it("keeps telemetry disabled when the user declines, regardless of VS Code's global toggle", async () => { const { TelemetryService } = await import("@roo-code/telemetry") vi.mocked(TelemetryService.hasInstance).mockReturnValue(true) vi.mocked(vscode.env).isTelemetryEnabled = true vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "telemetrySetting", text: "disabled" }) expect(TelemetryService.instance.updateTelemetryState).toHaveBeenCalledWith(false) }) // Finding #12 regression: without serialization, two concurrent "telemetrySetting" messages // each capture their own isOptedIn in a closure and apply it to TelemetryService whenever // their own persistence write resolves -- with no ordering guarantee between the two // invocations. A slow first write racing a fast second write could let the *first* // message's (now-stale) intent win the live telemetry state, even though the *second* // message reflects the user's actual final choice. it("applies the most recently sent telemetrySetting last, even if an earlier message's write is slower", async () => { const { TelemetryService } = await import("@roo-code/telemetry") vi.mocked(TelemetryService.hasInstance).mockReturnValue(true) vi.mocked(vscode.env).isTelemetryEnabled = true // Track the "stored" setting so the second call's getGlobalState read reflects // whatever the first call has (or hasn't yet) written -- mirrors ContextProxy's real // synchronous stateCache update inside setValue. let storedSetting: string | undefined vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation(() => storedSetting) let resolveSlowWrite!: () => void const slowWrite = new Promise((resolve) => { resolveSlowWrite = resolve }) vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (_key, value) => { if (value === "disabled") { // First message's write is slow -- resolves only after we explicitly release it // below, once the second (fast) message has already been sent. await slowWrite } storedSetting = value as string }) // First message: turn telemetry off (slow write). const first = webviewMessageHandler(mockClineProvider, { type: "telemetrySetting", text: "disabled" }) // Second message: turn telemetry back on (fast write), sent immediately after. const second = webviewMessageHandler(mockClineProvider, { type: "telemetrySetting", text: "enabled" }) // Now let the first message's write proceed. resolveSlowWrite() await Promise.all([first, second]) // The user's final, most-recently-sent choice was "enabled" -- the live telemetry // state must reflect that, not "disabled" from the stale, slower first message. const calls = vi.mocked(TelemetryService.instance.updateTelemetryState).mock.calls expect(calls.at(-1)).toEqual([true]) }) // CodeRabbit follow-up on the finding #12 fix: webviewDidLaunch's telemetry init read state // via an async provider.getStateToPostToWebview().then(...) continuation, outside // telemetrySettingQueue -- so it could resolve after a concurrent "telemetrySetting" message // and clobber that message's queued (correct) update with a stale value. webviewDidLaunch now // reads getGlobalState synchronously and is routed through the same queue. it("does not let webviewDidLaunch's telemetry init race and clobber a concurrent telemetrySetting message", async () => { const { TelemetryService } = await import("@roo-code/telemetry") vi.mocked(TelemetryService.hasInstance).mockReturnValue(true) vi.mocked(vscode.env).isTelemetryEnabled = true // webviewDidLaunch starts out "unset" (disclosed opt-out default -- opted in). Scoped to // the "telemetrySetting" key specifically -- webviewDidLaunch also calls // updateGlobalState("customModes", ...) through the same contextProxy mock, which must // not clobber storedSetting. let storedSetting: string | undefined = "unset" vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "telemetrySetting" ? storedSetting : undefined, ) vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (key: string, value) => { if (key === "telemetrySetting") { storedSetting = value as string } }) vi.mocked(mockClineProvider.customModesManager.getCustomModes).mockResolvedValue([]) const providerForLaunch = mockClineProvider as unknown as { getMcpHub: ReturnType providerSettingsManager: { listConfig: ReturnType } getStateToPostToWebview: ReturnType } providerForLaunch.getMcpHub = vi.fn().mockReturnValue(undefined) providerForLaunch.providerSettingsManager = { listConfig: vi.fn().mockResolvedValue(undefined), } // Deferred-promise handshake instead of setTimeout delays, so ordering is enforced // explicitly rather than by racing real clock delays. Signals when webviewDidLaunch has // taken its (pre-fix) state snapshot -- only fires under the *old* code path // (provider.getStateToPostToWebview().then(...)); the fix never calls it at all. let snapshotTaken!: () => void const snapshotTakenPromise = new Promise((resolve) => { snapshotTaken = resolve }) let releaseSnapshot!: () => void const snapshotReleased = new Promise((resolve) => { releaseSnapshot = resolve }) // Snapshots storedSetting at call time (mirroring the real ClineProvider building its // state object synchronously before any internal awaits), signals it was taken, then // waits until the test explicitly releases it -- by which point the concurrent // telemetrySetting write below has already landed, making the snapshot genuinely stale // once its .then() callback finally runs. providerForLaunch.getStateToPostToWebview = vi.fn().mockImplementation(async () => { const snapshot = storedSetting snapshotTaken() await snapshotReleased return { telemetrySetting: snapshot } }) // webviewDidLaunch fires first (e.g. webview reload) -- its telemetry init is now queued // behind telemetrySettingQueue rather than resolving independently. const launch = webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch" }) // Wait for webviewDidLaunch to either take its (pre-fix) snapshot, or flush a fixed // number of microtask turns as a same-tick fallback for the fixed code path (which never // triggers that signal) -- enough for its synchronous prefix (await getCustomModes(), // await updateGlobalState()) to run, without relying on a wall-clock timer. await Promise.race([ snapshotTakenPromise, (async () => { for (let i = 0; i < 10; i++) { await Promise.resolve() } })(), ]) // A concurrent "telemetrySetting" message turns telemetry off, and is awaited to // completion -- including its own updateTelemetryState(false) call -- *before* the // deferred (pre-fix-only) snapshot below is released. Against the pre-fix code, this // proves the snapshot it captured earlier ("unset") is genuinely stale by the time its // .then() callback finally runs: the user's real, later choice already landed. const disable = webviewMessageHandler(mockClineProvider, { type: "telemetrySetting", text: "disabled" }) await disable // Now release the deferred snapshot so a getStateToPostToWebview() call, if the old code // path is exercised, resolves (with its already-captured, now-stale value) only after // the disable write above has fully landed. const snapshotResolved = vi.mocked(providerForLaunch.getStateToPostToWebview).mock.results[0]?.value as Promise | undefined releaseSnapshot() await Promise.all([launch, snapshotResolved]) // webviewDidLaunch's telemetry init is fire-and-forget from the handler's own point of // view (the "webviewDidLaunch" case doesn't await it), so even awaiting // getStateToPostToWebview() directly isn't enough to observe its .then() callback -- // flush one more microtask turn for that callback to run. await Promise.resolve() // The user's explicit "disabled" choice must be the final state -- webviewDidLaunch's // queued re-application of the (by-then-stale) "unset"/opted-in state must not run after // and override it. const calls = vi.mocked(TelemetryService.instance.updateTelemetryState).mock.calls expect(calls.at(-1)).toEqual([false]) }) // Review finding: webviewDidLaunch's queued telemetry update wasn't awaited by the // "webviewDidLaunch" case, so a thrown error inside it was only ever caught by a later, // unrelated queue link's leading .catch(() => undefined) -- silently swallowed rather than // logged. Now awaited with its own .catch that logs via provider.log. it("logs an error via provider.log if the queued telemetry init throws on launch", async () => { const { TelemetryService } = await import("@roo-code/telemetry") vi.mocked(TelemetryService.hasInstance).mockReturnValue(true) vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => { if (key === "telemetrySetting") { throw new Error("contextProxy read failed") } return undefined }) vi.mocked(mockClineProvider.customModesManager.getCustomModes).mockResolvedValue([]) const providerForLaunch = mockClineProvider as unknown as { getMcpHub: ReturnType providerSettingsManager: { listConfig: ReturnType } getStateToPostToWebview: ReturnType } providerForLaunch.getMcpHub = vi.fn().mockReturnValue(undefined) providerForLaunch.providerSettingsManager = { listConfig: vi.fn().mockResolvedValue(undefined) } providerForLaunch.getStateToPostToWebview = vi.fn().mockResolvedValue({ telemetrySetting: "unset" }) await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch" }) expect(mockClineProvider.log).toHaveBeenCalledWith( expect.stringContaining("Error initializing telemetry state on launch"), ) }) // CodeRabbit finding: webviewDidLaunch's queued telemetry update called // TelemetryService.instance directly, unlike the "telemetrySetting" case a few lines // below which checks hasInstance() first. If webviewDidLaunch fires before the service // is created (e.g. during activation), TelemetryService.instance throws -- and since // this whole chain isn't awaited by the "webviewDidLaunch" case, that throw becomes an // unhandled promise rejection instead of a no-op. it("does not throw or update telemetry state when webviewDidLaunch fires before TelemetryService exists", async () => { const { TelemetryService } = await import("@roo-code/telemetry") vi.mocked(TelemetryService.hasInstance).mockReturnValue(false) vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue("unset") vi.mocked(mockClineProvider.customModesManager.getCustomModes).mockResolvedValue([]) const providerForLaunch = mockClineProvider as unknown as { getMcpHub: ReturnType providerSettingsManager: { listConfig: ReturnType } getStateToPostToWebview: ReturnType } providerForLaunch.getMcpHub = vi.fn().mockReturnValue(undefined) providerForLaunch.providerSettingsManager = { listConfig: vi.fn().mockResolvedValue(undefined) } providerForLaunch.getStateToPostToWebview = vi.fn().mockResolvedValue({ telemetrySetting: "unset" }) await expect(webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch" })).resolves.not.toThrow() // The queued telemetry update is fire-and-forget from the handler's own point of // view -- flush a microtask turn so its .then() callback runs before asserting. await Promise.resolve() expect(TelemetryService.instance.updateTelemetryState).not.toHaveBeenCalled() }) }) describe("webviewMessageHandler - experiments", () => { beforeEach(() => { vi.clearAllMocks() }) it("persists dynamicThinkingEffort true merged with the saved experiments", async () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "experiments" ? { preventFocusDisruption: true } : undefined, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { experiments: { dynamicThinkingEffort: true } }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("experiments", { preventFocusDisruption: true, dynamicThinkingEffort: true, }) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) it("persists dynamicThinkingEffort false over a previously enabled value", async () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "experiments" ? { dynamicThinkingEffort: true } : undefined, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { experiments: { dynamicThinkingEffort: false } }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("experiments", { dynamicThinkingEffort: false, }) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) it("persists the experiment defaults when no experiments are saved yet", async () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { experiments: {} }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("experiments", { ...experimentDefault, dynamicThinkingEffort: false, }) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) }) describe("webviewMessageHandler - collapseCommandOutputByDefault", () => { beforeEach(() => { vi.clearAllMocks() }) it.each([true, false, undefined])( "persists the output collapse preference (%s) without changing terminal mode", async (value) => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { collapseCommandOutputByDefault: value }, }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith( "collapseCommandOutputByDefault", value, ) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith( "terminalShellIntegrationDisabled", expect.anything(), ) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }, ) }) describe("updateProfileModel", () => { let updateProfileModel: Mock beforeEach(() => { vi.clearAllMocks() updateProfileModel = vi.fn().mockResolvedValue(undefined) mockClineProvider.updateProfileModel = updateProfileModel }) it("delegates a valid message to the provider", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateProfileModel", text: "my-profile", values: { expectedProvider: providerIdentifiers.openrouter, patch: { openRouterModelId: "a/b", reasoningEffort: null }, }, }) expect(updateProfileModel).toHaveBeenCalledWith("my-profile", providerIdentifiers.openrouter, { openRouterModelId: "a/b", reasoningEffort: null, }) }) it.each([ ["missing profile name", { values: { expectedProvider: providerIdentifiers.openrouter, patch: {} } }], ["missing expectedProvider", { text: "p", values: { patch: {} } }], ["non-object patch", { text: "p", values: { expectedProvider: providerIdentifiers.openrouter, patch: "x" } }], ["array patch", { text: "p", values: { expectedProvider: providerIdentifiers.openrouter, patch: [] } }], ["missing values", { text: "p" }], ])("ignores a malformed message: %s", async (_label, partial) => { await webviewMessageHandler(mockClineProvider, { type: "updateProfileModel", ...partial, } as unknown as Parameters[1]) expect(updateProfileModel).not.toHaveBeenCalled() }) }) describe("webviewMessageHandler - renameTaskWithId", () => { beforeEach(() => { vi.mocked(mockClineProvider.renameTaskWithId).mockClear() }) it.each([ ["forwards taskId and text", { taskId: "task-1", text: "New name" }, [["task-1", "New name"]]], ["forwards an empty title so the provider can clear it", { taskId: "task-1", text: "" }, [["task-1", ""]]], ["skips the call when taskId is missing", { text: "New name" }, []], ])("%s", async (_label, payload, expectedCalls) => { await webviewMessageHandler(mockClineProvider, { type: "renameTaskWithId", ...payload }) expect(vi.mocked(mockClineProvider.renameTaskWithId).mock.calls).toEqual(expectedCalls) }) }) // The display settings are written like any other setting, but the webview is not trusted: a value that its own // controls cannot produce (a hand-written message) is ignored before anything is done for it. describe("updateSettings with the display settings", () => { const save = (updatedSettings: Record) => webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings }) beforeEach(() => { vi.clearAllMocks() }) afterEach(() => { vi.mocked(mockClineProvider.contextProxy.setValue).mockReset().mockResolvedValue(undefined) }) it.each([ ["timeFormat", "auto"], ["timeFormat", "12h"], ["timeFormat", "24h"], ["dateFormat", "auto"], ["dateFormat", "mdy"], ["dateFormat", "dmy"], ["dateFormat", "ymd"], ["showRelativeTimes", true], ["showRelativeTimes", false], ["timeFormat", undefined], ["showRelativeTimes", undefined], ])("persists %s = %j as it is", async (key, value) => { await save({ [key]: value }) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith(key, value) expect(mockClineProvider.log).not.toHaveBeenCalled() expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) it.each([["de"], ["ja"], ["zh-TW"]])("applies and stores the display language %s", async (language) => { await save({ language }) expect(changeLanguage).toHaveBeenCalledWith(language) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("language", language) }) it.each([[undefined], [null]])("uses the default language for %s", async (language) => { await save({ language }) expect(changeLanguage).toHaveBeenCalledWith("en") expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("language", "en") }) it.each([ ["timeFormat", "13h"], ["timeFormat", 24], ["dateFormat", "dd/mm"], ["showRelativeTimes", "yes"], ["language", "xx-not-a-language"], ["language", 42], ["language", ""], ])("ignores %s = %j, and says so in the log", async (key, value) => { await save({ [key]: value }) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith(key, expect.anything()) expect(changeLanguage).not.toHaveBeenCalled() expect(mockClineProvider.log).toHaveBeenCalledWith(`[updateSettings] Ignored an invalid value for ${key}`) }) it("still saves the other settings sent with an invalid display value, and refreshes the webview", async () => { await save({ timeFormat: "13h", dateFormat: "ymd", soundEnabled: true }) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("timeFormat", expect.anything()) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("dateFormat", "ymd") expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("soundEnabled", true) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) it("is not a transaction: if a write fails, the earlier ones stay, the later ones are not written, and the error is thrown", async () => { const failure = new Error("storage unavailable") vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (key) => { if (key === "dateFormat") throw failure }) await expect(save({ timeFormat: "24h", dateFormat: "ymd", showRelativeTimes: false })).rejects.toBe(failure) const written = vi.mocked(mockClineProvider.contextProxy.setValue).mock.calls.map(([key]) => key) expect(written).toEqual(["timeFormat", "dateFormat"]) // The webview is refreshed even so, to show what is really stored. expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) describe("the save result", () => { const saveWithId = (updatedSettings: Record, requestId?: string) => webviewMessageHandler(mockClineProvider, { type: "updateSettings", requestId, updatedSettings }) const saveAs = (updatedSettings: Record) => saveWithId(updatedSettings, "save-1") const results = () => vi .mocked(mockClineProvider.postMessageToWebview) .mock.calls.map(([message]) => message) .filter((message) => message.type === "settingsSaveResult") it("reports a stored save, after the state was refreshed", async () => { await saveAs({ timeFormat: "24h" }) expect(results()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: true }]) const [refreshOrder] = vi.mocked(mockClineProvider.postStateToWebview).mock.invocationCallOrder const [resultOrder] = vi.mocked(mockClineProvider.postMessageToWebview).mock.invocationCallOrder expect(refreshOrder).toBeLessThan(resultOrder) }) it.each([ ["an Error", new Error("storage unavailable"), "storage unavailable"], ["something that is not an Error", "disk full", "disk full"], ])("reports a failed save with the reason, for %s, and still throws it", async (_name, failure, reason) => { vi.mocked(mockClineProvider.contextProxy.setValue).mockRejectedValue(failure) await expect(saveAs({ dateFormat: "ymd" })).rejects.toBe(failure) expect(results()).toEqual([ { type: "settingsSaveResult", requestId: "save-1", success: false, error: reason }, ]) }) it("does nothing, and reports nothing, for a message that carries no settings", async () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", requestId: "save-1" }) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(mockClineProvider.postStateToWebview).not.toHaveBeenCalled() expect(results()).toEqual([]) }) it("sends no result for a save that has no request id", async () => { await saveWithId({ timeFormat: "24h" }) expect(results()).toEqual([]) }) it("still reports a stored save when refreshing the state fails", async () => { vi.mocked(mockClineProvider.postStateToWebview).mockRejectedValueOnce(new Error("webview gone")) await saveAs({ timeFormat: "24h" }) expect(results()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: true }]) expect(mockClineProvider.log).toHaveBeenCalledWith( "[updateSettings] Could not refresh the webview state: webview gone", ) }) it("reports a failed save when refreshing the state fails too", async () => { vi.mocked(mockClineProvider.contextProxy.setValue).mockRejectedValue(new Error("no")) vi.mocked(mockClineProvider.postStateToWebview).mockRejectedValueOnce("webview gone") await expect(saveAs({ timeFormat: "24h" })).rejects.toThrow("no") expect(results()).toEqual([ { type: "settingsSaveResult", requestId: "save-1", success: false, error: "no" }, ]) expect(mockClineProvider.log).toHaveBeenCalledWith( "[updateSettings] Could not refresh the webview state: webview gone", ) }) }) it("completes a partial save when the same values are saved again", async () => { let failOnce = true vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (key) => { if (key === "dateFormat" && failOnce) { failOnce = false throw new Error("storage unavailable") } }) const values = { timeFormat: "24h", dateFormat: "ymd", showRelativeTimes: false } await expect(save(values)).rejects.toThrow("storage unavailable") vi.mocked(mockClineProvider.contextProxy.setValue).mockClear() await save(values) const written = vi.mocked(mockClineProvider.contextProxy.setValue).mock.calls.map(([key]) => key) expect(written).toEqual(["timeFormat", "dateFormat", "showRelativeTimes"]) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(2) // once for the failed save, once for this one }) it("does not take a key that only exists on every object for a display setting", async () => { await save({ constructor: "x", toString: "y" }) expect(mockClineProvider.log).not.toHaveBeenCalled() 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 }) }) })