// 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(), })) // The save tests script the configuration state directly, so the import entry // points stay mocks. The lock is the module's own, delegated through the mock: the // save and the import are the two writers it serialises, and a case can only show // that ordering when both take the same lock. vi.mock("../../config/importExport", async () => { const actual = await vi.importActual("../../config/importExport") return { withCommandListLock: vi.fn(actual.withCommandListLock), exportSettings: vi.fn(), importSettingsWithFeedback: vi.fn(), } }) vi.mock("@roo-code/telemetry", () => ({ TelemetryService: { hasInstance: vi.fn().mockReturnValue(false), instance: { updateTelemetryState: vi.fn(), captureTelemetrySettingsChanged: vi.fn(), }, }, })) import type { ModelRecord, WebviewMessage } from "@roo-code/types" import * as vsCodeLmProvider from "../../../api/providers/vscode-lm" import * as copilotProvider from "../../../api/providers/github-copilot" import { Package } from "../../../shared/package" import { importSettingsWithFeedback, withCommandListLock } from "../../config/importExport" import { readCommandListScopes } from "../../auto-approval/commandScope" import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { seedCommandList } from "../../../utils/seedAllowedCommands" import { webviewMessageHandler } from "../webviewMessageHandler" 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 { 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(), 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(), }, 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 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" // Mutable so a test can script a multi-root workspace. Every other test sees // the single folder the command-list configuration resolves against. const mockWorkspaceFolders = vi.hoisted(() => ({ folders: [{ uri: { fsPath: "/mock/workspace" } }] as { uri: { fsPath: string } }[], })) vi.mock("vscode", () => { const showInformationMessage = vi.fn() const showErrorMessage = vi.fn() const showWarningMessage = vi.fn() const openTextDocument = vi.fn().mockResolvedValue({}) const showTextDocument = vi.fn().mockResolvedValue(undefined) return { ConfigurationTarget: { Global: 1, Workspace: 2, WorkspaceFolder: 3, }, window: { showInformationMessage, showErrorMessage, showWarningMessage, showTextDocument, }, workspace: { get workspaceFolders() { return mockWorkspaceFolders.folders }, 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 - 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 - 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) }) }) // 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 - command list scope-aware persistence", () => { beforeEach(() => { vi.clearAllMocks() mockWorkspaceFolders.folders = [{ uri: { fsPath: "/mock/workspace" } }] // The lock runs its callback by default. The cases that observe it script it. vi.mocked(withCommandListLock).mockImplementation(async (write) => write()) }) // The file-level vscode mock opens one workspace folder, so the configuration // for the command lists resolves to that uri. const mockWorkspaceFolderUri = { fsPath: "/mock/workspace" } // Mirrors the real configuration API: `inspect()` exposes per-scope values, // and `update()` records its target. Extension state stays unset. // `updateSequence` and `inspectSequence` script successive call outcomes in // call order. An Error element makes that call throw. // // One snapshot per key, plus the pre-write merge re-read. type InspectedCommandList = { globalValue?: string[] workspaceValue?: string[] workspaceFolderValue?: string[] // The package default `inspect()` reports. The save compares it to the state // copy to tell an activation-seeded copy from a key the user deleted. defaultValue?: string[] } // `inspected` may be a function of the requested key, so a two-key payload // test can give each list its own layers. `gateEnabled` scripts the // `workspaceCommandListsEnabled` read. Leaving it unset keeps the gate off, // which matches the extension default. function mockCommandConfiguration( inspected: InspectedCommandList | ((key: string) => InspectedCommandList), updateSequence?: unknown[], inspectSequence?: unknown[], gateEnabled?: boolean, ) { const update = vi.fn() if (updateSequence) { update.mockImplementation(() => updateSequence.shift()) } const inspect = vi.fn() if (inspectSequence) { // The most recent snapshot returned for each key. An unscripted read answers // with it, which is the layer as it stands, so a case that scripts only the // reads it is about does not have to restate a snapshot to get past the others. const lastSnapshot = new Map() inspect.mockImplementation((key: string) => { const next = inspectSequence.length > 0 ? inspectSequence.shift() : undefined if (next instanceof Error) { throw next } // `null` scripts the one outcome a snapshot cannot express: no inspection // object at all. Every other unscripted read repeats the key's latest one. if (next === null) { lastSnapshot.set(key, undefined) return undefined } const snapshot = next ?? lastSnapshot.get(key) lastSnapshot.set(key, snapshot) return snapshot }) } else { inspect.mockImplementation((key: string) => (typeof inspected === "function" ? inspected(key) : inspected)) } // The shared double keeps the configuration type correct. Each test // installs the scripted members. const config = makeWorkspaceConfiguration( gateEnabled === undefined ? {} : { workspaceCommandListsEnabled: gateEnabled }, ) config.update = update config.inspect = inspect vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) return { update, inspect } } it("takes the command-list lock only for a payload that writes a command list", async () => { // A payload with no command-list key writes neither store the lock orders, so it // must not take the lock and stall an import behind an unrelated save. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) mockCommandConfiguration({ globalValue: ["git"] }) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { mode: "code" }, }) expect(withCommandListLock).not.toHaveBeenCalled() await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git"] }, }) expect(withCommandListLock).toHaveBeenCalledTimes(1) }) it("holds a real import behind a parked save, and both stores end on the imported list", async () => { // The save and the import are the two writers the command-list lock orders. The // save parks inside the lock before its own state write; the import is started // behind it and must not reach its state write until the save releases. The save // then writes its own list first, and the import's list is what both stores hold // when the queue drains. A stub lock would let the import's state write land // first, which is the interleaving this case rules out. const { importSettingsFromPath, withCommandListLock: realCommandListLock } = await vi.importActual("../../config/importExport") const { sanitizeCommandList } = await vi.importActual( "../../auto-approval/commandScope", ) // The block's setup replaces the lock with a direct call, which would let the save // and the import run concurrently. This case puts the module's own lock back, so // both writers queue on the one lock the production code installs. vi.mocked(withCommandListLock).mockImplementation(realCommandListLock) const layers: Record = {} const { update } = mockCommandConfiguration({ globalValue: ["git"] }, undefined, undefined, true) update.mockImplementation(async (key: string, value: unknown) => { layers[key] = value as string[] }) // The state copy is the store the import writes, so both writers record into it. const stateCopy: Record = {} let stateWriteStarted!: () => void const stateWriteStart = new Promise((resolve) => { stateWriteStarted = resolve }) let releaseStateWrite!: () => void const stateWriteGate = new Promise((resolve) => { releaseStateWrite = resolve }) let stateWrites = 0 vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (key, value) => { stateWrites += 1 if (stateWrites === 1) { stateWriteStarted() await stateWriteGate } stateCopy[key] = value as string[] }) // The shared double predates the import's own proxy writes, so this case installs // the members it needs on its own proxy rather than widening the double. const proxy = mockClineProvider.contextProxy as unknown as { setValues: (values: Record) => Promise setProviderSettings: (settings: unknown) => Promise } proxy.setValues = vi.fn(async (values) => { Object.assign(stateCopy, values) }) proxy.setProviderSettings = vi.fn(async () => undefined) vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => stateCopy[key]) ;(fs.readFile as unknown as Mock).mockResolvedValue( JSON.stringify({ providerProfiles: { currentApiConfigName: "imported-profile", apiConfigs: { "imported-profile": { apiProvider: providerIdentifiers.openai, apiKey: "test-key", id: "imported-id", }, }, }, globalSettings: { allowedCommands: ["imported"] }, }), ) // The import path, its lock, and its command-list writes are the real ones. The // provider-profile and custom-mode stores are doubles, because they read VS Code // secrets and workspace files that this harness does not open — neither touches the // lock or the command lists, and the file carries no custom modes. type ImportOptions = Parameters[1] const providerSettings = { export: vi.fn(async () => ({ currentApiConfigName: "prior-profile", apiConfigs: {}, modeApiConfigs: {} })), import: vi.fn(async () => undefined), listConfig: vi.fn(async () => []), } const customModes = { updateCustomMode: vi.fn(async () => undefined) } const save = webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git"] }, }) await Promise.race([ stateWriteStart, (async () => { for (let turn = 0; turn < 20; turn++) { await Promise.resolve() } })(), ]) const imported = importSettingsFromPath("/mock/path/settings.json", { // Each double stands in for its real collaborator's public surface only. providerSettingsManager: providerSettings as unknown as ImportOptions["providerSettingsManager"], contextProxy: mockClineProvider.contextProxy, customModesManager: customModes as unknown as ImportOptions["customModesManager"], }) // The save still holds the lock, so the import has not written either store. for (let turn = 0; turn < 20; turn++) { await Promise.resolve() } expect(layers["allowedCommands"]).toEqual(["git"]) expect(stateCopy["allowedCommands"]).toBeUndefined() releaseStateWrite() await save const result = await imported expect(result.success).toBe(true) // Both stores hold the imported list, because the import ran last. expect(sanitizeCommandList(stateCopy["allowedCommands"])).toEqual(["imported"]) expect(layers["allowedCommands"]).toEqual(["imported"]) }) it("holds the lock until the state write has landed", async () => { // An import that took the lock between the configuration write and the state write // would leave the two stores describing different lists. The lock's guarantee is // therefore an ordering one: the callback the save hands it must not resolve until // the state write has landed. Invocation order is fixed when a call is made, not // when it completes, so both stores record their write only on completion and the // assertions read those records. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ globalValue: ["git"] }) const configuration: Record = {} update.mockImplementation(async (key: string, value: unknown) => { configuration[key] = value }) let stateCopy: unknown let stateWriteStarted!: () => void const stateWriteStart = new Promise((resolve) => { stateWriteStarted = resolve }) let settleStateWrite!: () => void const stateWrite = new Promise((resolve) => { settleStateWrite = resolve }) vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (key, value) => { if (key !== "allowedCommands") { return } stateWriteStarted() await stateWrite stateCopy = value }) let releases = 0 let releasedBeforeStateWriteLanded = false vi.mocked(withCommandListLock).mockImplementationOnce(async (write) => { try { return await write() } finally { releases += 1 releasedBeforeStateWriteLanded = stateCopy === undefined } }) const save = webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git"] }, }) // Reach the pending state write without counting the handler's own awaits. The // microtask flush keeps a handler that never writes the state copy from stalling // the case on an unresolved promise. await Promise.race([ stateWriteStart, (async () => { for (let turn = 0; turn < 20; turn++) { await Promise.resolve() } })(), ]) // While the state write is pending, the configuration half has already landed — // the save's fixed order — and the lock is still held. expect(configuration["allowedCommands"]).toEqual(["git"]) expect(stateCopy).toBeUndefined() expect(releases).toBe(0) settleStateWrite() await save // Both stores hold the submitted list, and the lock's single release happened only // after the state copy had landed. expect(configuration["allowedCommands"]).toEqual(["git"]) expect(stateCopy).toEqual(["git"]) expect(releasedBeforeStateWriteLanded).toBe(false) expect(releases).toBe(1) }) it("keeps workspace-scoped denied commands out of the global write when saving the merged list", async () => { // Gate on: the workspace entry is visible in the dialog, so keeping it is not // a re-add. With the gate off every submitted workspace entry is a re-add, // and the save promotes it to the global layer. const { update, inspect } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) // "docker" stays at the workspace scope instead of leaking into the user's // global settings. The save persists without scope leakage. expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) // Extension global state holds only the global layer, so the next save cannot // double-home the workspace entry. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) // One snapshot per command-list key. This key's scope read, write target, and // rollback all derive from the same inspect(). The merge before the workspace // write re-reads this key once, so the count is two and never more. expect(inspect).toHaveBeenCalledTimes(2) }) it("writes the workspace-folder value at the folder target in multi-root workspaces", async () => { // Gate on for the same reason as the merged-list split test. The kept folder // entry is visible in the dialog, so it stays at its scope. const { update } = mockCommandConfiguration( { workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) // Read, target resolution, and write all run on the configuration scoped to // the first workspace folder. The folder-target update is legal only on a // resource-scoped configuration. expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, mockWorkspaceFolderUri) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.WorkspaceFolder) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) it("clears a deleted workspace entry at the workspace scope without adding it to global", async () => { // Gate on: the entry is visible in the dialog, and only visible entries are // deletable there. The preservation rule re-adds a hidden entry instead. const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: [] }, }) // Deleting a project entry must clear it where it lives... expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) // ...and must not copy it into global settings. expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) }) it("does not create a workspace layer when none exists", async () => { const { update } = mockCommandConfiguration({}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git"] }, }) // Only the Global write happens, so saving never materializes an empty // workspace-scoped value in settings.json. expect(update).toHaveBeenCalledTimes(1) expect(update).toHaveBeenCalledWith("allowedCommands", ["git"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git"]) }) it("writes the global layer before the workspace layer and undoes only its own delta when the workspace write fails", async () => { // Call order: the global write succeeds, the workspace write rejects, and the // undo runs. The undo applies only this save's delta, so the third party's // mid-save addition survives while "aws" is removed and "keep" and "drop" are // restored. The gate is on so each scripted call stays distinguishable, and // call position pins the undo. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["keep", "drop"] : undefined, ) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], [ { globalValue: ["keep", "drop"], workspaceValue: ["npm docker", "docker"] }, undefined, { globalValue: ["aws", "mid-save"] }, ], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) // Global first, workspace second. The ordering itself is the pin. expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) // The undo removes only "aws", restores "keep" and "drop", and keeps the // mid-save addition. A stale-snapshot rewind would have dropped it. expect(update).toHaveBeenNthCalledWith( 3, "deniedCommands", ["mid-save", "keep", "drop"], vscode.ConfigurationTarget.Global, ) expect(update).toHaveBeenCalledTimes(3) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) it("computes the undo delta against the configuration layer when the extension-state copy is stale", async () => { // The global write targets the configuration layer, not the extension state // cache, so that layer's save-start value is the compensation's delta // baseline. Here the state copy is stale ("old" where the configuration holds // "manual"). A delta against the cache would restore the stale list over the // value the failed save replaced, and it would drop "manual" permanently. The // undo follows the configuration layer instead. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["old"] : undefined, ) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], [{ globalValue: ["manual"], workspaceValue: ["docker"] }, undefined, { globalValue: ["aws", "mid-save"] }], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) // The save wrote ["aws"] over the configuration's ["manual"]. expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) // The undo removes this save's addition, keeps the mid-save addition, and // restores the configuration-layer entry the save dropped. It does not restore // the stale state copy's "old". expect(update).toHaveBeenNthCalledWith( 3, "deniedCommands", ["mid-save", "manual"], vscode.ConfigurationTarget.Global, ) expect(update).toHaveBeenCalledTimes(3) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) it("rolls the global layer back on a folder-target save and still persists the payload's other keys", async () => { // update() call order. The global write succeeds, the folder-target workspace // write rejects, and the undo restores the global deletions at the Global // target. That is the only layer this save changed. A second key pins that the save // skips only the failed command-list key. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["drop"] : undefined, ) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("disk on fire")), undefined], [ { globalValue: ["drop"], workspaceValue: ["npm"], workspaceFolderValue: ["pnpm docker", "docker"] }, undefined, { globalValue: [], }, ], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"], alwaysDenyUnapprovedCommands: true }, }) // The capture, the failed write, and the undo all ran on the configuration // scoped to the first workspace folder. expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, mockWorkspaceFolderUri) expect(update).toHaveBeenNthCalledWith( 2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.WorkspaceFolder, ) // This save removed "drop", and another writer then cleared the layer to `[]`. // That clear outranks this save's removal, so the undo keeps it instead of // re-adding an entry the user just deleted. expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", [], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) // The failed key skips its extension global-state write... expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("deniedCommands", expect.anything()) // ...and the other key of the same payload still persists. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: disk on fire") expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("aborts the key without compensation when the global write fails", async () => { // The global layer comes first, so a rejected global write leaves nothing // changed: no workspace write may follow, and the save needs no compensation. // The rejection is a plain string, which pins the non-Error rendering of the // failure message. const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, [Promise.reject("global locked")]) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) // Only the failed global write happened, so the save never touches the // workspace layer and compensates nothing. The global write carries "aws" // alone: "docker" is the workspace layer's entry, so it is written at its own // scope and never promoted into the user's settings. expect(update).toHaveBeenCalledTimes(1) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.anything(), vscode.ConfigurationTarget.Workspace, ) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: global locked") }) it("aborts the key without writing when the configuration inspection has no result", async () => { // The save derives scopes, write target, and rollback from one inspect() // snapshot, so a missing snapshot means the workspace layer is unknown. // Proceeding would classify the retained workspace entry "docker" as new and // copy it back into global settings. The key aborts instead: no configuration // write and no extension global state. const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, [undefined]) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(update).not.toHaveBeenCalled() // Leak pin: the workspace entry must not land in the global layer. expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( "Failed to save deniedCommands: the configuration value could not be read", ) // No exception escaped the handler: the state post still ran. expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("aborts the command-list key when the inspection throws, while other keys of the payload still save", async () => { const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, [ new Error("configuration unavailable"), ]) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // A second key pins that the save skips only the aborted command-list key. updatedSettings: { deniedCommands: ["docker", "aws"], alwaysDenyUnapprovedCommands: true }, }) // The aborted key wrote nothing at any scope... expect(update).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("deniedCommands", expect.anything()) // ...while the other key of the same payload still persists. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( "Failed to save deniedCommands: configuration unavailable", ) }) it("propagates a configuration lookup failure instead of degrading it to a per-key abort", async () => { // The commandListConfiguration() lookup sits outside the guarded snapshot // read on purpose. A lookup that cannot return a configuration object is a // different failure class than an unreadable value. It therefore aborts the // entire message rather than the one key. vi.mocked(vscode.workspace.getConfiguration).mockImplementation(() => { throw new Error("workspace not ready") }) await expect( webviewMessageHandler(mockClineProvider, { type: "updateSettings", // A second key pins that the whole message aborts, not just the command-list // key. With the guarded per-key failure paths this key would still persist. updatedSettings: { deniedCommands: ["docker", "aws"], alwaysDenyUnapprovedCommands: true }, }), ).rejects.toThrow("workspace not ready") // Nothing persisted for any key, and no per-key error handling ran. The // rejection reached the caller. The webview still gets a state refresh, // because a failed save always re-posts before it re-throws. expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("reports partial failure when the compensating restore also fails", async () => { // update() call order: the global write succeeds, the workspace write rejects, // and the undo write rejects too. The gate is on so the workspace write is the // plain kept list and each scripted call stays distinguishable, and call // position pins the undo. The global layer starts empty here, because a mock // implementation from an earlier test outlives clearAllMocks, so this save // only adds. Pins the §6.5 clause (iv) divergence: the configuration holds a // half-applied undo while the state copy holds its pre-operation list. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, [ undefined, Promise.reject(new Error("workspace locked")), Promise.reject(new Error("restore also failed")), ], [{ workspaceValue: ["docker", "old"] }, undefined, { globalValue: ["aws"] }], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) // The undo ran at the Global target even though it failed. This save deleted // no global entry and added only "aws", so the undo computes an empty list. // The layer was absent at save start, and the re-read still holds only this // save's own write. The rollback therefore restores absence by clearing the key. expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( "Failed to save deniedCommands: workspace locked. The global-scoped restore also failed: Error: restore also failed. Review the command lists in your user and workspace settings.", ) // No exception escaped the handler: the state post still ran. expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("skips the undo without guessing when the global value cannot be re-read to undo it", async () => { // The compensation re-read is guarded. When even the fresh read fails, writing // the save-start value would clobber whatever the failed read could not show. // Nothing is therefore written, and the code reports the double failure. update() // order: the global write succeeds, the workspace write rejects, and the third // inspect() call, the undo re-read, throws. Pins the §6.5 clause (iv) divergence: // the configuration keeps this save's write while the state copy keeps its // pre-operation list. const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked"))], [{ workspaceValue: ["docker"] }, undefined, new Error("inspect unavailable")], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) // The failed workspace write is the last configuration write: a // stale-snapshot fallback would have written a third value here. expect(update).toHaveBeenCalledTimes(2) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( "Failed to save deniedCommands: workspace locked. The global-scoped value could not be re-read to undo this save: Error: inspect unavailable. Review the command lists in your user and workspace settings.", ) expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("aborts the workspace write and restores the global layer when the workspace re-read fails", async () => { // The re-read exists so this save does not overwrite an entry another writer // added during the global write. A failed re-read cannot rule that out, so the // key aborts instead of writing the precomputed list: the global half is undone // and the workspace layer is never written. Both stores then hold their // save-start values rather than diverging. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["old"] : undefined, ) const { update } = mockCommandConfiguration( { globalValue: ["old"], workspaceValue: ["docker"] }, [undefined, undefined], // Save start, the opposite key's snapshot, the merge re-read that throws, // then the undo's re-read. [ { globalValue: ["old"], workspaceValue: ["docker"] }, new Error("workspace unreadable"), { globalValue: ["old", "aws"] }, ], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "old", "aws"] }, }) // The global write landed, and the failed re-read came before any workspace write. expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["old", "aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.anything(), vscode.ConfigurationTarget.Workspace, ) // The undo removes only this save's addition, so the global layer is back to the // value it held at save start. expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["old"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(2) // Both stores are read here. The configuration's global layer holds its save-start // value again, and the extension-state copy was never written, so neither store // was left ahead of the other. const globalWrites = update.mock.calls .filter((call) => call[2] === vscode.ConfigurationTarget.Global) .map((call) => call[1]) expect(globalWrites.at(-1)).toEqual(["old"]) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( "Failed to save deniedCommands: the workspace layer could not be re-read: workspace unreadable", ) expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("aborts the workspace write and restores the global layer when the merge re-read returns no inspection object", async () => { // An inspection that returns no object is not evidence about the workspace // layer, exactly as a thrown re-read is not. Writing the list computed before // the global write would drop an entry another writer added during it, so the // key aborts and the global half is undone. Neither store is left ahead of the // other. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["old"] : undefined, ) const { update } = mockCommandConfiguration( { globalValue: ["old"], workspaceValue: ["docker"] }, [undefined, undefined], // Save start, the merge re-read that finds no object, then the undo's // re-read, which sees this save's own global write. [{ globalValue: ["old"], workspaceValue: ["docker"] }, null, { globalValue: ["old", "aws"] }], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "old", "aws"] }, }) // The global write landed, and the unreadable re-read came before any workspace // write, so the workspace layer is never written at all. expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["old", "aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.anything(), vscode.ConfigurationTarget.Workspace, ) // The undo removes only this save's addition, so the global layer is back to the // value it held at save start. expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["old"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(2) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( "Failed to save deniedCommands: the workspace layer could not be re-read: the configuration value could not be read", ) expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) // Entries the dialog never displayed cannot be deleted by omission from a // list the user could not see. A save therefore re-adds them to the workspace // layer it rewrites. Such entries are hidden while the gate is off, or shadowed by a // global entry with the gate on. it("carries gate-hidden workspace entries into the workspace write instead of deleting them", async () => { const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "npm"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // The gate was off at display, so the dialog showed no workspace entry. The // empty baseline is that display, and the two entries are carried unchanged. updatedSettings: { deniedCommands: [] }, commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: false }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "npm"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) // Neither entry was displayed, so neither is a settings-file addition. expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) it("keeps hidden workspace entries out of the global write", async () => { const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "npm"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: [] }, }) // Preservation is workspace-side only, so re-adding hidden entries never // leaks them into the user's global settings. expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "npm"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) }) it("carries a workspace deny entry shadowed by a global allow entry when the gate is on", async () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, ) const { update } = mockCommandConfiguration( (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"] } : {}), undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // The global allow "git" shadows "git push", so the dialog displayed an empty // deny list. That display carries the workspace entry instead of deleting it. updatedSettings: { deniedCommands: [] }, commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) }) it("keeps a configuration-global deny addition past the hidden-entry exclusion when the workspace copy is shadowed", async () => { // The global allow "git" shadows the workspace deny "git push", so the // displayed deny list stays empty. While the dialog was open the user added // the same "git push" to the user-level deny list in settings.json. The // hidden-entry exclusion classifies by bare membership, so without a rule for // provenance it excludes the configuration-global addition from the // external-addition re-admit. The split source is then empty, and the Global // write deletes the user's file addition instead of keeping it. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, ) const { update } = mockCommandConfiguration( (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"], globalValue: ["git push"] } : {}), undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // The dialog displayed nothing deletable, because the workspace deny was // shadowed and the global addition arrived after the display. updatedSettings: { deniedCommands: [] }, commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: true }, }) // The user's new global denial survives the save in the layer the user added // it to, instead of being written away as []. expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) // The hidden-entry re-add preserves the shadowed workspace copy. expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) // The changed-settings warning names the genuine file addition. expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("git push")) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["git push"]) }) it("does not warn about an allow entry the global deny layer hid", async () => { // The same cross-key effect in the other direction: the user's global deny layer // holds "git", so the composition drops the workspace allow "git status" from the // dialog. The allow key's own global layer is empty, so without the other key's // layer the classifier reads the entry's absence from the baseline as an addition. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["git"] : undefined, ) mockCommandConfiguration( (key) => (key === "allowedCommands" ? { workspaceValue: ["git status"] } : { globalValue: ["git"] }), undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // The dialog never showed the entry, so the submission omits it. updatedSettings: { allowedCommands: [] }, commandListBaseline: { allowedCommands: [], workspaceCommandListsEnabled: true }, }) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) it("warns about a deny entry no global layer covers", async () => { // The positive control for the caller wiring: the same save with a workspace deny // that no global entry covers. The entry was never displayed, so it is an // addition and the warning must name it. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, ) mockCommandConfiguration( (key) => (key === "deniedCommands" ? { workspaceValue: ["docker"] } : { globalValue: ["git"] }), undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // The dialog never showed the entry, so the submission omits it. Nothing // covers it, so its absence is a genuine addition. updatedSettings: { deniedCommands: [] }, commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: true }, }) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("docker")) }) it("keeps a global entry added after display when the dialog deletes the entry it showed", async () => { // The dialog displayed "echo" from the workspace layer, and the posted global // layer was empty. While the dialog was open another writer added "echo" to the // global layer. The merged baseline still names "echo", so treating it as the // global layer too would count that addition as displayed and the omission would // delete it. The posted global layer says it was never on screen. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( { globalValue: ["echo"], workspaceValue: ["echo"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: [] }, commandListBaseline: { deniedCommands: ["echo"], globalDeniedCommands: [], workspaceDeniedCommands: ["echo"], workspaceCommandListsEnabled: true, }, }) // The workspace copy was displayed and omitted, so it goes. The global copy was // never displayed, so the save carries it instead of deleting it. expect(update).toHaveBeenCalledWith("deniedCommands", ["echo"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) }) it("deletes a global entry the posted global layer showed and the submission omits", async () => { // The other direction, so the field cannot pass by ignoring the submission: the // posted global layer names both entries, and the user removed one of them. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ globalValue: ["echo", "docker"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker"] }, commandListBaseline: { deniedCommands: ["echo", "docker"], globalDeniedCommands: ["echo", "docker"], workspaceCommandListsEnabled: true, }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Global) }) it("keeps a gate-hidden workspace entry out of the global write when the baseline omits it", async () => { // With the gate off the dialog showed only the global layer, so the baseline // lists no workspace entry. "docker" was never displayed, so the save carries it // into the workspace write unchanged and never promotes it. Only "aws", which no // layer held at save start, is new and lands in the global layer. const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: false }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) it("keeps a gate-flip-hidden workspace entry the dialog displayed at the workspace scope", async () => { // The dialog opened with the gate on, so it displayed the workspace entry. // The gate flipped off before the save, which hides every workspace entry. // The baseline carries the gate as displayed and shows the entry. Keeping it // therefore stays a workspace decision. It is not a new promotion into the // global layer. const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) // The save promotes only the genuinely new entry, and "docker" stays out of // the global write. expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) it("keeps a displayed workspace entry out of the global write when the baseline gate matches the current gate", async () => { // The gate is off at display time and still off at save time. The workspace // layer's "docker" is hidden now, but the baseline names it, so the dialog did // show it. Keeping it stays a workspace decision: the baseline alone decides, // whether or not the gate moved. Only the genuinely new "aws" promotes. const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: false }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) // The retained workspace entry survives at its own scope. A save that wrote // `[]` here would delete it from the settings file while keeping the global // half, so the workspace write is asserted, not only the global one. expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) // The entry the baseline shows is not re-added as hidden, so the workspace // layer is rewritten without it: its submitted copy is retained as workspace // state, not promoted. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) it("keeps a displayed workspace entry the global layer shadows in the workspace write without duplicating it into the global write", async () => { // The workspace layer holds "echo" and a global entry shadows it, so the // composed list no longer carries the entry at save time. The dialog // displayed it before, because the baseline names it. Reading the composed // list as the workspace origin set would drop "echo" from the workspace // write, which deletes a workspace decision the user kept. The baseline // keeps it a workspace decision, and the global write keeps the user's own // copy of the entry instead of gaining a second one from the workspace layer. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["echo"]) const { update } = mockCommandConfiguration( { globalValue: ["echo"], workspaceValue: ["echo"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["echo"] }, commandListBaseline: { deniedCommands: ["echo"], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["echo"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) // The shadowed entry is a workspace decision. The global layer holds the // user's own copy, so the global write neither loses it nor duplicates it // from the workspace layer. expect(update).toHaveBeenCalledWith("deniedCommands", ["echo"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["echo"]) }) it("keeps a displayed workspace entry in the workspace write after the gate flips off before the save", async () => { // The dialog displayed "echo" from the workspace layer with the gate on, and // the gate was off at save time. The entry is hidden at save time and the // baseline names it, so the save keeps it a workspace decision and promotes // nothing into the global layer. const { update } = mockCommandConfiguration({ workspaceValue: ["echo"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["echo"] }, commandListBaseline: { deniedCommands: ["echo"], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["echo"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["echo"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) }) it("keeps a state-only seeded global entry that also sits in the workspace layer", async () => { // A fresh profile seeds the extension global state, not the settings file, so // the configuration has no global layer at save start while the state copy // holds "aws". The same entry also sits in the workspace layer. // `displayedCommandListScopes` carries an entry the baseline omits, and the // seed disjunct keeps it in the global write when the configuration layer is // absent. The split's origin set must agree, or it reads "aws" as new, emits // it in neither write, and the state copy loses it. The gate is off, so the // workspace layer enforces nothing and the global layer is the only home the // entry has. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["aws"]) const { update } = mockCommandConfiguration( { workspaceValue: ["aws", "docker"], defaultValue: ["aws"] }, undefined, undefined, false, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["aws", "docker"] }, // The baseline shows both entries, so neither is a re-add. Without it every // workspace entry would count as new and the gate-off re-add would promote // both, which is a different behaviour from the one this case pins. commandListBaseline: { deniedCommands: ["aws", "docker"], workspaceCommandListsEnabled: false }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws", "docker"], vscode.ConfigurationTarget.Workspace) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) it("drops the entries of a key the user deleted from user settings", async () => { // The user removed the whole key from User Settings, so the snapshot reports // no global layer and no state copy equals the shipped default. The state copy // still holds "aws" and the dialog displayed it. The save must honor the // deletion instead of writing the entry back unwarned. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["aws"]) const { update, inspect } = mockCommandConfiguration({}, undefined, undefined, false) // The snapshot reports the shipped default, which the state copy does not hold. vi.mocked(inspect).mockReturnValue({ defaultValue: ["git log"] } as never) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["aws"] }, commandListBaseline: { deniedCommands: ["aws"], workspaceCommandListsEnabled: false }, }) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) }) it("reports a conflict and compensates the global write when the folder override vanishes mid-save", async () => { // The save targets the folder layer. While the global write runs, another // writer removes that override, leaving only the workspace value. Reading the // fallback would copy the shared entries into the folder layer and recreate // the override the other writer removed. The save reports the conflict and // undoes its own global write instead. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( { globalValue: ["aws"], workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }, [undefined, undefined], // Save start holds the folder override; the second entry answers the // unguarded read for the opposite key; the third is the merge re-read, which // finds only the workspace value because the override is gone; the fourth is // the undo's re-read. [ { globalValue: ["aws"], workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }, { workspaceValue: ["npm"] }, { globalValue: [] }, ], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) // No folder-target write at all: recreating the override is the defect. expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.anything(), vscode.ConfigurationTarget.WorkspaceFolder, ) expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", [], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(2) // The failed key skips its state write, and the conflict is reported. expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("deniedCommands", expect.anything()) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.stringContaining("removed during the save")) expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("lands both writes when a folder override appears while a workspace-target save runs", async () => { // The save targets the workspace layer, so that layer is the one it must // still find at the re-read. A folder override appearing mid-save outranks // it in enforcement but does not remove it. Reading the selector's winner // instead would call the workspace layer gone, refuse a valid save, and undo // its global half. The merge must also take the workspace layer's own value: // copying the folder override's entries would leak project entries into the // user's workspace settings. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update, inspect } = mockCommandConfiguration( { globalValue: ["aws"], workspaceValue: ["docker"] }, [undefined, undefined], // Save start holds only the workspace layer. The second entry is the merge // re-read, which finds the folder override another writer added and the // workspace value still in place. [ { globalValue: ["aws"], workspaceValue: ["docker"] }, { globalValue: ["aws"], workspaceValue: ["docker"], workspaceFolderValue: ["npm"] }, ], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, // The dialog displayed both layers' entries, so neither is a deletion and the // folder override is not mistaken for one. commandListBaseline: { deniedCommands: ["docker", "aws"], workspaceCommandListsEnabled: true }, }) // The global half is not rolled back: no second global write undoes it. expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) // The workspace write lands on the layer the save targeted, and it carries the // workspace layer's entry, never the folder override's. expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.arrayContaining(["npm"]), vscode.ConfigurationTarget.Workspace, ) expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.anything(), vscode.ConfigurationTarget.WorkspaceFolder, ) expect(update).toHaveBeenCalledTimes(2) // The save completes, so the state write happens and no error is reported. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() // Exactly the two scripted reads: the snapshot and the merge re-read. A third // would mean the re-read got no inspection object and the check under test was // skipped. expect(inspect).toHaveBeenCalledTimes(2) }) it("does not write a blank workspace entry back when the layer holds one at the merge re-read", async () => { // The workspace layer holds a blank entry, which the schema admits and a hand // edit or a synced dotfile can produce. The save-start read drops it, so the // start side never contains it. The merge re-read sees the layer itself, and // an entry the start side lacks counts as added by another writer. Unsanitised, // that reading writes the blank entry back and the save can never remove it. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update, inspect } = mockCommandConfiguration( { globalValue: ["aws"], workspaceValue: ["docker"] }, [undefined, undefined], // The second entry is the merge re-read, which finds the layer still holding // the blank entry beside the entry the dialog kept. [ { globalValue: ["aws"], workspaceValue: ["docker"] }, { globalValue: ["aws"], workspaceValue: ["docker", ""] }, ], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, // The dialog displayed both entries, so the blank entry the re-read finds is // an addition by another writer, never a displayed entry to write back. commandListBaseline: { deniedCommands: ["docker", "aws"], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) // The workspace write carries only what the save-start side knew about. expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.arrayContaining([""]), vscode.ConfigurationTarget.Workspace, ) expect(update).toHaveBeenCalledTimes(2) expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() expect(inspect).toHaveBeenCalledTimes(2) }) it("does not restore a workspace entry another writer removed during the global write", async () => { // The dialog submitted "keep" and "drop", and both sat in the workspace layer // at save start. While the global write runs, another writer removes "drop". // A pure union of the submission and the fresh read writes "drop" back, which // undoes that removal. The save applies the submission to the fresh value // instead: it keeps what both still hold, honors the removal, and preserves // what the other writer added. const update = vi.fn() const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: true }) let workspaceLayer = ["keep", "drop"] const inspect: vscode.WorkspaceConfiguration["inspect"] = (section: string) => ({ key: section, workspaceValue: workspaceLayer as T, }) config.inspect = inspect config.update = update update.mockImplementation(async (_key: string, _value: unknown, target?: number) => { if (target === vscode.ConfigurationTarget.Global) { workspaceLayer = ["keep", "concurrent"] } return undefined }) vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["keep", "drop"] }, }) expect(update).toHaveBeenCalledWith( "deniedCommands", ["keep", "concurrent"], vscode.ConfigurationTarget.Workspace, ) expect(update).not.toHaveBeenCalledWith( "deniedCommands", ["keep", "drop", "concurrent"], vscode.ConfigurationTarget.Workspace, ) expect(update).not.toHaveBeenCalledWith( "deniedCommands", ["keep", "drop"], vscode.ConfigurationTarget.Workspace, ) }) it("reports a failed re-read and writes nothing when the undo finds no inspection object", async () => { // An inspection that returns no object is not evidence about the layer, so the // rollback must refuse it. Treating the missing value as a deleted layer would // clear the key instead of restoring what this save removed. The key reports // the failure and skips its state write. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked"))], // Save start, merge re-read, then the undo's re-read: the last returns no // inspection object at all, which is the failed read this case pins. [{ globalValue: ["drop"], workspaceValue: ["docker"] }, undefined, null], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) // The undo writes nothing: no clear, no restore. expect(update).toHaveBeenCalledTimes(2) expect(update).not.toHaveBeenCalledWith("deniedCommands", undefined, vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["drop"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( expect.stringContaining("could not be re-read to undo this save"), ) expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("still clears the key when the undo's inspection object reports no global value", async () => { // The other side of the boundary: an inspection object that reports no // global value is a genuine absent layer, so the rollback keeps taking the // absent-layer branch and clears the key. Collapsing this case into the // failed-read path would leave the layer half-applied. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], // Save start, merge re-read, then the undo's re-read, which finds the // inspection object but no global value. [{ globalValue: ["drop"], workspaceValue: ["docker"] }, undefined, {}], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) it("does not promote a displayed entry no layer holds", async () => { // The dialog displayed "docker" from the workspace layer, and while it was open // the settings file lost it, so no layer holds it at save start. The dialog holds // back host updates after an edit, so the submission still carries "docker". An // entry reaches Global only when the dialog never displayed it, so this one is // dropped from both writes rather than granted to every workspace. "aws" was // never displayed, so it still promotes, and nothing was displayed-and-omitted, // so no preservation warning fires. const { update } = mockCommandConfiguration({ workspaceValue: [] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.arrayContaining(["docker"]), vscode.ConfigurationTarget.Global, ) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) it("keeps a workspace allowance out of Global when another writer removed it after display", async () => { // The allowlist path end to end. Gate on, the dialog displayed allowedCommands // "docker" from the workspace layer, and another writer removed it before the // save. Promoting it would auto-approve "docker" in every workspace, so the // global write must not gain it while the unrelated deny edit still lands. const { update } = mockCommandConfiguration( (key: string) => (key === "allowedCommands" ? { workspaceValue: [] } : {}), undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["docker"], deniedCommands: ["aws"] }, commandListBaseline: { allowedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) expect(update).not.toHaveBeenCalledWith( "allowedCommands", expect.arrayContaining(["docker"]), vscode.ConfigurationTarget.Global, ) expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) }) it("keeps a retained baseline entry the layers still hold while promoting a new entry", async () => { // The reconciliation's accept side: the baseline names "docker" and the // save-start snapshot still finds it in the workspace layer. The user kept it as // known state. It stays at its scope, not promoted, while "aws", absent from the // baseline, promotes normally. const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) // The save result is the dialog's only answer for a per-key command-list // failure. Those paths report through the flags instead of throwing, so each // one must reach the ack with success false. const deniedSaveResults = () => vi .mocked(mockClineProvider.postMessageToWebview) .mock.calls.map(([message]) => message) .filter((message) => message.type === "settingsSaveResult") it("reports a failed save through the result when the configuration inspection has no result", async () => { // The snapshot-abort leg marks the save failed for the ack, because a dialog // told the save succeeded would discard the user's list edits. mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, [undefined]) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", requestId: "save-1", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) }) it("promotes a gate-hidden workspace entry named by a baseline without the gate slot", async () => { // A baseline that predates the gate slot keeps the current result. Without // the gate as displayed, the entry's presence in the baseline does not prove // the dialog showed it. Re-adding it therefore promotes to the global layer // exactly as it does with no baseline. const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, commandListBaseline: { deniedCommands: ["docker"] }, }) // A baseline without the gate slot cannot say the workspace layer was on // screen, so the displayed set is empty and the workspace entry is carried. expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) }) it("promotes only an entry no layer held when a gate-flipped baseline displayed the rest", async () => { // The gate flipped off while the dialog was open. The baseline lists "docker", // so it was displayed and keeping it stays a workspace decision. "npm" was never // displayed, but the workspace layer holds it at save start, so it is carried // too and is not new. Only "aws", held by no layer, promotes. const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "npm"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "npm", "aws"] }, commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.arrayContaining(["npm"]), vscode.ConfigurationTarget.Global, ) // Both workspace entries were never deleted, so both stay in the settings file. expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "npm"], vscode.ConfigurationTarget.Workspace) }) it("keeps a displayed entry the user deleted out of the hidden-entry re-add after a gate flip", async () => { // The dialog displayed "docker" with the gate on, while "curl" was hidden all // along, shadowed by the global allow. The baseline shows that. The user // deleted "docker", and the gate flipped off before the save. That hides every // workspace entry, so the hidden set now holds both. The baseline proves // "docker" was displayed, so its absence from the submission is a deletion the // re-add must honor. The preservation re-add still restores "curl". vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["curl"] : undefined, ) const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "curl"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: [] }, commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true, workspaceDeniedCommands: ["docker"], }, }) // The deletion sticks: "docker" is gone from the workspace layer... expect(update).toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) // ...and nothing promoted it into the global layer either. expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) }) it("keeps an entry the save retained out of the undo's removal set", async () => { // The compensation removes only what this save added. The global layer already // held "keep", and this save kept it. The undo is computed against the fresh // read, so it leaves "keep" in place. It removes only this save's addition // ("aws") and restores its deletion ("drop"). vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["keep", "drop"] : undefined, ) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], [ { globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, undefined, { globalValue: ["keep", "aws", "mid-save"] }, ], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["keep", "docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["keep", "aws"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenNthCalledWith( 3, "deniedCommands", ["keep", "mid-save", "drop"], vscode.ConfigurationTarget.Global, ) expect(update).toHaveBeenCalledTimes(3) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) it("does not restore a global entry a third party removed while undoing", async () => { // The fresh read during the compensation shows "keep" gone. Someone else // removed it mid-save. The undo must therefore not resurrect an entry this save // never deleted. Only its own deletion ("drop") returns. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["keep", "drop"] : undefined, ) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], [ { globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, undefined, { globalValue: ["aws", "mid-save"] }, ], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["keep", "docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith( 3, "deniedCommands", ["mid-save", "drop"], vscode.ConfigurationTarget.Global, ) expect(update).toHaveBeenCalledTimes(3) }) it("clears the key instead of restoring its deletion when the re-read reports no global value", async () => { // A cleared key inspects as no value at all. The layer existed at save start, so // an absent re-read means a later writer deleted it during the save. That // decision outranks this save's removed delta: writing "drop" back would // resurrect a layer the other writer removed. The undo clears the key, and it // does not treat the absent value as a failed re-read. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["keep", "drop"] : undefined, ) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], // The layer is present but holds no global value: an absent layer, not a // failed read. No inspection object at all is the failed read. [{ globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, undefined, {}], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["keep", "docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["drop"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) // Only the plain write-failure message: the re-read did not fail. expect(vscode.window.showErrorMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) it("keeps a workspace entry another writer added during the global write", async () => { // The global write is not instantaneous, and the configuration API offers no // compare-and-set. While it runs, a third party adds "concurrent" to the // workspace layer. The workspace write re-reads that layer and merges the // addition, so the save does not overwrite it. The entry the user deleted // ("drop") is in the save-start workspace layer, so it is not a mid-save // addition and stays deleted. const update = vi.fn() const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: true }) let workspaceLayer = ["keep", "drop"] // The double reports the two layers the save path reads. The list values are // the string lists the production call asks for. const inspect: vscode.WorkspaceConfiguration["inspect"] = (section: string) => ({ key: section, globalValue: ["keep"] as T, workspaceValue: workspaceLayer as T, }) config.inspect = inspect config.update = update update.mockImplementation(async (_key: string, _value: unknown, target?: number) => { if (target === vscode.ConfigurationTarget.Global) { workspaceLayer = [...workspaceLayer, "concurrent"] } return undefined }) vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["keep"] }, }) // The submitted list drops "drop", so the workspace write keeps "keep" and adds // the entry that arrived mid-save. expect(update).toHaveBeenCalledWith( "deniedCommands", ["keep", "concurrent"], vscode.ConfigurationTarget.Workspace, ) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["keep"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith( "deniedCommands", ["keep", "drop", "concurrent"], vscode.ConfigurationTarget.Workspace, ) }) it("clears the key only when the undo's re-read finds no layer", async () => { // The undo must not leave an empty `[]` layer where the re-read found none. // `[]` is the activation seed's override and would suppress the default // lists. It clears the key instead. Both legs share the scenario: a third party // cleared the layer while the save ran. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], // Both legs find an inspection object that reports no global value, which is // the absent-layer shape. A missing object is a failed read instead. [{ workspaceValue: ["docker"] }, undefined, {}], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) // The layer existed when the save started, and the re-read during the // compensation reports it gone: someone cleared it mid-save. Nothing present // remains to restore either, so the undo clears the key. const { update: clearedMidSave } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], [{ globalValue: ["aws"], workspaceValue: ["docker"] }, undefined, {}], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(clearedMidSave).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(clearedMidSave).toHaveBeenNthCalledWith( 2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace, ) expect(clearedMidSave).toHaveBeenNthCalledWith( 3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global, ) expect(clearedMidSave).toHaveBeenCalledTimes(3) }) it("clears the key when the undo's re-read finds only this save's own write", async () => { // The re-read finds the layer holding exactly this save's own write over an // absent start. That is the half-applied save itself, not another writer's // decision, so the undo clears the key and restores the absence. Both legs // share that signature. The second save's own global write was empty. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) // Writing `[]` here instead would read back after the rolled-back save as the // user's explicit empty override of the default command lists. expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) // The second leg: the save's own global write was itself empty, because every // submitted entry stayed workspace-scoped. The re-read finds that same empty // layer, still the save's own write over an absent start, so the undo clears // rather than writing `[]` back. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update: emptyWrite } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], [{ workspaceValue: ["docker"] }, undefined, { globalValue: [] }], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker"] }, }) expect(emptyWrite).toHaveBeenNthCalledWith(1, "deniedCommands", [], vscode.ConfigurationTarget.Global) expect(emptyWrite).toHaveBeenNthCalledWith( 2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace, ) expect(emptyWrite).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) expect(emptyWrite).toHaveBeenCalledTimes(3) }) it("preserves an empty global layer another writer created during the save", async () => { // The global layer was absent when the save started, and by undo time a third // party had created it holding the explicit `[]` list. An explicit empty layer // is as much the other writer's decision as one that predates the save. The // compensation reads the current state, finds that layer, and writes its empty // undo back over it instead of clearing. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], [{ workspaceValue: ["docker"] }, undefined, { globalValue: [] }], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) // A clear here would silently suppress the other writer's override // through the activation seed. expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", [], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) }) it("still writes an empty undo list when the global layer exists but holds nothing to keep", async () => { // The other side of the guard: a layer that exists stays present after the // rollback, even when the undo computes an empty list. Clearing an existing // empty layer would restore the seeded defaults that the user had explicitly // overridden with an empty list. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], [{ globalValue: [], workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", [], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) }) it("reports a failed save through the result when the global value cannot be re-read", async () => { // The guarded re-read leg writes nothing, so the ack is the dialog's only // notice that the save did not go through. const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked"))], [{ workspaceValue: ["docker"] }, undefined, new Error("inspect unavailable")], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", requestId: "save-1", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(update).toHaveBeenCalledTimes(2) expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) }) it("reports a failed save through the result when the compensating restore also fails", async () => { // The undo-failure leg reports both failures to the user but throws nothing, // so only its flag can tell the dialog the save was lost. The global layer was // absent at save start, and the re-read finds only this save's own write. The // undo therefore clears the key to restore absence. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, [ undefined, Promise.reject(new Error("workspace locked")), Promise.reject(new Error("restore also failed")), ], [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", requestId: "save-1", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) }) it("carries a shadowed workspace entry without promoting it to the global write", async () => { // The global allow "git" shadows the workspace deny "git push", so the dialog // displayed an empty deny list. "git push" was never displayed, so the save // carries it into the workspace write and never duplicates it into the global // layer, which would change the scope the user chose. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, ) const { update } = mockCommandConfiguration( (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"] } : {}), undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["git push"] }, commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) }) it("carries a shadowed workspace allow entry alongside the user's visible deletions", async () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["git"] : undefined, ) const { update } = mockCommandConfiguration( (key) => (key === "allowedCommands" ? { workspaceValue: ["git", "docker"] } : {}), undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // "docker" stayed visible and kept. The global deny hid "git", and the user // cannot delete a workspace entry the user never saw. updatedSettings: { allowedCommands: ["docker"] }, commandListBaseline: { allowedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) // The carry keeps the workspace layer's own order, so "git" leads the write. expect(update).toHaveBeenCalledWith("allowedCommands", ["git", "docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) }) it("does not persist a webview-supplied workspaceCommandListsEnabled value", async () => { mockCommandConfiguration({}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // A settings payload is not a second source for the gate. The synchronous // user-scope configuration read is. updatedSettings: { workspaceCommandListsEnabled: true, alwaysDenyUnapprovedCommands: true }, }) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith( "workspaceCommandListsEnabled", expect.anything(), ) // The refusal does not affect the sibling keys of the same payload. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) }) it("abandons a payload carrying only the gate key without writing configuration", async () => { const { update } = mockCommandConfiguration({}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { workspaceCommandListsEnabled: true }, }) expect(update).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() // The state post still runs, so the dialog re-reads the effective value // instead of keeping the refused one. expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) // A payload can carry both command-list keys. The hidden-entry check for the // second-processed key must judge shadowing against the state as it was when the // save started. It must not judge against the state the same loop's earlier key // left behind. The double below mirrors ContextProxy. Its setValue publishes the // in-memory copy before it resolves, so a fresh read after the first key's awaited // write would observe it. That read would let the never-displayed entry be deleted. function mockCommandListStateStore(initial: Partial>) { const store: Partial> = { ...initial } vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" || key === "deniedCommands" ? store[key] : undefined, ) vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (key: string, value: unknown) => { if (key === "allowedCommands" || key === "deniedCommands") { store[key] = value as string[] | undefined } }) return store } it("carries a workspace deny entry shadowed by a global allow the same save removes", async () => { mockCommandListStateStore({ allowedCommands: ["git"] }) const { update } = mockCommandConfiguration( (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"] } : {}), undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // The handler processes "allowedCommands" first and drops the shadowing global // "git". The dialog hid "git push", so an empty deny list must not delete it. updatedSettings: { allowedCommands: [], deniedCommands: [] }, commandListBaseline: { allowedCommands: [], deniedCommands: [], workspaceCommandListsEnabled: true, }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("carries a workspace allow entry shadowed by a global deny the same save removes", async () => { mockCommandListStateStore({ deniedCommands: ["git"] }) const { update } = mockCommandConfiguration( (key) => (key === "allowedCommands" ? { workspaceValue: ["git push"] } : {}), undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // The mirror order: the handler processes the deny key first, so this pins // that preservation does not depend on which key arrives first. updatedSettings: { deniedCommands: [], allowedCommands: [] }, commandListBaseline: { allowedCommands: [], deniedCommands: [], workspaceCommandListsEnabled: true, }, }) expect(update).toHaveBeenCalledWith("allowedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Workspace) expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("reports a rejected extension-state write without aborting the save", async () => { // The configuration writes succeeded. Silently dropping the state write would // therefore leave the settings files and the stored list disagreeing, with // nothing shown to the user. The rejection is queued once, so it consumes exactly this // key's write and the sibling key still persists. Pins the §6.5 clause (iv) // divergence: the configuration holds the attempted list while the state copy // holds its pre-operation list, and the failure names the leg. vi.mocked(mockClineProvider.contextProxy.setValue).mockRejectedValueOnce(new Error("state store unavailable")) const { update } = mockCommandConfiguration({}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["aws"], alwaysDenyUnapprovedCommands: true }, }) // The configuration leg did persist... expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) // ...so the message names the leg that failed... expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( "Failed to save deniedCommands: state store unavailable. The configuration was updated, but the extension's stored copy of the list was not, so the two disagree until a later save succeeds.", ) // ...the save continued to the next key... expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) // ...and the dialog re-reads state instead of keeping an unsaved value. expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("reports a failed save through the result when the extension-state write is rejected", async () => { // The same rejection seen by a sender that awaits an answer: the toast names // the failed leg, so the answer must agree with it. An ack of success would let // the dialog discard edits its stored copy never received, while a retry would // converge. Pins the same §6.5 clause (iv) pair as the case above, through the // result a sender reads. vi.mocked(mockClineProvider.contextProxy.setValue).mockRejectedValueOnce(new Error("state store unavailable")) const { update } = mockCommandConfiguration({}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", requestId: "save-1", updatedSettings: { deniedCommands: ["aws"], alwaysDenyUnapprovedCommands: true }, }) expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) // The configuration leg did persist, and the user still hears which leg failed... expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( "Failed to save deniedCommands: state store unavailable. The configuration was updated, but the extension's stored copy of the list was not, so the two disagree until a later save succeeds.", ) // ...and the save continued to the next key. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) }) it("still propagates a rejected state write for non-command-list keys", async () => { // The partial-failure report is scoped to the command-list keys, whose // configuration legs succeeded first. Other keys have no half-completed save // to explain, so their failures keep propagating. The rejection is queued // once, so it stays scoped to this test. vi.mocked(mockClineProvider.contextProxy.setValue).mockRejectedValueOnce(new Error("state store unavailable")) await expect( webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { alwaysDenyUnapprovedCommands: true }, }), ).rejects.toThrow("state store unavailable") expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() // The webview still gets a state refresh, because a failed save re-posts // before the rejection propagates. expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) it("keeps a settings-file entry the dialog never displayed and warns that it was preserved", async () => { // An entry the settings file gained while the dialog was open has the same // shape as a user deletion. It is in the file and absent from the submitted // list. The baseline tells them apart, so the new entry stays in the layer the // snapshot found it in. The user hears about it instead of losing it silently. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ workspaceValue: ["aws", "rm -rf"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["aws"] }, commandListBaseline: { deniedCommands: ["aws"] }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws", "rm -rf"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("rm -rf")) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("1 entry was")) }) it("applies a user deletion of a displayed entry without warning", async () => { // The counterpart classification: the baseline shows the dialog displayed the // entry and the submitted list omits it, so the user deleted it on purpose. // The save drops it from every layer that held it, and discloses nothing. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ workspaceValue: ["aws", "rm -rf"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["aws"] }, commandListBaseline: { deniedCommands: ["aws", "rm -rf"], workspaceDeniedCommands: ["aws", "rm -rf"], }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["rm -rf"], vscode.ConfigurationTarget.Global) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) it("keeps a file-added entry while applying a displayed deletion in one save, warning once", async () => { // Both divergence classes in one payload: "git" was displayed and the user // deleted it, so the deletion applies. "curl" arrived after the dialog opened, // so the save preserves it. The warning names only the preserved entry. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ workspaceValue: ["git", "curl"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: [] }, commandListBaseline: { deniedCommands: ["git"], workspaceDeniedCommands: ["git"] }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("curl")) expect(vscode.window.showWarningMessage).not.toHaveBeenCalledWith(expect.stringContaining("git")) }) it("saves command lists unchanged when the message carries no baseline", async () => { // Senders that omit the baseline keep the old behavior: the omitted entry is // dropped as a deletion, and the save produces no warning. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ workspaceValue: ["aws", "rm -rf"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["aws"] }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) it("routes a preserved entry to the layer the save-start snapshot found it in", async () => { // A preserved entry must land where it lives, not be flattened into the // global layer. "rm -rf" is in the workspace snapshot and "npm" in the // extension's stored global layer, and the dialog displayed neither. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["npm"] : undefined, ) const { update } = mockCommandConfiguration({ workspaceValue: ["rm -rf"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: [] }, commandListBaseline: { deniedCommands: [] }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["rm -rf"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", ["npm"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["npm"]) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("2 entries were")) }) it("treats a malformed command-list baseline exactly like a missing one", async () => { // The save message crosses a JSON boundary, so a baseline whose key holds a // non-array is reachable at runtime even though the declared type forbids it. // The classification guard treats it as no baseline at all. The save writes // the submitted list unclassified. No entry the dialog never displayed counts // as user-deleted. const wireMessage: WebviewMessage = JSON.parse( JSON.stringify({ type: "updateSettings", updatedSettings: { deniedCommands: ["aws"] }, commandListBaseline: { deniedCommands: "aws" }, }), ) vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ workspaceValue: ["aws", "rm -rf"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, wireMessage) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) it("composes and writes only the first workspace folder's layer in a multi-root save", async () => { // The dialog composes against the first folder, so a save must never read or // write the second folder's per-folder layer. Folder B's entries survive a // folder A save untouched. const secondFolderUri = { fsPath: "/mock/second-folder" } mockWorkspaceFolders.folders = [{ uri: mockWorkspaceFolderUri }, { uri: secondFolderUri }] const { update } = mockCommandConfiguration( { workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, mockWorkspaceFolderUri) expect(vscode.workspace.getConfiguration).not.toHaveBeenCalledWith(Package.name, secondFolderUri) // The folder-target write the save does make goes to the first folder's layer. expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.WorkspaceFolder) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) }) it("aggregates preserved entries from both command-list keys into a single save warning", async () => { // A payload carrying both list keys classifies per key. Two file entries the // dialog never displayed, one per key, must survive in their own layers. The // save discloses them together in exactly one warning. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( (key) => key === "allowedCommands" ? { workspaceValue: ["git", "curl"] } : { workspaceValue: ["rm -rf", "docker"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git"], deniedCommands: ["rm -rf"] }, commandListBaseline: { allowedCommands: ["git"], deniedCommands: ["rm -rf"] }, }) // "curl" stays in the workspace allow layer, "docker" in the workspace deny layer. expect(update).toHaveBeenCalledWith("allowedCommands", ["git", "curl"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith( "deniedCommands", ["rm -rf", "docker"], vscode.ConfigurationTarget.Workspace, ) expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) // One aggregated warning naming both preserved entries and counting them together. expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("2 entries were")) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("curl")) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("docker")) }) // A workspace entry the dialog never displayed is carried into its own layer. // Whether that carry is also reported as a settings-file addition depends on the // gate: with the gate off no workspace entry was on screen, so the classifier // treats the whole workspace layer as hidden and stays silent; with the gate on // the entry was merely shadowed, which the classifier reports. it.each([ { name: "hidden while the workspace gate is off", gateEnabled: false, hiddenEntry: "docker", warns: false, prepare: () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) }, }, { // The global allow covers the workspace deny, so the composition dropped it // from the dialog. Its absence from the baseline is display, not an addition, // so the save carries it silently — the same reading the composition applies. name: "shadowed by a global allow while the gate is on", gateEnabled: true, hiddenEntry: "git push", warns: false, prepare: () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, ) }, }, ])("carries a $name deny entry without deleting it", async ({ gateEnabled, hiddenEntry, warns, prepare }) => { prepare() const { update } = mockCommandConfiguration( { workspaceValue: [hiddenEntry] }, undefined, undefined, gateEnabled, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: [] }, // The dialog displayed the effective deny list, which never // contained the hidden entry, so the baseline omits it. The gate // slot is what tells the classifier this save did not display it. commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: gateEnabled }, }) expect(update).toHaveBeenCalledWith("deniedCommands", [hiddenEntry], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) if (warns) { expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining(hiddenEntry)) } else { expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() } }) it("warns only about the genuine file addition when a carried entry is also present", async () => { // Mixed divergence in one save. The baseline omits both "git push" and "wget", // so both are carried into the workspace write unchanged. Only "wget" is also // absent from the submission, which is what makes it a settings-file addition // the user must be told about; "git push" was submitted, so it is silent. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, ) const { update } = mockCommandConfiguration( (key) => (key === "deniedCommands" ? { workspaceValue: ["git push", "curl", "wget"] } : {}), undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["curl", "git push"] }, // The dialog displayed the shadow-filtered deny list. "curl" was visible and // kept, and the dialog never displayed "git push". "wget" arrived in the // settings file after the dialog opened. commandListBaseline: { deniedCommands: ["curl"] }, }) // The carry-over clause keeps both hidden entries, and the global layer stays // empty because neither entry is new. // The carry keeps the workspace layer's own order. expect(update).toHaveBeenCalledWith( "deniedCommands", ["git push", "curl", "wget"], vscode.ConfigurationTarget.Workspace, ) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("1 entry was")) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("wget")) expect(vscode.window.showWarningMessage).not.toHaveBeenCalledWith(expect.stringContaining("git push")) }) it("still warns about a visible workspace addition alongside the hidden-entry exclusion", async () => { // Regression witness for the hidden-entry exclusion: an entry that arrived in // the displayed part of the file is a genuine external addition. The save keeps // it in the layer the snapshot found it in and names it in the warning. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ workspaceValue: ["git", "curl"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git"] }, commandListBaseline: { allowedCommands: ["git"] }, }) expect(update).toHaveBeenCalledWith("allowedCommands", ["git", "curl"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("curl")) }) it("preserves a deny entry only the configuration global layer holds", async () => { // The user added "curl" to the user-level deny list directly in settings.json // while the dialog was open. No such edit refreshes the extension-state copy // that the split consults, and neither the dialog baseline nor the submitted // list names the entry. The save-start configuration global layer is therefore // the only source that can classify it as an external addition. Without that // source the save's Global write would delete it from the user's settings file. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ globalValue: ["curl"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", // The dialog displayed nothing for this key and saved nothing back. updatedSettings: { deniedCommands: [] }, commandListBaseline: { deniedCommands: [] }, }) // The Global write re-admits the file-side entry instead of clearing // the layer that holds it. expect(update).toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) // The snapshot found no workspace layer, so the save never creates one. expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.anything(), vscode.ConfigurationTarget.Workspace, ) // The save discloses the preserved entry like the other external additions, // and the state copy keeps the layer the save wrote. expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("1 entry was")) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("curl")) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["curl"]) }) it("still promotes a genuinely new entry when the configuration global layer already holds another", async () => { // The accept side of the external-addition union: "curl" lives in the // configuration global layer and the state copy the dialog displayed. It is // therefore known state kept in place. "aws", which no layer held at save start, // keeps the brand-new promotion path into the global write. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["curl"] : undefined, ) const { update } = mockCommandConfiguration({ globalValue: ["curl"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["curl", "aws"] }, commandListBaseline: { deniedCommands: ["curl"] }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["curl", "aws"], vscode.ConfigurationTarget.Global) // The split also keeps the entry. expect(update).not.toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.anything(), vscode.ConfigurationTarget.Workspace, ) // No entry counted as an external addition, so no warning fires. expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["curl", "aws"]) }) it("retains a baseline entry only the configuration global layer still holds", async () => { // The dialog displayed "curl", and the user kept it. No direct settings-file // edit refreshes the extension-state copy that the retained-entry check // consults. Only the save-start configuration global layer still holds the // entry. A check limited to the state copy and the workspace layer treats the // entry as externally removed and drops it. The Global write then deletes it // from the user's settings file. // Global write then deletes it from the user's settings file. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ globalValue: ["curl"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["curl"] }, commandListBaseline: { deniedCommands: ["curl"], workspaceCommandListsEnabled: true }, }) // The split keeps the retained entry, and the Global write rewrites the layer // that still holds it instead of clearing it. expect(update).toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) // The snapshot found no workspace layer, so the save never creates one. expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.anything(), vscode.ConfigurationTarget.Workspace, ) // A kept entry the dialog displayed is retention, not a file-side // change to disclose. expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["curl"]) }) it("drops a baseline entry the user deleted from the configuration global layer while the state copy still holds it", async () => { // The dialog displayed the global deny "curl", and the submitted list still // holds it. The user deleted it from the user-level deny list in settings.json // while the dialog was open. No direct file edit refreshes the extension-state // copy. Treating that stale copy as proof the entry remains would restore the // deleted entry over the file. The rule consults `configSet` and the seed, // never the state copy, so the stale copy cannot disprove the removal. // External removal wins over the stale buffer. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["curl"] : undefined, ) const { update } = mockCommandConfiguration({ globalValue: [] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["curl"] }, commandListBaseline: { deniedCommands: ["curl"], workspaceCommandListsEnabled: true }, }) // The deletion sticks: the Global write clears the layer the file now shows // empty, instead of re-adding "curl" from the stale state copy. expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Global) // The snapshot found no workspace layer, so the save never creates one. expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.anything(), vscode.ConfigurationTarget.Workspace, ) // An external removal is not a file-side addition to disclose. expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) }) it("preserves activation-seeded default entries whose configuration global layer is absent", async () => { // A default install holds nothing in the user-level settings. Activation seeded // the built-in defaults into extension state. No global configuration layer // exists, so the state copy is the only evidence that the displayed entries // have a home. A rule that required a store would drop these entries and empty // the state copy. The Global write clears the layer to []. The emptied state // then stops activation from ever seeding the defaults again. The seed // disjunct names every one of them, so the retention stands and the save // writes the defaults back. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) // The state copy still equals the shipped default, which is what makes the // absent global layer mean "seeded" rather than "deleted". const { update } = mockCommandConfiguration( { defaultValue: ["git log", "git diff", "git show"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git log", "git diff", "git show"] }, commandListBaseline: { allowedCommands: ["git log", "git diff", "git show"], workspaceCommandListsEnabled: true, }, }) // The retained entries survive the split and the Global write // rewrites them, instead of clearing the never-created layer. expect(update).toHaveBeenCalledWith( "allowedCommands", ["git log", "git diff", "git show"], vscode.ConfigurationTarget.Global, ) expect(update).not.toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) // The snapshot found no workspace layer, so the save never creates one. expect(update).not.toHaveBeenCalledWith( "allowedCommands", expect.anything(), vscode.ConfigurationTarget.Workspace, ) // Entries the dialog displayed and the user kept are retention, not a // file-side change to disclose. expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", [ "git log", "git diff", "git show", ]) }) it("preserves a settings-imported entry that sits in the configuration global layer", async () => { // The import writes the configuration first and the state copy second, pinned in // importExport.spec.ts. This test pins the save side. Without that configuration // layer the next unrelated Save would classify the displayed entry as externally // removed and delete it. The scripted configuration is stateful: update() changes // what the next inspect() reports, as the real API does. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => // The import's state write: "imported" exists here too. key === "allowedCommands" ? ["git", "imported"] : undefined, ) // The import's first write holds the full list in the global layer. An earlier // dialog save had already created that layer. The absent-layer exception // therefore cannot carry the case either. const layers: { globalValue?: string[] } = { globalValue: ["git", "imported"] } const update = vi.fn() update.mockImplementation(async (_key: string, value: string[]) => { layers.globalValue = value }) const inspect = vi.fn() inspect.mockImplementation((key: string) => (key === "allowedCommands" ? layers : {})) const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: true }) config.update = update config.inspect = inspect vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) // The next unrelated Save submits the same list with the baseline the // import re-posted to the dialog. await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git", "imported"] }, commandListBaseline: { allowedCommands: ["git", "imported"], workspaceCommandListsEnabled: true, }, }) // The entry survives because the configuration layer holds it (`configSet.has`), // not because anything put it there for the save. Both homes keep it instead of // the save dropping it as externally removed. expect(update).toHaveBeenCalledWith("allowedCommands", ["git", "imported"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("allowedCommands", ["git"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git", "imported"]) // Retention, not a file-side change: no disclosure. expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) it("delegates the import case to the shared import function without a configuration write", async () => { // The import's write pair lives inside importSettingsWithFeedback, pinned in // importExport.spec.ts. The message case must therefore stay a thin delegate. // It adds no configuration write of its own, even with a state copy holding // command lists. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git", "imported"] : undefined, ) const { update } = mockCommandConfiguration({ globalValue: ["git"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "importSettings" }) expect(importSettingsWithFeedback).toHaveBeenCalledWith({ providerSettingsManager: mockClineProvider.providerSettingsManager, contextProxy: mockClineProvider.contextProxy, customModesManager: mockClineProvider.customModesManager, provider: mockClineProvider, }) expect(update).not.toHaveBeenCalled() }) it("preserves a configuration-global entry the dialog displayed at the workspace scope", async () => { // The user added "docker" to the user-level list in settings.json while the // dialog was open. The dialog displayed the same entry from the workspace // layer. The split classifies kept entries against the global origin set. // Sourced only from the lagging state copy, that set misses the // configuration's own global layer. "docker" would therefore count as never // routed and be dropped from the Global write. That write deletes it from the // user's settings file. The unioned origin set keeps it in the layer the // save-start snapshot found it in. It also keeps that layer's order, ahead of // the dialog-ordered new entry "aws". vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( { globalValue: ["docker"], workspaceValue: ["docker"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) // The workspace layer holds the entry too, and a kept entry present in // both layers stays in both. expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) // The file did not add this displayed entry. The user kept it, so no warning fires. expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"]) }) // Post-save probe for the activation seed. `seedCommandList` skips only a key // whose global state is set. The saved copy therefore decides whether the // declared package default can ever return to that key. function mockSeededGlobalState(initial: Record) { const store = new Map(Object.entries(initial)) // Structurally complete Memento double with keys, get, and update. The seed // call site therefore needs no type assertion. return { keys: vi.fn((): readonly string[] => [...store.keys()]), get: vi.fn().mockImplementation((key: string) => store.get(key)), update: vi.fn().mockImplementation(async (key: string, value: unknown) => { store.set(key, value) }), } } // The fresh-install configuration the seed would act on: the declared default // with no layer value anywhere. That is the shape that re-seeds the defaults // whenever the guard above does not hold. function mockSeedConfiguration(defaultValue: string[]) { const config = makeWorkspaceConfiguration() config.inspect = vi.fn().mockReturnValue({ defaultValue }) vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) } it("round-trips a dialog addition through the global write and keeps the activation seed blocked", async () => { // A fresh install holds the defaults only in the extension-state copy. An add // must rewrite the full list plus the addition into the global layer in dialog // order. Those seeded entries have no other home that survives the save. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) // The state copy still equals the shipped default, which is what makes the // absent global layer mean "seeded" rather than "deleted". const { update } = mockCommandConfiguration( { defaultValue: ["git log", "git diff", "git show"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git log", "git diff", "git show", "aws"] }, commandListBaseline: { allowedCommands: ["git log", "git diff", "git show"], workspaceCommandListsEnabled: true, }, }) // Exact array: the seeded defaults keep their state-copy order and the // brand-new entry lands after them. expect(update).toHaveBeenCalledWith( "allowedCommands", ["git log", "git diff", "git show", "aws"], vscode.ConfigurationTarget.Global, ) expect(update).not.toHaveBeenCalledWith( "allowedCommands", ["git log", "git diff", "git show"], vscode.ConfigurationTarget.Global, ) // The snapshot found no workspace layer, so the save never creates one. expect(update).not.toHaveBeenCalledWith( "allowedCommands", expect.anything(), vscode.ConfigurationTarget.Workspace, ) // A dialog addition is not a settings-file change: no disclosure. expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() // The state mirror holds exactly the global layer the save wrote. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", [ "git log", "git diff", "git show", "aws", ]) expect(update).toHaveBeenCalledTimes(1) // A second activation cannot re-grant the defaults: the saved state copy is // truthy, so the seed guard returns before it reads the configuration. mockSeedConfiguration(["git log", "git diff", "git show"]) const globalState = mockSeededGlobalState({ allowedCommands: ["git log", "git diff", "git show", "aws"], }) await seedCommandList(globalState, "allowedCommands") expect(globalState.update).not.toHaveBeenCalled() expect(globalState.get("allowedCommands")).toEqual(["git log", "git diff", "git show", "aws"]) }) it("persists an explicitly emptied list and keeps the activation seed blocked for it", async () => { // Clearing every entry must clear the global layer and the state copy. The // emptied `[]` must still count as existing state, so a later activation never // re-seeds the default list the user deleted. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) // The state copy still equals the shipped default, which is what makes the // absent global layer mean "seeded" rather than "deleted". const { update } = mockCommandConfiguration( { defaultValue: ["git log", "git diff", "git show"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: [] }, commandListBaseline: { allowedCommands: ["git log", "git diff", "git show"], workspaceCommandListsEnabled: true, }, }) expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith( "allowedCommands", ["git log", "git diff", "git show"], vscode.ConfigurationTarget.Global, ) // The snapshot found no workspace layer, so the save never creates one. expect(update).not.toHaveBeenCalledWith( "allowedCommands", expect.anything(), vscode.ConfigurationTarget.Workspace, ) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", []) expect(update).toHaveBeenCalledTimes(1) // The `[]` state copy is truthy. The seed guard therefore treats the emptied // list as existing state, even against a configuration that still reports the // declared default. mockSeedConfiguration(["git log", "git diff", "git show"]) const globalState = mockSeededGlobalState({ allowedCommands: [] }) await seedCommandList(globalState, "allowedCommands") expect(globalState.update).not.toHaveBeenCalled() expect(globalState.get("allowedCommands")).toEqual([]) }) it("materializes the seeded defaults in the global layer when the user edited only workspace entries", async () => { // For a workspace-only edit the user deletes the workspace entry "npm test" // and touches nothing on the global side. The global write still materializes // the activation-seeded defaults, because with the configuration global layer // absent the state copy is the only home those entries have. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) const { update } = mockCommandConfiguration( { workspaceValue: ["npm test", "docker"], defaultValue: ["git log", "git diff", "git show"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git log", "git diff", "git show", "docker"] }, commandListBaseline: { allowedCommands: ["git log", "git diff", "git show", "npm test", "docker"], workspaceCommandListsEnabled: true, // "npm test" was the only workspace-layer entry on screen; the rest are // global entries the flat list carries too. workspaceAllowedCommands: ["npm test", "docker"], }, }) // The save writes the untouched global side back verbatim. expect(update).toHaveBeenCalledWith( "allowedCommands", ["git log", "git diff", "git show"], vscode.ConfigurationTarget.Global, ) expect(update).not.toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) // The kept workspace entry stays at the workspace scope, and the deleted entry // clears it there, so nothing leaks into the global layer. expect(update).toHaveBeenCalledWith("allowedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", [ "git log", "git diff", "git show", ]) expect(update).toHaveBeenCalledTimes(2) }) it("keeps a seeded default the workspace layer also holds in the global write with the gate on", async () => { // For a seeded default the workspace layer also holds, and the gate on. The // workspace layer carries "git log" only while the gate is on, so the global // layer is still its home: dropping it there is a loss the user never asked // for, and a later save with the gate off would have no copy left to keep. An // unchanged save therefore writes the seeded list back to the global layer and // clears the workspace duplicate it now holds twice. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) const { update } = mockCommandConfiguration( { workspaceValue: ["git log"], defaultValue: ["git log", "git diff", "git show"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git log", "git diff", "git show"] }, commandListBaseline: { allowedCommands: ["git log", "git diff", "git show"], workspaceCommandListsEnabled: true, }, }) expect(update).toHaveBeenCalledWith( "allowedCommands", ["git log", "git diff", "git show"], vscode.ConfigurationTarget.Global, ) expect(update).not.toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) // A kept entry stays in every layer that held it, so the workspace copy is // rewritten too and enforcement still finds it there. expect(update).toHaveBeenCalledWith("allowedCommands", ["git log"], vscode.ConfigurationTarget.Workspace) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", [ "git log", "git diff", "git show", ]) expect(update).toHaveBeenCalledTimes(2) // Enforcement still covers every entry after the save. The merged set the // composed reader returns holds the global list the save wrote. const afterSaveScopes = readCommandListScopes("allowedCommands", ["git log", "git diff", "git show"], { workspaceValue: ["git log"], }) expect(afterSaveScopes.merged).toEqual(["git log", "git diff", "git show"]) }) it("keeps a gate-hidden workspace copy the user deleted only from the displayed global list", async () => { // The gate is off, so the dialog displayed only the global layer. "git log" // sits in both layers, and the baseline names it from the global copy. The user // deletes it there. That deletion is a decision about the user-level list, not // about a workspace copy the dialog never showed, so the workspace entry stays // while the global one goes. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log"] : undefined, ) const { update } = mockCommandConfiguration( { globalValue: ["git log"], workspaceValue: ["git log"] }, undefined, undefined, false, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: [] }, commandListBaseline: { allowedCommands: ["git log"], workspaceCommandListsEnabled: false }, }) // The user-level entry the dialog showed is deleted where it lives... expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) // ...and the workspace copy the dialog could not show survives. expect(update).toHaveBeenCalledWith("allowedCommands", ["git log"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Workspace) // The workspace copy is not promoted into the user's settings file. expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", []) }) it("keeps a gate-hidden workspace copy the user never saw when the baseline names only the global list", async () => { // The same save with nothing submitted and a baseline that shows only the // global copy. Both entries go unmentioned by the submission, and the baseline // proves the dialog displayed the global one alone. The workspace copy is // preserved, and the global deletion the baseline proves is applied. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["rm -rf"] : undefined, ) const { update } = mockCommandConfiguration( { globalValue: ["rm -rf"], workspaceValue: ["rm -rf", "docker"] }, undefined, undefined, false, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: [] }, commandListBaseline: { deniedCommands: ["rm -rf"], workspaceCommandListsEnabled: false }, }) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) // Both hidden workspace entries survive the rewrite, including the one the // global layer also held. expect(update).toHaveBeenCalledWith( "deniedCommands", ["rm -rf", "docker"], vscode.ConfigurationTarget.Workspace, ) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) }) it("applies a displayed deletion to both copies when the gate is on", async () => { // The gate-on counterpart of the case above, with the same fixture. The dialog // displayed the workspace copy, so deleting the entry there is a deletion of // that copy too, and the save clears both layers. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log"] : undefined, ) const { update } = mockCommandConfiguration( { globalValue: ["git log"], workspaceValue: ["git log"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: [] }, commandListBaseline: { allowedCommands: ["git log"], workspaceCommandListsEnabled: true, // The workspace layer held a copy the dialog showed, so the omission is a // deletion of that copy as well as of the global one. workspaceAllowedCommands: ["git log"], }, }) expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Workspace) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", []) }) it("keeps a workspace entry a displayed global entry of the same text did not put on screen", async () => { // The user-global layer holds "echo", so the dialog showed "echo". The workspace // layer gained its own "echo" after display, and the user removed "echo" in the // dialog. The merged baseline names "echo" once, which cannot say which layer // showed it. The per-layer share says the workspace layer did not, so the // workspace copy is carried instead of deleted by an omission it never saw. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["echo"] : undefined, ) const { update } = mockCommandConfiguration( { globalValue: ["echo"], workspaceValue: ["echo"] }, undefined, undefined, true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: [] }, commandListBaseline: { allowedCommands: ["echo"], workspaceCommandListsEnabled: true, workspaceAllowedCommands: [], }, }) // The global deletion lands, because that layer did show the entry... expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) // ...and the workspace copy, which was never on screen, survives. expect(update).toHaveBeenCalledWith("allowedCommands", ["echo"], vscode.ConfigurationTarget.Workspace) }) it("keeps a seeded default in the global write with the gate off while the workspace layer duplicates it", async () => { // The gate-off half of the seeded-default pair. Activation wrote the defaults // into extension state and the configuration's global layer is absent, so the // state copy is their only home. The workspace layer duplicates "git log". The // save keeps the seeded entry in the global write, and the workspace copy stays // where it is because the gate off means the dialog never showed it. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff"] : undefined, ) const { update } = mockCommandConfiguration( { workspaceValue: ["git log"], defaultValue: ["git log", "git diff"] }, undefined, undefined, false, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git log", "git diff"] }, commandListBaseline: { allowedCommands: ["git log", "git diff"], workspaceCommandListsEnabled: false, }, }) expect(update).toHaveBeenCalledWith( "allowedCommands", ["git log", "git diff"], vscode.ConfigurationTarget.Global, ) expect(update).not.toHaveBeenCalledWith("allowedCommands", ["git diff"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledWith("allowedCommands", ["git log"], vscode.ConfigurationTarget.Workspace) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git log", "git diff"]) }) }) 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([ { name: "deploy", content: "existing command", source: "project", filePath: "/mock/workspace/.roo/commands/deploy.md", description: "Deploy command", }, ]) 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] // The complete array in order: the discovered command first, then the skills in // discovery order. The duplicate skill contributes nothing, and the surviving // copy is the first one seen. expect(commandMessage?.commands).toEqual([ { name: "deploy", source: "project", filePath: "/mock/workspace/.roo/commands/deploy.md", description: "Deploy command", }, { 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", }, ]) }) 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 = { listConfig: vi.fn().mockResolvedValue([ { name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }, { name: "Backup Zoo", apiProvider: providerIdentifiers.zooGateway }, ]), getProfile: vi .fn() .mockResolvedValueOnce({ apiProvider: providerIdentifiers.zooGateway, zooSessionToken: "token-active", zooGatewayModelId: "anthropic/claude-sonnet-4", }) .mockResolvedValueOnce({ apiProvider: providerIdentifiers.zooGateway, zooSessionToken: "token-backup", }), 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, ) }) }) 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("reports a failed save when a command-list write fails, without throwing", async () => { // A command-list key abandons only its own key on a write failure. The failure // path reports and continues without a throw. The save result must therefore // still say the save was not stored. The dialog keeps the user's list edits // unsaved on this answer. const config = makeWorkspaceConfiguration({}) config.inspect = vi.fn().mockReturnValue({}) config.update = vi.fn().mockRejectedValue(new Error("disk on fire")) vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) await expect(saveAs({ deniedCommands: ["aws"] })).resolves.toBeUndefined() expect(results()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() }) it("reports a failed save when a command-list write fails and the state refresh fails too", async () => { // The code catches the refresh failure on its own, so it cannot mask the write failure in the ack. const config = makeWorkspaceConfiguration({}) config.inspect = vi.fn().mockReturnValue({}) config.update = vi.fn().mockRejectedValue(new Error("disk on fire")) vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) vi.mocked(mockClineProvider.postStateToWebview).mockRejectedValueOnce(new Error("webview gone")) await expect(saveAs({ deniedCommands: ["aws"] })).resolves.toBeUndefined() expect(results()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: disk on fire") expect(mockClineProvider.log).toHaveBeenCalledWith( "[updateSettings] Could not refresh the webview state: webview gone", ) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() }) it("still reports a stored save when a command-list write succeeds", async () => { // The accept-path counterpart: the failure flag must not stick for a save // whose command-list writes all succeeded. const config = makeWorkspaceConfiguration({}) config.inspect = vi.fn().mockReturnValue({}) vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) await saveAs({ deniedCommands: ["aws"] }) expect(config.update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(results()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: true }]) }) }) 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") }) })