// pnpm --filter roo-cline test core/webview/__tests__/ClineProvider.spec.ts import fs from "fs" import fsPromises from "fs/promises" import * as path from "path" import { TaskRegistry } from "../../task/TaskRegistry" import Anthropic from "@anthropic-ai/sdk" import * as vscode from "vscode" import axios from "axios" import pWaitFor from "p-wait-for" import { type ProviderSettingsEntry, type ProviderSettings, type ClineMessage, type ExtensionMessage, type ExtensionState, type RooCodeSettings, type WebviewMessage, ORGANIZATION_ALLOW_ALL, DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, DEFAULT_DIFF_FUZZY_THRESHOLD, DEFAULT_WRITE_DELAY_MS, providerIdentifiers, openAiModelInfoSaneDefaults, } from "@roo-code/types" import { TelemetryService } from "@roo-code/telemetry" import { CloudService } from "@roo-code/cloud" import { defaultModeSlug } from "../../../shared/modes" import { joinSegments } from "../../../shared/mentionSegments" import type { MentionSegment } from "@roo-code/types" import { experimentDefault } from "../../../shared/experiments" import { EMBEDDING_MODEL_PROFILES } from "../../../shared/embeddingModels" import { setTtsEnabled } from "../../../utils/tts" import { ContextProxy } from "../../config/ContextProxy" import { ProviderSettingsManager, ProviderSettingsNotFoundError } from "../../config/ProviderSettingsManager" import { importSettingsFromPath } from "../../config/importExport" import { WorkspaceIndexingEnablementManager } from "../../../services/code-index/workspace-indexing-enablement-manager" import { Task, TaskOptions } from "../../task/Task" import { safeWriteJson } from "../../../utils/safeWriteJson" import { t } from "../../../i18n" import { ClineProvider } from "../ClineProvider" import { McpServerManager } from "../../../services/mcp/McpServerManager" import { webviewMessageHandler } from "../webviewMessageHandler" import type { MdmService } from "../../../services/mdm/MdmService" import { Terminal } from "../../../integrations/terminal/Terminal" import { MessageManager } from "../../message-manager" import { forceFullModelDetailsLoad, hasLoadedFullDetails } from "../../../api/providers/fetchers/lmstudio" import { makeCompositeDisposable, makeEventEmitter } from "../../../test-utils/vscode" import { WebviewFocusTracker } from "../WebviewFocusTracker" import { resolveChatProvider } from "../../../activate/resolveChatProvider" // Mock setup must come before imports. vi.mock("../../prompts/sections/custom-instructions") vi.mock("p-wait-for", () => ({ __esModule: true, default: vi.fn().mockResolvedValue(undefined), })) vi.mock("fs/promises", async (importOriginal) => { const actual = await importOriginal() const mocked = { mkdir: vi.fn().mockResolvedValue(undefined), writeFile: vi.fn().mockResolvedValue(undefined), readFile: vi.fn().mockResolvedValue(""), unlink: vi.fn().mockResolvedValue(undefined), rmdir: vi.fn().mockResolvedValue(undefined), } return { ...actual, ...mocked, default: { ...actual, ...mocked, }, } }) vi.mock("axios", async (importOriginal) => ({ default: { isAxiosError: (await importOriginal()).default.isAxiosError, get: vi.fn().mockResolvedValue({ data: { data: [] } }), post: vi.fn(), }, get: vi.fn().mockResolvedValue({ data: { data: [] } }), post: vi.fn(), })) vi.mock("../../../utils/safeWriteJson") vi.mock("../../../utils/path", async (importOriginal) => { const actual = await importOriginal() return { ...actual, getWorkspacePath: vi.fn().mockReturnValue(""), } }) vi.mock("../../../utils/storage", () => ({ getSettingsDirectoryPath: vi.fn().mockResolvedValue("/test/settings/path"), getTaskDirectoryPath: vi.fn().mockResolvedValue("/test/task/path"), getGlobalStoragePath: vi.fn().mockResolvedValue("/test/storage/path"), // Deletion resolves the tasks directory before it removes a history // file, so the harness must provide the passthrough base path. getStorageBasePath: vi.fn().mockImplementation((defaultPath: string) => defaultPath), })) vi.mock("@modelcontextprotocol/sdk/types.js", () => ({ CallToolResultSchema: {}, ListResourcesResultSchema: {}, ListResourceTemplatesResultSchema: {}, ListToolsResultSchema: {}, ReadResourceResultSchema: {}, ErrorCode: { InvalidRequest: "InvalidRequest", MethodNotFound: "MethodNotFound", InternalError: "InternalError", }, McpError: class McpError extends Error { code: string constructor(code: string, message: string) { super(message) this.code = code this.name = "McpError" } }, })) // Remove duplicate mock - it's already defined below. const mockAddCustomInstructions = vi.fn().mockResolvedValue("Combined instructions") ;(vi.mocked(await import("../../prompts/sections/custom-instructions")) as any).addCustomInstructions = mockAddCustomInstructions vi.mock("delay", () => { const delayFn = (_ms: number) => Promise.resolve() delayFn.createDelay = () => delayFn delayFn.reject = () => Promise.reject(new Error("Delay rejected")) delayFn.range = () => Promise.resolve() return { default: delayFn } }) // MCP-related modules are mocked once above (lines 87-109). vi.mock("@modelcontextprotocol/sdk/client/index.js", () => ({ Client: vi.fn().mockImplementation(function () { return { connect: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), listTools: vi.fn().mockResolvedValue({ tools: [] }), callTool: vi.fn().mockResolvedValue({ content: [] }), } }), })) vi.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({ StdioClientTransport: vi.fn().mockImplementation(function () { return { connect: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), } }), })) vi.mock("vscode", () => ({ ExtensionContext: vi.fn(), OutputChannel: vi.fn(), WebviewView: vi.fn(), Disposable: { from: (...subscriptions: vscode.Disposable[]) => makeCompositeDisposable(...subscriptions) }, EventEmitter: vi.fn().mockImplementation(function () { return { event: vi.fn(), fire: vi.fn(), dispose: vi.fn(), } }), Uri: { joinPath: vi.fn(), file: vi.fn(), }, CodeActionKind: { QuickFix: { value: "quickfix" }, RefactorRewrite: { value: "refactor.rewrite" }, }, ViewColumn: { Active: -1 }, commands: { getCommands: vi.fn().mockResolvedValue([]), executeCommand: vi.fn().mockResolvedValue(undefined), }, window: { createWebviewPanel: vi.fn(), showInformationMessage: vi.fn(), showWarningMessage: vi.fn().mockResolvedValue(undefined), showErrorMessage: vi.fn(), showSaveDialog: vi.fn(), showOpenDialog: vi.fn(), activeTextEditor: undefined, onDidChangeActiveTextEditor: vi.fn(() => ({ dispose: vi.fn() })), }, workspace: { getConfiguration: vi.fn().mockReturnValue({ get: vi.fn().mockReturnValue([]), update: vi.fn(), }), getWorkspaceFolder: vi.fn(), onDidChangeConfiguration: vi.fn().mockImplementation(() => { return { dispose: vi.fn(), } }), onDidSaveTextDocument: vi.fn(() => ({ dispose: vi.fn() })), onDidChangeTextDocument: vi.fn(() => ({ dispose: vi.fn() })), onDidOpenTextDocument: vi.fn(() => ({ dispose: vi.fn() })), onDidCloseTextDocument: vi.fn(() => ({ dispose: vi.fn() })), }, env: { uriScheme: "vscode", language: "en", appName: "Visual Studio Code", }, ExtensionMode: { Production: 1, Development: 2, Test: 3, }, version: "1.85.0", })) vi.mock("../../../utils/tts", () => ({ playTts: vi.fn().mockResolvedValue(undefined), setTtsEnabled: vi.fn(), setTtsSpeed: vi.fn(), stopTts: vi.fn(), })) vi.mock("../../../integrations/misc/open-file", () => ({ openFile: vi.fn().mockResolvedValue(undefined), })) vi.mock("../../../integrations/misc/image-handler", () => ({ openImage: vi.fn().mockResolvedValue(undefined), saveImage: vi.fn().mockResolvedValue(undefined), })) vi.mock("../../mentions", () => ({ openMention: vi.fn().mockResolvedValue(undefined), })) vi.mock("../../../utils/export", () => ({ resolveDefaultSaveUri: vi.fn().mockResolvedValue({ fsPath: "/test/default-export.yaml" }), saveLastExportPath: vi.fn().mockResolvedValue(undefined), })) 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("../../../api", () => ({ buildApiHandler: vi.fn(), })) vi.mock("../../prompts/system", () => ({ SYSTEM_PROMPT: vi.fn().mockImplementation(async () => "mocked system prompt"), codeMode: "code", })) vi.mock("../../../integrations/workspace/WorkspaceTracker", () => { return { default: vi.fn().mockImplementation(function () { return { initializeFilePaths: vi.fn().mockResolvedValue(undefined), dispose: vi.fn(), } }), } }) vi.mock("../../task/Task", () => ({ Task: vi.fn().mockImplementation(function (options: TaskOptions) { return { api: undefined, abortTask: vi.fn(), dispose: vi.fn().mockResolvedValue(undefined), handleWebviewAskResponse: vi.fn(), clineMessages: [], apiConversationHistory: [], overwriteClineMessages: vi.fn(), overwriteApiConversationHistory: vi.fn(), getTaskNumber: vi.fn().mockReturnValue(0), setTaskNumber: vi.fn(), setParentTask: vi.fn(), setRootTask: vi.fn(), taskId: options?.historyItem?.id || "test-task-id", emit: vi.fn(), } }), })) vi.mock("../../../integrations/misc/extract-text", () => ({ extractTextFromFile: vi.fn().mockImplementation(async (_filePath: string) => { const content = "const x = 1;\nconst y = 2;\nconst z = 3;" const lines = content.split("\n") return lines.map((line, index) => `${index + 1} | ${line}`).join("\n") }), })) vi.mock("../../../api/providers/fetchers/modelCache", () => ({ getModels: vi.fn().mockResolvedValue({}), flushModels: vi.fn(), getModelsFromCache: vi.fn().mockReturnValue(undefined), })) vi.mock("../../../api/providers/fetchers/lmstudio", () => ({ hasLoadedFullDetails: vi.fn().mockReturnValue(false), forceFullModelDetailsLoad: vi.fn().mockResolvedValue(undefined), })) vi.mock("../../../services/zoo-code-auth", () => ({ getZooCodeBaseUrl: vi.fn(() => "https://www.zoocode.dev"), getCachedZooCodeToken: vi.fn(), handleAuthCallback: vi.fn(), setZooCodeUserInfo: vi.fn(), disconnectZooCode: vi.fn(), })) vi.mock("../../../shared/modes", () => ({ modes: [ { slug: "code", name: "Code Mode", roleDefinition: "You are a code assistant", groups: ["read", "edit"], }, { slug: "architect", name: "Architect Mode", roleDefinition: "You are an architect", groups: ["read", "edit"], }, { slug: "ask", name: "Ask Mode", roleDefinition: "You are a helpful assistant", groups: ["read"], }, ], getModeBySlug: vi.fn().mockReturnValue({ slug: "code", name: "Code Mode", roleDefinition: "You are a code assistant", groups: ["read", "edit"], }), getGroupName: vi.fn().mockImplementation((group: string) => { // Return appropriate group names for different tool groups switch (group) { case "read": return "Read Tools" case "edit": return "Edit Tools" case "mcp": return "MCP Tools" default: return "General Tools" } }), defaultModeSlug: "code", })) vi.mock("../../prompts/system", () => ({ SYSTEM_PROMPT: vi.fn().mockResolvedValue("mocked system prompt"), codeMode: "code", })) vi.mock("../../../api", () => ({ buildApiHandler: vi.fn().mockReturnValue({ getModel: vi.fn().mockReturnValue({ id: "claude-3-sonnet", }), }), })) vi.mock("../../../integrations/misc/extract-text", () => ({ extractTextFromFile: vi.fn().mockImplementation(async (_filePath: string) => { const content = "const x = 1;\nconst y = 2;\nconst z = 3;" const lines = content.split("\n") return lines.map((line, index) => `${index + 1} | ${line}`).join("\n") }), })) vi.mock("../../../api/providers/fetchers/modelCache", () => ({ getModels: vi.fn().mockResolvedValue({}), flushModels: vi.fn(), getModelsFromCache: vi.fn().mockReturnValue(undefined), })) vi.mock("../diff/strategies/multi-search-replace", () => ({ MultiSearchReplaceDiffStrategy: vi.fn().mockImplementation(function () { return { getToolDescription: () => "test", getName: () => "test-strategy", applyDiff: vi.fn(), } }), })) vi.mock("@roo-code/cloud", () => ({ CloudService: { hasInstance: vi.fn().mockReturnValue(true), get instance() { return { isAuthenticated: vi.fn().mockReturnValue(false), login: vi.fn().mockResolvedValue(undefined), logout: vi.fn().mockResolvedValue(undefined), off: vi.fn(), } }, }, getRooCodeApiUrl: vi.fn().mockReturnValue("https://app.roocode.com"), })) afterAll(() => { vi.restoreAllMocks() }) /** * Minimal profile shape the stalled getProfile double resolves to. The * settings fields are optional so a lookup that resolves name-only (a * profile with no configured provider) also type-checks. */ type StalledProfile = { name: string apiProvider?: string openRouterModelId?: string } /** * Swap the provider's ProviderSettingsManager for a double whose getProfile * stalls until the test resolves it, so tests can mutate view state while * loadViewState is in flight. The double only backs getProfile, the member * loadViewState awaits; the documented @ts-ignore replaces the per-test * suppressions the inlined copies used. */ function stallProviderSettingsProfile(provider: ClineProvider) { let resolveProfile: (value: StalledProfile) => void = () => {} const getProfileSpy = vi.fn(() => { // Only one lookup is resolvable: resolveProfile is bound to the first // promise's resolver, so a second getProfile would strand its promise. // Fail loudly instead of hanging. if (getProfileSpy.mock.calls.length > 1) { throw new Error( "stallProviderSettingsProfile: getProfile called more than once; only one lookup is resolvable", ) } return new Promise((resolve) => (resolveProfile = resolve)) }) // @ts-ignore - Reassign the readonly providerSettingsManager for the test; the double only backs getProfile. provider.providerSettingsManager = { getProfile: getProfileSpy, runExclusiveAcrossInstances: runManagerSectionInline, } // Return a stable wrapper around the closure binding: resolveProfile is // reassigned to the pending promise's resolver once getProfile is called, // so returning the variable directly would hand the test the initial no-op. return { getProfile: getProfileSpy, resolveProfile: (value: StalledProfile) => resolveProfile(value) } } // A same-name profile save joins the manager's cross-instance critical section, so a // double that stubs the manager must still run the callback inline: the real lock does // that whenever no other view holds the section. const runManagerSectionInline = (cb: () => Promise): Promise => cb() // Matches a non-empty segment list that holds only generated text. const noUserSegments = { asymmetricMatch: (value: unknown) => Array.isArray(value) && value.length > 0 && value.every((segment) => segment?.source === "generated"), toString: () => "onlyGeneratedSegments", } // The text equals the joined parts, and only the typed input is a user part. // The generated context holds a mention and stays generated. function expectMixedPayload(call: unknown[], context: string, sources: MentionSegment["source"][]) { const [text, , , options] = call as [string, unknown, unknown, { segments: MentionSegment[] }] const { segments } = options expect(joinSegments(segments)).toBe(text) expect(segments.map((s) => s.source)).toEqual(sources) expect(segments.filter((s) => s.source === "user")).toEqual([{ text: "@/allowed", source: "user" }]) expect(segments.filter((s) => s.source === "generated").some((s) => s.text.includes(context))).toBe(true) expect(segments.filter((s) => s.source === "user").some((s) => s.text.includes("@/generated"))).toBe(false) } // Order-insensitive content comparison for the memento double. A real Memento serializes what // update is handed, so a test may not compare stored state to a caller object by identity; the // comparison has to be by content, and by content that does not depend on key insertion order // (a JSON.stringify comparison silently does depend on it). Two semantic choices are pinned here // rather than discovered later: keys whose value is undefined are ignored, so { a: undefined } // equals {}; nesting compares plain objects by entries and arrays by index; primitives compare // with Object.is, treating NaN as equal to NaN. const mapContentEquals = (a: unknown, b: unknown): boolean => { if (Object.is(a, b)) { return true } if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) { return false } if (Array.isArray(a) || Array.isArray(b)) { if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) { return false } const rightItems = b as readonly unknown[] return a.every((item, position) => mapContentEquals(item, rightItems[position])) } const sortable = (value: object) => Object.entries(value) .filter(([, entry]) => entry !== undefined) .sort(([first], [second]) => first.localeCompare(second)) const left = sortable(a) const right = sortable(b) if (left.length !== right.length) { return false } return left.every((pair, position) => { const [key, value] = pair const [rightKey, rightValue] = right[position] return key === rightKey && mapContentEquals(value, rightValue) }) } describe("ClineProvider", () => { beforeAll(() => { vi.mocked(Task).mockImplementation(function (options: any) { const task: any = { api: undefined, abortTask: vi.fn(), dispose: vi.fn().mockResolvedValue(undefined), handleWebviewAskResponse: vi.fn(), clineMessages: [], apiConversationHistory: [], overwriteClineMessages: vi.fn(), overwriteApiConversationHistory: vi.fn(), getTaskNumber: vi.fn().mockReturnValue(0), setTaskNumber: vi.fn(), setParentTask: vi.fn(), setRootTask: vi.fn(), taskId: options?.historyItem?.id || "test-task-id", emit: vi.fn(), } Object.defineProperty(task, "messageManager", { get: () => new MessageManager(task), }) return task }) }) let defaultTaskOptions: TaskOptions let provider: ClineProvider let mockContext: vscode.ExtensionContext let mockOutputChannel: vscode.OutputChannel let mockWebviewView: any let mockPostMessage: any let updateGlobalStateSpy: any afterEach(() => { // Tests construct providers directly and many never dispose them; clear the // static registry so a leaked instance cannot claim stable view state ids // ahead of a later test. ClineProvider["activeInstances"] = new Set() }) beforeEach(() => { vi.clearAllMocks() if (!TelemetryService.hasInstance()) { TelemetryService.createInstance([]) } const globalState: Record = { mode: "architect", currentApiConfigName: "current-config", } const secrets: Record = {} mockContext = { extensionPath: "/test/path", extensionUri: { fsPath: "/test/path" } as vscode.Uri, globalState: { get: vi.fn().mockImplementation((key: string) => { return globalState[key] }), update: vi.fn().mockImplementation((key: string, value: unknown) => { // A real Memento serializes what it is handed (review comment 4750247491), so the double // stores a snapshot and a later in-place mutation by the caller cannot reach stored state. const snapshot = value && typeof value === "object" ? structuredClone(value) : value ;(globalState as Record)[key] = snapshot return snapshot }), keys: vi.fn().mockImplementation(() => { return Object.keys(globalState) }), }, secrets: { get: vi.fn().mockImplementation((key: string) => { return secrets[key] }), store: vi.fn().mockImplementation((key: string, value: string | undefined) => { return (secrets[key] = value) }), delete: vi.fn().mockImplementation((key: string) => { return delete secrets[key] }), }, workspaceState: { get: vi.fn().mockReturnValue(undefined), update: vi.fn().mockResolvedValue(undefined), keys: vi.fn().mockReturnValue([]), }, subscriptions: [], extension: { packageJSON: { version: "1.0.0" }, }, globalStorageUri: { fsPath: "/test/storage/path", }, } as unknown as vscode.ExtensionContext // Mock CustomModesManager const mockCustomModesManager = { updateCustomMode: vi.fn().mockResolvedValue(undefined), getCustomModes: vi.fn().mockResolvedValue([]), dispose: vi.fn(), } // Mock output channel mockOutputChannel = { show: vi.fn(), appendLine: vi.fn(), clear: vi.fn(), dispose: vi.fn(), } as unknown as vscode.OutputChannel // Mock webview mockPostMessage = vi.fn() mockWebviewView = { webview: { postMessage: mockPostMessage, html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), cspSource: "vscode-webview://test-csp-source", }, visible: true, show: vi.fn(), onDidDispose: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), onDidChangeVisibility: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), } provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Start without the snapshot from initial fixture storage; profile tests seed their own mapping. provider["initialModeConfigIds"] = Promise.resolve({}) defaultTaskOptions = { provider, apiConfiguration: { apiProvider: providerIdentifiers.openrouter, }, } // @ts-ignore - Access private property for testing updateGlobalStateSpy = vi.spyOn(provider.contextProxy, "setValue") // @ts-ignore - Accessing private property for testing. provider.customModesManager = mockCustomModesManager // Mock getMcpHub method for generateSystemPrompt provider.getMcpHub = vi.fn().mockReturnValue({ listTools: vi.fn().mockResolvedValue([]), callTool: vi.fn().mockResolvedValue({ content: [] }), listResources: vi.fn().mockResolvedValue([]), readResource: vi.fn().mockResolvedValue({ contents: [] }), getAllServers: vi.fn().mockReturnValue([]), }) }) test("exposes only the explicitly associated workspace without a fallback", () => { provider["currentWorkspacePath"] = "/workspace-a" expect(provider.workspacePath).toBe("/workspace-a") provider["currentWorkspacePath"] = "/workspace-b" expect(provider.workspacePath).toBe("/workspace-b") provider["currentWorkspacePath"] = undefined expect(provider.workspacePath).toBeUndefined() }) test("constructor initializes correctly", () => { expect(provider).toBeInstanceOf(ClineProvider) // Since getVisibleInstance returns the last instance where view.visible is true // @ts-ignore - accessing private property for testing provider.view = mockWebviewView expect(ClineProvider.getVisibleInstance()).toBe(provider) }) describe("getInstanceForView", () => { it("returns the instance that owns the given view", async () => { await provider.resolveWebviewView(mockWebviewView) expect(ClineProvider.getInstanceForView(mockWebviewView)).toBe(provider) }) it("returns undefined when no live instance owns the view", () => { expect(ClineProvider.getInstanceForView({} as vscode.WebviewView)).toBeUndefined() }) it("ignores an instance whose disposal is already in flight", async () => { await provider.resolveWebviewView(mockWebviewView) // Hold the disposal after _disposed is set: mcpHub.unregisterClient is awaited // inside dispose(), so the view is still registered while the provider is // already closing. The double is structural because only unregisterClient is // reached before the gate is released. let releaseDisposal!: () => void const disposalGate = new Promise((resolve) => { releaseDisposal = resolve }) Object.assign(provider, { mcpHub: { unregisterClient: () => disposalGate } }) const disposal = provider.dispose() await vi.waitFor(() => expect(provider["_disposed"]).toBe(true)) // Still registered at this moment: the undefined below must come from the // disposal gate inside getInstanceForView, not from the registry having // already dropped the instance. expect(ClineProvider.getAllInstances()).toContain(provider) expect(provider["view"]).toBe(mockWebviewView) expect(ClineProvider.getInstanceForView(mockWebviewView)).toBeUndefined() releaseDisposal() await disposal }) }) test("reports an unresolved webview as not visible", () => { expect(provider.isViewVisible).toBe(false) }) describe("manual context condensation", () => { beforeEach(async () => { vi.spyOn(await import("../../../i18n"), "t").mockImplementation((key) => key) }) afterEach(() => { vi.mocked(t).mockRestore() }) // A partial Task double: condenseTaskContext reads only taskId, abort, abandoned, and condenseContext. const registerTask = ( condenseContext: () => Promise, state: { abort?: boolean; abandoned?: boolean } = {}, ) => { const task = { taskId: "selected-task", abandoned: false, abort: false, condenseContext, ...state } Object.assign(provider, { taskRegistry: new TaskRegistry() }) provider["taskRegistry"].push(task as unknown as Task) return task } const expectResponse = (postMessage: ReturnType, taskId: string) => expect(postMessage).toHaveBeenCalledExactlyOnceWith({ type: "condenseTaskContextResponse", text: taskId }) it("responds and reports an unavailable task", async () => { const postMessage = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) Object.assign(provider, { taskRegistry: new TaskRegistry() }) await provider.condenseTaskContext("missing-task") expectResponse(postMessage, "missing-task") expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( "common:errors.condense_task_unavailable", ) }) it.each([new Error("summary request exploded"), "provider unavailable"])( "responds and reports an unexpected throw: %s", async (error) => { const postMessage = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) registerTask(vi.fn().mockRejectedValue(error)) await provider.condenseTaskContext("selected-task") expectResponse(postMessage, "selected-task") expect(t).toHaveBeenCalledWith("common:errors.condense_failed_with_reason", { reason: error instanceof Error ? error.message : error, }) expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( "common:errors.condense_failed_with_reason", ) }, ) it.each(["success", "expected rejection"])("responds without a duplicate popup after %s", async (outcome) => { const postMessage = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) const reported = vi.fn() const condenseContext = vi.fn(async () => { reported(outcome === "success" ? "condense_context" : "condense_context_error") }) registerTask(condenseContext) await provider.condenseTaskContext("selected-task") expect(reported).toHaveBeenCalledExactlyOnceWith( outcome === "success" ? "condense_context" : "condense_context_error", ) expect(condenseContext).toHaveBeenCalledOnce() expectResponse(postMessage, "selected-task") expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() }) it.each(["abort", "abandoned"] as const)("ends the wait without a popup after %s", async (state) => { const postMessage = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) const task = registerTask(vi.fn()) task.condenseContext = vi.fn(async () => { task[state] = true throw new Error("task selected-task aborted") }) await provider.condenseTaskContext("selected-task") expectResponse(postMessage, "selected-task") expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() }) it("posts the response only after condensation settles", async () => { const postMessage = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) let settle: () => void = () => {} registerTask(() => new Promise((resolve) => (settle = resolve))) const pending = provider.condenseTaskContext("selected-task") await Promise.resolve() expect(postMessage).not.toHaveBeenCalled() settle() await pending expectResponse(postMessage, "selected-task") }) it("does not reject when the final response cannot be posted", async () => { vi.spyOn(provider, "postMessageToWebview").mockRejectedValue(new Error("webview disposed")) registerTask(vi.fn().mockResolvedValue(undefined)) await expect(provider.condenseTaskContext("selected-task")).resolves.toBeUndefined() }) }) describe("instance registry", () => { let originalInstances: Set beforeEach(() => { originalInstances = ClineProvider["activeInstances"] ClineProvider["activeInstances"] = new Set() }) afterEach(() => { ClineProvider["activeInstances"] = originalInstances }) const newProvider = () => new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), provider.webviewFocusTracker, ) it("lists a provider from the moment it is constructed, so extension-wide broadcasts reach it", () => { const created = newProvider() expect(ClineProvider.getAllInstances()).toEqual([created]) }) it("lists every provider that is open, in the sidebar or an editor tab", () => { const first = newProvider() const second = newProvider() expect(ClineProvider.getAllInstances()).toEqual([first, second]) }) it("stops listing a provider once it is disposed, so broadcasts do not reach a closed view", async () => { const kept = newProvider() const closed = newProvider() await closed.dispose() expect(ClineProvider.getAllInstances()).toEqual([kept]) }) }) describe("Add to Context destination", () => { let originalInstances: Set let tabProvider: ClineProvider let sidebar: ReturnType let tab: ReturnType let panel: vscode.WebviewPanel let panelState: vscode.EventEmitter function createView() { const messages = makeEventEmitter() const visibility = makeEventEmitter() const disposed = makeEventEmitter() const postMessage = vi.fn<(message: ExtensionMessage) => Promise>().mockResolvedValue(true) const view: vscode.WebviewView = { viewType: ClineProvider.sideBarId, visible: true, webview: { html: "", options: {}, cspSource: "vscode-webview://test-csp-source", asWebviewUri: (uri) => uri, postMessage, onDidReceiveMessage: messages.event, }, onDidChangeVisibility: visibility.event, onDidDispose: disposed.event, show: vi.fn(), } return { view, messages, visibility, disposed, postMessage } } beforeEach(async () => { originalInstances = ClineProvider["activeInstances"] ClineProvider["activeInstances"] = new Set([provider]) tabProvider = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), provider.webviewFocusTracker, ) sidebar = createView() tab = createView() panelState = makeEventEmitter() panel = { viewType: ClineProvider.tabPanelId, title: "Zoo Code", viewColumn: undefined, webview: tab.view.webview, options: {}, active: false, visible: true, onDidChangeViewState: panelState.event, onDidDispose: tab.disposed.event, reveal: vi.fn(), dispose: vi.fn(), } await provider.resolveWebviewView(sidebar.view) await tabProvider.resolveWebviewView(panel) sidebar.postMessage.mockClear() tab.postMessage.mockClear() }) afterEach(async () => { await provider.dispose() await tabProvider.dispose() ClineProvider["activeInstances"] = originalInstances }) const addSelection = async () => { const target = await resolveChatProvider(provider.webviewFocusTracker) await target?.handleCodeAction("addToContext", "ADD_TO_CONTEXT", { selectedText: "selected code" }) } test("reports current visibility independently of panel activation", () => { expect(provider.isViewVisible).toBe(true) expect(tabProvider.isViewVisible).toBe(true) expect(panel.active).toBe(false) Object.defineProperty(sidebar.view, "visible", { value: false, configurable: true }) Object.defineProperty(panel, "visible", { value: false, configurable: true }) expect(provider.isViewVisible).toBe(false) expect(tabProvider.isViewVisible).toBe(false) Object.defineProperty(sidebar.view, "visible", { value: true, configurable: true }) Object.defineProperty(panel, "visible", { value: true, configurable: true }) expect(provider.isViewVisible).toBe(true) expect(tabProvider.isViewVisible).toBe(true) }) test("follows chat focus rather than registration order after returning to the source editor", async () => { sidebar.messages.fire({ type: "webviewDidFocus" }) // Both views stay visible while the source editor has focus. expect(ClineProvider.getVisibleInstance()).toBe(tabProvider) await addSelection() expect(sidebar.postMessage).toHaveBeenCalledWith({ type: "invoke", invoke: "setChatBoxMessage", text: expect.stringContaining("selected code"), // Generated context has no user segment. segments: noUserSegments, }) expect(sidebar.postMessage).toHaveBeenCalledWith({ type: "action", action: "focusInput" }) expect(tab.postMessage).not.toHaveBeenCalled() sidebar.postMessage.mockClear() tab.messages.fire({ type: "webviewDidFocus" }) await addSelection() expect(tab.postMessage).toHaveBeenCalledTimes(2) expect(sidebar.postMessage).not.toHaveBeenCalled() }) test("remembers explicit chat focus after panel deactivation and background visibility events", async () => { tab.messages.fire({ type: "webviewDidFocus" }) Object.defineProperty(panel, "active", { value: false, configurable: true }) panelState.fire({ webviewPanel: panel }) sidebar.visibility.fire() sidebar.postMessage.mockClear() tab.postMessage.mockClear() await addSelection() expect(tab.postMessage).toHaveBeenCalledTimes(2) expect(sidebar.postMessage).not.toHaveBeenCalled() }) test.each([ { change: "activation", property: "active", value: true }, { change: "visibility", property: "visible", value: false }, { change: "position", property: "viewColumn", value: 2 }, ])("panel $change does not overwrite a more recent sidebar interaction", async ({ property, value }) => { Object.defineProperty(panel, "active", { value: property !== "active", configurable: true }) tab.messages.fire({ type: "webviewDidFocus" }) sidebar.messages.fire({ type: "webviewDidFocus" }) Object.defineProperty(panel, property, { value, configurable: true }) panelState.fire({ webviewPanel: panel }) expect(provider.webviewFocusTracker.getLastActiveProvider()).toBe(provider) sidebar.postMessage.mockClear() tab.postMessage.mockClear() await addSelection() expect(sidebar.postMessage).toHaveBeenCalledTimes(2) expect(tab.postMessage).not.toHaveBeenCalled() }) it.each([ { message: { type: "diagnosticsResponse", requestId: "request-1", diagnostics: { capturedAt: "2026-11-01T00:00:00.000Z" }, }, routed: true, }, { message: { type: "diagnosticsResponse", diagnostics: { capturedAt: "2026-11-01T00:00:00.000Z" } }, routed: false, }, { message: { type: "themeFixtureProbeResponse", requestId: "request-1" }, routed: false }, ] satisfies { message: WebviewMessage; routed: boolean }[])( "routes $message to the diagnostics broker only when addressed", async ({ message, routed }) => { const handler = vi .spyOn(await import("../webviewMessageHandler"), "webviewMessageHandler") .mockResolvedValue(undefined) const resolve = vi.spyOn(provider["diagnosticsRequestBroker"], "resolve") try { sidebar.messages.fire(message) if (routed) { expect(resolve).toHaveBeenCalledExactlyOnceWith("request-1", message.diagnostics) expect(handler).not.toHaveBeenCalled() } else { expect(resolve).not.toHaveBeenCalled() expect(handler).toHaveBeenCalledOnce() expect(handler.mock.calls[0].slice(0, 2)).toEqual([provider, message]) } } finally { handler.mockRestore() resolve.mockRestore() } }, ) test("background messages reach the provider handler without changing the last focused chat", async () => { sidebar.messages.fire({ type: "webviewDidFocus" }) const handler = vi .spyOn(await import("../webviewMessageHandler"), "webviewMessageHandler") .mockResolvedValue(undefined) try { const message: WebviewMessage = { type: "themeFixtureProbeResponse" } tab.messages.fire(message) expect(handler).toHaveBeenCalledOnce() expect(handler.mock.calls[0].slice(0, 2)).toEqual([tabProvider, message]) expect(provider.webviewFocusTracker.getLastActiveProvider()).toBe(provider) } finally { handler.mockRestore() } await addSelection() expect(sidebar.postMessage).toHaveBeenCalledTimes(2) expect(tab.postMessage).not.toHaveBeenCalled() }) test("waits for explicit focus even when a panel is already active during registration", () => { const state = makeEventEmitter() const activePanel = { ...panel, active: true, onDidChangeViewState: state.event } const tracker = new WebviewFocusTracker() tracker.init(tabProvider, activePanel) expect(tracker.getLastActiveProvider()).toBeUndefined() state.fire({ webviewPanel: activePanel }) expect(tracker.getLastActiveProvider()).toBeUndefined() tab.messages.fire({ type: "webviewDidFocus" }) expect(tracker.getLastActiveProvider()).toBe(tabProvider) tracker.dispose() expect(tracker.getLastActiveProvider()).toBeUndefined() tab.messages.fire({ type: "webviewDidFocus" }) expect(tracker.getLastActiveProvider()).toBeUndefined() }) test("closing a different chat does not clear the last focused chat", async () => { tab.messages.fire({ type: "webviewDidFocus" }) sidebar.disposed.fire() await addSelection() expect(tab.postMessage).toHaveBeenCalledTimes(2) expect(sidebar.postMessage).not.toHaveBeenCalled() }) test("tracks focus using only message and disposal events", () => { const tracker = new WebviewFocusTracker() const messages = makeEventEmitter() const disposed = makeEventEmitter() tracker.init(provider, { webview: { onDidReceiveMessage: messages.event }, onDidDispose: disposed.event, }) messages.fire({ type: "webviewDidFocus" }) expect(tracker.getLastActiveProvider()).toBe(provider) disposed.fire() expect(tracker.getLastActiveProvider()).toBeUndefined() messages.fire({ type: "webviewDidFocus" }) expect(tracker.getLastActiveProvider()).toBeUndefined() tracker.dispose() }) test("tracker instances keep focus state and disposal independent", () => { const first = new WebviewFocusTracker() const second = new WebviewFocusTracker() const firstView = createView() const secondView = createView() const firstRegistration = first.init(provider, firstView.view) second.init(tabProvider, secondView.view) firstView.messages.fire({ type: "webviewDidFocus" }) secondView.messages.fire({ type: "webviewDidFocus" }) expect(first.getLastActiveProvider()).toBe(provider) expect(second.getLastActiveProvider()).toBe(tabProvider) firstRegistration.dispose() firstRegistration.dispose() firstView.messages.fire({ type: "webviewDidFocus" }) expect(first.getLastActiveProvider()).toBeUndefined() expect(second.getLastActiveProvider()).toBe(tabProvider) first.dispose() second.dispose() second.dispose() secondView.messages.fire({ type: "webviewDidFocus" }) expect(second.getLastActiveProvider()).toBeUndefined() }) test("preserves the visible-provider fallback when no chat has been focused", async () => { await addSelection() expect(tab.postMessage).toHaveBeenCalledTimes(2) expect(sidebar.postMessage).not.toHaveBeenCalled() }) test.each(["sidebar", "tab"])( "falls back to the visible chat when the last focused %s is hidden", async (source) => { const hidden = source === "sidebar" ? sidebar : tab const visible = source === "sidebar" ? tab : sidebar hidden.messages.fire({ type: "webviewDidFocus" }) Object.defineProperty(source === "sidebar" ? sidebar.view : panel, "visible", { value: false, configurable: true, }) const target = await resolveChatProvider(provider.webviewFocusTracker) expect(target).toBe(source === "sidebar" ? tabProvider : provider) await target?.handleCodeAction("addToContext", "ADD_TO_CONTEXT", { selectedText: "selected code" }) expect(hidden.postMessage).not.toHaveBeenCalled() expect(visible.postMessage).toHaveBeenCalledWith({ type: "invoke", invoke: "setChatBoxMessage", text: expect.stringContaining("selected code"), // Generated context is never the authorized substring. segments: noUserSegments, }) expect(visible.postMessage).toHaveBeenCalledWith({ type: "action", action: "focusInput" }) expect(vscode.commands.executeCommand).not.toHaveBeenCalled() }, ) test.each(["sidebar", "tab"])( "opens the sidebar when the last focused %s and all other chats are hidden", async (source) => { const focused = source === "sidebar" ? sidebar : tab focused.messages.fire({ type: "webviewDidFocus" }) Object.defineProperty(sidebar.view, "visible", { value: false, configurable: true }) Object.defineProperty(panel, "visible", { value: false, configurable: true }) vi.mocked(vscode.commands.executeCommand).mockImplementationOnce(async () => { Object.defineProperty(sidebar.view, "visible", { value: true, configurable: true }) }) const target = await resolveChatProvider(provider.webviewFocusTracker) expect(target).toBe(provider) await target?.handleCodeAction("addToContext", "ADD_TO_CONTEXT", { selectedText: "selected code" }) expect(vscode.commands.executeCommand).toHaveBeenCalledExactlyOnceWith( `${ClineProvider.sideBarId}.focus`, ) expect(sidebar.postMessage).toHaveBeenCalledWith({ type: "invoke", invoke: "setChatBoxMessage", text: expect.stringContaining("selected code"), // Generated context is never the authorized substring. segments: noUserSegments, }) expect(tab.postMessage).not.toHaveBeenCalled() expect(panel.reveal).not.toHaveBeenCalled() }, ) test("remembers the last focused chat across hiding and showing it without another interaction", async () => { sidebar.messages.fire({ type: "webviewDidFocus" }) Object.defineProperty(sidebar.view, "visible", { value: false, configurable: true }) expect(await resolveChatProvider(provider.webviewFocusTracker)).toBe(tabProvider) expect(provider.webviewFocusTracker.getLastActiveProvider()).toBe(provider) Object.defineProperty(sidebar.view, "visible", { value: true, configurable: true }) expect(await resolveChatProvider(provider.webviewFocusTracker)).toBe(provider) }) test("preserves single-view behavior", async () => { await tabProvider.dispose() await addSelection() expect(sidebar.postMessage).toHaveBeenCalledTimes(2) }) test("preserves the sidebar fallback when the last focused tab is disposed", async () => { tab.messages.fire({ type: "webviewDidFocus" }) await tabProvider.dispose() Object.defineProperty(sidebar.view, "visible", { value: false, configurable: true }) vi.mocked(vscode.commands.executeCommand).mockImplementationOnce(async () => { Object.defineProperty(sidebar.view, "visible", { value: true, configurable: true }) }) await addSelection() expect(vscode.commands.executeCommand).toHaveBeenCalledWith(`${ClineProvider.sideBarId}.focus`) expect(sidebar.postMessage).toHaveBeenCalledTimes(2) expect(tab.postMessage).not.toHaveBeenCalled() }) test("forgets a disposed sidebar webview even while its provider remains registered", async () => { sidebar.messages.fire({ type: "webviewDidFocus" }) sidebar.disposed.fire() expect(provider.webviewFocusTracker.getLastActiveProvider()).toBeUndefined() await addSelection() expect(tab.postMessage).toHaveBeenCalledTimes(2) expect(sidebar.postMessage).not.toHaveBeenCalled() }) test.each([ ["explainCode", "EXPLAIN"], ["fixCode", "FIX"], ["improveCode", "IMPROVE"], ] as const)("creates a task only in the last focused chat for %s", async (command, promptType) => { sidebar.messages.fire({ type: "webviewDidFocus" }) const task = new Task(defaultTaskOptions) const sidebarTask = vi.spyOn(provider, "createTask").mockResolvedValue(task) const tabTask = vi.spyOn(tabProvider, "createTask").mockResolvedValue(task) try { const target = provider.webviewFocusTracker.getLastActiveProvider()! await target.handleCodeAction(command, promptType, { selectedText: "selected code" }) expect(sidebarTask).toHaveBeenCalledOnce() expect(sidebarTask).toHaveBeenCalledWith( expect.stringContaining("selected code"), undefined, undefined, { segments: noUserSegments }, ) expect(tabTask).not.toHaveBeenCalled() } finally { sidebarTask.mockRestore() tabTask.mockRestore() } }) test("preserves visible-provider fallback for task creation when no chat has been focused", async () => { const task = new Task(defaultTaskOptions) const sidebarTask = vi.spyOn(provider, "createTask").mockResolvedValue(task) const tabTask = vi.spyOn(tabProvider, "createTask").mockResolvedValue(task) const target = await ClineProvider.getInstance() await target?.handleCodeAction("explainCode", "EXPLAIN", { selectedText: "selected code" }) expect(tabTask).toHaveBeenCalledOnce() expect(sidebarTask).not.toHaveBeenCalled() sidebarTask.mockRestore() tabTask.mockRestore() }) test.each([ ["explainCode", "EXPLAIN"], ["fixCode", "FIX"], ["improveCode", "IMPROVE"], ] as const)( "forwards user-authored code action input as a user segment for %s", async (command, promptType) => { const task = new Task(defaultTaskOptions) const createTask = vi.spyOn(provider, "createTask").mockResolvedValue(task) try { await provider.handleCodeAction(command, promptType, { selectedText: "selected @/generated", userInput: "@/allowed", }) expectMixedPayload(createTask.mock.calls[0], "selected @/generated", [ "generated", "user", "generated", ]) } finally { createTask.mockRestore() } }, ) test("forwards user-authored terminal action input as a user segment", async () => { const task = new Task(defaultTaskOptions) const sidebarTask = vi.spyOn(provider, "createTask").mockResolvedValue(task) const tabTask = vi.spyOn(tabProvider, "createTask").mockResolvedValue(task) try { // No chat focus fired, so the last registered visible provider // (the tab) receives the task, as in the fallback test above. await ClineProvider.handleTerminalAction("terminalFixCommand", "TERMINAL_FIX", { terminalContent: "output @/generated", userInput: "@/allowed", }) expect(tabTask).toHaveBeenCalledOnce() expectMixedPayload(tabTask.mock.calls[0], "output @/generated", ["user", "generated"]) expect(sidebarTask).not.toHaveBeenCalled() } finally { sidebarTask.mockRestore() tabTask.mockRestore() } }) }) test("loads full model details when preparing an LM Studio task", async () => { // buildApiHandler is a module-level mock shared across describes; pin its return value // so this test always passes a handler double to forceFullModelDetailsLoad. const { buildApiHandler } = await import("../../../api") vi.mocked(buildApiHandler).mockReturnValue({ getModel: vi.fn().mockReturnValue({ id: "claude-3-sonnet" }), } as unknown as ReturnType) await provider.performPreparationTasks({ apiConfiguration: { apiProvider: providerIdentifiers.lmstudio, lmStudioBaseUrl: "http://localhost:1234", lmStudioModelId: "test-model", }, } as Task) expect(forceFullModelDetailsLoad).toHaveBeenCalledWith("http://localhost:1234", "test-model", expect.anything()) }) test("does not reload full model details when the LM Studio model is already loaded", async () => { vi.mocked(hasLoadedFullDetails).mockReturnValueOnce(true) await provider.performPreparationTasks({ apiConfiguration: { apiProvider: providerIdentifiers.lmstudio, lmStudioBaseUrl: "http://localhost:1234", lmStudioModelId: "test-model", }, } as Task) expect(forceFullModelDetailsLoad).not.toHaveBeenCalled() }) test("resolveWebviewView hydrates the saved terminalProfile into the process-wide Terminal state", async () => { const setTerminalProfileSpy = vi.spyOn(Terminal, "setTerminalProfile").mockImplementation(() => {}) // Seed the persisted setting so the real getState() returns it during hydration. await (provider as any).contextProxy.setValue("terminalProfile", "Git Bash") await provider.resolveWebviewView(mockWebviewView) // The hydration runs in a getState().then(...) callback, so flush microtasks. await new Promise((resolve) => setImmediate(resolve)) expect(setTerminalProfileSpy).toHaveBeenCalledWith("Git Bash") setTerminalProfileSpy.mockRestore() }) test("resolveWebviewView sets up webview correctly", async () => { await provider.resolveWebviewView(mockWebviewView) expect(mockWebviewView.webview.options).toEqual({ enableScripts: true, localResourceRoots: [mockContext.extensionUri], }) expect(mockWebviewView.webview.html).toContain("") expect(mockWebviewView.webview.html).toContain("Zoo Code") }) describe("logWebviewHiddenDiagnostics", () => { let visibilityCallback: () => void beforeEach(async () => { // Capture the visibility callback registered during resolveWebviewView mockWebviewView.onDidChangeVisibility = vi.fn().mockImplementation((cb: () => void) => { visibilityCallback = cb return { dispose: vi.fn() } }) // @ts-ignore - accessing private property for testing provider.view = mockWebviewView await provider.resolveWebviewView(mockWebviewView) ;(mockOutputChannel.appendLine as ReturnType).mockClear() }) test("does not log when no task is active", () => { // view becomes hidden with no task on the stack Object.defineProperty(mockWebviewView, "visible", { value: false, configurable: true }) visibilityCallback() expect(mockOutputChannel.appendLine).not.toHaveBeenCalled() }) test("does not log when the active task is aborted", async () => { const task = new Task(defaultTaskOptions) Object.defineProperty(task, "taskId", { value: "aborted-task", writable: true }) Object.assign(task, { abort: true }) await provider.addClineToStack(task) Object.defineProperty(mockWebviewView, "visible", { value: false, configurable: true }) visibilityCallback() expect(mockOutputChannel.appendLine).not.toHaveBeenCalled() }) test("logs task state to output channel when an active task is running", async () => { const task = new Task(defaultTaskOptions) Object.defineProperty(task, "taskId", { value: "running-task", writable: true }) await provider.addClineToStack(task) Object.defineProperty(mockWebviewView, "visible", { value: false, configurable: true }) visibilityCallback() expect(mockOutputChannel.appendLine).toHaveBeenCalledWith(expect.stringContaining("running-task")) }) }) describe("webview heartbeat watchdog", () => { let visibilityCallback: () => void let disposeCallback: () => void function trackHtmlAssignments() { let html = mockWebviewView.webview.html const assignHtml = vi.fn((value: string) => { html = value }) Object.defineProperty(mockWebviewView.webview, "html", { configurable: true, get: () => html, set: assignHtml, }) return assignHtml } beforeEach(() => { vi.mocked(vscode.commands.executeCommand).mockReset().mockResolvedValue(undefined) vi.mocked(vscode.window.showWarningMessage).mockResolvedValue(undefined) vi.mocked(vscode.commands.getCommands).mockResolvedValue([ `${ClineProvider.sideBarId}.removeView`, `${ClineProvider.sideBarId}.focus`, ]) // Fake timers must be active before resolveWebviewView so the // watchdog interval is registered on the fake clock. vi.useFakeTimers() mockWebviewView.onDidChangeVisibility = vi.fn().mockImplementation((cb: () => void) => { visibilityCallback = cb return { dispose: vi.fn() } }) // VS Code events are multi-listener: the provider and the focus // tracker each register a disposal callback, and both must fire. const disposeCallbacks: Array<() => void> = [] disposeCallback = () => disposeCallbacks.forEach((cb) => cb()) mockWebviewView.onDidDispose = vi.fn().mockImplementation((cb: () => void) => { disposeCallbacks.push(cb) return { dispose: vi.fn() } }) }) afterEach(async () => { await provider.dispose() vi.useRealTimers() }) test("does not reload the webview while heartbeats are fresh", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html await vi.advanceTimersByTimeAsync(110_000) await webviewMessageHandler(provider, { type: "webviewHeartbeat", timestamp: Date.now() }) await vi.advanceTimersByTimeAsync(60_000) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) }) test("reloads the webview with fresh HTML when the heartbeat is stale and the view is visible", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html await vi.advanceTimersByTimeAsync(120_000) // Reassigning webview.html with a fresh nonce is what forces the reload. expect(mockWebviewView.webview.html).not.toBe(htmlAfterResolve) expect(mockWebviewView.webview.html).toContain("Zoo Code") }) test.each([ { age: 89_999, reloads: 0 }, { age: 90_000, reloads: 0 }, { age: 90_001, reloads: 1 }, ])("at heartbeat age $age ms performs $reloads reloads", async ({ age, reloads }) => { await provider.resolveWebviewView(mockWebviewView) const assignHtml = trackHtmlAssignments() // Keep the next tick ordinary while placing heartbeat age exactly on // either side of the stale threshold at that tick. provider["lastWebviewHeartbeatAt"] = Date.now() + 60_000 - age await vi.advanceTimersByTimeAsync(60_000) expect(assignHtml).toHaveBeenCalledTimes(reloads) }) test.each([ { gap: 89_999, reloads: 1 }, { gap: 90_000, reloads: 1 }, { gap: 90_001, reloads: 0 }, ])("at watchdog tick gap $gap ms performs $reloads reloads", async ({ gap, reloads }) => { await provider.resolveWebviewView(mockWebviewView) const assignHtml = trackHtmlAssignments() // The heartbeat is stale in every row; only the suspend-gap guard // can suppress recovery. No wall-clock jumps or extra ticks mask it. provider["lastWebviewHeartbeatAt"] = Date.now() - 120_000 provider["lastWebviewWatchdogTickAt"] = Date.now() + 60_000 - gap await vi.advanceTimersByTimeAsync(60_000) expect(assignHtml).toHaveBeenCalledTimes(reloads) }) test.each(["none", "disposed", "epoch"] as const)( "checks only the %s post-await recovery guard", async (guard) => { await provider.resolveWebviewView(mockWebviewView) const assignHtml = trackHtmlAssignments() let finishReload: (html: string) => void = () => { throw new Error("Recovery HTML generation has not started") } provider["getWebviewHtml"] = vi.fn( () => new Promise((resolve) => { finishReload = resolve }), ) const recovery = provider["reloadWebviewForRecovery"]() // Change one field only: real dispose/re-resolve paths change // multiple fields and would let other guards mask this one. if (guard === "disposed") provider["_disposed"] = true if (guard === "epoch") provider["webviewRecoveryEpoch"]++ try { finishReload("recovered-html") await recovery expect(assignHtml).toHaveBeenCalledTimes(guard === "none" ? 1 : 0) if (guard === "none") expect(mockWebviewView.webview.html).toBe("recovered-html") } finally { // Allow the regular afterEach to dispose the provider's resources. provider["_disposed"] = false } }, ) test("grants a new grace window after recovery and caps reloads until sustained heartbeats", async () => { await provider.resolveWebviewView(mockWebviewView) const assignHtml = trackHtmlAssignments() await vi.advanceTimersByTimeAsync(120_000) expect(assignHtml).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(60_000) expect(assignHtml).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(180_000) expect(assignHtml).toHaveBeenCalledTimes(3) const log = vi.spyOn(provider, "log") // Visibility changes and host suspension grant grace, but cannot // replenish attempts for a renderer that has never responded. visibilityCallback() vi.setSystemTime(Date.now() + 120_000) await vi.advanceTimersByTimeAsync(600_000) expect(assignHtml).toHaveBeenCalledTimes(3) expect(log).not.toHaveBeenCalledWith(expect.stringContaining("Webview heartbeat stale")) await webviewMessageHandler(provider, { type: "webviewHeartbeat" }) await vi.advanceTimersByTimeAsync(120_000) expect(assignHtml).toHaveBeenCalledTimes(3) // One mount heartbeat is insufficient: a new healthy window must // span a full minute of periodic heartbeats before replenishing. const attempts = provider["webviewRecoveryAttempts"] expect(attempts).toBe(3) provider.updateWebviewHeartbeat() expect(provider["webviewRecoveryAttempts"]).toBe(attempts) await vi.advanceTimersByTimeAsync(30_000) provider.updateWebviewHeartbeat() expect(provider["webviewRecoveryAttempts"]).toBe(attempts) await vi.advanceTimersByTimeAsync(30_000) provider.updateWebviewHeartbeat() expect(provider["webviewRecoveryAttempts"]).toBe(0) await vi.advanceTimersByTimeAsync(120_000) expect(assignHtml).toHaveBeenCalledTimes(4) }) test.each([false, true])( "recreates only the failed sidebar host, retaining its task and budget (interrupted: %s)", async (interrupted) => { await provider.resolveWebviewView(mockWebviewView) const task = new Task(defaultTaskOptions) Object.assign(task, { abort: interrupted }) provider["taskRegistry"].push(task) const evict = vi.spyOn(provider, "evictCurrentTask") const remove = vi.spyOn(provider, "removeClineFromStack") const replacement = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() if (command === `${ClineProvider.sideBarId}.focus`) await provider.resolveWebviewView(replacement) }) await vi.advanceTimersByTimeAsync(120_000) expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith(`${ClineProvider.sideBarId}.removeView`) await vi.advanceTimersByTimeAsync(10_000) expect(vscode.commands.executeCommand).toHaveBeenCalledWith(`${ClineProvider.sideBarId}.removeView`) expect(vscode.commands.executeCommand).toHaveBeenCalledWith(`${ClineProvider.sideBarId}.focus`, { preserveFocus: true, }) expect(provider["view"]).toBe(replacement) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(provider.getCurrentTask()).toBe(task) expect(evict).not.toHaveBeenCalled() expect(remove).not.toHaveBeenCalled() expect(task.dispose).not.toHaveBeenCalled() expect(task.abortTask).not.toHaveBeenCalled() }, ) test.each(["HTML generation", "state hydration"] as const)( "preserves normal sidebar startup rejection for failed %s outside recovery", async (stage) => { const error = new Error("initial view failed") provider["getWebviewHtml"] = vi.fn().mockResolvedValue("initial-html") if (stage === "HTML generation") vi.mocked(provider["getWebviewHtml"]).mockRejectedValueOnce(error) else vi.spyOn(provider, "getState").mockRejectedValueOnce(error) await expect(provider.resolveWebviewView(mockWebviewView)).rejects.toBe(error) expect(provider["webviewWatchdogInterval"]).toBeNull() expect(provider["webviewRecoveryAttempts"]).toBe(0) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }, ) describe("sidebar replacement timing", () => { beforeEach(async () => { const actual = await vi.importActual("p-wait-for") vi.mocked(pWaitFor).mockImplementation(actual.default) }) afterEach(() => { vi.mocked(pWaitFor).mockReset().mockResolvedValue(undefined) }) function removeSidebarOnCommand() { vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() }) } test.each([false, true])( "explicit retry renews a timed-out sidebar incident after ambiguous reopen: %s", async (reopened) => { await provider.resolveWebviewView(mockWebviewView) const task = new Task(defaultTaskOptions) Object.assign(task, { abort: true }) provider["taskRegistry"].push(task) const remove = vi.spyOn(provider, "removeClineFromStack") let choose: (value: string) => void = () => { throw new Error("No warning") } vi.mocked(vscode.window.showWarningMessage).mockImplementation( vi.fn().mockReturnValue( new Promise((resolve) => { choose = resolve }), ), ) removeSidebarOnCommand() await vi.advanceTimersByTimeAsync(140_000) expect(provider["pendingSidebarRecovery"]).toBe(true) expect(provider["webviewRecoveryAttempts"]).toBe(3) if (reopened) { await provider.resolveWebviewView({ ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" }, }) expect(provider["webviewRecoveryAttempts"]).toBe(3) expect(provider.getCurrentTask()).toBe(task) } const healthy = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() if (command === `${ClineProvider.sideBarId}.focus`) await provider.resolveWebviewView(healthy) }) choose("Retry Interface Recovery") await vi.advanceTimersByTimeAsync(50) expect(provider["view"]).toBe(healthy) expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(provider["webviewRecoveryRequestGeneration"]).toBe(1) expect(provider["webviewRecoveryFailureReported"]).toBe(false) expect(provider["webviewRecoveryStopLogged"]).toBe(false) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(provider.getCurrentTask()).toBe(task) expect(remove).not.toHaveBeenCalled() expect(task.abortTask).not.toHaveBeenCalled() expect(task.dispose).not.toHaveBeenCalled() expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith("workbench.action.reloadWindow") }, ) test.each(["focus failure", "replacement timeout"] as const)( "explicit retry reports %s without an automatic retry loop", async (failure) => { await provider.resolveWebviewView(mockWebviewView) removeSidebarOnCommand() await vi.advanceTimersByTimeAsync(140_000) if (failure === "focus failure") vi.mocked(vscode.commands.executeCommand).mockRejectedValue(new Error("focus unavailable")) const retry = provider.retryWebviewRecovery() await vi.advanceTimersByTimeAsync(10_000) await retry expect(provider["webviewRecoveryAttempts"]).toBe(3) expect(provider["pendingSidebarRecovery"]).toBe(failure === "replacement timeout") expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(2) await vi.advanceTimersByTimeAsync(120_000) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(2) }, ) test("warns once after ten seconds without a replacement and releases recovery ownership", async () => { await provider.resolveWebviewView(mockWebviewView) removeSidebarOnCommand() await vi.advanceTimersByTimeAsync(130_000) expect(provider["webviewHostRecoveryInProgress"]).toBe(true) await vi.advanceTimersByTimeAsync(9_999) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() await vi.advanceTimersByTimeAsync(1) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(provider["webviewRecoveryAttempts"]).toBe(3) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(120_000) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) }) test("settles the replacement wait when the provider is disposed", async () => { await provider.resolveWebviewView(mockWebviewView) removeSidebarOnCommand() await vi.advanceTimersByTimeAsync(130_000) expect(provider["webviewHostRecoveryInProgress"]).toBe(true) await provider.dispose() await vi.advanceTimersByTimeAsync(50) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) test.each([5_000, 11_000])( "retains an interrupted task and budget when replacement starts after %s ms", async (delay) => { await provider.resolveWebviewView(mockWebviewView) const task = new Task(defaultTaskOptions) Object.assign(task, { abort: true }) provider["taskRegistry"].push(task) const remove = vi.spyOn(provider, "removeClineFromStack") removeSidebarOnCommand() await vi.advanceTimersByTimeAsync(130_000 + delay) const attempts = delay < 10_000 ? 1 : 3 expect(provider["webviewRecoveryAttempts"]).toBe(attempts) expect(provider["webviewHostRecoveryInProgress"]).toBe(delay < 10_000) const replacement = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } await provider.resolveWebviewView(replacement) await vi.advanceTimersByTimeAsync(50) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(provider["pendingSidebarRecovery"]).toBe(false) expect(provider["webviewRecoveryAttempts"]).toBe(attempts) expect(provider["webviewRecoveryFailureReported"]).toBe(delay >= 10_000) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(delay < 10_000 ? 0 : 1) expect(provider.getCurrentTask()).toBe(task) expect(remove).not.toHaveBeenCalled() expect(task.dispose).not.toHaveBeenCalled() expect(task.abortTask).not.toHaveBeenCalled() }, ) test.each(["HTML generation", "state hydration"] as const)( "recovers an interrupted sidebar task after failed replacement %s", async (stage) => { await provider.resolveWebviewView(mockWebviewView) const task = new Task(defaultTaskOptions) Object.assign(task, { abort: true }) provider["taskRegistry"].push(task) const remove = vi.spyOn(provider, "removeClineFromStack") provider["getWebviewHtml"] = vi.fn().mockResolvedValue("recovered-html") const failed = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } const healthy = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } const replacements = [failed, healthy] let resolution: Promise | undefined vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() if (command === `${ClineProvider.sideBarId}.focus`) { const next = replacements.shift() if (!next) throw new Error("Unexpected third replacement") if (next === failed) { if (stage === "HTML generation") vi.mocked(provider["getWebviewHtml"]).mockRejectedValueOnce( new Error("HTML failed"), ) else vi.spyOn(provider, "getState").mockRejectedValueOnce(new Error("hydration failed")) } // VS Code resolves the view independently of its focus command. resolution = provider.resolveWebviewView(next) } }) await vi.advanceTimersByTimeAsync(130_050) await expect(resolution).resolves.toBeUndefined() expect(provider["view"]).toBe(failed) expect(provider["webviewWatchdogInterval"]).not.toBeNull() expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(provider.getCurrentTask()).toBe(task) expect(remove).not.toHaveBeenCalled() await vi.advanceTimersByTimeAsync(130_000) await expect(resolution).resolves.toBeUndefined() expect(provider["view"]).toBe(healthy) expect(healthy.webview.html).toBe("recovered-html") expect(provider["webviewRecoveryAttempts"]).toBe(2) expect(replacements).toHaveLength(0) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(provider.getCurrentTask()).toBe(task) expect(remove).not.toHaveBeenCalled() expect(task.abortTask).not.toHaveBeenCalled() expect(task.dispose).not.toHaveBeenCalled() }, ) test("caps repeated failed sidebar replacements without evicting the task", async () => { await provider.resolveWebviewView(mockWebviewView) const task = new Task(defaultTaskOptions) provider["taskRegistry"].push(task) provider["getWebviewHtml"] = vi.fn().mockResolvedValue("recovered-html") const resolutions: Promise[] = [] vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() if (command === `${ClineProvider.sideBarId}.focus`) { vi.spyOn(provider, "getState").mockRejectedValueOnce(new Error("hydration failed")) const replacement = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } resolutions.push(provider.resolveWebviewView(replacement)) } }) await vi.advanceTimersByTimeAsync(720_000) await Promise.all(resolutions) expect(resolutions).toHaveLength(3) expect(provider["webviewRecoveryAttempts"]).toBe(3) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(provider.getCurrentTask()).toBe(task) expect(task.abortTask).not.toHaveBeenCalled() expect(task.dispose).not.toHaveBeenCalled() }) test("keeps retries available when a published sidebar rejects after the replacement wait", async () => { await provider.resolveWebviewView(mockWebviewView) removeSidebarOnCommand() await vi.advanceTimersByTimeAsync(130_000) let rejectHtml: (error: Error) => void = () => { throw new Error("HTML generation has not started") } provider["getWebviewHtml"] = vi.fn( () => new Promise((_resolve, reject) => { rejectHtml = reject }), ) const replacement = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } const resolution = provider.resolveWebviewView(replacement) await vi.advanceTimersByTimeAsync(10_000) expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) rejectHtml(new Error("late HTML failure")) await expect(resolution).resolves.toBeUndefined() expect(provider["view"]).toBe(replacement) expect(provider["webviewWatchdogInterval"]).not.toBeNull() expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) }) test("retains recovery intent and remaining attempts while replacement HTML generation outlasts the wait", async () => { await provider.resolveWebviewView(mockWebviewView) const task = new Task(defaultTaskOptions) Object.assign(task, { abort: true }) provider["taskRegistry"].push(task) const remove = vi.spyOn(provider, "removeClineFromStack") removeSidebarOnCommand() await vi.advanceTimersByTimeAsync(130_000) let finishHtml: (html: string) => void = () => { throw new Error("HTML generation has not started") } provider["getWebviewHtml"] = vi.fn( () => new Promise((resolve) => { finishHtml = resolve }), ) const replacement = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } const resolving = provider.resolveWebviewView(replacement) await vi.advanceTimersByTimeAsync(10_000) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) finishHtml("replacement-html") await resolving expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(provider.getCurrentTask()).toBe(task) expect(remove).not.toHaveBeenCalled() }) }) test("recreates the sidebar again after a second incident", async () => { await provider.resolveWebviewView(mockWebviewView) const replacements = [0, 1].map(() => ({ ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" }, })) vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() if (command === `${ClineProvider.sideBarId}.focus`) { const next = replacements.shift() if (!next) throw new Error("Unexpected third replacement") await provider.resolveWebviewView(next) } }) await vi.advanceTimersByTimeAsync(130_000) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) provider.updateWebviewHeartbeat() await vi.advanceTimersByTimeAsync(30_000) provider.updateWebviewHeartbeat() await vi.advanceTimersByTimeAsync(30_000) provider.updateWebviewHeartbeat() expect(provider["webviewRecoveryAttempts"]).toBe(0) await vi.advanceTimersByTimeAsync(130_000) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(replacements).toHaveLength(0) expect( vi .mocked(vscode.commands.executeCommand) .mock.calls.filter(([command]) => command === `${ClineProvider.sideBarId}.removeView`), ).toHaveLength(2) }) test.each(["heartbeat", "hidden", "disposed", "suspended"] as const)( "does not recreate the host after %s during the confirmation window", async (event) => { await provider.resolveWebviewView(mockWebviewView) await vi.advanceTimersByTimeAsync(120_000) if (event === "heartbeat") provider.updateWebviewHeartbeat() if (event === "hidden") Object.defineProperty(mockWebviewView, "visible", { value: false, configurable: true }) if (event === "disposed") await provider.dispose() if (event === "suspended") vi.setSystemTime(Date.now() + 120_000) await vi.advanceTimersByTimeAsync(10_000) expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith(`${ClineProvider.sideBarId}.removeView`) }, ) test.each(["heartbeat", "hidden", "disposed", "replacement"] as const)( "cancels host recreation after %s during command discovery", async (event) => { await provider.resolveWebviewView(mockWebviewView) vi.mocked(vscode.commands.getCommands).mockImplementation(async () => { if (event === "heartbeat") provider.updateWebviewHeartbeat() if (event === "hidden") Object.defineProperty(mockWebviewView, "visible", { value: false, configurable: true }) if (event === "disposed") await provider.dispose() if (event === "replacement") provider["view"] = { ...mockWebviewView } // Even an unavailable-command result must be ignored after cancellation. return [] }) await vi.advanceTimersByTimeAsync(130_000) expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith(`${ClineProvider.sideBarId}.removeView`) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }, ) test("ignores a late command-discovery error after a heartbeat returns", async () => { await provider.resolveWebviewView(mockWebviewView) vi.mocked(vscode.commands.getCommands).mockImplementation(async () => { provider.updateWebviewHeartbeat() throw new Error("discovery failed") }) await vi.advanceTimersByTimeAsync(130_000) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) test.each(["unavailable commands", "failed removal"] as const)( "stops and notifies once when scoped recovery has %s", async (failure) => { await provider.resolveWebviewView(mockWebviewView) if (failure === "unavailable commands") vi.mocked(vscode.commands.getCommands).mockResolvedValue([]) if (failure === "failed removal") vi.mocked(vscode.commands.executeCommand).mockRejectedValue(new Error("removal failed")) const assignHtml = trackHtmlAssignments() await vi.advanceTimersByTimeAsync(600_000) expect(assignHtml).toHaveBeenCalledTimes(1) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(provider["pendingSidebarRecovery"]).toBe(false) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith("workbench.action.reloadWindow") expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( expect.stringContaining("Webview recovery stopped:"), ) }, ) test("clears a failed focus incident before a manual sidebar open", async () => { await provider.resolveWebviewView(mockWebviewView) const task = new Task(defaultTaskOptions) Object.assign(task, { abort: true }) provider["taskRegistry"].push(task) const remove = vi.spyOn(provider, "removeClineFromStack") vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() if (command === `${ClineProvider.sideBarId}.focus`) throw new Error("focus failed") }) await vi.advanceTimersByTimeAsync(130_000) expect(provider["view"]).toBeUndefined() expect(provider["pendingSidebarRecovery"]).toBe(false) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(provider["webviewRecoveryAttempts"]).toBe(3) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(remove).not.toHaveBeenCalled() const manualView = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } await provider.resolveWebviewView(manualView) expect(provider["view"]).toBe(manualView) expect(provider["webviewRecoveryAttempts"]).toBe(0) expect(provider["webviewRecoveryFailureReported"]).toBe(false) expect(remove).toHaveBeenCalledTimes(1) expect(provider.getCurrentTask()).toBeUndefined() }) test.each([false, true])( "logs one terminal stop and notification despite repeated ticks (prior retry warning: %s)", async (priorWarning) => { await provider.resolveWebviewView(mockWebviewView) const html = mockWebviewView.webview.html const log = vi.spyOn(provider, "log") if (priorWarning) { provider["reportWebviewRecoveryFailure"]("Initialization failed; retry pending", false) expect(provider["webviewRecoveryAttempts"]).toBe(0) expect(log).toHaveBeenCalledWith( "[Zoo Code] Webview recovery will retry: Initialization failed; retry pending", ) } provider["reportWebviewRecoveryFailure"]("Recovery is unavailable") expect(log).toHaveBeenCalledWith("[Zoo Code] Webview recovery stopped: Recovery is unavailable") await vi.advanceTimersByTimeAsync(300_000) expect(provider["webviewRecoveryAttempts"]).toBe(3) expect(mockWebviewView.webview.html).toBe(html) expect(log.mock.calls.filter(([line]) => line.includes("Webview recovery stopped:"))).toEqual([ ["[Zoo Code] Webview recovery stopped: Recovery is unavailable"], ]) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) }, ) test.each(["heartbeat", "manual reopen"] as const)( "logs a new terminal stop after %s begins a new incident", async (reset) => { await provider.resolveWebviewView(mockWebviewView) const log = vi.spyOn(provider, "log") provider["reportWebviewRecoveryFailure"]("First incident") if (reset === "heartbeat") provider.updateWebviewHeartbeat() else { disposeCallback() await provider.resolveWebviewView({ ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" }, }) } expect(provider["webviewRecoveryStopLogged"]).toBe(false) provider["reportWebviewRecoveryFailure"]("Second incident") await vi.advanceTimersByTimeAsync(300_000) expect(log.mock.calls.filter(([line]) => line.includes("Webview recovery stopped:"))).toEqual([ ["[Zoo Code] Webview recovery stopped: First incident"], ["[Zoo Code] Webview recovery stopped: Second incident"], ]) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(2) }, ) test.each(["Retry Interface Recovery", "Reload Window", "Show Logs"] as const)( "an old notification action cannot restart a renewed generation: %s", async (choice) => { await provider.resolveWebviewView(mockWebviewView) let choose: (value: string) => void = () => { throw new Error("No warning") } vi.mocked(vscode.window.showWarningMessage).mockImplementation( vi.fn().mockReturnValue( new Promise((resolve) => { choose = resolve }), ), ) provider["reportWebviewRecoveryFailure"]("Old incident") const healthy = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() if (command === `${ClineProvider.sideBarId}.focus`) await provider.resolveWebviewView(healthy) }) await provider.retryWebviewRecovery() choose(choice) await vi.advanceTimersByTimeAsync(0) expect(provider["webviewRecoveryRequestGeneration"]).toBe(1) expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith("workbench.action.reloadWindow") expect(mockOutputChannel.show).toHaveBeenCalledTimes(choice === "Show Logs" ? 1 : 0) }, ) test.each(["disposed", "stale notification"] as const)("does not renew recovery after %s", async (event) => { await provider.resolveWebviewView(mockWebviewView) if (event === "disposed") await provider.dispose() else provider["webviewRecoveryRequestGeneration"] = 1 vi.mocked(vscode.commands.executeCommand).mockClear() await provider.retryWebviewRecovery(0) expect(provider["webviewRecoveryRequestGeneration"]).toBe(event === "disposed" ? 0 : 1) expect(vscode.commands.executeCommand).not.toHaveBeenCalled() }) test("an old focus rejection cannot release or stop a newer explicit retry", async () => { await provider.resolveWebviewView(mockWebviewView) let rejectOldFocus: (error: Error) => void = () => { throw new Error("Old focus has not started") } let finishNewFocus: () => void = () => { throw new Error("New focus has not started") } let focusCount = 0 vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() if (command === `${ClineProvider.sideBarId}.focus`) { focusCount++ if (focusCount === 1) await new Promise((_resolve, reject) => { rejectOldFocus = reject }) else await new Promise((resolve) => { finishNewFocus = resolve }) } }) const old = provider["recreateWebviewHostForRecovery"](mockWebviewView) await vi.advanceTimersByTimeAsync(0) const retry = provider.retryWebviewRecovery() await vi.advanceTimersByTimeAsync(0) rejectOldFocus(new Error("obsolete focus rejection")) await old expect(provider["webviewHostRecoveryInProgress"]).toBe(true) expect(provider["pendingSidebarRecovery"]).toBe(true) expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() await provider.resolveWebviewView({ ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } }) finishNewFocus() await retry expect(provider["webviewHostRecoveryInProgress"]).toBe(false) }) test.each(["resolve", "reject"] as const)( "ignores old initialization that completes on the same view after explicit retry: %s", async (completion) => { let finishHtml: (html: string) => void = () => { throw new Error("HTML has not started") } let rejectHtml: (error: Error) => void = () => { throw new Error("HTML has not started") } provider["getWebviewHtml"] = vi .fn() .mockImplementationOnce( () => new Promise((resolve, reject) => { finishHtml = resolve rejectHtml = reject }), ) .mockResolvedValue("fresh-html") const old = provider.resolveWebviewView(mockWebviewView) let finishDiscovery: (commands: string[]) => void = () => { throw new Error("Discovery has not started") } vi.mocked(vscode.commands.getCommands).mockImplementationOnce( () => new Promise((resolve) => { finishDiscovery = resolve }), ) const retry = provider.retryWebviewRecovery() await vi.advanceTimersByTimeAsync(0) if (completion === "resolve") finishHtml("obsolete-html") else rejectHtml(new Error("obsolete initialization failure")) await old expect(mockWebviewView.webview.html).toBe("") expect(mockWebviewView.webview.onDidReceiveMessage).not.toHaveBeenCalled() expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() const healthy = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } } vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() if (command === `${ClineProvider.sideBarId}.focus`) await provider.resolveWebviewView(healthy) }) finishDiscovery([`${ClineProvider.sideBarId}.removeView`, `${ClineProvider.sideBarId}.focus`]) await retry expect(provider["view"]).toBe(healthy) expect(healthy.webview.html).toBe("fresh-html") }, ) test("old hydration cannot change terminal settings after explicit retry renews the same view", async () => { await provider.resolveWebviewView(mockWebviewView) const state = await provider.getState() provider["getWebviewHtml"] = vi.fn().mockResolvedValue("fresh-html") let finishHydration: (value: typeof state) => void = () => { throw new Error("Hydration has not started") } vi.spyOn(provider, "getState").mockImplementationOnce( () => new Promise((resolve) => { finishHydration = resolve }), ) const old = provider.resolveWebviewView(mockWebviewView) await vi.advanceTimersByTimeAsync(0) let finishDiscovery: (commands: string[]) => void = () => { throw new Error("Discovery has not started") } vi.mocked(vscode.commands.getCommands).mockImplementationOnce( () => new Promise((resolve) => { finishDiscovery = resolve }), ) const retry = provider.retryWebviewRecovery() await vi.advanceTimersByTimeAsync(0) const terminal = vi.spyOn(Terminal, "setTerminalProfile") finishHydration({ ...state, terminalProfile: "obsolete-profile" }) await old expect(terminal).not.toHaveBeenCalled() vi.mocked(vscode.commands.executeCommand).mockImplementation(async (command) => { if (command === `${ClineProvider.sideBarId}.removeView`) disposeCallback() if (command === `${ClineProvider.sideBarId}.focus`) await provider.resolveWebviewView({ ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" }, }) }) finishDiscovery([`${ClineProvider.sideBarId}.removeView`, `${ClineProvider.sideBarId}.focus`]) await retry expect(terminal).not.toHaveBeenCalledWith("obsolete-profile") }) test.each(["Reload Window", "Show Logs"] as const)( "runs only the selected recovery action: %s", async (action) => { await provider.resolveWebviewView(mockWebviewView) vi.mocked(vscode.commands.getCommands).mockResolvedValue([]) vi.mocked(vscode.window.showWarningMessage).mockImplementation(vi.fn().mockResolvedValue(action)) await vi.advanceTimersByTimeAsync(130_000) if (action === "Reload Window") expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.reloadWindow") if (action === "Show Logs") { expect(mockOutputChannel.show).toHaveBeenCalledTimes(1) expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith("workbench.action.reloadWindow") } }, ) test("ignores an old Reload Window choice after a heartbeat returns", async () => { await provider.resolveWebviewView(mockWebviewView) vi.mocked(vscode.commands.getCommands).mockResolvedValue([]) let choose: (value: string) => void = () => { throw new Error("Notification not shown") } const choice = new Promise((resolve) => { choose = resolve }) vi.mocked(vscode.window.showWarningMessage).mockImplementation(vi.fn().mockReturnValue(choice)) await vi.advanceTimersByTimeAsync(130_000) provider.updateWebviewHeartbeat() choose("Reload Window") await vi.advanceTimersByTimeAsync(0) expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith("workbench.action.reloadWindow") }) test("offers a fresh actionable warning when one heartbeat is followed by another stall", async () => { await provider.resolveWebviewView(mockWebviewView) vi.mocked(vscode.commands.getCommands).mockResolvedValue([]) let chooseOld: (value: string) => void = () => { throw new Error("Notification not shown") } const oldChoice = new Promise((resolve) => { chooseOld = resolve }) vi.mocked(vscode.window.showWarningMessage).mockImplementationOnce(vi.fn().mockReturnValue(oldChoice)) await vi.advanceTimersByTimeAsync(130_000) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) provider.updateWebviewHeartbeat() expect(provider["webviewRecoveryAttempts"]).toBe(3) chooseOld("Reload Window") await vi.advanceTimersByTimeAsync(0) expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith("workbench.action.reloadWindow") vi.mocked(vscode.window.showWarningMessage).mockImplementation(vi.fn().mockResolvedValue("Reload Window")) await vi.advanceTimersByTimeAsync(170_000) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(2) expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.reloadWindow") await vi.advanceTimersByTimeAsync(240_000) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(2) }) test("keeps the Reload Window action available after visibility grace resets", async () => { await provider.resolveWebviewView(mockWebviewView) vi.mocked(vscode.commands.getCommands).mockResolvedValue([]) let choose: (value: string) => void = () => { throw new Error("Notification not shown") } const choice = new Promise((resolve) => { choose = resolve }) vi.mocked(vscode.window.showWarningMessage).mockImplementation(vi.fn().mockReturnValue(choice)) await vi.advanceTimersByTimeAsync(130_000) visibilityCallback() choose("Reload Window") await vi.advanceTimersByTimeAsync(0) expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.reloadWindow") }) test("waits for the final HTML attempt to settle before reporting the limit", async () => { await provider.resolveWebviewView(mockWebviewView) provider["webviewRecoveryAttempts"] = 2 let rejectHtml: (error: Error) => void = () => { throw new Error("HTML not requested") } const html = new Promise((_resolve, reject) => { rejectHtml = reject }) provider["getWebviewHtml"] = vi.fn<(webview: vscode.Webview) => Promise>().mockReturnValue(html) await vi.advanceTimersByTimeAsync(240_000) expect(provider["webviewRecoveryAttempts"]).toBe(3) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() rejectHtml(new Error("cannot generate")) await vi.advanceTimersByTimeAsync(60_000) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) }) test("bounds failed HTML generation and reports the exhausted budget once", async () => { await provider.resolveWebviewView(mockWebviewView) const generate = vi.fn().mockRejectedValue(new Error("cannot generate")) provider["getWebviewHtml"] = generate const assignHtml = trackHtmlAssignments() await vi.advanceTimersByTimeAsync(600_000) expect(generate).toHaveBeenCalledTimes(3) expect(assignHtml).not.toHaveBeenCalled() expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) }) test("does not replenish attempts in a mount-heartbeat-crash loop", async () => { await provider.resolveWebviewView(mockWebviewView) const assignHtml = trackHtmlAssignments() for (let attempt = 0; attempt < 3; attempt++) { await vi.advanceTimersByTimeAsync(120_000) provider.updateWebviewHeartbeat() } await vi.advanceTimersByTimeAsync(240_000) expect(assignHtml).toHaveBeenCalledTimes(3) expect(provider["webviewRecoveryAttempts"]).toBe(3) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) }) test("gives a user-opened replacement a fresh budget after unavailable host recovery", async () => { await provider.resolveWebviewView(mockWebviewView) vi.mocked(vscode.commands.getCommands).mockResolvedValue([]) const generateHtml = vi.fn(provider["getWebviewHtml"].bind(provider)) provider["getWebviewHtml"] = generateHtml await vi.advanceTimersByTimeAsync(130_000) expect(generateHtml).toHaveBeenCalledTimes(1) expect(provider["webviewRecoveryAttempts"]).toBe(3) disposeCallback() const replacementView = { ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" }, } await provider.resolveWebviewView(replacementView) const htmlAfterResolve = replacementView.webview.html generateHtml.mockClear() await vi.advanceTimersByTimeAsync(60_000) expect(replacementView.webview.html).toBe(htmlAfterResolve) await vi.advanceTimersByTimeAsync(60_000) expect(generateHtml).toHaveBeenCalledTimes(1) expect(replacementView.webview.html).not.toBe(htmlAfterResolve) expect(replacementView.webview.html).toContain("Zoo Code") }) test("does not reload while the view is hidden even when the heartbeat is stale", async () => { await provider.resolveWebviewView(mockWebviewView) Object.defineProperty(mockWebviewView, "visible", { value: false, configurable: true }) const htmlAfterResolve = mockWebviewView.webview.html const log = vi.spyOn(provider, "log") await vi.advanceTimersByTimeAsync(180_000) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) expect(log).not.toHaveBeenCalledWith(expect.stringContaining("Webview heartbeat stale")) }) test("resets the grace window when the view becomes visible", async () => { await provider.resolveWebviewView(mockWebviewView) Object.defineProperty(mockWebviewView, "visible", { value: false, configurable: true }) const htmlAfterResolve = mockWebviewView.webview.html await vi.advanceTimersByTimeAsync(120_000) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) Object.defineProperty(mockWebviewView, "visible", { value: true, configurable: true }) visibilityCallback() const htmlAfterBecomingVisible = mockWebviewView.webview.html await vi.advanceTimersByTimeAsync(60_000) expect(mockWebviewView.webview.html).toBe(htmlAfterBecomingVisible) // Watchdog ticks every 60s; 120s after the flip the heartbeat is stale again. await vi.advanceTimersByTimeAsync(60_000) expect(mockWebviewView.webview.html).not.toBe(htmlAfterBecomingVisible) }) test("restarts the grace window when a tick gap shows the host slept", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html // One ordinary tick, then a wall-clock jump past the stale // threshold before the next tick. The gap means the host slept // while both timers were paused, not that the renderer died. await vi.advanceTimersByTimeAsync(60_000) vi.setSystemTime(Date.now() + 120_000) await vi.advanceTimersByTimeAsync(60_000) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) // The grace window restarted at the post-sleep tick, so the // watchdog still reloads once the heartbeat genuinely goes stale. await vi.advanceTimersByTimeAsync(60_000) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) await vi.advanceTimersByTimeAsync(60_000) expect(mockWebviewView.webview.html).not.toBe(htmlAfterResolve) }) test("stops watching after the provider is disposed", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html await provider.dispose() await vi.advanceTimersByTimeAsync(180_000) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) }) test("stops watching and clears the view when the sidebar webview is disposed", async () => { mockWebviewView.webview.onDidReceiveMessage = vi.fn(() => ({ dispose: vi.fn() })) await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html const epochBefore = provider["webviewRecoveryEpoch"] const trackedDisposables = [...provider["webviewDisposables"]] expect(trackedDisposables).not.toHaveLength(0) const disposeSpies = trackedDisposables.map((disposable) => vi.spyOn(disposable, "dispose")) // Precondition: the watchdog interval was actually scheduled, so the // null check below proves disposal stopped it rather than it never // having started. expect(provider["webviewWatchdogInterval"]).not.toBeNull() // The provider outlives a disposed sidebar view; VS Code re-resolves // a fresh view later. Disposal must stop the watchdog and drop the // stale view reference so no recovery reload targets the dead view. disposeCallback() expect(provider["webviewWatchdogInterval"]).toBeNull() expect(provider["view"]).toBeUndefined() expect(provider["webviewDisposables"]).toHaveLength(0) for (const disposeSpy of disposeSpies) { expect(disposeSpy).toHaveBeenCalled() } expect(provider["webviewRecoveryEpoch"]).toBe(epochBefore + 1) await vi.advanceTimersByTimeAsync(180_000) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) }) test("does not stack watchdog intervals when resolveWebviewView runs again", async () => { await provider.resolveWebviewView(mockWebviewView) const timersAfterFirstResolve = vi.getTimerCount() await provider.resolveWebviewView(mockWebviewView) expect(vi.getTimerCount()).toBe(timersAfterFirstResolve) // Each watchdog reload regenerates the HTML once, so calls after this point count reloads. const regenerate = vi.fn(provider["getWebviewHtml"].bind(provider)) provider["getWebviewHtml"] = regenerate await vi.advanceTimersByTimeAsync(120_000) expect(regenerate).toHaveBeenCalledTimes(1) }) test("logs when regenerating the reload HTML fails", async () => { await provider.resolveWebviewView(mockWebviewView) provider["getWebviewHtml"] = vi.fn().mockRejectedValue(new Error("regen boom")) ;(mockOutputChannel.appendLine as ReturnType).mockClear() await vi.advanceTimersByTimeAsync(120_000) expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( expect.stringContaining("[Zoo Code] Failed to reload webview: regen boom"), ) }) test("logs and keeps the webview html when the recovery reload rejects", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html // The watchdog reload no longer goes through a VS Code command; stub // the recovery HTML regeneration itself to reject. provider["getWebviewHtml"] = vi.fn().mockRejectedValue(new Error("reload boom")) ;(mockOutputChannel.appendLine as ReturnType).mockClear() await vi.advanceTimersByTimeAsync(120_000) expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( expect.stringContaining("[Zoo Code] Failed to reload webview: reload boom"), ) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) }) test("does not reassign html when the provider is disposed mid-recovery", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html let finishReload: (html: string) => void = () => {} provider["getWebviewHtml"] = vi.fn().mockImplementation( () => new Promise((resolve) => { finishReload = resolve }), ) await vi.advanceTimersByTimeAsync(120_000) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) await provider.dispose() finishReload("recovered") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) }) test("does not reassign html when the sidebar view is disposed mid-recovery", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html // Defer the recovery reload's own HTML generation so the test proves // the disposal lands while recovery is in flight, not before it starts. let finishReload: (html: string) => void = () => {} provider["getWebviewHtml"] = vi.fn().mockImplementation( () => new Promise((resolve) => { finishReload = resolve }), ) await vi.advanceTimersByTimeAsync(120_000) // The stale heartbeat started a recovery reload, and its HTML // generation is still pending. expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) disposeCallback() finishReload("recovered") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) }) test("does not reassign html when the watched view is replaced mid-recovery", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html // Defer the recovery reload's own HTML generation so the test proves // the replacement lands while recovery is in flight, not before it // starts. let finishReload: (html: string) => void = () => {} provider["getWebviewHtml"] = vi.fn().mockImplementation( () => new Promise((resolve) => { finishReload = resolve }), ) await vi.advanceTimersByTimeAsync(120_000) // The stale heartbeat started a recovery reload, and its HTML // generation is still pending. expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) // VS Code re-resolves a fresh view (e.g. sidebar re-opened) while the // recovery reload for the old view is still awaiting its HTML. // @ts-ignore - accessing private property for testing provider.view = { webview: { postMessage: vi.fn(), html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), cspSource: "vscode-webview://test-csp-source", }, visible: true, } finishReload("recovered") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) }) test("skips the recovery reload when a heartbeat arrives while regenerating HTML", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html let finishReload: (html: string) => void = () => {} provider["getWebviewHtml"] = vi.fn().mockImplementation( () => new Promise((resolve) => { finishReload = resolve }), ) await vi.advanceTimersByTimeAsync(120_000) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) // The renderer process reported in again while the recovery HTML was // still being generated, so the webview is alive and must not reload. provider.updateWebviewHeartbeat() finishReload("recovered") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) }) test("skips the recovery reload when two heartbeats land in the same millisecond during recovery", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html let finishReload: (html: string) => void = () => {} provider["getWebviewHtml"] = vi.fn().mockImplementation( () => new Promise((resolve) => { finishReload = resolve }), ) await vi.advanceTimersByTimeAsync(120_000) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) // Pin the clock to the timestamp captured before recovery: both // heartbeats stamp the same millisecond, so a timestamp comparison // would see no change, but the heartbeat revision moved, so the // reload must still be skipped. const heartbeatAtCapture = provider["lastWebviewHeartbeatAt"] const nowSpy = vi.spyOn(Date, "now").mockReturnValue(heartbeatAtCapture) provider.updateWebviewHeartbeat() expect(provider["lastWebviewHeartbeatAt"]).toBe(heartbeatAtCapture) provider.updateWebviewHeartbeat() expect(provider["lastWebviewHeartbeatAt"]).toBe(heartbeatAtCapture) nowSpy.mockRestore() finishReload("recovered") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) }) test("skips the recovery reload when the view hides while regenerating HTML", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html let finishReload: (html: string) => void = () => {} provider["getWebviewHtml"] = vi.fn().mockImplementation( () => new Promise((resolve) => { finishReload = resolve }), ) await vi.advanceTimersByTimeAsync(120_000) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) // The view hid while the recovery HTML was still being generated; a // hidden webview throttles heartbeats, so the stale heartbeat no // longer proves a dead renderer. Object.defineProperty(mockWebviewView, "visible", { value: false, configurable: true }) finishReload("recovered") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) }) test("does not start a second recovery while one is in flight and recovers after a failure", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html // The first recovery blocks on a controlled pending generation; the // retry (second call) gets its own deferred generation. let failFirst: (error: Error) => void = () => {} let finishRetry: (html: string) => void = () => {} provider["getWebviewHtml"] = vi .fn() .mockImplementationOnce( () => new Promise((_resolve, reject) => { failFirst = reject }), ) .mockImplementationOnce( () => new Promise((resolve) => { finishRetry = resolve }), ) await vi.advanceTimersByTimeAsync(120_000) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) // The watchdog ticks again while the first recovery still awaits // its HTML; no second generation may start for the same view. await vi.advanceTimersByTimeAsync(60_000) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) // The pending generation rejects; the finally block must clear the // in-flight state so a later watchdog tick can start a fresh // recovery instead of being blocked forever. failFirst(new Error("reload boom")) await vi.advanceTimersByTimeAsync(0) await vi.advanceTimersByTimeAsync(60_000) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(2) // The retry's generation resolves with fresh HTML and must land in // the webview. finishRetry("recovered-retry") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView.webview.html).toContain("recovered-retry") }) test("lets the replacement view's recovery start while a stale one is pending", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html // Each recovery generation gets its own deferred finish callback. const generations: Array<{ finish: (html: string) => void }> = [] provider["getWebviewHtml"] = vi.fn().mockImplementation( () => new Promise((resolve) => { generations.push({ finish: resolve }) }), ) await vi.advanceTimersByTimeAsync(120_000) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) // The sidebar view is disposed (bumping webviewRecoveryEpoch) and a // replacement view takes over while recovery A's HTML generation is // still pending, making A stale. disposeCallback() // @ts-ignore - accessing private property for testing provider.view = { webview: { postMessage: vi.fn(), html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), cspSource: "vscode-webview://test-csp-source", }, visible: true, } const replacementEpoch = provider["webviewRecoveryEpoch"] // Recovery B for the new view must start even though A is still // pending: the in-flight guard is scoped to the epoch. void provider["reloadWebviewForRecovery"]() await vi.advanceTimersByTimeAsync(0) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(2) // A's completion is stale: it must not reassign the old view's html, // and its finally must NOT release the ownership B took. generations[0].finish("stale-A") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) expect(provider["webviewRecoveryInFlightEpoch"]).toBe(replacementEpoch) // B completes and lands its HTML on the new view, then releases // ownership so future recoveries can start. generations[1].finish("recovered-B") await vi.advanceTimersByTimeAsync(0) // @ts-ignore - accessing private property for testing expect(provider.view.webview.html).toContain("recovered-B") expect(provider["webviewRecoveryInFlightEpoch"]).toBeUndefined() }) test("advances the recovery epoch when resolveWebviewView replaces the view and lets the new recovery start", async () => { await provider.resolveWebviewView(mockWebviewView) const htmlAfterResolve = mockWebviewView.webview.html const epochBeforeReplacement = provider["webviewRecoveryEpoch"] // Recovery generations get their own deferred finish callbacks; the // replacement view's initial HTML generation resolves immediately so // resolveWebviewView can complete. const generations: Array<{ finish: (html: string) => void }> = [] provider["getWebviewHtml"] = vi .fn() .mockImplementationOnce( () => new Promise((resolve) => { generations.push({ finish: resolve }) }), ) .mockImplementationOnce(() => Promise.resolve("view2-initial")) .mockImplementation( () => new Promise((resolve) => { generations.push({ finish: resolve }) }), ) await vi.advanceTimersByTimeAsync(120_000) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) // VS Code re-resolves a DIFFERENT view without a disposal in between // (the gap path): the epoch must advance so the stale recovery can // neither block nor reassign the replacement view's recovery. const mockWebviewView2 = { webview: { postMessage: vi.fn(), html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), cspSource: "vscode-webview://test-csp-source", }, visible: true, onDidDispose: vi.fn(), onDidChangeVisibility: vi.fn().mockImplementation(() => ({ dispose: vi.fn() })), } as unknown as vscode.WebviewView await provider.resolveWebviewView(mockWebviewView2) expect(provider["webviewRecoveryEpoch"]).toBe(epochBeforeReplacement + 1) // Recovery B for the replacement view starts immediately, unblocked // by A's still-pending generation. void provider["reloadWebviewForRecovery"]() await vi.advanceTimersByTimeAsync(0) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(3) // A's completion is stale: the old view's html is untouched and A's // finally does not release the ownership B took. generations[0].finish("stale-A") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView.webview.html).toBe(htmlAfterResolve) expect(provider["webviewRecoveryInFlightEpoch"]).toBe(provider["webviewRecoveryEpoch"]) // B completes and lands its HTML on the replacement view, then // releases ownership. generations[1].finish("recovered-B") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView2.webview.html).toContain("recovered-B") expect(provider["webviewRecoveryInFlightEpoch"]).toBeUndefined() }) test("does not advance the recovery epoch when the same view is re-resolved and keeps the pending recovery intact", async () => { await provider.resolveWebviewView(mockWebviewView) const epochAfterFirstResolve = provider["webviewRecoveryEpoch"] // Recovery A blocks on a controlled pending generation; the same // view's re-resolve initial HTML resolves immediately. let finishReload: (html: string) => void = () => {} provider["getWebviewHtml"] = vi .fn() .mockImplementationOnce( () => new Promise((resolve) => { finishReload = resolve }), ) .mockImplementation(() => Promise.resolve("same-view-reresolve"), ) await vi.advanceTimersByTimeAsync(120_000) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(1) // Re-resolving the SAME view must not bump the epoch nor disrupt the // pending recovery that belongs to it. await provider.resolveWebviewView(mockWebviewView) expect(provider["webviewRecoveryEpoch"]).toBe(epochAfterFirstResolve) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(2) expect(provider["webviewRecoveryInFlightEpoch"]).toBe(epochAfterFirstResolve) // A still owns the view across the re-resolve: another recovery // attempt is blocked until A settles. void provider["reloadWebviewForRecovery"]() await vi.advanceTimersByTimeAsync(0) expect(provider["getWebviewHtml"]).toHaveBeenCalledTimes(2) // A settles cleanly: the re-resolve restarted the watchdog, which // re-stamped the heartbeat, so the revision guard (not the epoch) // skips the stale assignment; the ownership A held is released. finishReload("recovered-A") await vi.advanceTimersByTimeAsync(0) expect(mockWebviewView.webview.html).toContain("same-view-reresolve") expect(provider["webviewRecoveryInFlightEpoch"]).toBeUndefined() }) test("reloads only its own webview when multiple providers are active", async () => { // Structural stand-in for the VS Code webview API surface this scenario // exercises, same as the mockContext cast below. const mockWebviewViewB = { webview: { postMessage: vi.fn(), html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), cspSource: "vscode-webview://test-csp-source", }, visible: true, onDidDispose: vi.fn(), onDidChangeVisibility: vi.fn().mockImplementation(() => ({ dispose: vi.fn() })), } as unknown as vscode.WebviewView const providerB = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) try { await provider.resolveWebviewView(mockWebviewView) await providerB.resolveWebviewView(mockWebviewViewB) const htmlBeforeA = mockWebviewView.webview.html const htmlBeforeB = mockWebviewViewB.webview.html // The pre-PR reload path fired the global // workbench.action.webview.reloadWebviewAction command, which // resets every webview. The html assertions below cannot catch a // regression back to that command because the vscode mock // swallows executeCommand without touching any view, so also // assert the global command was never invoked. const executeCommandMock = vscode.commands.executeCommand as ReturnType await vi.advanceTimersByTimeAsync(119_000) // B's view is still alive; refresh its heartbeat so a stale one // would reload it too, leaving only A's watchdog to fire. await webviewMessageHandler(providerB, { type: "webviewHeartbeat", timestamp: Date.now() }) await vi.advanceTimersByTimeAsync(1_000) expect(mockWebviewView.webview.html).not.toBe(htmlBeforeA) expect(mockWebviewViewB.webview.html).toBe(htmlBeforeB) expect(executeCommandMock).not.toHaveBeenCalledWith("workbench.action.webview.reloadWebviewAction") } finally { await providerB.dispose() } }) describe("tab panel (WebviewPanel shape)", () => { let viewStateCallback: () => void // Structural stand-in for the VS Code webview API surface this // scenario exercises, same as the mockWebviewViewB cast below. let mockWebviewPanel: vscode.WebviewPanel beforeEach(() => { // WebviewPanel-shaped stand-in: same webview surface, but the // visibility listener is onDidChangeViewState instead of // onDidChangeVisibility, matching resolveWebviewView's tab branch. mockWebviewPanel = { webview: { postMessage: vi.fn(), html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), cspSource: "vscode-webview://test-csp-source", }, visible: true, onDidDispose: vi.fn().mockImplementation(() => ({ dispose: vi.fn() })), onDidChangeViewState: vi.fn().mockImplementation((cb: () => void) => { viewStateCallback = cb return { dispose: vi.fn() } }), dispose: vi.fn(), reveal: vi.fn(), } as unknown as vscode.WebviewPanel }) test("disposes the current tab provider and its watchdog registration", async () => { const onDispose: Array<() => unknown> = [] const registration = { dispose: vi.fn() } vi.mocked(mockWebviewPanel.onDidDispose).mockImplementation((listener, _thisArg, disposables) => { onDispose.push(listener) const disposable = onDispose.length === 1 ? registration : { dispose: vi.fn() } disposables?.push(disposable) return disposable }) await provider.resolveWebviewView(mockWebviewPanel) expect(provider["webviewWatchdogInterval"]).not.toBeNull() const dispose = vi.spyOn(provider, "dispose") const html = mockWebviewPanel.webview.html await onDispose[0]() expect(dispose).toHaveBeenCalledTimes(1) expect(provider["_disposed"]).toBe(true) expect(provider["webviewWatchdogInterval"]).toBeNull() expect(registration.dispose).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(600_000) expect(mockWebviewPanel.webview.html).toBe(html) }) test.each([false, true])( "replaces the tab host without disposing its provider or task (interrupted: %s)", async (interrupted) => { const callbacks: Array<() => unknown> = [] vi.mocked(mockWebviewPanel.onDidDispose).mockImplementation((listener) => { callbacks.push(listener) return { dispose: vi.fn() } }) vi.mocked(mockWebviewPanel.dispose).mockImplementation(() => { callbacks.forEach((callback) => callback()) }) mockWebviewPanel.title = "Zoo Code task" await provider.resolveWebviewView(mockWebviewPanel) const task = new Task(defaultTaskOptions) Object.assign(task, { abort: interrupted }) provider["taskRegistry"].push(task) const evict = vi.spyOn(provider, "evictCurrentTask") const remove = vi.spyOn(provider, "removeClineFromStack") const replacement = { ...mockWebviewPanel, webview: { ...mockWebviewPanel.webview, html: "" }, onDidDispose: vi.fn(() => ({ dispose: vi.fn() })), dispose: vi.fn(), } vi.mocked(vscode.window.createWebviewPanel).mockReturnValue(replacement) await vi.advanceTimersByTimeAsync(130_000) expect(mockWebviewPanel.dispose).toHaveBeenCalledTimes(1) expect(provider["view"]).toBe(replacement) expect(provider["_disposed"]).toBe(false) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(provider.getCurrentTask()).toBe(task) expect(evict).not.toHaveBeenCalled() expect(remove).not.toHaveBeenCalled() expect(task.dispose).not.toHaveBeenCalled() expect(task.abortTask).not.toHaveBeenCalled() expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith( `${ClineProvider.sideBarId}.removeView`, ) }, ) test("explicit retry replaces an exhausted tab without evicting its interrupted task", async () => { await provider.resolveWebviewView(mockWebviewPanel) const task = new Task(defaultTaskOptions) Object.assign(task, { abort: true }) provider["taskRegistry"].push(task) const remove = vi.spyOn(provider, "removeClineFromStack") provider["reportWebviewRecoveryFailure"]("Exhausted incident") const healthy = replacementPanel() vi.mocked(vscode.window.createWebviewPanel).mockReturnValue(healthy) await provider.retryWebviewRecovery() expect(provider["view"]).toBe(healthy) expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(provider.getCurrentTask()).toBe(task) expect(remove).not.toHaveBeenCalled() expect(task.dispose).not.toHaveBeenCalled() expect(task.abortTask).not.toHaveBeenCalled() }) test("keeps the old tab and its task when replacement resolution fails before publication", async () => { await provider.resolveWebviewView(mockWebviewPanel) const task = new Task(defaultTaskOptions) provider["taskRegistry"].push(task) const replacement = { ...mockWebviewPanel, dispose: vi.fn() } vi.mocked(vscode.window.createWebviewPanel).mockReturnValue(replacement) vi.spyOn(provider, "resolveWebviewView").mockRejectedValue(new Error("resolver unavailable")) await provider["recreateWebviewHostForRecovery"](mockWebviewPanel) expect(mockWebviewPanel.dispose).not.toHaveBeenCalled() expect(replacement.dispose).toHaveBeenCalledTimes(1) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(provider["view"]).toBe(mockWebviewPanel) expect(provider.getCurrentTask()).toBe(task) expect(task.dispose).not.toHaveBeenCalled() expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) }) function replacementPanel() { return { ...mockWebviewPanel, webview: { ...mockWebviewPanel.webview, html: "", onDidReceiveMessage: vi.fn(() => ({ dispose: vi.fn() })), }, onDidDispose: vi.fn(() => ({ dispose: vi.fn() })), dispose: vi.fn(), } } test.each(["HTML generation", "state hydration"] as const)( "retries a published tab after failed %s without disposing its interrupted task", async (stage) => { await provider.resolveWebviewView(mockWebviewPanel) const task = new Task(defaultTaskOptions) Object.assign(task, { abort: true }) provider["taskRegistry"].push(task) const remove = vi.spyOn(provider, "removeClineFromStack") provider["getWebviewHtml"] = vi.fn().mockResolvedValue("recovered-html") await provider["reloadWebviewForRecovery"]() const failed = replacementPanel() const healthy = replacementPanel() vi.mocked(vscode.window.createWebviewPanel).mockReturnValueOnce(failed).mockReturnValue(healthy) if (stage === "HTML generation") { vi.mocked(provider["getWebviewHtml"]).mockRejectedValueOnce(new Error("HTML failed")) } else { vi.spyOn(provider, "getState").mockRejectedValueOnce(new Error("hydration failed")) } await vi.advanceTimersByTimeAsync(10_000) expect(provider["view"]).toBe(failed) expect(failed.webview.onDidReceiveMessage).not.toHaveBeenCalled() expect(failed.dispose).not.toHaveBeenCalled() expect(provider["webviewWatchdogInterval"]).not.toBeNull() expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(provider["webviewRecoveryAttempts"]).toBe(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( expect.stringContaining("interface is not responding"), "Retry Interface Recovery", "Reload Window", "Show Logs", ) expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( expect.stringContaining("Failed to initialize replacement tab"), ) await vi.advanceTimersByTimeAsync(130_000) expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(2) expect(provider["view"]).toBe(healthy) // The provider and focus tracker each install one message listener. expect(healthy.webview.onDidReceiveMessage).toHaveBeenCalledTimes(2) expect(failed.dispose).toHaveBeenCalledTimes(1) expect(provider["webviewRecoveryAttempts"]).toBe(2) expect(provider.getCurrentTask()).toBe(task) expect(provider["_disposed"]).toBe(false) expect(remove).not.toHaveBeenCalled() expect(task.dispose).not.toHaveBeenCalled() expect(task.abortTask).not.toHaveBeenCalled() }, ) test.each(["disposed", "replaced"] as const)( "does not restart a stale replacement watchdog after the provider is %s", async (event) => { await provider.resolveWebviewView(mockWebviewPanel) provider["getWebviewHtml"] = vi.fn().mockResolvedValue("recovered-html") await provider["reloadWebviewForRecovery"]() let rejectHtml: (error: Error) => void = () => { throw new Error("Replacement HTML generation has not started") } vi.mocked(provider["getWebviewHtml"]).mockImplementationOnce( () => new Promise((_resolve, reject) => { rejectHtml = reject }), ) const failed = replacementPanel() vi.mocked(vscode.window.createWebviewPanel).mockReturnValue(failed) await vi.advanceTimersByTimeAsync(10_000) expect(provider["view"]).toBe(failed) if (event === "disposed") await provider.dispose() else await provider.resolveWebviewView(replacementPanel()) const watchdog = provider["webviewWatchdogInterval"] rejectHtml(new Error("stale HTML failure")) await vi.advanceTimersByTimeAsync(0) expect(provider["webviewWatchdogInterval"]).toBe(watchdog) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }, ) test("bounds repeated published-tab initialization failures and keeps the task available", async () => { await provider.resolveWebviewView(mockWebviewPanel) const task = new Task(defaultTaskOptions) provider["taskRegistry"].push(task) provider["getWebviewHtml"] = vi.fn().mockResolvedValue("recovered-html") vi.mocked(vscode.window.createWebviewPanel).mockImplementation(() => { const replacement = replacementPanel() // Fail after publication, before any message listener is installed. vi.spyOn(provider, "getState").mockRejectedValueOnce(new Error("hydration failed")) return replacement }) await vi.advanceTimersByTimeAsync(720_000) expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(3) expect(provider["webviewRecoveryAttempts"]).toBe(3) expect(provider["webviewHostRecoveryInProgress"]).toBe(false) expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect( vi .mocked(mockOutputChannel.appendLine) .mock.calls.filter(([line]) => line.includes("Webview recovery stopped:")), ).toHaveLength(1) expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( expect.stringContaining( "Webview recovery stopped: Recovery attempt limit reached without sustained heartbeats", ), ) expect(provider["_disposed"]).toBe(false) expect(provider.getCurrentTask()).toBe(task) expect(task.dispose).not.toHaveBeenCalled() expect(task.abortTask).not.toHaveBeenCalled() }) test("reloads the tab webview when the heartbeat is stale and the tab is visible", async () => { await provider.resolveWebviewView(mockWebviewPanel) const htmlAfterResolve = mockWebviewPanel.webview.html await vi.advanceTimersByTimeAsync(120_000) expect(mockWebviewPanel.webview.html).not.toBe(htmlAfterResolve) expect(mockWebviewPanel.webview.html).toContain("Zoo Code") }) test("does not reload a hidden tab even when the heartbeat is stale", async () => { await provider.resolveWebviewView(mockWebviewPanel) Object.defineProperty(mockWebviewPanel, "visible", { value: false, configurable: true }) const htmlAfterResolve = mockWebviewPanel.webview.html await vi.advanceTimersByTimeAsync(180_000) expect(mockWebviewPanel.webview.html).toBe(htmlAfterResolve) }) test("resets the grace window when the tab becomes visible", async () => { await provider.resolveWebviewView(mockWebviewPanel) Object.defineProperty(mockWebviewPanel, "visible", { value: false, configurable: true }) const htmlAfterResolve = mockWebviewPanel.webview.html await vi.advanceTimersByTimeAsync(120_000) expect(mockWebviewPanel.webview.html).toBe(htmlAfterResolve) Object.defineProperty(mockWebviewPanel, "visible", { value: true, configurable: true }) viewStateCallback() const htmlAfterBecomingVisible = mockWebviewPanel.webview.html await vi.advanceTimersByTimeAsync(60_000) expect(mockWebviewPanel.webview.html).toBe(htmlAfterBecomingVisible) // Watchdog ticks every 60s; 120s after the flip the heartbeat is stale again. await vi.advanceTimersByTimeAsync(60_000) expect(mockWebviewPanel.webview.html).not.toBe(htmlAfterBecomingVisible) }) }) }) // Provider lookups run in the extension host, so configured endpoints must never reach the CSP. test.each(["getHtmlContent", "getHMRHtmlContent"] as const)( "%s keeps configured provider endpoints out of the CSP", async (build) => { const state = await provider.getState() vi.spyOn(provider, "getState").mockResolvedValue({ ...state, apiConfiguration: { ...state.apiConfiguration, openRouterBaseUrl: "https://evil.example;script-src 'unsafe-inline'\">", requestyBaseUrl: "https://requesty.example", }, }) vi.mocked(axios.get).mockResolvedValue({ data: "" }) const html = await provider[build](mockWebviewView.webview) const csp = html.match( /http-equiv="Content-Security-Policy" content="([\s\S]*?)">\s* { const developmentContext = { ...mockContext, extensionMode: vscode.ExtensionMode.Development } provider = new ClineProvider( developmentContext, mockOutputChannel, "sidebar", new ContextProxy(developmentContext), new WebviewFocusTracker(), ) // The dev-server probe fails, so the HMR path falls back to the production HTML. ;(axios.get as any).mockRejectedValueOnce(new Error("Network error")) await provider.resolveWebviewView(mockWebviewView) expect(mockWebviewView.webview.options).toEqual({ enableScripts: true, localResourceRoots: [mockContext.extensionUri], }) expect(mockWebviewView.webview.html).toContain("") // Verify Content Security Policy contains the necessary PostHog domains expect(mockWebviewView.webview.html).toContain( "connect-src vscode-webview://test-csp-source https://us.i.posthog.com", ) // Extract the script-src directive section and verify required security elements const html = mockWebviewView.webview.html const scriptSrcMatch = html.match(/script-src[^;]*;/) expect(scriptSrcMatch).not.toBeNull() expect(scriptSrcMatch![0]).toContain("'nonce-") // Verify wasm-unsafe-eval is present for Shiki syntax highlighting expect(scriptSrcMatch![0]).toContain("'wasm-unsafe-eval'") }) test.each([ ["ECONNABORTED", "errors.hmr_probe_timeout"], ["ETIMEDOUT", "errors.hmr_probe_timeout"], ["ECONNREFUSED", "errors.hmr_not_running"], ])("reports dev-server probe failure %s accurately and falls back to built HTML", async (code, message) => { const { AxiosError } = await vi.importActual("axios") vi.mocked(axios.get).mockRejectedValueOnce(new AxiosError("probe failed", code)) const html = await provider["getHMRHtmlContent"](mockWebviewView.webview) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(message) expect(html).toContain("") expect(html).not.toContain("/@react-refresh") }) test("resolveWebviewView builds HMR content against the local dev server when it is reachable", async () => { const originalThemeFixtureProbe = process.env.ROO_CODE_THEME_FIXTURE_PROBE delete process.env.ROO_CODE_THEME_FIXTURE_PROBE // getHMRHtmlContent prefers an on-disk .vite-port file when one exists, so a // stale dev leftover could silently move the probe (and the HMR URLs) to // another port. Establish the default-port branch for this test by hiding // exactly that file from the existence check; every other path falls // through to the real implementation. const realExistsSync = fs.existsSync const existsSyncSpy = vi .spyOn(fs, "existsSync") .mockImplementation((target) => path.basename(String(target)) === ".vite-port" ? false : realExistsSync(target), ) try { provider = new ClineProvider( { ...mockContext, extensionMode: vscode.ExtensionMode.Development }, mockOutputChannel, "sidebar", new ContextProxy({ ...mockContext, extensionMode: vscode.ExtensionMode.Development }), new WebviewFocusTracker(), ) // The default axios mock resolves, so the dev-server probe succeeds and the // HMR HTML branch (instead of the production fallback) is taken. vi.mocked(axios.get).mockClear() await provider.resolveWebviewView(mockWebviewView) // Pin the health-check URL itself: the mock resolves for any URL, so only // this assertion keeps the probe from silently drifting back to // `localhost` (the IPv6 resolution failure this branch fixes). expect(axios.get).toHaveBeenCalledWith("http://127.0.0.1:5173", { timeout: 5_000 }) const html = mockWebviewView.webview.html // The dev server URL must be baked into the module script tag and CSP directives. expect(html).toContain("http://127.0.0.1:5173/src/index.tsx") expect(html).toContain("ws://127.0.0.1:5173") expect(html).toContain("http://127.0.0.1:5173/@react-refresh") } finally { existsSyncSpy.mockRestore() // Always restore the probe flag (even when an assertion above throws), // so later tests outside the fixture-probe describe block cannot observe // this test's deletion. if (originalThemeFixtureProbe !== undefined) { process.env.ROO_CODE_THEME_FIXTURE_PROBE = originalThemeFixtureProbe } else { delete process.env.ROO_CODE_THEME_FIXTURE_PROBE } } }) test("postMessageToWebview sends message to webview", async () => { await provider.resolveWebviewView(mockWebviewView) const mockState: ExtensionState = { version: "1.0.0", clineMessages: [], taskHistory: [], shouldShowAnnouncement: false, apiConfiguration: { apiProvider: providerIdentifiers.openrouter, }, customInstructions: undefined, alwaysAllowReadOnly: false, alwaysAllowReadOnlyOutsideWorkspace: false, alwaysAllowWrite: false, codebaseIndexConfig: { codebaseIndexEnabled: true, codebaseIndexQdrantUrl: "", codebaseIndexEmbedderProvider: providerIdentifiers.openai, codebaseIndexEmbedderBaseUrl: "", codebaseIndexEmbedderModelId: "", }, alwaysAllowWriteOutsideWorkspace: false, alwaysAllowExecute: false, alwaysAllowMcp: false, uriScheme: "vscode", soundEnabled: false, ttsEnabled: false, enableCheckpoints: false, writeDelayMs: 1000, mcpEnabled: true, mode: defaultModeSlug, customModes: [], experiments: experimentDefault, maxOpenTabsContext: 20, maxWorkspaceFiles: 200, telemetrySetting: "unset", showRooIgnoredFiles: false, enableSubfolderRules: false, renderContext: "sidebar", maxImageFileSize: 5, maxTotalImageSize: 20, cloudUserInfo: null, organizationAllowList: ORGANIZATION_ALLOW_ALL, autoCondenseContext: true, autoCondenseContextPercent: 100, cloudIsAuthenticated: false, sharingEnabled: false, publicSharingEnabled: false, profileThresholds: {}, hasOpenedModeSelector: false, diagnosticsEnabled: true, openRouterImageApiKey: undefined, openRouterImageGenerationSelectedModel: undefined, taskSyncEnabled: false, checkpointTimeout: DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, diffFuzzyThreshold: DEFAULT_DIFF_FUZZY_THRESHOLD, } const message: ExtensionMessage = { type: "state", state: mockState, } await provider.postMessageToWebview(message) expect(mockPostMessage).toHaveBeenCalledWith(message) }) test("postMessageToWebview does not throw when webview is disposed", async () => { await provider.resolveWebviewView(mockWebviewView) // Simulate postMessage throwing after webview disposal mockPostMessage.mockRejectedValueOnce(new Error("Webview is disposed")) const message: ExtensionMessage = { type: "action", action: "chatButtonClicked" } // Should not throw await expect(provider.postMessageToWebview(message)).resolves.toBeUndefined() }) test("postMessageToWebview does not await the webview ack", async () => { await provider.resolveWebviewView(mockWebviewView) let releaseAck!: () => void const ack = new Promise((resolve) => { releaseAck = resolve }) mockPostMessage.mockImplementationOnce(() => ack) const message: ExtensionMessage = { type: "action", action: "chatButtonClicked" } // The caller must not wait for the renderer ack: a webview page remounted or disposed // while the post is in flight never acknowledges it, and awaiting that promise would // wedge every caller on the task critical path. await provider.postMessageToWebview(message) expect(mockPostMessage).toHaveBeenCalledWith(message) releaseAck() }) test("postMessageToWebview leaves originalContent of file-edit tool messages out of the state it posts", async () => { await provider.resolveWebviewView(mockWebviewView) const originalFile = "line of the original file\n".repeat(500) const toolText = JSON.stringify({ tool: "appliedDiff", path: "a.ts", diff: "@@ d", originalContent: originalFile, }) // Only the field under test is populated; the rest of ExtensionState is irrelevant here. const message = { type: "state", state: { clineMessages: [{ ts: 1, type: "ask", ask: "tool", text: toolText }] }, } as unknown as ExtensionMessage await provider.postMessageToWebview(message) const posted = mockPostMessage.mock.calls.at(-1)![0] as ExtensionMessage const postedText = posted.state!.clineMessages![0]!.text! expect(JSON.parse(postedText)).toEqual({ tool: "appliedDiff", path: "a.ts", diff: "@@ d", originalContentLength: originalFile.length, }) // the extension's own message (and so the persisted task) keeps the full content expect(message.state!.clineMessages![0]!.text).toBe(toolText) }) test("postMessageToWebview leaves originalContent out of messageUpdated", async () => { await provider.resolveWebviewView(mockWebviewView) const toolText = JSON.stringify({ tool: "appliedDiff", path: "a.ts", originalContent: "original file\n".repeat(100), }) await provider.postMessageToWebview({ type: "messageUpdated", clineMessage: { ts: 2, type: "ask", ask: "tool", text: toolText }, }) const posted = mockPostMessage.mock.calls.at(-1)![0] as ExtensionMessage expect(JSON.parse(posted.clineMessage!.text!)).toEqual({ tool: "appliedDiff", path: "a.ts", originalContentLength: "original file\n".length * 100, }) }) describe("theme fixture probes", () => { const fixture = { themeId: "Default Dark Modern", bodyClass: "vscode-dark", variables: { "--vscode-foreground": "#cccccc" }, } const originalProbeSetting = process.env.ROO_CODE_THEME_FIXTURE_PROBE beforeEach(() => { 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 } vi.useRealTimers() }) test("rejects requests when probing is disabled", async () => { delete process.env.ROO_CODE_THEME_FIXTURE_PROBE await expect(provider.requestWebviewThemeFixture()).rejects.toThrow("Theme fixture probing is disabled") }) test("posts a request and resolves the matching response", async () => { const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) const request = provider.requestWebviewThemeFixture() await Promise.resolve() const requestId = postMessageSpy.mock.calls[0]?.[0].requestId const unknownFixture = { ...fixture, themeId: "Unexpected Theme" } expect(requestId).toBeTruthy() expect(postMessageSpy).toHaveBeenCalledWith({ type: "themeFixtureProbeRequest", requestId }) provider.resolveWebviewThemeFixtureProbe("unknown-request", unknownFixture) provider.resolveWebviewThemeFixtureProbe(requestId!, fixture) await expect(request).resolves.toEqual(fixture) }) test("rejects a request after its timeout", async () => { vi.useFakeTimers() vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) const request = provider.requestWebviewThemeFixture(100) const rejection = expect(request).rejects.toThrow("Theme fixture probe timed out after 100ms") await vi.advanceTimersByTimeAsync(100) await rejection }) test("rejects pending requests when webview resources are cleared", async () => { vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) const request = provider.requestWebviewThemeFixture() const rejection = expect(request).rejects.toThrow( "Webview was disposed before the theme fixture probe completed", ) provider["clearWebviewResources"]() await rejection }) }) test("postStateToWebview does not force action navigation for non-compliant MDM state", async () => { // Structural double: the post path only reads these two members, and // MdmService cannot be constructed as a plain object; Object.assign // keeps this a single structural assertion. const mdmService = Object.assign({} as MdmService, { requiresCloudAuth: vi.fn().mockReturnValue(true), isCompliant: vi.fn().mockReturnValue({ compliant: false, reason: "auth required" }), }) provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), mdmService, ) const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockImplementation(async () => undefined) vi.spyOn(provider, "getStateToPostToWebview").mockResolvedValue( Object.assign({} as ExtensionState, { version: "1.0.0", }), ) await provider.postStateToWebview() expect(postMessageSpy).toHaveBeenCalledTimes(1) expect(postMessageSpy).not.toHaveBeenCalledWith(expect.objectContaining({ type: "action" })) }) test("postStateToWebviewWithoutTaskHistory waits for the webview post boundary", async () => { let releasePost!: () => void const pendingPost = new Promise((resolve) => { releasePost = resolve }) let statePostSettled = false vi.spyOn(provider, "getStateToPostToWebview").mockResolvedValue( Object.assign({} as ExtensionState, { taskHistory: [], }), ) const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockReturnValue(pendingPost) const statePost = provider.postStateToWebviewWithoutTaskHistory() void statePost.then(() => { statePostSettled = true }) await Promise.resolve() expect(postMessageSpy).toHaveBeenCalledOnce() expect(statePostSettled).toBe(false) releasePost() await statePost expect(statePostSettled).toBe(true) }) test.each([ ["postStateToWebview", (currentProvider: ClineProvider) => currentProvider.postStateToWebview()], [ "postStateToWebviewWithoutTaskHistory", (currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutTaskHistory(), ], ])("%s assigns message sequence numbers before asynchronous state construction", async (_methodName, postState) => { let releaseOlderSnapshot!: (state: ExtensionState) => void const olderSnapshot = new Promise((resolve) => { releaseOlderSnapshot = resolve }) const baseState = await provider.getStateToPostToWebview({ includeTaskHistory: false }) const emptyState: ExtensionState = { ...baseState, taskHistory: [], clineMessages: [] } const readyState: ExtensionState = { ...baseState, taskHistory: [], clineMessages: [{ ts: 1, type: "say", say: "text", text: "child ready" }], } vi.spyOn(provider, "getStateToPostToWebview") .mockReturnValueOnce(olderSnapshot) .mockResolvedValueOnce(readyState) const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) const olderPost = postState(provider) await Promise.resolve() const newerPost = postState(provider) await newerPost releaseOlderSnapshot(emptyState) await olderPost expect(postMessageSpy.mock.calls.map(([message]) => message.state?.clineMessages)).toEqual([ readyState.clineMessages, emptyState.clineMessages, ]) expect(postMessageSpy.mock.calls.map(([message]) => message.state?.clineMessagesSeq)).toEqual([2, 1]) }) test.each([ [ "postStateToWebviewWithoutTaskHistory", (currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutTaskHistory(), ], [ "postStateToWebviewWithoutClineMessages", (currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutClineMessages(), ], ])("%s skips task history computation", async (_methodName, postState) => { const getAllSpy = vi.spyOn(provider.taskHistoryStore, "getAll") const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) await postState(provider) expect(getAllSpy).not.toHaveBeenCalled() expect(postMessageSpy).toHaveBeenCalledOnce() expect(postMessageSpy.mock.calls[0]?.[0].state).not.toHaveProperty("taskHistory") }) test("getStateToPostToWebview computes task history once after its base state resolves", async () => { const historyItem = { id: "history-task", number: 1, ts: 1, task: "History task", tokensIn: 0, tokensOut: 0, totalCost: 0, } const originalGetState = provider.getState.bind(provider) let baseStateResolved = false const getStateSpy = vi.spyOn(provider, "getState").mockImplementation(async (options) => { const state = await originalGetState(options) baseStateResolved = true return state }) const historyReadPhases: boolean[] = [] const getAllSpy = vi.spyOn(provider.taskHistoryStore, "getAll").mockImplementation(() => { historyReadPhases.push(baseStateResolved) return [historyItem] }) const state = await provider.getStateToPostToWebview() expect(getStateSpy).toHaveBeenCalledOnce() expect(getStateSpy).toHaveBeenCalledWith({ includeTaskHistory: false }) expect(getAllSpy).toHaveBeenCalledOnce() expect(historyReadPhases).toEqual([true]) expect(state.taskHistory).toEqual([historyItem]) }) describe("viewId uniqueness", () => { it("should assign unique viewId to each instance", async () => { const provider1 = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const provider2 = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Each instance gets a unique viewId, prefixed by the render context it was built for. expect(provider1.viewId).toMatch(/^sidebar-\d+$/) expect(provider2.viewId).toMatch(/^editor-\d+$/) expect(provider1.viewId).not.toBe(provider2.viewId) await provider1.dispose() await provider2.dispose() }) it("should have viewId in correct format: {renderContext}-{instanceCount}", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) expect(provider.viewId).toMatch(/^sidebar-\d+$/) await provider.dispose() }) it("should increment instance count for each new instance", async () => { const provider1 = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const provider2 = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // First editor instance should be "editor-0" (or next available) // Second editor instance should have a different number const num1 = parseInt(provider1.viewId.split("-")[1]!) const num2 = parseInt(provider2.viewId.split("-")[1]!) expect(num2).toBeGreaterThan(num1) await provider1.dispose() await provider2.dispose() }) }) describe("active instance tracking", () => { it("removes the provider from active instances when dispose completes", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // A live provider is tracked... expect(ClineProvider.getAllInstances()).toContain(provider) await provider.dispose() // ...and disposal releases it. expect(ClineProvider.getAllInstances()).not.toContain(provider) }) // Measured before the fix: one dispose() ran each of these releases twice - the teardown // body performed the broker release, the listener removal and the MCP unregistration after // the caller's finally had already done them. The second dispose() was already a no-op, so // the existing guard test could not see the doubling; only a count across the pair can. it("releases the broker, the listeners and the MCP registration exactly once across a double dispose", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await new Promise((resolve) => setImmediate(resolve)) const broker = vi.spyOn(provider["diagnosticsRequestBroker"], "dispose") const listeners = vi.spyOn(provider, "removeAllListeners") const unregister = vi.spyOn(McpServerManager, "unregisterProvider") await provider.dispose() await provider.dispose() expect(broker).toHaveBeenCalledTimes(1) expect(listeners).toHaveBeenCalledTimes(1) expect(unregister).toHaveBeenCalledTimes(1) expect(ClineProvider.getAllInstances()).not.toContain(provider) broker.mockRestore() listeners.mockRestore() unregister.mockRestore() }) // The dispose-time hydrate was a merge artifact that neither parent carried: it started a // state load against a provider that is already closing, with no live view to deliver to. it("does not start a view-state load while disposing", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await new Promise((resolve) => setImmediate(resolve)) // loadViewState is private and private keys sit outside keyof, so the spy needs one // assertion onto the method shape it actually has (AGENTS.md: last resort, commented). const load = vi.spyOn( ClineProvider.prototype as unknown as { loadViewState: () => Promise }, "loadViewState", ) await provider.dispose() expect(load).not.toHaveBeenCalled() load.mockRestore() }) it("releases the provider and reports the failure when a cleanup step rejects", async () => { // Force a cleanup step inside dispose() to reject. _disposed is set // before cleanup runs, so the provider must still be released from // activeInstances and the error must surface to the caller instead // of being swallowed. const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const taskHistoryDispose = vi.spyOn(provider.taskHistoryStore, "dispose").mockImplementation(() => { throw new Error("task history store dispose failed") }) expect(ClineProvider.getAllInstances()).toContain(provider) await expect(provider.dispose()).rejects.toThrow("task history store dispose failed") // The failing step is reported with its label and the original message. expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( "Provider cleanup step 'taskHistoryStore' failed: task history store dispose failed", ) expect(ClineProvider.getAllInstances()).not.toContain(provider) // The idempotency guard still holds: a second dispose is a no-op. await provider.dispose() taskHistoryDispose.mockRestore() }) it("runs every later cleanup step when an earlier step rejects", async () => { // A single failing cleanup step must not skip the remaining releases: // _disposed is already set, so skipped steps would leak for the life of // the extension host. mcpHub.unregisterClient rejects; the manager and // store releases that come after it must still run, and the first error // must still surface to the caller. const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // The constructor resolves McpServerManager.getInstance asynchronously and // assigns this.mcpHub in its .then; let that settle first so the double // below is not overwritten by the hub before dispose reads it. await new Promise((resolve) => setImmediate(resolve)) // Structural double: dispose() only ever calls unregisterClient on mcpHub. provider["mcpHub"] = { unregisterClient: vi.fn().mockRejectedValue(new Error("mcp unregister failed")), } as unknown as (typeof provider)["mcpHub"] const customModesDispose = vi.spyOn(provider["customModesManager"], "dispose") const taskHistoryDispose = vi.spyOn(provider.taskHistoryStore, "dispose") await expect(provider.dispose()).rejects.toThrow("mcp unregister failed") expect(customModesDispose).toHaveBeenCalledOnce() expect(taskHistoryDispose).toHaveBeenCalledOnce() customModesDispose.mockRestore() taskHistoryDispose.mockRestore() }) it("runs every cleanup branch when the provider is fully wired", async () => { // Exercises the cleanup branches dispose() skips in the default unit harness: a // task on the stack, a live view, registered disposables, and an initialized // CloudService. Spies and exact log strings pin the cleanup sequence so a // removed or reordered step fails the test. const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // A task on the stack forces the eviction branch (evictCurrentTask). drain // calls task.dispose(), so a task double with a spied dispose() proves the // drain ran without spying the private method itself. const fakeTask = { taskId: "dispose-test-task", dispose: vi.fn().mockResolvedValue(undefined), } as unknown as Task provider["taskRegistry"].push(fakeTask) const evictCurrentTask = vi.spyOn(provider, "evictCurrentTask").mockImplementation(async () => { provider["taskRegistry"].pop() }) // Defensive pop: if the eviction branch is mutated away, the stack-drain while // loop still terminates instead of spinning on a task that is never removed. const removeClineFromStack = vi.spyOn(provider, "removeClineFromStack").mockImplementation(async () => { provider["taskRegistry"].pop() }) const clearAllPendingEditOperations = vi.spyOn(provider["pendingEditOperations"], "clearAll") // A live view and registered disposables exercise the webview teardown branches. const viewDispose = vi.fn() // @ts-ignore - accessing private property for testing provider.view = { dispose: viewDispose, visible: true } const webviewDisposableDispose = vi.fn() provider["webviewDisposables"].push({ dispose: webviewDisposableDispose }) const disposableDispose = vi.fn() provider["disposables"].push({ dispose: disposableDispose }) // An initialized CloudService instance exercises the listener-detach branch. // The @roo-code/cloud mock above reports hasInstance() === true by default, // so only the static instance getter needs swapping. It uses the same // defineProperty style the getTelemetryProperties tests use (and restores // the original descriptor exactly) so no mock getter leaks into later tests. // Spying on the mock's hasInstance instead would restore a cleared // implementation and break those tests. const cloudOff = vi.fn() const originalInstanceDescriptor = Object.getOwnPropertyDescriptor(CloudService, "instance")! // Minimal EventEmitter stand-in: only off() is observed. Object.defineProperty(CloudService, "instance", { get: () => ({ off: cloudOff }) as unknown as CloudService, configurable: true, }) try { await provider.dispose() // The eviction branch ran, and only the eviction branch (not the stack drain); // drainTaskDisposal() completed through the task's own dispose(). expect(evictCurrentTask).toHaveBeenCalledTimes(1) expect(fakeTask.dispose).toHaveBeenCalledTimes(1) expect(removeClineFromStack).not.toHaveBeenCalled() // Webview teardown and registered disposables ran. expect(viewDispose).toHaveBeenCalledTimes(1) expect(webviewDisposableDispose).toHaveBeenCalledTimes(1) expect(disposableDispose).toHaveBeenCalledTimes(1) expect(clearAllPendingEditOperations).toHaveBeenCalledTimes(1) // The cloud service listener was detached with the exact event and handler. expect(cloudOff).toHaveBeenCalledWith("settings-updated", provider["handleCloudSettingsUpdate"]) // The exact log strings pin the cleanup sequence. for (const line of [ "Cleared all tasks", "Cleared pending operations", "Disposed webview", "Disposed all disposables", ]) { expect(mockOutputChannel.appendLine).toHaveBeenCalledWith(line) } } finally { Object.defineProperty(CloudService, "instance", originalInstanceDescriptor) } evictCurrentTask.mockRestore() removeClineFromStack.mockRestore() clearAllPendingEditOperations.mockRestore() }) it("completes disposal when the optional manager instances are absent", async () => { // The constructor always initializes the manager instances, so the skip branches // of the optional call sites in dispose() are unreachable otherwise: null them // to prove disposal completes when they are absent instead of throwing on the // de-referenced call. const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) Object.assign(provider, { _workspaceTracker: undefined, skillsManager: undefined, marketplaceManager: undefined, customModesManager: undefined, }) await expect(provider.dispose()).resolves.toBeUndefined() expect(ClineProvider.getAllInstances()).not.toContain(provider) }) it("skips falsy disposable entries instead of calling dispose on them", async () => { // The disposal loop guards each popped entry with a falsy check: a falsy // entry must be skipped so disposal still resolves. Calling dispose() on it // would throw and make dispose() reject instead. const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const realDispose = vi.fn() provider["disposables"].push({ dispose: realDispose }) // @ts-ignore - push a falsy entry to exercise the falsy guard provider["disposables"].push(undefined) await expect(provider.dispose()).resolves.toBeUndefined() // The real entry was still disposed; the falsy one was skipped. expect(realDispose).toHaveBeenCalledTimes(1) expect(ClineProvider.getAllInstances()).not.toContain(provider) }) }) describe("saveViewState", () => { it("should update viewLocalState and persist mode through registered viewStates", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const contextProxySpy = vi.spyOn(provider.contextProxy, "setValue") await provider["setViewStateId"]("stable-sidebar-view") await provider.saveViewState("mode", "architect") expect(provider["viewLocalState"].mode).toBe("architect") expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ "stable-sidebar-view": { mode: "architect" }, }) expect(contextProxySpy).toHaveBeenCalledWith( "viewStates", expect.objectContaining({ "stable-sidebar-view": expect.objectContaining({ mode: "architect", updatedAt: expect.any(Number), }), }), ) expect(contextProxySpy).not.toHaveBeenCalledWith("__view_state_stable-sidebar-view_mode", expect.anything()) await provider.dispose() }) it("should update viewLocalState and persist currentApiConfigName through registered viewStates", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("stable-sidebar-view") await provider.saveViewState("currentApiConfigName", "my-profile") expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ "stable-sidebar-view": { currentApiConfigName: "my-profile" }, }) await provider.dispose() }) it("should update viewLocalState for apiConfiguration without persisting provider settings or secrets", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const testApiConfig = { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "claude-3.5-sonnet", openRouterApiKey: "secret-key", } await provider["setViewStateId"]("stable-sidebar-view") await provider.saveViewState("apiConfiguration", testApiConfig) expect(provider["viewLocalState"].apiConfiguration).toEqual(testApiConfig) expect(provider.contextProxy.getValue("viewStates")).toBeUndefined() await provider.dispose() }) it("should clear local override when saveViewState receives undefined", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.saveViewState("mode", "architect") expect(provider["viewLocalState"].mode).toBe("architect") await provider.saveViewState("mode", undefined) expect(Object.prototype.hasOwnProperty.call(provider["viewLocalState"], "mode")).toBe(false) await provider.dispose() }) it("should clear the currentApiConfigName override when saveViewState receives undefined", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.saveViewState("currentApiConfigName", "my-profile") expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") await provider.saveViewState("currentApiConfigName", undefined) expect(Object.prototype.hasOwnProperty.call(provider["viewLocalState"], "currentApiConfigName")).toBe(false) await provider.dispose() }) it("should not update viewLocalState when durable view-state persistence fails", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) vi.spyOn(provider.contextProxy, "setValue").mockRejectedValueOnce(new Error("persist failed")) await provider["setViewStateId"]("stable-sidebar-view") await expect(provider.saveViewState("mode", "architect")).rejects.toThrow("persist failed") expect(provider["viewLocalState"]).not.toHaveProperty("mode") expect(provider.contextProxy.getValue("viewStates")).toBeUndefined() await provider.dispose() }) it("should merge concurrent persisted updates from separate provider instances without lost viewStates", async () => { const provider1 = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const provider2 = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider1["setViewStateId"]("stable-sidebar-view") await provider2["setViewStateId"]("stable-editor-view") await Promise.all([ provider1.saveViewState("mode", "architect"), provider2.saveViewState("currentApiConfigName", "editor-profile"), ]) expect(mockContext.globalState.get("viewStates")).toMatchObject({ "stable-sidebar-view": { mode: "architect" }, "stable-editor-view": { currentApiConfigName: "editor-profile" }, }) await provider1.dispose() await provider2.dispose() }) it("rolls the shared values back when the durable view-state write fails on setValues", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("rollback-view") await provider.setValues({ mode: "code" }) expect(provider.contextProxy.getValue("mode")).toBe("code") // Fail only the durable viewStates write: rejecting the first contextProxy.setValue // call would fail the shared write itself, so the rollback branch would never run. const originalSetValue = provider.contextProxy.setValue.bind(provider.contextProxy) vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key, value) => { if (key === "viewStates") throw new Error("persist failed") return originalSetValue(key, value) }) await expect(provider.setValues({ mode: "architect" })).rejects.toThrow("persist failed") expect(provider.contextProxy.getValue("mode")).toBe("code") await provider.dispose() }) it("rolls the shared value back when the durable view-state write fails on setValue", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("rollback-view") await provider.setValue("mode", "code") expect(provider.contextProxy.getValue("mode")).toBe("code") // Fail only the durable viewStates write: rejecting the first contextProxy.setValue // call would fail the shared write itself, so the rollback branch would never run. const originalSetValue = provider.contextProxy.setValue.bind(provider.contextProxy) vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key, value) => { if (key === "viewStates") throw new Error("persist failed") return originalSetValue(key, value) }) await expect(provider.setValue("mode", "architect")).rejects.toThrow("persist failed") // The shared write landed before the durable viewStates write failed: it must be // rolled back so the cache cannot run ahead of storage. expect(provider.contextProxy.getValue("mode")).toBe("code") await provider.dispose() }) }) describe("loadViewState", () => { it("should keep viewLocalState empty when no stable per-view values exist", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await vi.waitFor(() => { expect(provider["viewLocalState"]).toEqual({}) }) const state = await provider.getState() // No per-view entry exists and the proxy's global-state cache is empty // (initialize() is never called in this fixture; only "taskHistory" passes // through to the context store), so getState() falls back to the shared // defaults: mode "code" (defaultModeSlug) and currentApiConfigName "default". expect(state.mode).toBe("code") expect(state.currentApiConfigName).toBe("default") await provider.dispose() }) it("should log and keep existing viewLocalState when loadViewState fails", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") // Register a stable id so the load is not skipped by the ownership guard: // only entries this instance authored are loaded under a temporary name. await provider["setViewStateId"]("stable-sidebar-view") provider["viewLocalState"] = { mode: "architect" } vi.spyOn(provider.contextProxy, "getValue").mockImplementation(() => { throw new Error("load failed") }) await provider["loadViewState"]() expect(provider["viewLocalState"].mode).toBe("architect") expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Error loading state")) await provider.dispose() }) it("keeps a mid-load flat provider-settings write shared instead of overlaying the pinned profile", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("midload-settings-view") // A previous session pinned a profile for this view (written through the // context proxy so the load's cache read sees the entry). await provider.contextProxy.setValue("viewStates", { "midload-settings-view": { currentApiConfigName: "profile-a", updatedAt: 1 }, }) const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) const loading = provider["loadViewState"]() await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) // A flat provider-settings change (not a full apiConfiguration write) // completes while the load is stalled: it is a SHARED write and must land in // the ContextProxy, but it is not a view-local mutation, so the settling // load still applies the pinned profile's resolved configuration to this // view's buffer (A semantics: flat keys never overlay viewLocalState). await provider.setValue("openRouterModelId", "model-z") resolveProfile({ name: "profile-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x", }) await loading // The shared write landed in the ContextProxy ... expect(provider.contextProxy.getValue("openRouterModelId")).toBe("model-z") // ... but the view-local buffer keeps the pinned profile's resolved // configuration: merging the flat key into viewLocalState.apiConfiguration // would turn it into a per-view override masking later shared updates. expect(provider["viewLocalState"].apiConfiguration?.openRouterModelId).toBe("model-x") await provider.dispose() }) it("discards an in-flight load when a reset clears view state mid-load", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("reset-view") await provider.contextProxy.setValue("viewStates", { "reset-view": { currentApiConfigName: "stale-profile", updatedAt: 1 }, }) const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) const loading = provider["loadViewState"]() await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) // A reset/import invalidation clears the view-local buffer mid-load (the // broadcast path does exactly this). The clear is not a field mutation, so // the mutation tracking above cannot protect it: the generation must. provider["_clearViewLocalState"]() resolveProfile({ name: "stale-profile", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x", }) await loading // The stale load must not resurrect the selections the reset cleared. expect(provider["viewLocalState"]).toEqual({}) await provider.dispose() }) it("does not resurrect a field cleared mid-load from the stale persisted value the load read", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("clear-view") // A previous session pinned a profile for this view. Write through the // context proxy so the cache the load reads from sees the entry (a raw // globalState write bypasses it). await provider.contextProxy.setValue("viewStates", { "clear-view": { currentApiConfigName: "stale-profile", updatedAt: 1 }, }) // Stall the load's profile lookup so a view-local mutation can complete // while the load is in flight. const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) const loading = provider["loadViewState"]() await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) // The user clears the view's profile selection while the load is stalled; // the clear is a durable write and must win over the stale value. await provider.saveViewState("currentApiConfigName", undefined) // The same view also clears its pinned configuration while the load is stalled. await provider.saveViewState("apiConfiguration", undefined) resolveProfile({ name: "stale-profile", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x", }) await loading // The load resolved the stale profile it read before the clear: without the // mutation tracking it would re-pin the cleared selection. The cleared field // must stay absent so the view keeps following the shared selection. expect(provider["viewLocalState"]).not.toHaveProperty("currentApiConfigName") expect(provider["viewLocalState"]).not.toHaveProperty("mode") // The cleared configuration must not be re-applied from the resolved profile // either: without the guard the load would restore the profile's config. expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") await provider.dispose() }) }) describe("persisted view state pruning", () => { it("should keep the newest 50 persisted view states", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const states = Object.fromEntries( Array.from({ length: 55 }, (_, index) => [ `view-${index}`, { mode: `mode-${index}`, updatedAt: index }, ]), ) const pruned = provider["prunePersistedViewStates"](states) expect(Object.keys(pruned)).toHaveLength(50) expect(pruned["view-54"]).toEqual({ mode: "mode-54", updatedAt: 54 }) expect(pruned["view-5"]).toEqual({ mode: "mode-5", updatedAt: 5 }) expect(pruned["view-4"]).toBeUndefined() await provider.dispose() }) }) describe("setter rollback scope", () => { it("restores the shared store when the initial multi-key shared write fails", async () => { const contextProxy = new ContextProxy(mockContext) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", contextProxy, new WebviewFocusTracker(), ) await contextProxy.setValue("mode", "code") await contextProxy.setValue("collapseCommandOutputByDefault", true) // Partial durability, the shape ContextProxy.setValues itself leaves: it stores each key on // its own, so this stub commits the payload's first key and then rejects before the second // one lands. The rollback owns the key that landed and must leave the other one where it was, // so the two final-value assertions below check the store rather than only the stub's calls. const setValuesOriginal = contextProxy.setValues.bind(contextProxy) const setValuesSpy = vi.spyOn(contextProxy, "setValues").mockImplementationOnce(async (values) => { const [firstKey] = Object.keys(values) as (keyof RooCodeSettings)[] const landedValues = { [firstKey]: values[firstKey] } as RooCodeSettings await setValuesOriginal(landedValues) throw new Error("shared write failed") }) await expect( provider.setValues({ mode: "architect", collapseCommandOutputByDefault: false }), ).rejects.toThrow("shared write failed") // Both settings' final values, read from the store the failed call wrote through: the landed // key is back to its prior value, and the key that never landed kept its prior value. expect(contextProxy.getValue("mode")).toBe("code") expect(contextProxy.getValue("collapseCommandOutputByDefault")).toBe(true) // Supplementary, not the proof of the restored state: the rollback call itself carried the // prior mode (the first call is the failed forward write, the second is the restore). expect(setValuesSpy).toHaveBeenCalledTimes(2) expect(setValuesSpy.mock.calls[1][0]).toEqual({ mode: "code" }) // The per-view buffer never saw either failed value. expect(provider["viewLocalState"].mode).toBeUndefined() expect(provider["viewLocalState"]).not.toHaveProperty("collapseCommandOutputByDefault") await provider.dispose() }) it("restores the shared store when the initial single-key shared write fails", async () => { const contextProxy = new ContextProxy(mockContext) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", contextProxy, new WebviewFocusTracker(), ) await contextProxy.setValue("mode", "code") // Same partial-durability shape as the multi-key case above: the value lands in the // store and the write still rejects, so the shared restore has a value of ours to undo. const setValueOriginal = contextProxy.setValue.bind(contextProxy) const setValueSpy = vi.spyOn(contextProxy, "setValue").mockImplementationOnce(async (key, value) => { await setValueOriginal(key, value) throw new Error("shared write failed") }) const restoreSpy = vi.spyOn(contextProxy, "setValues") await expect(provider.setValue("mode", "architect")).rejects.toThrow("shared write failed") // The rollback routes through setValues (shared restore helper), and it // must carry the prior value, not the failed one. (Later setValue calls // belong to teardown; the forward write is the first call.) expect(setValueSpy.mock.calls[0]).toEqual(["mode", "architect"]) expect(restoreSpy).toHaveBeenCalledWith({ mode: "code" }) expect(provider["viewLocalState"].mode).toBeUndefined() await provider.dispose() }) }) describe("broadcastResetToAllInstances durable failure", () => { it("clears every live buffer and posts siblings even when the durable clear fails", async () => { const contextProxy = new ContextProxy(mockContext) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", contextProxy, new WebviewFocusTracker(), ) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Live selections that a failed durable clear must not strand. provider["viewLocalState"] = { mode: "architect" } sibling["viewLocalState"] = { mode: "architect" } const siblingPost = vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) // The first proxy write is the queued durable clear of the shared slot. const setValueSpy = vi .spyOn(contextProxy, "setValue") .mockRejectedValueOnce(new Error("durable clear failed")) await expect(provider.broadcastResetToAllInstances()).rejects.toThrow("durable clear failed") // Live invalidation ran despite the durable failure, and the caller still // sees the durable error after the loop completed. expect(provider["viewLocalState"]).toEqual({}) expect(sibling["viewLocalState"]).toEqual({}) expect(siblingPost).toHaveBeenCalledTimes(1) expect(setValueSpy).toHaveBeenCalledWith("viewStates", undefined) setValueSpy.mockRestore() await provider.dispose() await sibling.dispose() }) }) describe("setViewStateId", () => { it('should ignore "__proto__" and keep the temporary viewId', async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("__proto__") // "__proto__" is rejected before assignment so a per-view entry can never be // keyed through the Object.prototype setter: the temporary id stays active and // nothing is persisted under the reserved name. expect(provider["viewStateId"]).toBe(provider.viewId) expect(mockContext.globalState.get("viewStates")).toBeUndefined() expect(provider["viewLocalState"]).toEqual({}) await provider.dispose() }) it("restores the previous view id when the registration write fails so a later launch retries", async () => { const contextProxy = new ContextProxy(mockContext) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", contextProxy, new WebviewFocusTracker(), ) // Author the pre-launch entry through the real write path so this instance // owns it: unowned temporary entries are never re-keyed. // Seed a pre-launch entry under the temporary id so the re-key has real work to do. // Author the pre-launch entry through the real write path so this instance owns it. await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) const setValueSpy = vi.spyOn(contextProxy, "setValue").mockRejectedValue(new Error("storage down")) await expect(provider["setViewStateId"]("stable-sidebar-view")).rejects.toThrow("storage down") // The failed id must not stick: the provider keeps its previous (temporary) // id so a later launch retries registration and the load instead of the // guard early-returning for an id that was never persisted. expect(provider["viewStateId"]).toBe(provider.viewId) // A later retry succeeds once the storage write works again, and the // pre-launch entry lands under the registered id. setValueSpy.mockRestore() await provider["setViewStateId"]("stable-sidebar-view") expect(provider["viewStateId"]).toBe("stable-sidebar-view") expect(mockContext.globalState.get("viewStates")).toEqual({ "stable-sidebar-view": { mode: "architect", updatedAt: 1 }, }) await provider.dispose() }) it("restores the previous view id when the persisted load fails, so a later launch reloads it", async () => { const contextProxy = new ContextProxy(mockContext) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", contextProxy, new WebviewFocusTracker(), ) await contextProxy.setValue("viewStates", { "view-b": { mode: "architect", updatedAt: 1 } }) // getCustomModes is read before the pinned mode can be restored and its rejection // is swallowed inside loadViewState (only logged), so this is the load failure that // the throw-based rollback never saw. const getCustomModesSpy = vi .spyOn(provider["customModesManager"], "getCustomModes") .mockRejectedValueOnce(new Error("modes unavailable")) await provider["setViewStateId"]("view-b") expect(provider["viewStateId"]).toBe(provider.viewId) expect(provider["viewLocalState"]).toEqual({}) // The retried registration loads the pin instead of early-returning on the id the // failed load left behind. getCustomModesSpy.mockRestore() await provider["setViewStateId"]("view-b") expect(provider["viewStateId"]).toBe("view-b") expect(provider["viewLocalState"].mode).toBe("architect") await provider.dispose() }) it("settles viewStateReadiness even when first read after the id is registered", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("late-reader-view") // First read happens after registration: a lazily created promise would hold a // fresh, never-resolving resolver here (the registration's resolve call was a // no-op), so settling proves the promise was created eagerly in the constructor. const settled = provider.viewStateReadiness.then( () => true, () => false, ) expect(await settled).toBe(true) await provider.dispose() }) it("settles viewStateReadiness when the launch carries no usable view id", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const readiness = provider.viewStateReadiness const settled = readiness.then( () => true, () => false, ) // The CLI launch sends the registration message without a view-state id: the // early return must still settle readiness so API-driven task creation does // not fall through to its timeout waiting for a state that never registers. await provider["setViewStateId"](undefined) await provider["setViewStateId"](" ") expect(await settled).toBe(true) expect(provider["viewStateId"]).toBe(provider.viewId) await provider.dispose() }) it("resolves viewStateReadiness when the provider disposes before the id is registered", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const readiness = provider.viewStateReadiness const settled = readiness.then( () => true, () => false, ) await provider.dispose() expect(await settled).toBe(true) }) it("resolves viewStateReadiness once the stable id is registered", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const readiness = provider.viewStateReadiness const settled = readiness.then( () => true, () => false, ) await provider["setViewStateId"]("ready-view") expect(await settled).toBe(true) await provider.dispose() }) }) it("aborts the shared settings write when a pinned sibling's profile cannot be snapshotted", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) try { sibling["viewLocalState"].currentApiConfigName = "sibling-profile" vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) await provider.contextProxy.setValue("listApiConfigMeta", [ { name: "sibling-profile", id: "sibling-id", apiProvider: providerIdentifiers.openrouter }, { name: "activated-profile", id: "activated-id", apiProvider: providerIdentifiers.anthropic }, ]) vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => { if ("name" in params && params.name === "activated-profile") { return { name: "activated-profile", id: "activated-id", apiProvider: providerIdentifiers.anthropic, apiKey: "activated-key", } } throw new Error("sibling profile read failed") }) vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("mode-id") vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) // The snapshot must abort before the manager is asked to switch: the store's // selected profile and the mode that follows it stay the pre-activation pair. const activateProfileSpy = vi.spyOn(provider.providerSettingsManager, "activateProfile") vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) const sharedSettingsBefore = provider.contextProxy.getProviderSettings() // The abort names the pin it could not snapshot. Match the pin rather than the // wording: the sibling branches that carry this rule phrase the abort differently, // and the rule - not the sentence - is what must stay covered. await expect(provider.activateProviderProfile({ name: "activated-profile" })).rejects.toThrow( /sibling-profile/, ) expect(activateProfileSpy).not.toHaveBeenCalled() // The sibling is still pinned to its own profile: if the shared write had // landed, its getState() would report that pin with the activated profile's // settings and credentials. expect(sibling["viewLocalState"].apiConfiguration).toBeUndefined() expect(provider.contextProxy.getProviderSettings()).toEqual(sharedSettingsBefore) } finally { await sibling.dispose() await provider.dispose() } }) it("tolerates an absent sibling pin while activating another profile", async () => { // A pin naming a record the store no longer has must not block an activation of // another profile: the deletion path re-points that view itself // (rePinViewLocalStateForDeletedProfile), and aborting here would let one stale view // block every later activation in the host. The tolerance at // ClineProvider.ts:4208 branches on ProviderSettingsNotFoundError, so getProfile // must deliver that type for a missing record instead of the wrapper plain Error - // verified through the real manager store, not an injected rejection. const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) try { // The manager store holds the surviving profiles; the sibling pins a name the // store never had (e.g. its secret was pruned by an earlier run while the pin // survived). await provider.providerSettingsManager.saveConfig("sibling-profile", { apiProvider: providerIdentifiers.anthropic, apiKey: "sibling-key", }) await provider.providerSettingsManager.saveConfig("activated-profile", { apiProvider: providerIdentifiers.anthropic, apiKey: "activated-key", }) await sibling["setViewStateId"]("ghost-view") await sibling.saveViewState("currentApiConfigName", "ghost-profile") vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) await provider.activateProviderProfile({ name: "activated-profile" }) // The activation committed: the manager wrote the selection and the write group // carried the activated profile into the shared store next to the profile list. expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("activated-profile") expect(provider.contextProxy.getProviderSettings().apiKey).toBe("activated-key") const entries = (provider.contextProxy.getValue("listApiConfigMeta") ?? []).map((entry) => entry.name) expect(entries).toContain("activated-profile") // The stale view keeps its pin - the deletion path re-points it later - and holds no // overlay, so it cannot pair another profile's settings with the ghost name. expect(sibling["pinnedProfileName"]).toBe("ghost-profile") expect(sibling["viewLocalState"].apiConfiguration).toBeUndefined() } finally { await sibling.dispose() await provider.dispose() } }) it("aborts the activation when the absent sibling pin fails for a reason other than absence", async () => { // The control for the tolerated absent pin: an unknown sibling profile - the record // exists but the read rejects - must still fail the mutation before the shared // write, so the activation never replaces settings nobody could read. const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) try { await provider.providerSettingsManager.saveConfig("sibling-profile", { apiProvider: providerIdentifiers.anthropic, apiKey: "sibling-key", }) await provider.providerSettingsManager.saveConfig("activated-profile", { apiProvider: providerIdentifiers.anthropic, apiKey: "activated-key", }) await sibling["setViewStateId"]("unreadable-view") await sibling.saveViewState("currentApiConfigName", "sibling-profile") vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) const sharedSettingsBefore = provider.contextProxy.getProviderSettings() // The pin names a stored record, but the settings read fails - a secret backend // outage, not an absent record. Scope the failure to the pin read: the listing // this activation reads before the snapshot stays readable, so the abort below // is attributable to the sibling read rather than to the store being down. // Shared-store baseline: the manager's secrets write spy is shared across the whole // suite, so the invariant here is "the activation added no store write and no new // store content", not an absolute call count (the seeding above wrote the store). const storeSpy = vi.spyOn(mockContext.secrets, "store") const storeWritesBefore = storeSpy.mock.calls.length const profilesKey = "roo_cline_config_api_config" const storeBlobBefore = mockContext.secrets.get(profilesKey) vi.spyOn(provider.providerSettingsManager, "getProfile").mockRejectedValue( new Error("Failed to get profile: secret store read down"), ) // The abort names the pin it could not resolve. await expect(provider.activateProviderProfile({ name: "activated-profile" })).rejects.toThrow( /sibling-profile/, ) // Nothing reached the manager: the activation aborted before activateProfile, so // the store holds no selection write and the shared provider keys still hold the // pre-activation settings. expect(storeSpy.mock.calls.length).toBe(storeWritesBefore) expect(mockContext.secrets.get(profilesKey)).toBe(storeBlobBefore) expect(provider.contextProxy.getProviderSettings()).toEqual(sharedSettingsBefore) expect(sibling["pinnedProfileName"]).toBe("sibling-profile") expect(sibling["viewLocalState"].apiConfiguration).toBeUndefined() } finally { await sibling.dispose() await provider.dispose() } }) describe("view state persistence edge cases", () => { it("should read viewStates from the ContextProxy cache when not fresh", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.contextProxy.setValue("viewStates", { "stable-sidebar-view": { mode: "architect" } }) expect(provider["getPersistedViewStates"]()).toEqual({ "stable-sidebar-view": { mode: "architect" } }) await provider.dispose() }) it("should treat a corrupted non-object viewStates value as an empty map", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // A string in storage is corrupt: the fresh-read guard must not spread it. await mockContext.globalState.update("viewStates", "corrupted-storage-value") expect(provider["getPersistedViewStates"]({ fresh: true })).toEqual({}) await provider.dispose() }) it("should merge saved fields, drop cleared fields and delete emptied entries", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") const save = provider.saveViewState.bind(provider) as (key: string, value: unknown) => Promise const states = () => mockContext.globalState.get>("viewStates") ?? {} await provider["setViewStateId"]("stable-sidebar-view") await provider.saveViewState("mode", "architect") await provider.saveViewState("currentApiConfigName", "profile-a") const merged = states()["stable-sidebar-view"] expect(merged).toMatchObject({ mode: "architect", currentApiConfigName: "profile-a" }) expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Saved mode=architect for viewId")) await save("mode", undefined) expect(states()["stable-sidebar-view"]).toStrictEqual({ currentApiConfigName: "profile-a", updatedAt: expect.any(Number), }) await save("mode", null) expect(states()["stable-sidebar-view"]).not.toHaveProperty("mode") await provider.saveViewState("mode", "architect") await save("currentApiConfigName", undefined) expect(states()["stable-sidebar-view"]).toStrictEqual({ mode: "architect", updatedAt: expect.any(Number), }) await provider.saveViewState("currentApiConfigName", "profile-c") await provider.saveViewState("mode", "architect") expect(states()["stable-sidebar-view"]).toMatchObject({ mode: "architect", currentApiConfigName: "profile-c", }) await save("currentApiConfigName", null) expect(states()["stable-sidebar-view"]).not.toHaveProperty("currentApiConfigName") await save("mode", null) expect(states()["stable-sidebar-view"]).toBeUndefined() expect(provider["viewLocalState"]).toStrictEqual({}) // buffer ends fully cleared await provider.dispose() }) it("should rekey a pre-launch entry under the temporary id to the registered stable id", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Seed through the write path so this instance is the author of the entry under // its temporary id; an entry authored by another session must not be adopted. await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) await provider["setViewStateId"]("stable-sidebar-view") expect(mockContext.globalState.get("viewStates")).toEqual({ "stable-sidebar-view": { mode: "architect", updatedAt: 1 }, }) await provider.dispose() }) it("should keep the stable entry and drop the temporary entry when both exist", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Author the temporary entry through the write path so this instance owns it, // then add a stable entry that already exists in storage. await provider["savePersistedViewState"]({ mode: "temp-mode", updatedAt: 1 }) await provider.contextProxy.setValue("viewStates", { [provider.viewId]: { mode: "temp-mode", updatedAt: 1 }, "stable-sidebar-view": { mode: "stable-mode", updatedAt: 5 }, }) await provider["setViewStateId"]("stable-sidebar-view") expect(mockContext.globalState.get("viewStates")).toEqual({ "stable-sidebar-view": { mode: "stable-mode", updatedAt: 5 }, }) await provider.dispose() }) it("should clear only this view's entry without clobbering an entry only storage knows about", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("stable-sidebar-view") // The cache only knows this view's entry; storage gains an extra view directly. await provider.contextProxy.setValue("viewStates", { "stable-sidebar-view": { mode: "architect" } }) await mockContext.globalState.update("viewStates", { "stable-sidebar-view": { mode: "architect" }, "stable-editor-view": { mode: "code" }, }) await provider["clearPersistedViewState"]() expect(mockContext.globalState.get("viewStates")).toEqual({ "stable-editor-view": { mode: "code" } }) await provider.dispose() }) it("should prune by updatedAt regardless of insertion order", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const states = Object.fromEntries( Array.from({ length: 55 }, (_, index) => [ `view-${index}`, { mode: `mode-${index}`, updatedAt: (index * 7) % 55 }, ]), ) const pruned = provider["prunePersistedViewStates"](states) expect(Object.keys(pruned)).toHaveLength(50) // view-1/view-54 survive the true newest-50 selection; view-8 (updatedAt 1) does not. expect(pruned["view-1"]).toEqual({ mode: "mode-1", updatedAt: 7 }) expect(pruned["view-54"]).toEqual({ mode: "mode-54", updatedAt: 48 }) expect(pruned["view-8"]).toBeUndefined() await provider.dispose() }) it("should sanitize, reject blank and undefined ids, and no-op on the active id", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") await provider["setViewStateId"]("a b/c") expect(provider["viewStateId"]).toBe("a_b_c") await provider["setViewStateId"](undefined) await provider["setViewStateId"](" ") expect(provider["viewStateId"]).toBe("a_b_c") logSpy.mockClear() await provider["setViewStateId"]("a_b_c") expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining("Loaded state for viewId")) await provider.dispose() }) it("should load persisted mode, profile name and resolved profile into viewLocalState", async () => { const writer = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await writer["setViewStateId"]("shared-view") await writer.saveViewState("mode", "architect") await writer.saveViewState("currentApiConfigName", "my-profile") const provider = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") const getProfileSpy = vi.fn().mockResolvedValue({ name: "my-profile", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x", }) // @ts-ignore - Replace providerSettingsManager with a test double for the profile lookup. provider.providerSettingsManager = { getProfile: getProfileSpy, runExclusiveAcrossInstances: runManagerSectionInline, } // The ownership check requires the writer to release the id before the // next view adopts it; the durable entry it wrote stays in storage. await writer.dispose() await provider.contextProxy.setValue( "viewStates", mockContext.globalState.get("viewStates"), ) await provider["setViewStateId"]("shared-view") expect(provider["viewLocalState"]).toEqual({ mode: "architect", currentApiConfigName: "my-profile", apiConfiguration: { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }, }) expect(getProfileSpy).toHaveBeenCalledWith({ name: "my-profile" }) expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Loaded state for viewId")) await provider.dispose() }) it("should log a successful empty load when no persisted entry exists", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") await provider["setViewStateId"]("stable-sidebar-view") expect(provider["viewLocalState"]).toEqual({}) expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Loaded state for viewId")) await provider.dispose() }) it("should keep the persisted profile name and log when the profile lookup fails", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") // @ts-ignore - Replace providerSettingsManager with a failing test double. provider.providerSettingsManager = { getProfile: vi.fn().mockRejectedValue(new Error("profile missing")), runExclusiveAcrossInstances: runManagerSectionInline, } await provider.saveViewState("currentApiConfigName", "my-profile") await provider["setViewStateId"]("stable-sidebar-view") expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Unable to resolve API profile 'my-profile'")) await provider.dispose() }) it("should discard a stale load when the viewStateId changes during the profile lookup", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") // @ts-ignore - Replace providerSettingsManager with a test double that registers a newer id. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getProfile: vi.fn().mockImplementation(() => { provider["viewStateId"] = "superseded-view" return Promise.resolve({ name: "my-profile", apiProvider: providerIdentifiers.openrouter }) }), } await provider.saveViewState("currentApiConfigName", "my-profile") await provider["setViewStateId"]("stable-sidebar-view") expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") const staleMsg = expect.stringContaining("Discarding stale state for superseded view id") expect(logSpy).toHaveBeenCalledWith(staleMsg) await provider.dispose() }) it("should reapply fields mutated while the load is in flight and keep persisted values for untouched fields", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) await provider.saveViewState("currentApiConfigName", "cfg-a") const load = provider["setViewStateId"]("stable-sidebar-view") // Let the stalled lookup begin so the in-flight mutations and the resolver // target the pending promise rather than the initial no-op. await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) // Selections made while the profile lookup is in flight must survive the load. await provider.saveViewState("mode", "architect") await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-y", }) resolveProfile({ name: "cfg-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }) await load // Dirty fields win over the loaded state; the untouched field keeps the persisted value. expect(provider["viewLocalState"]).toEqual({ mode: "architect", currentApiConfigName: "cfg-a", apiConfiguration: { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-y" }, }) expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Loaded state for viewId")) await provider.dispose() }) it("should keep the persisted mode authoritative when the pre-load buffer is untouched", async () => { const writer = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await writer["setViewStateId"]("shared-view") await writer.saveViewState("mode", "code") await writer.saveViewState("currentApiConfigName", "my-profile") const provider = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // @ts-ignore - Replace providerSettingsManager with a test double for the profile lookup. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getProfile: vi.fn().mockResolvedValue({ name: "my-profile", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x", }), } // A pre-load buffer write that was never persisted must not be merged over the load. provider["viewLocalState"] = { mode: "architect" } // The ownership check requires the writer to release the id before the // next view adopts it; the durable entry it wrote stays in storage. await writer.dispose() await provider.contextProxy.setValue( "viewStates", mockContext.globalState.get("viewStates"), ) await provider["setViewStateId"]("shared-view") expect(provider["viewLocalState"].mode).toBe("code") expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") expect(provider["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x", }) await provider.dispose() }) it("should not restore a persisted mode whose custom mode no longer exists", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") // @ts-ignore - Replace customModesManager with a test double (no custom modes). provider.customModesManager = { getCustomModes: vi.fn().mockResolvedValue([]), dispose: vi.fn() } // The file-level modes mock resolves every slug to a mode. Stand in the production lookup // instead: with no custom modes from the manager and no built-in of that name, the persisted // slug is unknown on its own terms rather than because a test said so. const actualModes = await vi.importActual("../../../shared/modes") const modesModule = vi.mocked(await import("../../../shared/modes")) const originalMode = modesModule.getModeBySlug("code") modesModule.getModeBySlug.mockImplementation(actualModes.getModeBySlug) try { await provider["setViewStateId"]("stable-sidebar-view") await provider.saveViewState("mode", "deleted-custom-mode") // Reload the persisted entry: the custom mode was deleted in the meantime. await provider["loadViewState"]() // The stale slug must not be restored into the buffer. expect(provider["viewLocalState"]).not.toHaveProperty("mode") expect(logSpy).toHaveBeenCalledWith( expect.stringContaining('Ignoring unknown persisted mode "deleted-custom-mode"'), ) } finally { modesModule.getModeBySlug.mockReturnValue(originalMode) } await provider.dispose() }) it("should not resurrect a field cleared mid-load from the pre-load buffer", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) // Persist a mode too: without it the load has no mode to resurrect, so the // cleared-field assertion below would pass even if the loaded value clobbered // the in-flight clear. await provider.saveViewState("currentApiConfigName", "cfg-a") await provider.saveViewState("mode", "code") provider["viewLocalState"] = { ...provider["viewLocalState"], mode: "architect" } const load = provider["setViewStateId"]("stable-sidebar-view") // Let the stalled lookup begin so the in-flight clear and the resolver // target the pending promise rather than the initial no-op. await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) // The user clears the mode while the load is in flight. await provider.saveViewState("mode", undefined) resolveProfile({ name: "cfg-a" }) await load // The cleared field must stay absent rather than keeping the persisted or // pre-load value; the untouched field keeps the persisted value. expect(provider["viewLocalState"]).not.toHaveProperty("mode") expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-a") await provider.dispose() }) it("should reapply an independently mutated mode when the load settles", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) await provider.saveViewState("currentApiConfigName", "cfg-a") const load = provider["setViewStateId"]("stable-sidebar-view") // Let the stalled lookup begin so the in-flight mutation and the resolver // target the pending promise rather than the initial no-op. await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) // Only the mode is mutated while the profile lookup is in flight. await provider.saveViewState("mode", "architect") resolveProfile({ name: "cfg-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }) await load expect(provider["viewLocalState"]).toEqual({ mode: "architect", currentApiConfigName: "cfg-a", apiConfiguration: { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }, }) await provider.dispose() }) it("should reapply an independently mutated profile name when the load settles", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) stallProviderSettingsProfile(provider) await provider.saveViewState("currentApiConfigName", "cfg-a") let flipped = false vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (args) => { const name = "name" in args ? args.name : undefined if (name === "cfg-a" && !flipped) { flipped = true // Only the profile name changes while the lookup is in flight. await provider.saveViewState("currentApiConfigName", "cfg-b") } return Object.assign({} as Awaited>, { name, apiProvider: providerIdentifiers.openrouter, openRouterModelId: name === "cfg-a" ? "model-x" : "model-y", }) }) await provider["setViewStateId"]("stable-sidebar-view") // The in-flight selection wins over the loaded state, and the settings follow it: // getState() pairs this view pin with this overlay and createTask hands that pair to the new // task, which records the same name - pairing cfg-b with cfg-a settings would run the new task // on a profile the view does not pin. Dropping the settings is not safe either: the view would // fall back to shared settings that can belong to a third profile. expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-b") expect(provider["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-y", }) expect(provider["viewLocalState"]).not.toHaveProperty("mode") expect(provider.providerSettingsManager.getProfile).toHaveBeenCalledWith({ name: "cfg-b" }) await provider.dispose() }) it("drops the loaded settings when a rename during the load no longer resolves", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.saveViewState("currentApiConfigName", "cfg-a") const logSpy = vi.spyOn(provider, "log") let flipped = false vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (args) => { const name = "name" in args ? args.name : undefined if (name === "cfg-a" && !flipped) { flipped = true await provider.saveViewState("currentApiConfigName", "gone-profile") } if (name === "gone-profile") { throw new Error("profile deleted") } return Object.assign({} as Awaited>, { name, id: `${name}-id`, apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x", }) }) await provider["setViewStateId"]("stable-sidebar-view") // The reapplied name is what the view holds, so it stays; only the settings that no longer // belong to it are dropped, and the view falls back to the shared store for them. expect(provider["viewLocalState"].currentApiConfigName).toBe("gone-profile") expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Unable to resolve API profile 'gone-profile'")) await provider.dispose() }) it("should reapply an independently mutated apiConfiguration when the load settles", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) await provider.saveViewState("currentApiConfigName", "cfg-a") const load = provider["setViewStateId"]("stable-sidebar-view") // Let the stalled lookup begin so the in-flight mutation and the resolver // target the pending promise rather than the initial no-op. await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) // Only the apiConfiguration is mutated while the profile lookup is in flight. await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-y", }) resolveProfile({ name: "cfg-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }) await load expect(provider["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-y", }) expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-a") await provider.dispose() }) it("should keep every persisted field authoritative when the load is untouched", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) // @ts-ignore - Replace customModesManager with a test double (no custom modes). provider.customModesManager = { getCustomModes: vi.fn().mockResolvedValue([]), dispose: vi.fn() } await provider.saveViewState("mode", "code") await provider.saveViewState("currentApiConfigName", "cfg-a") const load = provider["setViewStateId"]("stable-sidebar-view") // Let the stalled lookup begin so the in-flight mutation and the resolver // target the pending promise rather than the initial no-op. await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) // No mutation while the lookup is in flight: the persisted values must win. resolveProfile({ name: "cfg-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }) await load expect(provider["viewLocalState"]).toEqual({ mode: "code", currentApiConfigName: "cfg-a", apiConfiguration: { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" }, }) await provider.dispose() }) it("should persist known modes and reject unknown or non-string modes", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") // The mode definitions this test needs come from the manager fixture, the same source the // production lookup reads, instead of from a test-local copy of the lookup. const refactorMode = { slug: "refactor", name: "Refactor Mode", roleDefinition: "Test Role", groups: [] } // @ts-ignore - Replace customModesManager with a test double carrying this test's modes. provider.customModesManager = { getCustomModes: vi.fn().mockResolvedValue([refactorMode]), dispose: vi.fn(), } // The production lookup replaces this file's resolve-everything double, so an unknown slug is // unknown because no mode definition names it. const actualModes = await vi.importActual("../../../shared/modes") const modesModule = vi.mocked(await import("../../../shared/modes")) const originalMode = modesModule.getModeBySlug("code") modesModule.getModeBySlug.mockImplementation(actualModes.getModeBySlug) try { await provider.setValues({ mode: "refactor" }) expect(mockContext.globalState.get("mode")).toBe("refactor") expect(provider["viewLocalState"].mode).toBe("refactor") await provider.setValues({ mode: "bogus-mode" }) expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Ignoring invalid mode "bogus-mode"')) expect(mockContext.globalState.get("mode")).toBe("refactor") expect(provider["viewLocalState"].mode).toBe("refactor") // A non-string mode must be rejected before persistence; Object.assign // keeps this a single structural assertion, so it must not reach global // state or the buffer. await provider.setValues(Object.assign({} as RooCodeSettings, { mode: 42 })) expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Ignoring invalid mode "42"')) expect(mockContext.globalState.get("mode")).toBe("refactor") expect(provider["viewLocalState"].mode).toBe("refactor") } finally { modesModule.getModeBySlug.mockReturnValue(originalMode) } await provider.dispose() }) it("should apply setValue mutations to global state and keep or clear the right buffer fields", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const apiConfiguration = { apiProvider: providerIdentifiers.openrouter } await provider.saveViewState("mode", "architect") await provider.saveViewState("currentApiConfigName", "my-profile") await provider.saveViewState("apiConfiguration", apiConfiguration) // A mutation of an unrelated key reaches global state without dropping buffered fields. await provider.setValue("writeDelayMs", 500) expect(mockContext.globalState.get("writeDelayMs")).toBe(500) expect(provider.getValues().writeDelayMs).toBe(500) expect(provider["viewLocalState"].mode).toBe("architect") expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") expect(provider["viewLocalState"].apiConfiguration).toBe(apiConfiguration) await provider.setValue("mode", undefined) expect(provider["viewLocalState"]).not.toHaveProperty("mode") await provider.setValue("currentApiConfigName", undefined) expect(provider["viewLocalState"]).not.toHaveProperty("currentApiConfigName") await provider.dispose() }) it("should remove the buffered apiConfiguration when it is cleared", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const save = provider.saveViewState.bind(provider) as (key: string, value: unknown) => Promise await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter }) await provider.saveViewState("apiConfiguration", undefined) expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter }) await save("apiConfiguration", null) expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") await provider.dispose() }) it("should clear viewLocalState and the persisted entry when resetting state", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // @ts-ignore - Replace customModesManager with a test double (the real reset writes to disk). provider.customModesManager = { resetCustomModes: vi.fn().mockResolvedValue(undefined), dispose: vi.fn() } // The modal answer is a string label; the last-typed vscode overload expects a // MessageItem. A double assertion is the last-resort cast here (AGENTS.md): the // production path compares the answer against the string label directly, so the // runtime value must stay a string and cannot be a structural MessageItem double. vi.mocked(vscode.window.showInformationMessage).mockResolvedValue( t("common:answers.yes") as unknown as vscode.MessageItem, ) await provider["setViewStateId"]("stable-sidebar-view") await provider.saveViewState("mode", "architect") await provider.resetState() expect(provider["viewLocalState"]).toEqual({}) // F4 cross-instance broadcast clears the entire durable viewStates map, so the // key is removed (undefined) rather than left as an empty object. expect(mockContext.globalState.get("viewStates")).toBeUndefined() await provider.dispose() }) it("should clear a sibling's view-local state and post sibling state during a cross-instance resetState", async () => { const provider1 = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const provider2 = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const post1 = vi.spyOn(provider1, "postStateToWebview").mockResolvedValue(undefined) const post2 = vi.spyOn(provider2, "postStateToWebview").mockResolvedValue(undefined) // @ts-ignore - Replace customModesManager with a test double (the real reset writes to disk). provider1.customModesManager = { resetCustomModes: vi.fn().mockResolvedValue(undefined), dispose: vi.fn() } // The modal answer is a string label; the last-typed vscode overload expects a MessageItem. vi.mocked(vscode.window.showInformationMessage).mockResolvedValue( t("common:answers.yes") as unknown as vscode.MessageItem, ) await provider2.saveViewState("mode", "architect") await provider1.resetState() // The sibling's in-memory view-local cache must be cleared by the broadcast. expect(provider2["viewLocalState"]).toEqual({}) // The sibling receives exactly one posted state (from the broadcast); the caller // receives exactly one (its final reset post), never a double post from the broadcast. expect(post2).toHaveBeenCalledTimes(1) expect(post1).toHaveBeenCalledTimes(1) await provider1.dispose() await provider2.dispose() }) it("should roll back the shared write when setValue per-view persistence fails", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.contextProxy.setValue("mode", "architect") const originalUpdate = mockContext.globalState.update mockContext.globalState.update = vi.fn().mockImplementation((key: string) => { if (key === "viewStates") { return Promise.reject(new Error("storage unavailable")) } return Promise.resolve() }) await expect(provider.setValue("mode", "code")).rejects.toThrow("storage unavailable") // The shared store must not move ahead of the per-view record that failed. expect(provider.getValue("mode")).toBe("architect") mockContext.globalState.update = originalUpdate await provider.dispose() }) it("should roll back the shared writes when setValues per-view persistence fails", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.contextProxy.setValue("mode", "architect") await provider.contextProxy.setValue("currentApiConfigName", "current-config") const originalUpdate = mockContext.globalState.update mockContext.globalState.update = vi.fn().mockImplementation((key: string) => { if (key === "viewStates") { return Promise.reject(new Error("storage unavailable")) } return Promise.resolve() }) await expect(provider.setValues({ mode: "code", currentApiConfigName: "other-config" })).rejects.toThrow( "storage unavailable", ) expect(provider.getValue("mode")).toBe("architect") expect(provider.getValue("currentApiConfigName")).toBe("current-config") expect(provider["viewLocalState"].mode).toBeUndefined() mockContext.globalState.update = originalUpdate await provider.dispose() }) it("should reject unknown or non-string modes written through setValue", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const logSpy = vi.spyOn(provider, "log") // The mode definitions this test needs come from the manager fixture, the same source the // production lookup reads, instead of from a test-local copy of the lookup. const refactorMode = { slug: "refactor", name: "Refactor Mode", roleDefinition: "Test Role", groups: [] } // @ts-ignore - Replace customModesManager with a test double carrying this test's modes. provider.customModesManager = { getCustomModes: vi.fn().mockResolvedValue([refactorMode]), dispose: vi.fn(), } // The production lookup replaces this file's resolve-everything double. The non-string case is // rejected by the typeof check before any lookup runs, so 42 no longer needs a lookup that // resolves it on purpose. const actualModes = await vi.importActual("../../../shared/modes") const modesModule = vi.mocked(await import("../../../shared/modes")) const originalMode = modesModule.getModeBySlug("code") modesModule.getModeBySlug.mockImplementation(actualModes.getModeBySlug) try { await provider.setValue("mode", "refactor") expect(mockContext.globalState.get("mode")).toBe("refactor") expect(provider["viewLocalState"].mode).toBe("refactor") // The updateSettings webview handler routes every key through setValue: // an unknown mode must be rejected there too, not only in setValues. await provider.setValue("mode", "bogus-mode") expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Ignoring invalid mode "bogus-mode"')) expect(mockContext.globalState.get("mode")).toBe("refactor") expect(provider["viewLocalState"].mode).toBe("refactor") // A non-string mode must be rejected before persistence (double assertion: the // type excludes non-strings), so it must not reach global state or the buffer — // even though the slug lookup above resolves it. await provider.setValue("mode", 42 as unknown as RooCodeSettings["mode"]) expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Ignoring invalid mode "42"')) expect(mockContext.globalState.get("mode")).toBe("refactor") } finally { modesModule.getModeBySlug.mockReturnValue(originalMode) } await provider.dispose() }) }) describe("provider profile mutations", () => { it("should sync the view-local buffer when activating a profile over a loaded view state", async () => { const writer = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await writer["setViewStateId"]("shared-view") await writer.saveViewState("currentApiConfigName", "old-profile") const profile: ProviderSettingsEntry = { name: "new-profile", id: "new-id", apiProvider: providerIdentifiers.openrouter, } const provider = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, activateProfile: vi.fn().mockResolvedValue(profile), listConfig: vi.fn().mockResolvedValue([profile]), setModeConfig: vi.fn(), getProfile: vi.fn().mockResolvedValue({ name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.anthropic, }), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // The ownership check requires the writer to release the id before the // next view adopts it; the durable entry it wrote stays in storage. await writer.dispose() await provider.contextProxy.setValue( "viewStates", mockContext.globalState.get("viewStates"), ) await provider["setViewStateId"]("shared-view") expect(provider.getValues().currentApiConfigName).toBe("old-profile") await provider.activateProviderProfile({ name: "new-profile" }) // The buffer must track the activated profile so getValues() agrees with the proxy. expect(provider.getValues().currentApiConfigName).toBe("new-profile") expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("new-profile") await provider.dispose() }) it("should report the activated profile's settings over a stale view-local buffer in getState", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const freshSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "fresh-key" } // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, activateProfile: vi.fn().mockResolvedValue({ name: "new-profile", id: "new-id", ...freshSettings }), listConfig: vi.fn().mockResolvedValue([]), setModeConfig: vi.fn(), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // A stale view-local apiConfiguration (as loaded from a view state) that keeps // shadowing the activated profile's settings in getState() unless the mutation // path clears this view's buffer overlay. await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, apiKey: "stale-key", }) expect(provider.getValues().apiConfiguration).toEqual({ apiProvider: providerIdentifiers.openrouter, apiKey: "stale-key", }) await provider.activateProviderProfile({ name: "new-profile" }) // The constructed state must serve the activated profile's fresh shared // settings, not the stale view-local overlay. const state = await provider.getState({ includeTaskHistory: false }) expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) expect(state.apiConfiguration.apiKey).toBe("fresh-key") // A later shared settings edit must not be masked by a buffer copy taken at // mutation time: the e2e flow edits settings through the shared path after // configuring the profile, and a wrapped buffer snapshot would keep serving // the pre-edit values in getState(). await provider.contextProxy.setProviderSettings({ apiProvider: providerIdentifiers.anthropic, apiKey: "edited-key", }) const stateAfterEdit = await provider.getState({ includeTaskHistory: false }) expect(stateAfterEdit.apiConfiguration.apiKey).toBe("edited-key") await provider.dispose() }) it("should sync the view-local buffer when creating and activating a profile", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const profile: ProviderSettingsEntry = { name: "fresh-profile", id: "fresh-id", apiProvider: providerIdentifiers.openrouter, } const savedForReadBack1: Record> = {} // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, saveConfig: vi.fn(async (name: string, settings: Record) => { savedForReadBack1[name] = settings return "fresh-id" }), getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: "fresh-id", ...savedForReadBack1[name], })), listConfig: vi.fn().mockResolvedValue([profile]), setModeConfig: vi.fn(), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) await provider.setValue("currentApiConfigName", "stale-profile") await provider.upsertProviderProfile("fresh-profile", { apiProvider: providerIdentifiers.openrouter }) expect(provider.getValues().currentApiConfigName).toBe("fresh-profile") await provider.dispose() }) it("waits for another view's critical section before saving the profile record", async () => { const events: string[] = [] const savedForRival: Record> = {} let releaseOtherView!: () => void const otherViewHold = new Promise((resolve) => { releaseOtherView = resolve }) // A promise-chain double, matching the real shared lock: a caller queues behind // whoever holds the section instead of running inline. let section: Promise = Promise.resolve() const runExclusiveAcrossInstances = (cb: () => Promise): Promise => { const run = section.then(cb) section = run.then( () => {}, () => {}, ) return run } const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances, saveConfig: vi.fn(async (savedName: string, savedSettings: Record) => { events.push("saveConfig") savedForRival[savedName] = savedSettings return "rival-id" }), getProfile: vi.fn(async ({ name: readName }: { name: string }) => ({ name: readName, id: "rival-id", ...savedForRival[readName], })), listConfig: vi.fn().mockResolvedValue([]), setModeConfig: vi.fn(), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // Another view's rename holds the section across its name check, its save, and its // compensation delete. const heldSection = runExclusiveAcrossInstances(async () => { events.push("otherViewEnter") await otherViewHold events.push("otherViewExit") }) const upsert = provider.upsertProviderProfile("rival-profile", { apiProvider: providerIdentifiers.anthropic, }) await new Promise((resolve) => setImmediate(resolve)) // The rename's rollback deletes whatever the new name holds, so a save that skipped // the section would be deleted by the other view's compensation. expect(events).toEqual(["otherViewEnter"]) releaseOtherView() await upsert await heldSection expect(events).toEqual(["otherViewEnter", "otherViewExit", "saveConfig"]) await provider.dispose() }) it("should report the fresh profile's settings over a stale view-local buffer in getState after upserting and activating a profile", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const profile: ProviderSettingsEntry = { name: "fresh-profile", id: "fresh-id", apiProvider: providerIdentifiers.openrouter, } const savedForReadBack2: Record> = {} // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, saveConfig: vi.fn(async (name: string, settings: Record) => { savedForReadBack2[name] = settings return "fresh-id" }), getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: "fresh-id", ...savedForReadBack2[name], })), listConfig: vi.fn().mockResolvedValue([profile]), setModeConfig: vi.fn(), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // A stale view-local apiConfiguration (as loaded from a view state) that keeps // shadowing the fresh profile's settings in getState() unless the mutation // path clears this view's buffer overlay. await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.anthropic, apiKey: "stale-key", }) expect(provider.getValues().apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic, apiKey: "stale-key", }) await provider.upsertProviderProfile("fresh-profile", { apiProvider: providerIdentifiers.openrouter }) // The constructed state must serve the fresh profile's shared settings, not // the stale view-local overlay. const state = await provider.getState({ includeTaskHistory: false }) expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.openrouter) // Same masking guard as the activation case: later shared edits stay visible. await provider.contextProxy.setProviderSettings({ apiProvider: providerIdentifiers.openrouter, apiKey: "edited-key", }) const stateAfterEdit = await provider.getState({ includeTaskHistory: false }) expect(stateAfterEdit.apiConfiguration.apiKey).toBe("edited-key") await provider.dispose() }) it("should sync the view-local buffer when deleting the current profile", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.setValue("currentApiConfigName", "old-profile") // @ts-ignore - Replace providerSettingsManager with a test double: deleting the // current profile now activates the fallback, which reads its settings. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, deleteConfig: vi.fn().mockResolvedValue(undefined), getProfile: vi .fn() .mockRejectedValue(new Error("Failed to get profile: Config with name 'old-profile' not found")), // getProfile wraps absence and a storage read failure in one plain Error, so the // deletion classifies absence with hasConfig: the record here is absent. hasConfig: vi.fn().mockResolvedValue(false), activateProfile: vi.fn().mockResolvedValue(keeperProfile), listConfig: vi.fn().mockResolvedValue([keeperProfile]), setModeConfig: vi.fn(), // The delete compensation snapshots the manager gate (its selection and mode map) before // committing; this double reports a gate the deletion never moved, so the gated restore // legs stay inert here. getSelectionAndModeConfigs: vi .fn() .mockResolvedValue({ currentApiConfigName: "default", modeApiConfigs: {} }), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) await provider.deleteProviderProfile(oldProfile) // The fallback profile must replace the deleted one in both the proxy and the buffer. expect(provider.getValues().currentApiConfigName).toBe("keeper-profile") expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("keeper-profile") await provider.dispose() }) it("fails the upsert and compensates the record when the post-save read-back fails", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // The pre-save snapshot sees the prior record; the post-save read-back // fails: the raw caller payload must never stand in for the validated // stored record. let saved = false const saveSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig").mockImplementation(async () => { saved = true return "p-id" }) vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async () => { if (saved) { throw new Error("read-back down") } return { name: "p", id: "p-id", apiProvider: providerIdentifiers.anthropic, apiKey: "prior-key", } }) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) const setValueSpy = vi.spyOn(provider.contextProxy, "setValue") await expect( provider["persistProviderProfile"]( "p", { apiProvider: providerIdentifiers.anthropic, apiKey: "raw-key" }, true, new AbortController().signal, ), ).rejects.toThrow("could not be read back") // The landed save was compensated with the prior record, and no // activation write carried the raw payload into the shared store. expect(saveSpy).toHaveBeenLastCalledWith("p", expect.objectContaining({ apiKey: "prior-key" })) expect(setValueSpy).not.toHaveBeenCalledWith("currentApiConfigName", "p") await provider.dispose() }) it("aborts the save when the pre-save profile lookup fails for a reason other than absence", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // The record exists but its storage read fails. getProfile wraps absence and read // failure in one plain Error, so treating every rejection as absence would take the // create path here, and the compensation below would then deleteConfig a profile // that exists and take its credentials with it. vi.spyOn(provider.providerSettingsManager, "getProfile").mockRejectedValue( new Error("Failed to get profile: secret store read down"), ) vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) const saveSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("p-id") const deleteSpy = vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) await expect( provider["persistProviderProfile"]( "p", { apiProvider: providerIdentifiers.anthropic, apiKey: "raw-key" }, true, new AbortController().signal, ), ).rejects.toThrow("secret store read down") // Nothing was written and nothing was compensated: the failure surfaced before // saveConfig, so there was no landed save to roll back. expect(saveSpy).not.toHaveBeenCalled() expect(deleteSpy).not.toHaveBeenCalled() await provider.dispose() }) it("aborts the deletion when the pre-delete lookup fails for a reason other than absence", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.setValue("currentApiConfigName", "old-profile") // The record is present but unreadable: continuing would delete the secrets-backed // record and then skip its restore, because the snapshot came back empty. vi.spyOn(provider.providerSettingsManager, "getProfile").mockRejectedValue( new Error("Failed to get profile: secret store read down"), ) vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) const deleteSpy = vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) const saveSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("x") await expect(provider.deleteProviderProfile(oldProfile)).rejects.toThrow("secret store read down") expect(deleteSpy).not.toHaveBeenCalled() expect(saveSpy).not.toHaveBeenCalled() await provider.dispose() }) it("restores the manager record and shared state when a post-delete write fails", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.setValue("currentApiConfigName", "old-profile") vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => { if ("name" in params && params.name === "old-profile") { return { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, apiKey: "old-key", } } return { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", } }) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) const saveSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("x") vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // The first write after the committed manager delete fails: the // deletion must be compensated, not left half-applied. vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key) => { if (key === "listApiConfigMeta") { throw new Error("state write down") } }) await expect(provider.deleteProviderProfile(oldProfile)).rejects.toThrow("state write down") // The secrets-backed record was restored with its pre-delete settings and its // original id: the record is gone at that point, so a save that drops the id mints a // new one while mode mappings and task pins still name the original. expect(saveSpy).toHaveBeenCalledWith( "old-profile", expect.objectContaining({ apiKey: "old-key", id: "old-id" }), ) // The secrets-backed record was restored with its pre-delete settings. expect(saveSpy).toHaveBeenCalledWith("old-profile", expect.objectContaining({ apiKey: "old-key" })) await provider.dispose() }) it("waits for another view's critical section before deleting the profile record", async () => { const events: string[] = [] let releaseOtherView!: () => void const otherViewHold = new Promise((resolve) => { releaseOtherView = resolve }) // A promise-chain double, matching the real shared lock: a caller queues behind // whoever holds the section instead of running inline. let section: Promise = Promise.resolve() const runExclusiveAcrossInstances = (cb: () => Promise): Promise => { const run = section.then(cb) section = run.then( () => {}, () => {}, ) return run } const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.setValue("currentApiConfigName", keeperProfile.name) // This view pins a profile the deletion does not touch, so the flow reaches the store // write without running the activation write group that follows it. await provider.saveViewState("currentApiConfigName", keeperProfile.name) // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances, getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: name === oldProfile.name ? "old-id" : "keeper-id", apiProvider: name === oldProfile.name ? providerIdentifiers.openrouter : providerIdentifiers.anthropic, })), hasConfig: vi.fn().mockResolvedValue(true), getSelectionAndModeConfigs: vi.fn().mockResolvedValue({ currentApiConfigName: keeperProfile.name, modeApiConfigs: {}, }), listConfig: vi.fn().mockResolvedValue([keeperProfile]), deleteConfig: vi.fn(async () => { events.push("deleteConfig") }), saveConfig: vi.fn().mockResolvedValue("keeper-id"), activateProfile: vi.fn(), setModeConfig: vi.fn(), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // Another view's save holds the section across its own read-modify-write of the same // secrets-backed file. const heldSection = runExclusiveAcrossInstances(async () => { events.push("otherViewEnter") await otherViewHold events.push("otherViewExit") }) const deletion = provider.deleteProviderProfile(oldProfile) await new Promise((resolve) => setImmediate(resolve)) // The delete rewrites the whole profiles file from the map it just loaded, so it may // not start while that other view is still inside the section: it queues behind it the // way the save, rename and webview delete paths already do. expect(events).toEqual(["otherViewEnter"]) releaseOtherView() await deletion await heldSection expect(events).toEqual(["otherViewEnter", "otherViewExit", "deleteConfig"]) await provider.dispose() }) it("leaves a record a newer writer re-created during the deletion to that writer", async () => { const events: string[] = [] const profiles: Record> = { "old-profile": { id: "old-id", apiProvider: providerIdentifiers.openrouter, apiKey: "old-key", }, "keeper-profile": { id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }, } const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.setValue("currentApiConfigName", "old-profile") // This view pins a profile the deletion does not touch: the first write this deletion // makes after the committed store delete is the shared profile list, and that is the // write that fails below, so the deletion is compensated. await provider.saveViewState("currentApiConfigName", keeperProfile.name) const logSpy = vi.spyOn(provider, "log") // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, ...profiles[name] })), hasConfig: vi.fn(async (name: string) => name in profiles), getSelectionAndModeConfigs: vi.fn().mockResolvedValue({ currentApiConfigName: "old-profile", modeApiConfigs: {}, }), listConfig: vi.fn().mockResolvedValue([keeperProfile]), deleteConfig: vi.fn(async () => { events.push("deleteConfig") delete profiles["old-profile"] // Another view saves this same name again before this deletion own rollback runs, // so the record the store holds from here on is newer than the snapshot this // deletion captured before it deleted anything. profiles["old-profile"] = { id: "recreated-id", apiProvider: providerIdentifiers.anthropic, apiKey: "rival-key", } events.push("otherViewRecreate") }), saveConfig: vi.fn(async (name: string, settings: Record) => { events.push("saveConfig") profiles[name] = { ...settings } return "restored-id" }), activateProfile: vi.fn(), setModeConfig: vi.fn(), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // The first write after the committed store delete fails: the deletion must be // compensated rather than left half-applied. vi.spyOn(provider.contextProxy, "setValue").mockImplementation(async (key) => { if (key === "listApiConfigMeta") { throw new Error("state write down") } }) await expect(provider.deleteProviderProfile(oldProfile)).rejects.toThrow("state write down") // The compensation ran, but the name came back holding a record this deletion never // wrote: replaying the pre-delete copy here would put that newer writer's record away // again, so the restore stands down and the store keeps the newer record. expect(events).toEqual(["deleteConfig", "otherViewRecreate"]) expect(profiles["old-profile"]).toEqual({ id: "recreated-id", apiProvider: providerIdentifiers.anthropic, apiKey: "rival-key", }) expect(logSpy).toHaveBeenCalledWith( expect.stringContaining("left the manager record of old-profile to a newer writer"), ) await provider.dispose() }) it("keeps the mutation queue owned by a mode switch past its timeout", async () => { // The fake timers, the provider, the gate and the prototype spy are declared // before the try below so its finally block can name them: a failed assertion // must not leave the gate unresolved, the spy installed, or the timers faked // for every later test in this file. vi.useFakeTimers() const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) let release!: () => void const gate = new Promise((resolve) => { release = resolve }) // Bracket access: handleModeSwitchUnlocked is private; the double // assertion is the only way to install the gate on the prototype. const proto = ClineProvider.prototype as unknown as { handleModeSwitchUnlocked: (...args: unknown[]) => Promise } const switchSpy = vi.spyOn(proto, "handleModeSwitchUnlocked").mockReturnValue(gate) try { vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) // The caller-side timeout rejection is expected: runToCompletion only // keeps the QUEUE waiting for the run, it does not silence the caller. const switchSettled = provider.handleModeSwitch("programmer").catch(() => undefined) await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) // The queue tail is still the mode switch: a later mutation must // not start while the switch's writes are still in flight. let secondStarted = false void provider["enqueueProviderProfileMutation"](async () => { secondStarted = true }) await vi.advanceTimersByTimeAsync(0) expect(secondStarted).toBe(false) release() await switchSettled await vi.advanceTimersByTimeAsync(0) expect(secondStarted).toBe(true) } finally { release() switchSpy.mockRestore() vi.useRealTimers() await provider.dispose() } }) it("leaves a sibling view's newer shared write alone when rolling back a failed write", async () => { // Production shares one ContextProxy across views (ContextProxy.getInstance); the two // views here share one too, so a sibling write lands in the same shared store. const sharedProxy = new ContextProxy(mockContext) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", sharedProxy, new WebviewFocusTracker(), ) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", sharedProxy, new WebviewFocusTracker(), ) await sharedProxy.setValue("mode", "code") vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) // The shared write lands, then a sibling view moves the same shared key while this // view's paired per-view write is still in flight and then fails. // Double assertion: _saveViewLocalStateFromMutation is private and has no typed // accessor, and the failure has to be injected inside the paired write. const proto = ClineProvider.prototype as unknown as { _saveViewLocalStateFromMutation: (values: Record) => Promise } const saveSpy = vi.spyOn(proto, "_saveViewLocalStateFromMutation").mockImplementation(async () => { await sibling.contextProxy.setValue("mode", "programmer") throw new Error("view write down") }) try { await expect(provider.setValues({ mode: "architect" })).rejects.toThrow("view write down") // The rollback replays only keys that still hold what this call wrote, so the sibling's // newer shared value survives instead of being reverted to the captured "code". expect(provider.contextProxy.getValue("mode")).toBe("programmer") expect(sibling.contextProxy.getValue("mode")).toBe("programmer") } finally { // Restored from a finally block: the spy replaces a prototype method, so a failing // assertion above would otherwise leave every later test in this file writing through // this mock implementation. saveSpy.mockRestore() } await provider.dispose() await sibling.dispose() }) it("should refresh the view-local apiConfiguration when deleting the active profile", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key" } // @ts-ignore - Replace providerSettingsManager with a test double: the view was // pinned to the deleted profile, so the deletion takes the activation path and // reads the survivor's settings through activateProfile. provider.providerSettingsManager = { deleteConfig: vi.fn().mockResolvedValue(undefined), getProfile: vi .fn() .mockRejectedValue(new Error("Failed to get profile: Config with name 'old-profile' not found")), // getProfile wraps a missing record and a storage read failure in one plain Error, // so the deletion classifies absence with hasConfig: this record is absent. hasConfig: vi.fn().mockResolvedValue(false), runExclusiveAcrossInstances: runManagerSectionInline, activateProfile: vi .fn() .mockResolvedValue({ name: "keeper-profile", id: "keeper-id", ...keeperSettings }), listConfig: vi.fn().mockResolvedValue([keeperProfile]), setModeConfig: vi.fn(), // The delete compensation snapshots the manager gate (its selection and mode map) before // committing; this double reports a gate the deletion never moved, so the gated restore // legs stay inert here. getSelectionAndModeConfigs: vi .fn() .mockResolvedValue({ currentApiConfigName: "default", modeApiConfigs: {} }), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.setValue("currentApiConfigName", "old-profile") // A stale view-local apiConfiguration (the deleted profile's settings) that would // keep shadowing the surviving profile's settings in getState() if the activation // path did not clear this view's buffer overlay. await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, apiKey: "stale-key", }) expect(provider.getValues().apiConfiguration).toEqual({ apiProvider: providerIdentifiers.openrouter, apiKey: "stale-key", }) await provider.deleteProviderProfile(oldProfile) // The shared provider keys are rewritten with the survivor's settings and the // view's stale overlay is cleared, so getState() serves the survivor's // settings instead of the deleted profile's. const state = await provider.getState({ includeTaskHistory: false }) expect(state.apiConfiguration).toMatchObject(keeperSettings) expect(provider["viewLocalState"].apiConfiguration).toBeUndefined() expect(provider.getValues().currentApiConfigName).toBe("keeper-profile") await provider.dispose() }) it("should swallow only the typed not-found signal when pruning a stale profile entry", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const staleProfile: ProviderSettingsEntry = { name: "stale-profile", id: "stale-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [staleProfile, keeperProfile]) await provider.setValue("currentApiConfigName", "keeper-profile") vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // The secret was already pruned: the typed not-found must be an idempotent // success so the stale list entry is still removed. vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockRejectedValue( new ProviderSettingsNotFoundError(`Config 'stale-profile' not found`), ) await provider.deleteProviderProfile(staleProfile) expect(provider.contextProxy.getValue("listApiConfigMeta")).toEqual([keeperProfile]) await provider.dispose() }) it("should propagate a non-not-found deletion failure for a profile named like the not-found message", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const profile: ProviderSettingsEntry = { name: "not found config", id: "nf-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [profile, keeperProfile]) await provider.setValue("currentApiConfigName", "keeper-profile") vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // An unrelated failure (wrapped the way deleteConfig wraps storage errors) // must not be mistaken for the idempotent not-found path just because the // profile name contains "not found". const deleteConfigSpy = vi .spyOn(provider.providerSettingsManager, "deleteConfig") .mockRejectedValue( new Error(`Failed to delete config: Error: storage write failed for 'not found config'`), ) await expect(provider.deleteProviderProfile(profile)).rejects.toThrow("storage write failed") // The list entry must remain untouched when the deletion failed. expect(provider.contextProxy.getValue("listApiConfigMeta")).toEqual([profile, keeperProfile]) expect(deleteConfigSpy).toHaveBeenCalledTimes(1) await provider.dispose() }) it("reconfigures a view pinned to the deleted profile even when the global selection points elsewhere", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) // The global selection points at the keeper profile, but this view's buffer // is still pinned to the profile being deleted (it loaded it earlier): // the nested overlay still carries the deleted profile's configuration. await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") provider["viewLocalState"].currentApiConfigName = "old-profile" provider["viewLocalState"].apiConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "deleted-profile-secret", } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // @ts-ignore - Replace providerSettingsManager with a test double: the pinned // view takes the activation path, so the survivor's settings are read through // activateProfile. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, activateProfile: vi.fn().mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, }), listConfig: vi.fn().mockResolvedValue([keeperProfile]), setModeConfig: vi.fn(), deleteConfig: vi.fn().mockResolvedValue(undefined), getProfile: vi .fn() .mockRejectedValue(new Error("Failed to get profile: Config with name 'old-profile' not found")), // getProfile wraps a missing record and a storage read failure in one plain Error, // so the deletion classifies absence with hasConfig: this record is absent. hasConfig: vi.fn().mockResolvedValue(false), // The delete compensation snapshots the manager gate (its selection and mode map) before // committing; this double reports a gate the deletion never moved, so the gated restore // legs stay inert here. getSelectionAndModeConfigs: vi .fn() .mockResolvedValue({ currentApiConfigName: "default", modeApiConfigs: {} }), } const setProviderSettingsSpy = vi.spyOn(provider.contextProxy, "setProviderSettings") await provider.deleteProviderProfile(oldProfile) // The pin still names the deleted profile, so the view is reconfigured through // the activation path: the shared provider keys take the surviving profile's // settings and the view's stale overlay is cleared, so no key of the deleted // profile survives in getState(). expect(setProviderSettingsSpy).toHaveBeenCalledWith( expect.objectContaining({ apiProvider: providerIdentifiers.anthropic }), ) expect(provider.getValues().currentApiConfigName).toBe("keeper-profile") expect(provider["viewLocalState"].apiConfiguration).toBeUndefined() const state = await provider.getState({ includeTaskHistory: false }) expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) await provider.dispose() }) it("does not re-point a pinned sibling's task that follows another profile when its profile is deleted", async () => { // Defensive: the doubles in this suite can leave console writes pending // at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) try { const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") // The sibling pins the profile being deleted, but its active task // follows a different sticky profile: the deletion must re-point the // sibling's buffer to the surviving profile without switching that // conversation's handler or rewriting its persisted profile name. sibling["viewLocalState"].currentApiConfigName = "old-profile" sibling["viewLocalState"].apiConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "deleted-profile-secret", } vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) const siblingTask = { apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key" }, taskApiConfigName: "other-profile", taskId: "sibling-task", setTaskApiConfigName: vi.fn(), updateApiConfiguration: vi.fn(), } vi.spyOn(sibling, "getCurrentTask").mockReturnValue( siblingTask as unknown as ReturnType, ) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, }) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) await provider.deleteProviderProfile(oldProfile) // The sibling's view buffer is still re-pointed to the surviving // profile... expect(sibling["viewLocalState"].currentApiConfigName).toBe("keeper-profile") expect(sibling["viewLocalState"].apiConfiguration).toEqual({ id: "keeper-id", apiProvider: providerIdentifiers.anthropic, }) // ...but the task follows another profile: neither the handler rebuild // nor the sticky-name rewrite may touch it. expect(siblingTask.updateApiConfiguration).not.toHaveBeenCalled() expect(siblingTask.setTaskApiConfigName).not.toHaveBeenCalled() // Wait on the serialized view-state write queue that every // viewStates mutation goes through, so queued persistence finishes // while the console spies are still installed and teardown has no // pending writes. await ClineProvider["persistedViewStateWriteQueue"] } finally { await sibling.dispose() await provider.dispose() } }) it("does not re-pin a sibling whose queued re-pin had not started when the deletion timed out", async () => { // Defensive: the doubles in this suite can leave console writes pending at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) // The mutation timeout is the provider's own 30-second clock, driven here by the fake timer // instead of by waiting, so this cell stays a fast test. vi.useFakeTimers() const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Declared before the try below so its finally block can name them: a failed assertion must // not leave the sibling queue held or the fake clock installed for every later test. let releaseSiblingQueue!: () => void const siblingQueue = new Promise((resolve) => { releaseSiblingQueue = resolve }) // Also declared before the try: the finally must settle the work these promises // name after releasing the gate, instead of disposing over it. let siblingMutation!: Promise let deletion: Promise | undefined const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") try { const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "deleted-profile-secret", } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.setViewStateId("stable-sidebar-view") await sibling.setViewStateId("stable-editor-view") // The sibling pins the deleted profile through the real view-state write, so the durable // entry and the buffered overlay both exist before the deletion starts. await sibling.saveViewState("currentApiConfigName", "old-profile") await sibling.saveViewState("apiConfiguration", deletedSettings) const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName // The instance registry is environment: the re-pin must see exactly these two views. instancesSpy.mockReturnValue([provider, sibling]) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) const siblingPostSpy = vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) const activateProfileSpy = vi.spyOn(provider.providerSettingsManager, "activateProfile") activateProfileSpy.mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A gate this deletion never moved: the gated manager-gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) const getProfileSpy = vi.spyOn(provider.providerSettingsManager, "getProfile") getProfileSpy.mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, apiKey: "old-key", } : { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }, ) const saveRecordSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig") saveRecordSpy.mockResolvedValue("restored") // A mutation on the sibling's own queue holds that queue past the timeout, so the re-pin // joins it and never gets to start before the deletion gives up on it. let siblingMutationStarted = false siblingMutation = sibling["enqueueProviderProfileMutation"]( async () => { siblingMutationStarted = true return siblingQueue }, { runToCompletion: true }, ).catch(() => {}) deletion = provider.deleteProviderProfile(oldProfile) // Subscribe to the rejection before pumping the clock: the deletion rejects while the // clock runs, and an expectation attached only afterwards reports it as unhandled. const deletionResult = expect(deletion).rejects.toThrow("Provider profile mutation timed out") // Pump the fake clock until the deletion has committed the replacement activation: the sibling // re-pin is the next write in that chain, and its 30-second timer must already be scheduled // before the clock can be run past it. for (let pumped = 0; pumped < 40 && activateProfileSpy.mock.calls.length === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(activateProfileSpy).toHaveBeenCalledTimes(1) expect(siblingMutationStarted).toBe(true) for (let pumped = 0; pumped < 5; pumped++) { await vi.advanceTimersByTimeAsync(0) } await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionResult // The window the reviewer described: the deletion already reported failure and compensated // while the queued callback has still not started, so the sibling still holds the deleted // profile's pin and settings and posted nothing to its webview. expect(sibling["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(sibling["viewLocalState"].apiConfiguration).toEqual(deletedSettings) expect(siblingPostSpy).not.toHaveBeenCalled() expect(durablePin("stable-editor-view")).toBe("old-profile") // Release the held queue: the callback now gets its turn and must not write anything, because // the deletion it belonged to already failed. releaseSiblingQueue() await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] expect(sibling["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(sibling["viewLocalState"].apiConfiguration).toEqual(deletedSettings) expect(siblingPostSpy).not.toHaveBeenCalled() expect(durablePin("stable-editor-view")).toBe("old-profile") expect(saveRecordSpy).toHaveBeenCalledWith( "old-profile", expect.objectContaining({ apiKey: "old-key", id: "old-id" }), ) } finally { instancesSpy.mockRestore() releaseSiblingQueue() // Ordering, not a race this suite showed: release the gate, settle the work it // frees while the fake clock is still installed, and only then restore the // clock, drain the write queue, and dispose. Instrumented failure-path runs // (scratch/1565f-w1-instr2-A-*) found the disposed-over window never opens at // the current interleaving, so this ordering is explicit hygiene. await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await siblingMutation await deletion?.catch(() => {}) vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await sibling.dispose() await provider.dispose() } }) it("waits for a sibling's in-flight re-pin write before compensating a timed-out deletion", async () => { // Defensive: the doubles in this suite can leave console writes pending at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) // The mutation timeout is the provider's own 30-second clock, driven here by the fake timer // instead of by waiting, so this cell stays a fast test. vi.useFakeTimers() const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Seeded through the real view-state writes before the write gate below is installed, so the // gate can only ever hold the deletion's own re-pin write. const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "deleted-profile-secret", } // What the deletion resolves as the replacement settings for the re-pin: the keeper profile // from the manager minus its name, which is what the sibling's buffer must hold afterwards. const _keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", id: "keeper-id", } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.setViewStateId("stable-sidebar-view") await sibling.setViewStateId("stable-editor-view") await sibling.saveViewState("currentApiConfigName", "old-profile") await sibling.saveViewState("apiConfiguration", deletedSettings) const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName // Declared before the try below so its finally block can name them: a failed assertion must not // leave the write held, the storage seam wrapped, or the fake clock running for every later test. let releaseWrite!: () => void const pendingWrite = new Promise((resolve) => { releaseWrite = resolve }) // Also declared before the try: the finally must settle the deletion and the // in-flight write it releases before restoring the clock or disposing. let deletion: Promise | undefined const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") // Double assertion: the mock seam declares the string settings as its value type, while the // gate has to see the raw key/value pair to single out one write. The seam implementation is // called through for every write, so the durable write is still the one production reaches // through ContextProxy: no production method is replaced here. const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update // ContextProxy assigns its in-memory cache before the durable attempt, so the map handed to // the seam is identity-equal to the cache of the view that issued the write. That names the // writer without touching production: the gate holds only the re-pin write this view issued, // while the earlier durable re-point of persisted pins and this view own activation write // arrive through a different cache and stay unblocked. let rePinWriteStarted = false let rePinWriteSettled = false let rePointWritesUnblocked = 0 let compensationSawSettled: boolean | undefined storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } const ownRePinWrite = sibling.contextProxy.getValue("viewStates") === value if (ownRePinWrite && !rePinWriteStarted) { rePinWriteStarted = true return pendingWrite.then(() => { rePinWriteSettled = true return durableUpdate(key, value) }) } if (rePinWriteStarted) { if (compensationSawSettled === undefined) { compensationSawSettled = rePinWriteSettled } } else { rePointWritesUnblocked++ } return durableUpdate(key, value) } try { // The instance registry is environment: the re-pin must see exactly these two views. instancesSpy.mockReturnValue([provider, sibling]) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) const siblingPostSpy = vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A gate this deletion never moved: the gated manager-gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, apiKey: "old-key", } : { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }, ) const saveRecordSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig") saveRecordSpy.mockResolvedValue("restored") deletion = provider.deleteProviderProfile(oldProfile) // Pump the fake clock until the re-pin callback reaches the sibling's write: this proves the // callback had already started before the timeout, which is the case the fix is about. for (let pumped = 0; pumped < 40 && !rePinWriteStarted; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(rePinWriteStarted).toBe(true) await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) // The window: the timeout has landed and the write is still pending, so the deletion may not // have compensated yet - the manager record restore is the first leg of that compensation. expect(saveRecordSpy).not.toHaveBeenCalled() expect(sibling["viewLocalState"].currentApiConfigName).toBe("old-profile") // Both writes that passed through carry the replacement pin for this view: the deletion // re-points persisted pins first, then the activation path writes the entry of its own // view. Neither is the re-pin write, so the gate let both reach storage. expect(rePointWritesUnblocked).toBe(2) // The re-point reached durable storage while the re-pin write is still held: the rollback // the compensation performs later has to land on top of a pin that is already re-pointed. expect(durablePin("stable-editor-view")).toBe("keeper-profile") releaseWrite() await expect(deletion).rejects.toThrow("Provider profile mutation timed out") await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // The compensation write reached the seam only after the released re-pin write had settled, // so the durable rollback landed on top of that write instead of under it. expect(compensationSawSettled).toBe(true) // The write that had already started settled first, so the compensation rolled the durable pin // back onto the deleted profile instead of restoring a pin the write then landed on top of. expect(durablePin("stable-editor-view")).toBe("old-profile") // The compensation replays the live changes this re-pin had already committed: the buffer pin // and the settings overlay come back to the deleted profile together with the durable entry and // the manager record, so the durable and buffered state no longer name two profiles. The // failure path still posts nothing, so this view keeps serving the state its webview last // received, and its next post carries the restored one. expect(sibling["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(sibling["viewLocalState"].apiConfiguration).toEqual(deletedSettings) expect(siblingPostSpy).not.toHaveBeenCalled() expect(saveRecordSpy).toHaveBeenCalledWith( "old-profile", expect.objectContaining({ apiKey: "old-key", id: "old-id" }), ) } finally { instancesSpy.mockRestore() storageSeam.update = durableUpdate releaseWrite() // Ordering, not a race this suite showed: the held write sits inside the serialized // storage queue, so settle the deletion - it awaits that write through its re-pin - // under the still-installed fake clock, then restore the clock, drain the queue, and // dispose. Draining before the release would await a queue the held write has not // entered yet, then dispose over both. await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletion?.catch(() => {}) vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await sibling.dispose() await provider.dispose() } }) it("settles a second sibling's in-flight re-pin before compensating another view's failure", async () => { // Defensive: the doubles in this suite can leave console writes pending at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) // The mutation timeout is the provider's own 30-second clock, driven here by the fake timer // instead of by waiting: this cell never reaches it, but the pending timers must be fake so // the cell cannot hold the worker for 30 real seconds. vi.useFakeTimers() const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const first = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Seeded through the real view-state writes before the write spies below are installed, so the // spies can only ever hold the deletion's own re-pin writes. const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "deleted-profile-secret", } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.setViewStateId("stable-sidebar-view") await provider.saveViewState("currentApiConfigName", "old-profile") await provider.saveViewState("apiConfiguration", deletedSettings) await first.setViewStateId("stable-first-view") await first.saveViewState("currentApiConfigName", "old-profile") await first.saveViewState("apiConfiguration", deletedSettings) await second.setViewStateId("stable-second-view") await second.saveViewState("currentApiConfigName", "old-profile") await second.saveViewState("apiConfiguration", deletedSettings) const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName // Declared before the try below so its finally block can name them: a failed assertion must not // leave the second write held, the storage seam wrapped, or the fake clock running for later // tests. let releaseSecondWrite!: () => void const pendingSecondWrite = new Promise((resolve) => { releaseSecondWrite = resolve }) // Also declared before the try: the finally must settle the deletion this promise // names after releasing the gate, instead of disposing over its re-pin. let deletion: Promise | undefined const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") // Double assertion: the mock seam declares the string settings as its value type, while the // gate has to see the raw key/value pair to fail one write and hold the other. The seam // implementation is called through for every write that is not rejected, so those writes // are still the ones production reaches through ContextProxy. const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update // ContextProxy assigns its in-memory cache before the durable attempt, so the map handed to // the seam is identity-equal to the cache of the view that issued the write. That names the // writer without touching production: the earlier durable re-point of persisted pins and the // activation write of the deleting view arrive through a different cache and stay unblocked. let secondWriteStarted = false let secondWriteSettled = false let firstWriteRejectedAtStorage = 0 let rePointWritesUnblocked = 0 let storageRestoreWrites = 0 let readBackLegRan: boolean | undefined let compensationSawSettled: boolean | undefined storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } const issuedByFirst = first.contextProxy.getValue("viewStates") === value const issuedBySecond = second.contextProxy.getValue("viewStates") === value if (issuedByFirst && firstWriteRejectedAtStorage === 0) { firstWriteRejectedAtStorage++ return Promise.reject(new Error("first sibling write down")) } if (issuedBySecond && !secondWriteStarted) { secondWriteStarted = true // The rejection above reached storage, so this is where the cache read-back of the failed // view is observable: its cache must now be the very map durable storage holds. readBackLegRan = mapContentEquals( first.contextProxy.getValue("viewStates"), mockContext.globalState.get("viewStates"), ) return pendingSecondWrite.then(() => { secondWriteSettled = true return durableUpdate(key, value) }) } if (mockContext.globalState.get("viewStates") === value) { // A write that hands back the map storage already holds: production restoring the // storage-backed map after the rejection, not a view writing a new pin. storageRestoreWrites++ } else if (!secondWriteStarted) { rePointWritesUnblocked++ } if (secondWriteStarted && compensationSawSettled === undefined) { compensationSawSettled = secondWriteSettled } return durableUpdate(key, value) } try { // The instance registry is environment: the re-pin must see exactly these three views. instancesSpy.mockReturnValue([provider, first, second]) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(first, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(second, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A gate this deletion never moved: the gated manager-gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, apiKey: "old-key", } : { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }, ) const saveRecordSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig") saveRecordSpy.mockResolvedValue("restored") deletion = provider.deleteProviderProfile(oldProfile) let deletionSettled = false void deletion.then( () => { deletionSettled = true }, () => { deletionSettled = true }, ) // Pump the fake clock until the second view's re-pin write is in flight: the first view's // write has already failed by then, so this is the order the compensation must respect. for (let pumped = 0; pumped < 40 && !secondWriteStarted; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(secondWriteStarted).toBe(true) await vi.advanceTimersByTimeAsync(0) // The window: one view's re-pin already failed while the other's write is still pending, so // the deletion may not have compensated yet - the record restore is that compensation's // first leg, and no pin may be written back yet. expect(deletionSettled).toBe(false) expect(saveRecordSpy).not.toHaveBeenCalled() // Both writes that passed through carry the replacement pin for these views: the deletion // re-points persisted pins first, then the activation path writes the entry of its own // view. Neither is a sibling re-pin write, so the gate let both reach storage. expect(rePointWritesUnblocked).toBe(2) // The failure lands at the storage seam itself rather than inside a production method, so // the cache the seam had been handed optimistically has to come back to what storage // actually holds before the other view write is judged. expect(firstWriteRejectedAtStorage).toBe(1) expect(readBackLegRan).toBe(true) releaseSecondWrite() await expect(deletion).rejects.toThrow("first sibling write down") await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // The compensation write reached the seam only after the released write of the other view // had settled, so the rollback landed on top of that write instead of under it. expect(compensationSawSettled).toBe(true) // Production restored the storage-backed map on its own after the rejection: the second leg // of the compensation is that write, not only the cache read-back above. expect(storageRestoreWrites).toBe(1) // Both durable pins come back to the deleted profile: the compensation ran after the second // view's write settled, so it rolled that write back instead of being overwritten by it. expect(durablePin("stable-first-view")).toBe("old-profile") expect(durablePin("stable-second-view")).toBe("old-profile") expect(saveRecordSpy).toHaveBeenCalledWith( "old-profile", expect.objectContaining({ apiKey: "old-key", id: "old-id" }), ) } finally { instancesSpy.mockRestore() storageSeam.update = durableUpdate releaseSecondWrite() // Ordering, not a race this suite showed: the held write sits inside the serialized // storage queue, so settle the deletion - it awaits that write through its // compensation - under the still-installed fake clock, then restore the clock, drain // the queue, and dispose. Draining before the release would await a queue the held // write has not entered yet, then dispose over both. await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletion?.catch(() => {}) vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await first.dispose() await second.dispose() await provider.dispose() } }) it("compensates a failed sibling re-pin without waiting for another view's UI refresh", async () => { // The review's case, measured before this cell was written: one view's re-pin write fails at the // storage seam while another view has finished its own re-pin write. The rollback is driven by // the re-pin outcomes, so it must reach the record and the durable pins while that second // view's state post is still unavailable - not after it. // Defensive: the doubles in this suite can leave console writes pending at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) // The mutation timeout is the provider's own 30-second clock, driven here by the fake timer // instead of by waiting: this cell never reaches it, but the pending timers must be fake so // the cell cannot hold the worker for 30 real seconds. vi.useFakeTimers() const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const first = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Seeded through the real view-state writes before the write spies below are installed, so the // spies can only ever touch the deletion's own re-pin writes and the posts that follow them. const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "deleted-profile-secret", } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.setViewStateId("stable-sidebar-view") await provider.saveViewState("currentApiConfigName", "old-profile") await provider.saveViewState("apiConfiguration", deletedSettings) await first.setViewStateId("stable-first-view") await first.saveViewState("currentApiConfigName", "old-profile") await first.saveViewState("apiConfiguration", deletedSettings) await second.setViewStateId("stable-second-view") await second.saveViewState("currentApiConfigName", "old-profile") await second.saveViewState("apiConfiguration", deletedSettings) const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName // Declared before the try below so its finally block can name them: a failed assertion must not // leave this view's state post held, the other view's write held, the storage seam wrapped, or // the fake clock running for later tests. let releaseSecondWrite!: () => void const pendingSecondWrite = new Promise((resolve) => { releaseSecondWrite = resolve }) let releasePost!: () => void const pendingPost = new Promise((resolve) => { releasePost = resolve }) // Also declared before the try: the finally must settle the deletion this promise names after // releasing the gates, instead of disposing over an in-flight re-pin. // The observer handle below is declared here too: the finally settles the deletion // through a handler attached when the deletion starts, not after the clock was advanced. let deletionObserved: Promise | undefined let deletion: Promise | undefined const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") // Double assertion: the mock seam declares the string settings as its value type, while the gate // has to see the raw key/value pair to fail one write and hold the other. The seam // implementation is called through for every write that is not rejected, so those writes are // still the ones production reaches through ContextProxy. const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update // ContextProxy assigns its in-memory cache before the durable attempt, so the map handed to the // seam is identity-equal to the cache of the view that issued the write. That names the writer // without touching production: the earlier durable re-point of persisted pins and the // activation write of the deleting view arrive through a different cache and stay unblocked. let firstWriteRejectedAtStorage = 0 let secondWriteStarted = false storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } const issuedByFirst = first.contextProxy.getValue("viewStates") === value const issuedBySecond = second.contextProxy.getValue("viewStates") === value if (issuedByFirst && firstWriteRejectedAtStorage === 0) { firstWriteRejectedAtStorage++ return Promise.reject(new Error("first sibling write down")) } // The failed view's cache read-back hands back the very map storage holds, and until that view // wrote again its cache was the same object the second view cache holds, so the restore write is // told apart from the second view own re-pin write by the same test cell C uses for its // storage-restore counter: identity of the writer cache, and not the map storage already holds. if (issuedBySecond && !secondWriteStarted && mockContext.globalState.get("viewStates") !== value) { secondWriteStarted = true return pendingSecondWrite.then(() => durableUpdate(key, value)) } return durableUpdate(key, value) } // The state post of the view whose re-pin committed is gated here: the cell has to judge // what the deletion did while that refresh could not run, and its finally block has to be // able to name the call count after a failed assertion. const secondPostSpy = vi.spyOn(second, "postStateToWebview").mockImplementation(() => pendingPost) try { instancesSpy.mockReturnValue([provider, first, second]) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(first, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A gate this deletion never moved: the gated manager-gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, apiKey: "old-key", } : { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }, ) const saveRecordSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig") saveRecordSpy.mockResolvedValue("restored") deletion = provider.deleteProviderProfile(oldProfile) // Attach the rejection observer at once: the deletion can reject while this row is still // pumping the fake clock toward the window, and a rejection with no handler by then is // reported as unhandled even though the row below awaits this very promise. The assertion // still targets the promise the deletion returned, not the observer. deletionObserved = deletion.catch(() => {}) // Pump the fake clock until the premise the review names is at the seam: one view's re-pin // write rejected at storage, the other's re-pin write in flight and not yet released. for ( let pumped = 0; pumped < 40 && !(firstWriteRejectedAtStorage === 1 && secondWriteStarted); pumped++ ) { await vi.advanceTimersByTimeAsync(0) } expect([firstWriteRejectedAtStorage, secondWriteStarted]).toEqual([1, true]) releaseSecondWrite() // The view that did re-pin has now committed its write. Whether the deletion compensates // before this view's refresh runs is exactly the behaviour this cell pins: its state post is // still gated above, so the compensation below can only have run if the rollback does not // wait for that refresh. for (let pumped = 0; pumped < 40 && saveRecordSpy.mock.calls.length === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // The window: this view's state post had still not been dispatched, and the deletion had // already restored the deleted profile's record - the compensation's first leg. expect(saveRecordSpy).toHaveBeenCalledWith( "old-profile", expect.objectContaining({ apiKey: "old-key", id: "old-id" }), ) for (let pumped = 0; pumped < 40 && durablePin("stable-second-view") !== "old-profile"; pumped++) { await vi.advanceTimersByTimeAsync(0) } // The rollback also reached the durable pin of the view that had re-pinned, while its own // refresh was still gated: the compensation merged on top of that committed write and // rolled it back instead of being overwritten by it. expect(durablePin("stable-second-view")).toBe("old-profile") // And no UI work was dispatched for it on this path: the post is bound to every re-pin // succeeding, so a view whose sibling failed is not sent a state post that the rollback // would have to undo. expect(secondPostSpy).not.toHaveBeenCalled() releasePost() await expect(deletion).rejects.toThrow("first sibling write down") await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] } finally { instancesSpy.mockRestore() storageSeam.update = durableUpdate releaseSecondWrite() releasePost() // Ordering, not a race this suite showed: the held write sits inside the serialized // storage queue and the deletion awaits that write through its compensation, so settle the // deletion - and the state post this cell gates - under the still-installed fake clock, // then restore the clock, drain the queue, and dispose. Draining before the release would // await a queue the held write has not entered yet, then dispose over both. await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await first.dispose() await second.dispose() await provider.dispose() } }) it("restores the live state a rolled-back deletion moved in a re-pinned sibling", async () => { // Review comment 4733238427 asks for a re-pinned view live state to come back when the deletion // rolls that re-pin back. Measured on the committed bytes before this cell existed (the // instrument scratch/1565j-snip-measW4.txt, three repeats in scratch/1565j-matrix-out.txt): at the // moment the compensation had been entered and none of its restore legs had run, the view whose // re-pin had committed already served the replacement pin, the replacement settings overlay, an // API handler rebuilt from them and the replacement sticky profile name on the task it runs, and // after the last leg it still did while the manager record and the durable entry had come back. // This cell pins the repair on those layers, and pins that a view which chose a profile of its // own inside the compensation window keeps that choice. // Defensive: the doubles in this suite can leave console writes pending at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) // The mutation timeout is the provider own 30-second clock: this cell never reaches it, but // the pending timers are kept fake so the cell cannot hold the worker for 30 real seconds. vi.useFakeTimers() const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const first = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const third = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "deleted-profile-secret", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", id: "keeper-id", } const chosenSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "chosen-profile-key", } // Seeded through the real view-state writes before the write spies below are installed, so the // spies can only ever touch the writes this deletion makes. await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.setViewStateId("stable-sidebar-view") await provider.saveViewState("currentApiConfigName", "old-profile") await provider.saveViewState("apiConfiguration", deletedSettings) await first.setViewStateId("stable-first-view") await first.saveViewState("currentApiConfigName", "old-profile") await first.saveViewState("apiConfiguration", deletedSettings) await second.setViewStateId("stable-second-view") await second.saveViewState("currentApiConfigName", "old-profile") await second.saveViewState("apiConfiguration", deletedSettings) await third.setViewStateId("stable-third-view") await third.saveViewState("currentApiConfigName", "old-profile") await third.saveViewState("apiConfiguration", deletedSettings) // The view this cell expects back also runs a task under the deleted profile: that is the // running task the review names. The double keeps the two live members in step with the calls, // the way a real task does, because the repair re-checks the task own sticky name before // replaying it: a frozen double would hide the re-pin own change from that guard. Double // assertion: the double carries only the members the re-pin and the repair touch, and the // structural cast is the one the task fixtures in this suite already use. const firstTaskSettings: ProviderSettings = deletedSettings const firstTask = { apiConfiguration: firstTaskSettings, taskApiConfigName: "old-profile", taskId: "first-task", setTaskApiConfigName: vi.fn((name: string) => { firstTask.taskApiConfigName = name }), updateApiConfiguration: vi.fn((settings: ProviderSettings) => { firstTask.apiConfiguration = settings }), persistStickyProviderProfileToCurrentTask: vi.fn(), } vi.spyOn(first, "getCurrentTask").mockReturnValue( firstTask as unknown as ReturnType, ) const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName // Declared before the try so its finally block can name every gate and the deletion handle: a // failed assertion must not leave the compensation held on its first leg, the held write held, the // choice queued below unfinished, or the fake clock running for the later tests. let releaseFirstWrite!: () => void const pendingFirstWrite = new Promise((resolve) => { releaseFirstWrite = resolve }) let releaseRecord!: () => void const pendingRecord = new Promise((resolve) => { releaseRecord = resolve }) let deletionObserved: Promise | undefined let deletion: Promise | undefined let thirdChoseProfile: Promise | undefined let thirdChoseProfileObserved: Promise | undefined let firstWriteStarted = false let secondWriteRejectedAtStorage = 0 let compensationEntered = false let viewStatesWrites = 0 let writesAtCompensationEntry = 0 const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") // Double assertion: the mock seam declares its own value type, while this seam has to see the // raw key/value pair to fail one write, hold another, and count the rest; the seam // implementation is called through for every write that is not failed or held, so those writes // are still the ones production reaches through ContextProxy. ContextProxy assigns its // in-memory cache before the durable attempt, so the map handed to the seam is identity-equal // to the cache of the view that issued the write: that names the writer without touching // production, and the earlier durable re-point of persisted pins and the activation write of // the deleting view arrive through a different cache and stay unblocked. The held write is // told apart from a failed write cache read-back the way cell C does it: identity of the // writer cache, and not the map storage already holds. const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } viewStatesWrites++ const issuedByFirst = first.contextProxy.getValue("viewStates") === value && mockContext.globalState.get("viewStates") !== value const issuedBySecond = second.contextProxy.getValue("viewStates") === value if (issuedBySecond && secondWriteRejectedAtStorage === 0) { secondWriteRejectedAtStorage++ return Promise.reject(new Error("second sibling write down")) } if (issuedByFirst && !firstWriteStarted) { firstWriteStarted = true return pendingFirstWrite.then(() => durableUpdate(key, value)) } return durableUpdate(key, value) } try { // The instance registry is environment: the re-pin must see exactly these four views. instancesSpy.mockReturnValue([provider, first, second, third]) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) const firstPostSpy = vi.spyOn(first, "postStateToWebview").mockResolvedValue(undefined) const secondPostSpy = vi.spyOn(second, "postStateToWebview").mockResolvedValue(undefined) const thirdPostSpy = vi.spyOn(third, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A gate this deletion never moved: the manager-gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, apiKey: "old-key", } : { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }, ) // The record restore is the first leg of the compensation: holding it is what lets this cell // judge the state at the point where the re-pin had finished every live change and no restore // leg of the compensation had run yet, and place the third view own choice inside that window. const saveRecordSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig") saveRecordSpy.mockImplementation(async () => { compensationEntered = true writesAtCompensationEntry = viewStatesWrites await pendingRecord return "restored" }) deletion = provider.deleteProviderProfile(oldProfile) // Attach the rejection observer at once: the deletion can reject while this row is still // pumping the fake clock, and an unhandled rejection by then is reported even though the // rows below await this very promise. The assertions still target the deletion. deletionObserved = deletion.catch(() => {}) // Pump the fake clock until the view this cell expects back has started its re-pin write. for (let pumped = 0; pumped < 40 && !firstWriteStarted; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(firstWriteStarted).toBe(true) // Releasing that write first is what lets the other view own re-pin write reach storage at // all: every viewStates write is serialized behind it, so the failed write the rollback is // driven by can only be attempted once this one has landed. Landing it is also what commits // the live changes this cell then expects back. releaseFirstWrite() for (let pumped = 0; pumped < 40 && secondWriteRejectedAtStorage === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(secondWriteRejectedAtStorage).toBe(1) for (let pumped = 0; pumped < 80 && !compensationEntered; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P1: the compensation had been entered and was held on its first leg, so no restore leg of // the rollback had run yet. expect(compensationEntered).toBe(true) // P2: the re-pin had committed every live change it makes on the view whose write this cell // was holding: the pinned name, the settings overlay, the API handler of the task that view // runs, and that task sticky profile name - all on the replacement - and its durable entry // landed too, because the merge leg that rolls pins back runs after this gate. expect(first["viewLocalState"].currentApiConfigName).toBe("keeper-profile") expect(first["viewLocalState"].apiConfiguration).toEqual(keeperSettings) expect(durablePin("stable-first-view")).toBe("keeper-profile") expect(firstTask.updateApiConfiguration).toHaveBeenLastCalledWith(keeperSettings) expect(firstTask.setTaskApiConfigName).toHaveBeenLastCalledWith("keeper-profile") expect(firstTask.taskApiConfigName).toBe("keeper-profile") // The view whose write failed is the mirror image, and it is the reason the deletion rolls // back: its buffer never took the replacement, because its callback threw at that write, so // there is no live change of its own for the repair to undo. expect(second["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(durablePin("stable-second-view")).toBe("keeper-profile") // The third re-pinned view makes a selection of its own inside this window, after the deletion // had already written the replacement onto it: that choice is the user own, not the deletion own. thirdChoseProfile = third["enqueueProviderProfileMutation"](async () => { await third["_saveViewLocalStateFromMutation"]({ currentApiConfigName: "chosen-profile", apiConfiguration: chosenSettings, }) }) // Attach the rejection observer at once, the way this cell watches the deletion: the // choice can reject while this row is still pumping the fake clock, and a rejection // with no observer by then is reported even though the body below awaits this very // promise. The body keeps its own await, so a failed choice still fails this cell. thirdChoseProfileObserved = thirdChoseProfile.catch(() => {}) for ( let pumped = 0; pumped < 80 && third["viewLocalState"].currentApiConfigName !== "chosen-profile"; pumped++ ) { await vi.advanceTimersByTimeAsync(0) } // P3: the newer selection is in place before any repair runs, so a repair that re-pointed this // view could only have done it by overwriting what the user chose. expect(third["viewLocalState"].currentApiConfigName).toBe("chosen-profile") expect(third["viewLocalState"].apiConfiguration).toEqual(chosenSettings) releaseRecord() await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] await thirdChoseProfile // N1: the deletion reports the re-pin it could not complete, and its compensation restored the // deleted record. await expect(deletion).rejects.toThrow("second sibling write down") expect(saveRecordSpy).toHaveBeenCalledWith( "old-profile", expect.objectContaining({ apiKey: "old-key", id: "old-id" }), ) // N2: the view whose re-pin had committed no longer serves the replacement on any live layer: // the buffer pin and the settings overlay come back to the deleted profile together with the // durable entry and the manager record, and the task it runs gets its own handler and sticky // name back, so the next state that view posts carries the restored pair. expect(first["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(first["viewLocalState"].apiConfiguration).toEqual(deletedSettings) expect(durablePin("stable-first-view")).toBe("old-profile") expect(firstTask.updateApiConfiguration).toHaveBeenLastCalledWith(deletedSettings) expect(firstTask.setTaskApiConfigName).toHaveBeenLastCalledWith("old-profile") expect(firstTask.taskApiConfigName).toBe("old-profile") // N3: the repair queues no durable write of its own. After the compensation was entered, the // only durable viewStates writes are the merge leg that rolls the pins back plus the choice // the third view queued above. expect(viewStatesWrites - writesAtCompensationEntry).toBe(2) // N4: the view that chose a profile of its own keeps that choice in its own buffer: the // deletion owns a pin it wrote itself, not a pin the user moved afterwards. expect(third["viewLocalState"].currentApiConfigName).toBe("chosen-profile") expect(third["viewLocalState"].apiConfiguration).toEqual(chosenSettings) // The deletion re-pointed this view stored pin from the deleted profile onto the // replacement before this cell queued its own selection; the durable rollback must // restore only the pins it still owns, so the choice this view made of its own stays // on disk too - review comment 4746420935 asks for the stored value, not just the // buffer, and the stored value here is the user own choice. expect(durablePin("stable-third-view")).toBe("chosen-profile") // N5: the view whose write failed is left on the profile it was already serving, and its // durable entry is rolled back with every other pin: nothing was replayed onto it. expect(second["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(durablePin("stable-second-view")).toBe("old-profile") // N6: the failure path still posts no state to a sibling, per review comment 4733238422, and // the repair refreshes state only: it dispatches no post of its own either. expect(firstPostSpy).not.toHaveBeenCalled() expect(secondPostSpy).not.toHaveBeenCalled() expect(thirdPostSpy).not.toHaveBeenCalled() } finally { instancesSpy.mockRestore() storageSeam.update = durableUpdate releaseFirstWrite() releaseRecord() // Ordering, not a race this suite showed: the held write sits inside the serialized storage // queue and the deletion awaits that write through its compensation, so settle the deletion // - and the choice this cell queued - under the still-installed fake clock, then restore the // clock, drain the queue, and dispose. Draining before the release would await a queue the // held write has not entered yet, then dispose over both. await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved // Settle the queued choice through its observer: a choice that rejected must not throw // here, because the lines below restore the clock, drain the write queue and dispose // the views, and a throw here would replace the failure this cell is about. await thirdChoseProfileObserved vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await first.dispose() await second.dispose() await third.dispose() await provider.dispose() } }) it("restores the overlay a re-pinned sibling queued onto its own pin before the re-pin ran", async () => { // Defensive: the doubles in this suite can leave console writes pending at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) // The mutation timeout is the provider own 30-second clock: this cell never reaches it, but the // pending timers stay fake so a held gate cannot hold the worker for 30 real seconds. vi.useFakeTimers() const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const first = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const third = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } // One settings object per profile. The overlay a sibling overlay snapshot fills is the settings the // manager resolves for that pin, so the deleted profile own configuration below is both what the // queued snapshot writes and what the rollback has to hand back. const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "old-profile-key", id: "old-id", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", id: "keeper-id", } // Seeded through the real view-state writes before the write seam below is installed, so the seam // can only ever touch the writes this deletion and these two queued mutations make. await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") // The shared provider keys stay on the replacement throughout: a view pinned to another profile // with no overlay of its own reports its own pin name together with THESE settings, which is the // mix the rollback must not put back. await provider.contextProxy.setProviderSettings(keeperSettings) await provider.setViewStateId("stable-sidebar-view") // The deleting view pins a survivor of its own: the deletion reaches the sibling re-pin through the // branch that leaves its own pin alone, and it never waits on a sibling queue before that re-pin, // so both held mutations below can sit inside the window. await provider.saveViewState("currentApiConfigName", "keeper-profile") await provider.saveViewState("apiConfiguration", keeperSettings) // The view whose overlay this cell fills later pins the deleted profile with no overlay of its own: // that is the empty overlay the review names. await first.setViewStateId("stable-first-view") await first.saveViewState("currentApiConfigName", "old-profile") // The view whose durable write this cell fails: pinned and holding an overlay, so its re-pin has // both a buffer change to make and a write to attempt. await second.setViewStateId("stable-second-view") await second.saveViewState("currentApiConfigName", "old-profile") await second.saveViewState("apiConfiguration", deletedSettings) // The third view pins the deleted profile too, and selects the replacement itself while the // deletion is in flight: the deletion owns a pin it wrote, not a pin the user moved. await third.setViewStateId("stable-third-view") await third.saveViewState("currentApiConfigName", "old-profile") const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName // Declared before the try below so its finally block can name every gate and every handle: a failed // assertion must not leave a sibling mutation queue held, a queued mutation unfinished, or the // fake clock running for the later tests. let releaseSnapshot!: () => void const pendingSnapshot = new Promise((resolve) => { releaseSnapshot = resolve }) let releaseSelection!: () => void const pendingSelection = new Promise((resolve) => { releaseSelection = resolve }) // The record restore is the first leg of the compensation: holding it is what turns the moment // between "every re-pin had settled" and "the rollback had run anything" into a window this cell // can read, instead of a state the loop below would only ever see after it had moved on. let releaseRecord!: () => void const pendingRecord = new Promise((resolve) => { releaseRecord = resolve }) let compensationEntered = 0 let deletionSettled = 0 let deletion: Promise | undefined let deletionObserved: Promise | undefined let snapshotObserved: Promise | undefined let selectionObserved: Promise | undefined let secondWriteRejectedAtStorage = 0 const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") // Double assertion: the mock seam declares its own value type, while this seam has to see the raw // key/value pair to fail one write and count the rest. ContextProxy assigns its in-memory cache // before the durable attempt, so the map handed to the seam is identity-equal to the cache of the // view that issued the write: that names the writer without touching production. const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } if (second.contextProxy.getValue("viewStates") === value && secondWriteRejectedAtStorage === 0) { secondWriteRejectedAtStorage++ return Promise.reject(new Error("second sibling write down")) } return durableUpdate(key, value) } try { // The instance registry is environment: the re-pin must see exactly these four views. instancesSpy.mockReturnValue([provider, first, second, third]) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(first, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(second, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(third, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A gate this deletion never moved: the manager-gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) const saveRecordSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig") saveRecordSpy.mockImplementation(async () => { compensationEntered++ await pendingRecord return "restored" }) vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", ...deletedSettings } : { name: "keeper-profile", ...keeperSettings }, ) // Two mutations the views queue before this deletion reaches its re-pin, each held open: // - the first view own overlay snapshot, committed through that view own mutation queue exactly // as snapshotSiblingOverlaysBeforeSharedSettingsWrite commits one for a concurrent activation. // It fills an empty overlay and leaves the pinned name where it was. // - the third view own selection of the replacement, committed through that view own queue. // Holding them open is what puts this deletion own read of the live pins between the moment it // filtered the affected views and the moment each queued write actually lands. snapshotObserved = first["enqueueProviderProfileMutation"](async () => { await pendingSnapshot // Direct private access: the save a sibling overlay snapshot commits through that queue. await first["_saveViewLocalStateFromMutation"]({ apiConfiguration: deletedSettings }) }) selectionObserved = third["enqueueProviderProfileMutation"](async () => { await pendingSelection await third["_saveViewLocalStateFromMutation"]({ currentApiConfigName: "keeper-profile", apiConfiguration: keeperSettings, }) }) // Observe at once: a queued mutation can reject while this row is still pumping the fake clock, // and an unhandled rejection by then is reported even though the rows below await these very // promises. The finally settles each one without throwing. deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) void deletionObserved.then(() => { deletionSettled++ }) // Pump the fake clock until the view this cell fails has had its re-pin write reach storage. That // attempt is only possible after the re-pin pass had read every affected pin and queued each write // behind the held mutation on that view, which is the point this cell is about. for (let pumped = 0; pumped < 80 && secondWriteRejectedAtStorage === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P1: the re-pin had reached storage for one affected view while neither held mutation had landed: // the first view overlay was still the empty one at that read, and the third view was still // pinned to the profile being deleted. expect(secondWriteRejectedAtStorage).toBe(1) expect(first["viewLocalState"].apiConfiguration).toBeUndefined() expect(third["viewLocalState"].currentApiConfigName).toBe("old-profile") releaseSnapshot() releaseSelection() // Pump until the deletion had entered its compensation: it cannot get there before every held // mutation and every sibling re-pin had settled, because the re-pin collects all sibling outcomes // before it reports the first failure. for (let pumped = 0; pumped < 200 && compensationEntered === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(compensationEntered).toBe(1) // P2: every held mutation and every re-pin had settled, and the compensation had only just begun // on its first leg - so the first view still held the pin and the settings this deletion wrote it, // and the third view still held the choice it had made itself. expect(first["viewLocalState"].currentApiConfigName).toBe("keeper-profile") expect(first["viewLocalState"].apiConfiguration).toEqual(keeperSettings) expect(third["viewLocalState"].currentApiConfigName).toBe("keeper-profile") releaseRecord() for (let pumped = 0; pumped < 200 && deletionSettled === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(deletionSettled).toBe(1) await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // N1: the deletion reports the re-pin it could not complete; the error is the original failure, // not a repair of its own. await expect(deletion).rejects.toThrow("second sibling write down") // N2: the view whose overlay was filled by its own queued snapshot returns to THAT overlay, not to // the empty one this deletion saw when it read the live pins. The rollback restores the state the // view held when the re-pin executed, so the view keeps reporting the deleted profile with the // deleted profile own settings instead of with the shared replacement settings. expect(first["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(first["viewLocalState"].apiConfiguration).toEqual(deletedSettings) expect(durablePin("stable-first-view")).toBe("old-profile") // N3: the view whose own write rejected never took the replacement on any layer, so nothing was // replayed onto it and its durable entry came back with every other pin. expect(second["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(second["viewLocalState"].apiConfiguration).toEqual(deletedSettings) expect(durablePin("stable-second-view")).toBe("old-profile") // N4: the view that selected the replacement itself is not reverted at all. Its own re-pin was // declined at the queued name check because it had already chosen the replacement, and the merge // leg declines it too: the name its durable entry holds is one this deletion wrote AND one that // view wrote itself afterwards, so the name cannot say whose write it is - only the writer token // can. Restoring the entry here would undo the selection in storage while the live view stayed on // the profile the user chose, and the reload would then undo the choice a second time. expect(third["viewLocalState"].currentApiConfigName).toBe("keeper-profile") expect(third["viewLocalState"].apiConfiguration).toEqual(keeperSettings) expect(durablePin("stable-third-view")).toBe("keeper-profile") } finally { instancesSpy.mockRestore() storageSeam.update = durableUpdate releaseSnapshot() releaseSelection() releaseRecord() // Settle the released work under the still-installed fake clock, then restore the clock, drain // the durable queue and dispose every view: draining before the release would await a queue the // held write has not entered yet, then dispose over both. await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved await snapshotObserved await selectionObserved vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await first.dispose() await second.dispose() await third.dispose() await provider.dispose() } }) // Cleanup for the providers a cell in this describe built, for review comments 4750073716, // 4750247526 and the matching sentence of review 6126330613: a rejected dispose() must not // skip the providers that were built before it. The afterEach hook at the top of this file // clears ClineProvider.activeInstances without disposing anything, so a view this cleanup // leaves behind keeps its webview, its listeners and its managers for the rest of the run, // and the sidebar - built first, attempted last - is the first one that leaks. Every // instance is still attempted, in the reverse creation order the replaced loops walked (the // array is reversed in place, exactly as they did), and every rejection is collected: a // single rejected dispose is rethrown unchanged, so a cell whose cleanup fails still fails // with that very rejection; two or more are reported together as an AggregateError naming // how many cleanups failed; and a cleanup where nothing rejects still reports nothing. const disposeBuiltProvidersAndReportCleanupErrors = async ( built: Array<{ dispose(): Promise }>, ): Promise => { const cleanupErrors: unknown[] = [] for (const instance of built.reverse()) { try { await instance.dispose() } catch (cleanupError: unknown) { cleanupErrors.push(cleanupError) } } if (cleanupErrors.length === 1) { throw cleanupErrors[0] } if (cleanupErrors.length > 1) { const summary = `${cleanupErrors.length} of ${built.length} provider cleanups failed` throw new AggregateError(cleanupErrors, summary) } } it("keeps the view pin cache on what storage holds when the rollback write rejects", async () => { // Review comment 4747622579 reads the rollback merged write as an ordinary view-state save that // fills the in-memory cache before the durable attempt, and concludes that a rejected attempt // leaves every live view serving the pin this rollback meant to restore while storage still // holds the replacement, to be persisted by the next write of any view. This cell puts that // scenario in front of the layer that performs the write: two siblings are re-pinned, the first // durable write lands, a later one rejects so the deletion compensates, and the rollback own // merged write is then rejected on its own. What it pins is the agreement the write layer keeps // - ContextProxy reads a rejected store key back out of the Memento into its cache - so the // cache ends up equal to what storage holds and no survivor of an unstored state is left for // the next write to persist. Removing that read-back turns this cell red at N2 below. // Declared before the protected scope below so its finally block can name every gate and // dispose every view the setup had time to build, the shape review comment 4747622535 asks for. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] let firstRePinWriteLanded = 0 let triggerRejected = 0 let mergeWriteRejectedAtStorage = 0 let keeperWritesBeforeTarget = 0 let releaseSecondWrite: (() => void) | undefined // Held-open durable write: the seam below parks the second sibling own re-pin write on this // promise, and this cell releases it only after it has looked at the state while that write was // still in flight. Review comment 4748688438 asks for exactly that check, so the gate is declared // outside the protected scope below - its finally block has to be able to release it even when an // assertion threw first. const secondWriteGate = new Promise((resolveGate) => { releaseSecondWrite = () => { releaseSecondWrite = undefined resolveGate() } }) let deletion: Promise | undefined let deletionObserved: Promise | undefined try { vi.useFakeTimers() // Defensive: the doubles in this suite can leave console writes pending at worker teardown. for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(provider) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(sibling) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(second) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "old-profile-key", id: "old-id", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", id: "keeper-id", } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.contextProxy.setProviderSettings(keeperSettings) await provider.setViewStateId("stable-sidebar-view") // The deleting view pins a survivor of its own, so the deletion reaches the sibling re-pin and // then posts state: that post is the failure the compensation runs against. await provider.saveViewState("currentApiConfigName", "keeper-profile") await provider.saveViewState("apiConfiguration", keeperSettings) await sibling.setViewStateId("stable-sibling-view") await sibling.saveViewState("currentApiConfigName", "old-profile") // The second sibling pins the deleted profile as well: its own re-pin write is the one this // cell rejects, which is what lets the deletion reach the compensation with the first // sibling durable re-pin already committed in storage. await second.setViewStateId("second-sibling-view") await second.saveViewState("currentApiConfigName", "old-profile") const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") cleanups.push(() => instancesSpy.mockRestore()) // The instance registry is environment: the re-pin must see exactly these three views. instancesSpy.mockReturnValue([provider, sibling, second]) // Double assertion: ContextProxy assigns its in-memory cache before the durable attempt, so the // seam is the only place that can tell one view-state write from another by identity. Four writes // name both siblings at once in this scenario: the deletion own re-point pass, then the re-pin of // each sibling in turn - every one of them carries the replacement for both views, because each // write rebuilds the whole map from what storage holds at that instant - plus the compensating // read-back the failing sibling itself issues. The seam therefore cannot read the writer out of the // value, so it asks the writer instead: each sibling own ContextProxy tags the map object it hands // over, and only a map tagged by the second sibling is rejected. That aims the rejection at the // second sibling own re-pin write, which is what lets this cell check - rather than assume, as // review comment 4748688438 asks - that the first sibling re-pin had already committed in both // layers before the compensation opened. The rollback own merged map, which names the deleted // profile for both siblings, is recognised only after that trigger has been released below. const writeIssuer = new WeakMap() for (const [issuerLabel, issuerInstance] of [ ["first-sibling", sibling], ["second-sibling", second], ] as const) { const proxy = issuerInstance.contextProxy const issueToStorage = proxy.setValue.bind(proxy) // Double assertion: setValue is generic over the state key, and the tag only ever forwards one // key/value pair through it, so the wrapper is re-typed to that pair shape. const setValueSpy = vi.spyOn(proxy, "setValue").mockImplementation((( key: string, value: unknown, ) => { if (key === "viewStates" && value && typeof value === "object") { writeIssuer.set(value as object, issuerLabel) } return issueToStorage(key as never, value as never) }) as typeof proxy.setValue) cleanups.push(() => setValueSpy.mockRestore()) } const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update cleanups.push(() => { storageSeam.update = durableUpdate }) storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } const states = value as Record const firstPin = states["stable-sibling-view"]?.currentApiConfigName const secondPin = states["second-sibling-view"]?.currentApiConfigName if (firstPin === "keeper-profile" && secondPin === "keeper-profile") { if (writeIssuer.get(value as object) === "second-sibling" && triggerRejected === 0) { // The targeted write: park it on the gate so this cell can look at the state while the write is // still in flight, then reject it on release - that rejection is what opens the compensation. keeperWritesBeforeTarget = firstRePinWriteLanded triggerRejected++ return secondWriteGate.then(() => Promise.reject(new Error("second sibling re-pin write down")), ) } firstRePinWriteLanded++ return durableUpdate(key, value) } if ( triggerRejected === 1 && mergeWriteRejectedAtStorage === 0 && firstPin === "old-profile" && secondPin === "old-profile" ) { mergeWriteRejectedAtStorage++ return Promise.reject(new Error("rollback merge write down")) } return durableUpdate(key, value) } for (const instance of [provider, sibling, second]) { const postSpy = vi.spyOn(instance, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => postSpy.mockRestore()) } const rollbackLogLines: string[] = [] const logSpy = vi.spyOn(provider, "log").mockImplementation((line: string) => { rollbackLogLines.push(String(line)) }) cleanups.push(() => logSpy.mockRestore()) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("restored") vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", ...deletedSettings } : { name: "keeper-profile", ...keeperSettings }, ) deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) for (let pumped = 0; pumped < 200 && triggerRejected === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P1 (review comment 4748688438): the write this cell aims at is the second sibling own re-pin // write. The seam saw exactly two map writes naming both siblings before it - the deletion own // re-point pass and the first sibling own re-pin - and the targeted write is still in flight: the // rollback has not attempted its merged map while it is pending, so the compensation opens after a // sibling re-pin that really succeeded and not instead of one. expect(triggerRejected).toBe(1) expect(keeperWritesBeforeTarget).toBe(2) expect(mergeWriteRejectedAtStorage).toBe(0) // P2: while that write is still pending, the first sibling already pins the replacement in both // layers: its own re-pin committed to storage and moved its own buffer. expect(durablePin("stable-sibling-view")).toBe("keeper-profile") expect(sibling["viewLocalState"].currentApiConfigName).toBe("keeper-profile") releaseSecondWrite?.() for (let pumped = 0; pumped < 200; pumped++) { await vi.advanceTimersByTimeAsync(0) } await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // P3: two distinct rejections, each recorded at the seam: the targeted write really rejected, and // the rollback really did attempt its merged map exactly once. expect(triggerRejected).toBe(1) expect(mergeWriteRejectedAtStorage).toBe(1) // N1: storage still holds the replacement for both sibling pins: the merge never landed, which is // the divergence the review describes. expect(durablePin("stable-sibling-view")).toBe("keeper-profile") expect(durablePin("second-sibling-view")).toBe("keeper-profile") // N2: the cache does not keep the rolled-back map. The write layer reads the key back from // storage when the store rejects, so the two are the same object and not merely similar: were // it left holding the attempted value, every live view would serve a pin that was never // stored, and the next write from any of them would persist that survivor. expect(provider.contextProxy.getValue("viewStates")).toBe(mockContext.globalState.get("viewStates")) expect( (provider.contextProxy.getValue("viewStates") as Record)[ "stable-sibling-view" ]?.currentApiConfigName, ).toBe("keeper-profile") // N3 (review comment 4748688446): each sibling own live pin against its own stored pin. The first // sibling: its own re-pin landed and the rollback left it alone, so both layers name the replacement. expect(sibling["viewLocalState"].currentApiConfigName).toBe("keeper-profile") expect(durablePin("stable-sibling-view")).toBe("keeper-profile") // The second sibling: its own re-pin write is the one that rejected, and the durable write happens // before the buffer moves, so its buffer never left the deleted profile while its stored entry holds // the replacement. This is the divergence the review names, and it lives in the one buffer the live // leg skips. expect(second["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(durablePin("second-sibling-view")).toBe("keeper-profile") // N4: the incomplete-recovery report names both siblings now. The first because its own re-pin // came back and its live pin no longer carries the applied name; the second because its stored // pin never came back at all. The check that decides what to report runs before the check that // asks what the view pins now, so a view left on the replacement is reported whichever way its // buffer moved - which is what the comment above that call promises and what this cell used to // pin as silence (review comments 4748688446 and the production cell that follows it). const incompleteReport = rollbackLogLines .filter((line) => line.includes("incomplete view-pin rollback")) .join(" ; ") expect(rollbackLogLines.filter((line) => line.includes("incomplete view-pin rollback")).length).toBe(1) expect(incompleteReport).toContain("stable-sibling-view") expect(incompleteReport).toContain("second-sibling-view") // N5: the rollback reports the leg that failed and names the write that rejected it. expect( rollbackLogLines.some((line) => line.includes("failed to restore the persisted view pins: rollback merge write down"), ), ).toBe(true) // N6: the deletion rejects with the failure that opened the compensation, not with the write // that failed to repair anything. await expect(deletion).rejects.toThrow("second sibling re-pin write down") } finally { // Settle the released deletion first, under the fake clock that is still installed, then put the // fixtures back: an assertion that failed above leaves this deletion pending, and its resumed // rollback must not run against already-restored spies or against real timers. Nothing is swallowed // here - the settle leg is the try and the restoration is its finally - so an assertion error, or a // rejection surfacing while the released deletion settles, still reaches the runner after the // fixtures are restored and every built view is disposed (review comment 4748688451). releaseSecondWrite?.() try { await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved } finally { for (const cleanup of cleanups.reverse()) { cleanup() } vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await disposeBuiltProvidersAndReportCleanupErrors(built) } } }) it("snapshots the value a memento update is given instead of keeping the caller object", async () => { // Test-double contract (review comment 4750247491), not a production claim: a real VS Code // Memento serializes what update is handed, so the caller own object is not the stored // state and a later in-place mutation by the caller cannot reach the stored bytes. Two // rows in this file used to lean on the opposite behaviour - they compared the stored // map to the map production handed over and read the answer as "what storage holds" - // so this cell pins the contract out in the open: an edit that puts reference storage // back into the double has to redden here. A distinct key is used so no other cell own // durable map is disturbed. const submitted = { marker: { profileName: "snapshot-marker-profile" } } await mockContext.globalState.update("snapshotProbeKey", submitted) // The stored value says the same thing the caller handed over... expect(mockContext.globalState.get("snapshotProbeKey")).toEqual(submitted) // ...while being a different object, so mutating what the caller submitted cannot move // what a later get answers. expect(mockContext.globalState.get("snapshotProbeKey")).not.toBe(submitted) submitted.marker.profileName = "mutated-after-write" const stored = mockContext.globalState.get("snapshotProbeKey") as { marker?: { profileName?: string } } | undefined expect(stored?.marker?.profileName).toBe("snapshot-marker-profile") await mockContext.globalState.update("snapshotProbeKey", undefined) }) it("names the rollback divergence in the settled bytes and in the value a get returns", async () => { // Review comment 4749755310 reads the cells around this one as unable to see a difference // between two things a rejected durable write separates: the bytes the backing store holds, and // the value a get returns. On this suite the storage double only ever moves when a write is // forwarded to it, so a write this cell rejects moves neither, and the assertion below the // anchor can only ever read one thing. VS Code 1.100 separates them: a Memento get answers // with the value an update was given before the backing write settles, and a write that then // rejects leaves the backing bytes on the map that was there before. This cell keeps the // scenario of the cell above intact - same three views, same aimed rejection, same rollback // - and gives the storage layer those two readings, so each one is asserted by name and the // cell still reads correctly when the two disagree. Names are unique to this cell because the // doubles in this suite keep state between cells. // Declared before the protected scope below so its finally block can name every gate and // dispose every view the setup had time to build, the shape review comment 4747622535 asks for. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] let firstRePinWriteLanded = 0 let triggerRejected = 0 let mergeWriteRejectedAtStorage = 0 let keeperWritesBeforeTarget = 0 let releaseSecondWrite: (() => void) | undefined // Held-open durable write: the seam below parks the second sibling own re-pin write on this // promise, and this cell releases it only after it has looked at the state while that write was // still in flight. Review comment 4748688438 asks for exactly that check, so the gate is declared // outside the protected scope below - its finally block has to be able to release it even when an // assertion threw first. const secondWriteGate = new Promise((resolveGate) => { releaseSecondWrite = () => { releaseSecondWrite = undefined resolveGate() } }) let deletion: Promise | undefined let deletionObserved: Promise | undefined try { vi.useFakeTimers() // Defensive: the doubles in this suite can leave console writes pending at worker teardown. for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(provider) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(sibling) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(second) const oldProfile: ProviderSettingsEntry = { name: "readback-old-profile", id: "readback-old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "readback-keeper-profile", id: "readback-keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "readback-old-key", id: "readback-old-id", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "readback-keeper-key", id: "readback-keeper-id", } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "readback-keeper-profile") await provider.contextProxy.setProviderSettings(keeperSettings) await provider.setViewStateId("readback-sidebar-view") // The deleting view pins a survivor of its own, so the deletion reaches the sibling re-pin and // then posts state: that post is the failure the compensation runs against. await provider.saveViewState("currentApiConfigName", "readback-keeper-profile") await provider.saveViewState("apiConfiguration", keeperSettings) await sibling.setViewStateId("readback-sibling-view") await sibling.saveViewState("currentApiConfigName", "readback-old-profile") // The second sibling pins the deleted profile as well: its own re-pin write is the one this // cell rejects, which is what lets the deletion reach the compensation with the first // sibling durable re-pin already committed in storage. await second.setViewStateId("readback-held-view") await second.saveViewState("currentApiConfigName", "readback-old-profile") // Two readings of the same key: what a get answers now, and the bytes a reload would read. // Only a write that settles successfully moves the second. type StoredStates = Record const optimisticGet = true let backingStates: StoredStates = {} const getPin = (viewStateId: string): string | undefined => (mockContext.globalState.get("viewStates") as StoredStates | undefined)?.[viewStateId] ?.currentApiConfigName const backingPin = (viewStateId: string): string | undefined => backingStates[viewStateId]?.currentApiConfigName const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") cleanups.push(() => instancesSpy.mockRestore()) // The instance registry is environment: the re-pin must see exactly these three views. instancesSpy.mockReturnValue([provider, sibling, second]) // Double assertion: setValue is generic over the state key and the seam only ever forwards // one key/value pair through it, so each wrapper is re-typed to that pair shape. The seam // cannot read the writer out of the value - four writes name both siblings at once, because // each one rebuilds the whole map from what storage holds at that instant - so each sibling // own ContextProxy tags the map object it hands over, and only a map tagged by the second // sibling is rejected. That aims the rejection at the second sibling own re-pin write, which // is what lets this cell check that the rollback opens after a sibling re-pin that really // succeeded. The rollback own merged map, which names the deleted profile for both siblings, // is recognised after that trigger has been released. const writeIssuer = new WeakMap() for (const [issuerLabel, issuerInstance] of [ ["first-sibling", sibling], ["second-sibling", second], ] as const) { const proxy = issuerInstance.contextProxy const issueToStorage = proxy.setValue.bind(proxy) // Double assertion: setValue is generic over the state key, and the tag only ever forwards one // key/value pair through it, so the wrapper is re-typed to that pair shape. const setValueSpy = vi.spyOn(proxy, "setValue").mockImplementation((( key: string, value: unknown, ) => { if (key === "viewStates" && value && typeof value === "object") { writeIssuer.set(value as object, issuerLabel) } return issueToStorage(key as never, value as never) }) as typeof proxy.setValue) cleanups.push(() => setValueSpy.mockRestore()) } const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update cleanups.push(() => { storageSeam.update = durableUpdate }) backingStates = { ...(mockContext.globalState.get("viewStates") as StoredStates | undefined) } storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } const states = value as StoredStates const firstPin = states["readback-sibling-view"]?.currentApiConfigName const secondPin = states["readback-held-view"]?.currentApiConfigName let applied = false if (optimisticGet) { // A Memento moves what a get answers as soon as update is called with the new map. // The optimistic move of a get hands the write layer a snapshot of the submitted map, // not the caller own object. const optimisticSnapshot = { ...states } void durableUpdate(key, optimisticSnapshot) applied = true } if (firstPin === "readback-keeper-profile" && secondPin === "readback-keeper-profile") { if (writeIssuer.get(value as object) === "second-sibling" && triggerRejected === 0) { keeperWritesBeforeTarget = firstRePinWriteLanded triggerRejected++ return secondWriteGate.then(() => Promise.reject(new Error("readback held sibling re-pin write down")), ) } firstRePinWriteLanded++ backingStates = { ...states } return applied ? Promise.resolve() : durableUpdate(key, { ...states }) } if ( triggerRejected === 1 && mergeWriteRejectedAtStorage === 0 && firstPin === "readback-old-profile" && secondPin === "readback-old-profile" ) { // The rollback merged write: it lands on the get reading, and the settled bytes below // stay on whatever the last successful write left there. The cell rejects it here. mergeWriteRejectedAtStorage++ return Promise.reject(new Error("readback rollback merge write down")) } backingStates = { ...states } return applied ? Promise.resolve() : durableUpdate(key, value) } for (const instance of [provider, sibling, second]) { const postSpy = vi.spyOn(instance, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => postSpy.mockRestore()) } const rollbackLogLines: string[] = [] const logSpy = vi.spyOn(provider, "log").mockImplementation((line: string) => { rollbackLogLines.push(String(line)) }) cleanups.push(() => logSpy.mockRestore()) // Reviewer 4750247500: the profile store here is the real ProviderSettingsManager; // only the secret storage is mocked (the mock extension context backs secrets with a // plain object). Both profiles are seeded through saveConfig and the keeper is // activated through the manager, so the deletion really removes the record and the // compensation really writes it back instead of a mock reporting success. await provider.providerSettingsManager.saveConfig(oldProfile.name, { ...deletedSettings, openRouterApiKey: "readback-old-router-key", }) await provider.providerSettingsManager.saveConfig(keeperProfile.name, keeperSettings) await provider.providerSettingsManager.activateProfile({ name: keeperProfile.name }) deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) for (let pumped = 0; pumped < 200 && triggerRejected === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P1 (review comment 4748688438): the write this cell aims at is the second sibling own re-pin // write. The seam saw exactly two map writes naming both siblings before it - the deletion own // re-point pass and the first sibling own re-pin - and the targeted write is still in flight: the // rollback has not attempted its merged map while it is pending, so the compensation opens after a // sibling re-pin that really succeeded and not instead of one. expect(triggerRejected).toBe(1) expect(keeperWritesBeforeTarget).toBe(2) expect(mergeWriteRejectedAtStorage).toBe(0) // While the second write is pending the real store must already be without the // deleted record: the mocked deleteConfig reported success without removing anything, // and the mocked getProfile kept handing the old profile back. await expect(provider.providerSettingsManager.hasConfig(oldProfile.name)).resolves.toBe(false) await expect( provider.providerSettingsManager.listConfig().then((entries) => entries.map((entry) => entry.name)), ).resolves.not.toContain(oldProfile.name) // P2: while that write is still pending, the first sibling already pins the replacement in both // layers: its own re-pin committed to storage and moved its own buffer. expect(getPin("readback-sibling-view")).toBe("readback-keeper-profile") expect(backingPin("readback-sibling-view")).toBe("readback-keeper-profile") expect(sibling["viewLocalState"].currentApiConfigName).toBe("readback-keeper-profile") releaseSecondWrite?.() for (let pumped = 0; pumped < 200; pumped++) { await vi.advanceTimersByTimeAsync(0) } await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // P3: two distinct rejections, each recorded at the seam: the targeted write really rejected, and // the rollback really did attempt its merged map exactly once. expect(triggerRejected).toBe(1) expect(mergeWriteRejectedAtStorage).toBe(1) // N1 (the settled reading): the rejected merge write moved no bytes. A reload still reads the // replacement for both sibling pins, because the merge never landed. expect(backingPin("readback-sibling-view")).toBe("readback-keeper-profile") expect(backingPin("readback-held-view")).toBe("readback-keeper-profile") // N2 (the get reading): the very same two views answer with the deleted profile, because the // rejected write had already handed that map to the storage layer and a Memento does not take // it back. The two readings are named apart rather than merged into one claim about // disagreement: this is exactly the state review comment 4749755310 says the old assertion // could not tell apart, and it is why the read-back below cannot settle it. expect(getPin("readback-sibling-view")).toBe("readback-old-profile") expect(getPin("readback-held-view")).toBe("readback-old-profile") // N3: what the write layer reads back on a rejection is the get reading, so the cache agrees // with the value a get answers and not with the settled bytes. The double snapshots what // it is handed, so the divergence is asserted by content: the settled copy does not hold // the profiles the get still answers. Every live view therefore serves a pin no reload // will reproduce, and the next write from any of them persists it. Pinned as it stands: // closing the gap is production work for a follow-up cell, not something this cell // rewrites. expect(provider.contextProxy.getValue("viewStates")).toBe(mockContext.globalState.get("viewStates")) expect(provider.contextProxy.getValue("viewStates")).not.toEqual(backingStates) // N4: the rollback reports the leg that failed and names the write that rejected it. expect( rollbackLogLines.some((line) => line.includes("failed to restore the persisted view pins: readback rollback merge write down"), ), ).toBe(true) // N5: the deletion rejects with the failure that opened the compensation, not with the write // that failed to repair anything. await expect(deletion).rejects.toThrow("readback held sibling re-pin write down") // And after compensation the record must be back under its original id, which the canned // mock could not prove. Measured on the real store: the restored record carries name, // id and provider but not the apiKey the deletion read, so this row pins the id and // leaves the credential gap to the follow-up the review asks for. await expect( provider.providerSettingsManager.getProfile({ id: "readback-old-id" }), ).resolves.toMatchObject({ name: "readback-old-profile", id: "readback-old-id", openRouterApiKey: "readback-old-router-key", }) } finally { // Settle the released deletion first, under the fake clock that is still installed, then put the // fixtures back: an assertion that failed above leaves this deletion pending, and its resumed // rollback must not run against already-restored spies or against real timers. Nothing is swallowed // here - the settle leg is the try and the restoration is its finally - so an assertion error, or a // rejection surfacing while the released deletion settles, still reaches the runner after the // fixtures are restored and every built view is disposed (review comment 4748688451). releaseSecondWrite?.() try { await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved } finally { for (const cleanup of cleanups.reverse()) { cleanup() } vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await disposeBuiltProvidersAndReportCleanupErrors(built) } } }) it("leaves a view that re-selected the replacement while its own deletion replay waited", async () => { // Review comment 4747622590: the live replay of a rolled-back deletion decides with the name // the view still pins plus the recorded view id, and a view that selected the very name this // deletion had applied, after the durable restore, passes both. This cell holds the replay // inside the awaited task write of the first re-pinned view, lets the second view save a // selection of its own during that await, and pins that the replay leaves that view on what // it chose in both layers while the first view still comes all the way back. // Declared before the protected scope below so its finally block can name every gate and // dispose every view the setup had time to build: review comment 4747622535 asks the // protected scope to start before the fake clock is installed and each view to be tracked // as it is built, so a seed write that rejects cannot leave the fake clock, a held write // gate or a live provider behind for the later tests. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] const taskWriteNames: string[] = [] const rollbackLogLines: string[] = [] let releaseTaskWrite: (() => void) | undefined const pendingTaskWrite = new Promise((resolve) => { releaseTaskWrite = resolve }) let deletion: Promise | undefined let deletionObserved: Promise | undefined let reSelectionObserved: Promise | undefined let reSelectionSettled: Promise | undefined let deletionSettled = 0 let taskRestoreWritesAtSeam = 0 let thirdWriteRejectedAtStorage = 0 let armSelectionCount = 0 let secondSelectionLanded = 0 try { vi.useFakeTimers() // Defensive: the doubles in this suite can leave console writes pending at worker teardown. for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(provider) const first = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(first) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(second) const third = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(third) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "old-profile-key", id: "old-id", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", id: "keeper-id", } // Seeded through the real view-state writes before the write seam below is installed, so // the seam can only ever touch the writes this deletion, its rollback and the injected // re-selection make. await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.contextProxy.setProviderSettings(keeperSettings) await provider.setViewStateId("stable-sidebar-view") // The deleting view pins a survivor of its own, so the deletion reaches the sibling re-pin // through the branch that leaves its own pin and buffer alone. await provider.saveViewState("currentApiConfigName", "keeper-profile") await provider.saveViewState("apiConfiguration", keeperSettings) // The view whose replay this cell holds: pinned on the profile under deletion, with a // running task that follows that profile and a stored history item the restore write // actually has to update. That write is the await the review names. await first.setViewStateId("stable-first-view") await first.saveViewState("currentApiConfigName", "old-profile") // The view this cell is about: re-pinned cleanly onto the replacement, and free to save a // selection of its own while the replay is held. It carries no task, so all the replay // could do to it was move its buffer. await second.setViewStateId("stable-second-view") await second.saveViewState("currentApiConfigName", "old-profile") // The failure source: a third re-pinned view whose own re-pin write throws at storage, so // the deletion reaches its compensation. Its buffer never took the replacement, which is // why the replay declines it at the name check instead of on the write claim. await third.setViewStateId("stable-third-view") await third.saveViewState("currentApiConfigName", "old-profile") const firstTaskSettings: ProviderSettings = deletedSettings const firstTask = { apiConfiguration: firstTaskSettings, taskApiConfigName: "old-profile", taskId: "stored-first-task", setTaskApiConfigName: vi.fn((name: string) => { firstTask.taskApiConfigName = name }), updateApiConfiguration: vi.fn((settings: ProviderSettings) => { firstTask.apiConfiguration = settings }), persistStickyProviderProfileToCurrentTask: vi.fn(), } // Double assertion: the double implements the members the replay and the sticky write // touch, not the whole task surface, and the seam needs it where a real task would have // been started. const currentTaskSpy = vi.spyOn(first, "getCurrentTask") cleanups.push(() => currentTaskSpy.mockRestore()) currentTaskSpy.mockReturnValue(firstTask as unknown as ReturnType) const storedTask = { id: "stored-first-task", task: "first conversation", ts: 1, number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, apiConfigName: "old-profile", } first.taskHistoryStore["cache"].set(storedTask.id, storedTask) first["taskHistoryStoreInitialized"] = true const storedTaskPin = (): string | undefined => first.taskHistoryStore.get(storedTask.id)?.apiConfigName const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") cleanups.push(() => instancesSpy.mockRestore()) // The instance registry is environment: the re-pin must see exactly these four views. instancesSpy.mockReturnValue([provider, first, second, third]) // The restore-side task write is the only write this seam holds: it is the awaited line // inside the live replay the review names, and holding it is what opens the window the // re-selection lands in. The re-pin own keeper write passes untouched, and its name is // recorded so the order of the two directions is visible from the outside. const upsertThrough = first.taskHistoryStore.upsert.bind(first.taskHistoryStore) const taskWriteSpy = vi.spyOn(first.taskHistoryStore, "upsert") cleanups.push(() => taskWriteSpy.mockRestore()) taskWriteSpy.mockImplementation((item) => { taskWriteNames.push(String(item.apiConfigName)) if (item.apiConfigName === "old-profile" && taskRestoreWritesAtSeam === 0) { taskRestoreWritesAtSeam++ return pendingTaskWrite.then(() => upsertThrough(item)) } return upsertThrough(item) }) // Double assertion: the mock seam declares its own value type, while this seam has to see // the raw key and value pair to fail one write by identity and to count another. // ContextProxy assigns its in-memory cache before the durable attempt, so the map handed // to the seam is identity-equal to the cache of the view that issued the write. const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update cleanups.push(() => { storageSeam.update = durableUpdate }) storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } if (third.contextProxy.getValue("viewStates") === value && thirdWriteRejectedAtStorage === 0) { thirdWriteRejectedAtStorage++ return Promise.reject(new Error("third sibling write down")) } // Armed only once the replay window is open, so the count names the re-selection and not // the re-pin write that ran before it. if (armSelectionCount === 1 && second.contextProxy.getValue("viewStates") === value) { secondSelectionLanded++ } return durableUpdate(key, value) } for (const instance of [provider, first, second, third]) { const postSpy = vi.spyOn(instance, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => postSpy.mockRestore()) } // The rollback logs every leg it could not complete through this one method: spying on it // reads what each path reports without touching the console the doubles already mock. const rollbackLogSpy = vi.spyOn(provider, "log").mockImplementation((line: string) => { rollbackLogLines.push(String(line)) }) cleanups.push(() => rollbackLogSpy.mockRestore()) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A gate this deletion never moved: the manager-gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("restored") vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", ...deletedSettings } : { name: "keeper-profile", ...keeperSettings }, ) deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) void deletionObserved.then(() => { deletionSettled++ }) // Pump until the live replay reaches the awaited task write of the first view. It cannot // get there before the durable leg rewrote every pin this deletion owned, because the // replay runs after that leg and replays exactly the views it recorded. for (let pumped = 0; pumped < 200 && taskRestoreWritesAtSeam === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P1: the replay is inside the write the review names, and the deletion is still inside // the replay: this is the window a view-local save from another view can run in. expect(taskRestoreWritesAtSeam).toBe(1) expect(deletionSettled).toBe(0) // P2: the durable leg had already put both sibling pins back before the window opened, so // both views were recorded as rolled back and both are live replay candidates. expect(durablePin("stable-first-view")).toBe("old-profile") expect(durablePin("stable-second-view")).toBe("old-profile") // The second view selects the replacement of its own inside that window, committing // through its own mutation queue exactly as a view-local save from its webview does. armSelectionCount = 1 reSelectionObserved = second["enqueueProviderProfileMutation"](async () => { await second["_saveViewLocalStateFromMutation"]({ currentApiConfigName: "keeper-profile", apiConfiguration: keeperSettings, }) }) // Observe at once: the re-selection can reject while this row still pumps the fake clock, // and the finally settles it through this observer so a rejection cannot skip the clock // restore, the gate release or the disposes below - review comment 4747622550 asks for // the observer at the handle, not at the await. reSelectionSettled = reSelectionObserved.catch(() => {}) for (let pumped = 0; pumped < 200 && secondSelectionLanded === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P3: the selection landed while the replay was still held. Storage and the view buffer // both name the replacement, the task write of the first view is still pending, and // the replay has not reached this view yet. expect(secondSelectionLanded).toBe(1) expect(deletionSettled).toBe(0) expect(durablePin("stable-second-view")).toBe("keeper-profile") expect(second["viewLocalState"].currentApiConfigName).toBe("keeper-profile") expect(firstTask.taskApiConfigName).toBe("old-profile") releaseTaskWrite!() for (let pumped = 0; pumped < 200 && deletionSettled === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(deletionSettled).toBe(1) await deletionObserved await reSelectionSettled await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // N1: the view that saved its own selection during the held replay write stays on the // profile it chose. A name comparison cannot carry this decision: the selection chose // the very name this deletion had applied, so the guard sees exactly what it sees for a // view the deletion still owns. The durable write claim is the signal that tells the two // apart, and the replay has to stop here on it. expect(second["viewLocalState"].currentApiConfigName).toBe("keeper-profile") // N2: and it stays on that profile in both layers: the buffer this cell is about, the // settings of the profile it chose, and the entry its own write put back into storage. expect(second["viewLocalState"].apiConfiguration).toEqual(keeperSettings) expect(durablePin("stable-second-view")).toBe("keeper-profile") // N3: the view this deletion still owned comes all the way back: buffer, durable entry, // running task handler, sticky name and the stored task pin the replay writes through // the history store. expect(first["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(durablePin("stable-first-view")).toBe("old-profile") expect(firstTask.taskApiConfigName).toBe("old-profile") expect(firstTask.updateApiConfiguration).toHaveBeenLastCalledWith(deletedSettings) expect(storedTaskPin()).toBe("old-profile") // N4: the view whose re-pin write threw never took the replacement on its buffer, so the // replay declines it at the name check and its durable entry came back with the rest. expect(third["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(durablePin("stable-third-view")).toBe("old-profile") // N5: the deletion still rejects with the sibling write failure it hit, not with a repair // of its own. await expect(deletion).rejects.toThrow("third sibling write down") // N6: nothing is left unreconciled: every view the durable leg rewrote either came back // or was left on the profile its own newer write named. expect(rollbackLogLines.some((line) => line.includes("incomplete view-pin rollback"))).toBe(false) // N7: the stored task pin moved once in each direction and the replay issued no second // restore write for the view it left alone. expect(taskWriteNames).toEqual(["keeper-profile", "old-profile"]) expect(second.getCurrentTask()).toBeUndefined() } finally { // Release the held write first, then settle the released work under the still-installed fake clock, // then restore the clock, drain the durable write queue and dispose every view the setup built. // Draining before the release would await a queue the held write has not entered yet, then dispose // over both. The settle leg is the try and the restoration is its finally, so an assertion error, or // a rejection from the settled promises, still reaches the runner after the fixtures are restored and // every built view is disposed (review comment 4748688451). releaseTaskWrite?.() try { await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved await reSelectionSettled } finally { for (const cleanup of cleanups.reverse()) { cleanup() } vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await disposeBuiltProvidersAndReportCleanupErrors(built) } } }) it("keeps a selection the user completed on the deleting view when a sibling re-pin fails", async () => { // Review comment 4748265808: while this deletion awaited a sibling re-pin, every view pin this view // wrote in that window inherited the deletion token, including the ordinary selection the user // completed here. The compensation then passed its own ownership check on that write, put the // deleted profile back into this view stored pin, and left the live buffer on the replacement, so // a reload dropped a selection the user had already finished. The window is opened with a mutation // the sibling itself queued ahead of its re-pin: holding that queue parks the deletion without // occupying the serialized view pin write queue, so this view own write can still land in it. // Declared before the protected scope below so the finally can name every gate and dispose every // view the setup had time to build: a seed write that rejects cannot leave the fake clock, a held // mutation or a live provider behind for the later tests. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] const rollbackLogLines: string[] = [] let releaseGateWrite: (() => void) | undefined const pendingGateWrite = new Promise((resolve) => { releaseGateWrite = resolve }) let gateWriteObserved: Promise | undefined let deletionObserved: Promise | undefined let originatorSaveObserved: Promise | undefined let gateWriteSettled: Promise | undefined let originatorSaveSettled: Promise | undefined let deletionSettled = 0 let gateWriteRunning = 0 let originatorWriteLanded = 0 let thirdWriteRejected = 0 let armOriginatorSave = 0 try { vi.useFakeTimers() // Defensive: the doubles in this suite can leave console writes pending at worker teardown. for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(provider) const first = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(first) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(second) const third = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(third) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "old-profile-key", id: "old-id", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", id: "keeper-id", } // Seeded through the real view-state writes before any write seam below exists, so a seam can // only ever touch the writes this deletion, its rollback and the injected selection make. await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.contextProxy.setProviderSettings(keeperSettings) // Every view pins the deleted profile and carries its own overlay: an overlay is what keeps the // activation own sibling-overlay snapshot from queueing onto the sibling this cell holds, which // would park the deletion before this view own pin ever moved. const seedView = async (instance: ClineProvider, viewStateId: string) => { await instance.setViewStateId(viewStateId) await instance.saveViewState("currentApiConfigName", "old-profile") await instance.saveViewState("apiConfiguration", deletedSettings) } await seedView(provider, "stable-sidebar-view") await seedView(first, "stable-first-view") await seedView(second, "stable-second-view") await seedView(third, "stable-third-view") const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") cleanups.push(() => instancesSpy.mockRestore()) // The instance registry is environment: the re-pin and the rollback must see exactly these // four views, and no view an earlier test left behind. instancesSpy.mockReturnValue([provider, first, second, third]) // Double assertion: the mock seam declares its own value type, while this seam has to see the raw // key and value pair to fail one write by identity and to count another. ContextProxy assigns // its in-memory cache before the durable attempt, so the map handed to the seam is identity // equal to the cache of the view that issued the write. const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update cleanups.push(() => { storageSeam.update = durableUpdate }) storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } if (third.contextProxy.getValue("viewStates") === value && thirdWriteRejected === 0) { thirdWriteRejected++ return Promise.reject(new Error("sibling re-pin write down")) } // Armed only once the window is open, and counted once, so the count names the injected // selection and not the re-point or the activation write this same proxy issued earlier. if (armOriginatorSave === 1 && provider.contextProxy.getValue("viewStates") === value) { armOriginatorSave = 2 originatorWriteLanded++ } return durableUpdate(key, value) } for (const instance of [provider, first, second, third]) { const postSpy = vi.spyOn(instance, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => postSpy.mockRestore()) } // The rollback logs every leg it could not complete through this one method: spying on it reads // what each path reports without touching the console the doubles already mock. const rollbackLogSpy = vi.spyOn(provider, "log").mockImplementation((line: string) => { rollbackLogLines.push(String(line)) }) cleanups.push(() => rollbackLogSpy.mockRestore()) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A gate this deletion never moved: the manager-gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("restored") vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", ...deletedSettings } : { name: "keeper-profile", ...keeperSettings }, ) // The window: a mutation this sibling started for itself, queued ahead of the re-pin this deletion // awaits on the same queue, and held open while the deleting view finishes a selection. gateWriteObserved = first["enqueueProviderProfileMutation"](async () => { gateWriteRunning++ await pendingGateWrite }) // Observe at once: a mutation can reject while this row still pumps the fake clock, and the finally // settles it through this observer so a rejection cannot skip the clock restore or the disposes. gateWriteSettled = gateWriteObserved.catch(() => {}) const deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) void deletionObserved.then(() => { deletionSettled++ }) // Pump until the re-pin that fails has already failed: the loop below stops at the first tick where // that is true, so the deletion has not returned even though a sibling write is already down. for (let pumped = 0; pumped < 300 && (thirdWriteRejected === 0 || deletionSettled > 0); pumped++) { await vi.advanceTimersByTimeAsync(0) } // P1: the deleting view own pin already names the replacement in both layers, one sibling re-pin // is already down, and the deletion still has not returned - it waits behind the write the // remaining sibling queued for itself, and that queue is the one this view can still write on. expect(gateWriteRunning).toBe(1) expect(thirdWriteRejected).toBe(1) expect(deletionSettled).toBe(0) expect(durablePin("stable-sidebar-view")).toBe("keeper-profile") expect(provider["viewLocalState"].currentApiConfigName).toBe("keeper-profile") // The user commits a selection of the replacement on the deleting view itself, through this view // own mutation queue exactly as a settings save from its webview does. armOriginatorSave = 1 originatorSaveObserved = provider["enqueueProviderProfileMutation"](async () => { await provider["_saveViewLocalStateFromMutation"]({ currentApiConfigName: "keeper-profile", apiConfiguration: keeperSettings, }) }) originatorSaveSettled = originatorSaveObserved.catch(() => {}) for (let pumped = 0; pumped < 300 && originatorWriteLanded === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P2: the selection landed durably on the deleting view while the deletion had not reached its // compensation, and its entry still carries this view own write, not the deletion claim. expect(originatorWriteLanded).toBe(1) expect(deletionSettled).toBe(0) expect(durablePin("stable-sidebar-view")).toBe("keeper-profile") releaseGateWrite!() for (let pumped = 0; pumped < 300 && deletionSettled === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(deletionSettled).toBe(1) await deletionObserved await gateWriteSettled await originatorSaveSettled await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // N1: the completed selection is still what storage holds, which is what a reload reads. A name // comparison cannot carry this decision: the selection re-selected the very name this deletion // had applied, so only the writer claim on the entry tells the two writes apart. expect(durablePin("stable-sidebar-view")).toBe("keeper-profile") // N2: and the buffer agrees with storage: no leg left this view on the deleted profile its entry // carried before the deletion, nor on the deleted profile settings its overlay held. expect(provider["viewLocalState"].currentApiConfigName).toBe("keeper-profile") expect(provider["viewLocalState"].apiConfiguration).toEqual(keeperSettings) // N3: this view own write owns its entry: the claim is this view own write, not the token of a // deletion that had already moved on to its compensation. expect(provider["durableViewPinWriteOwner"]).toBeUndefined() // N4: the views this deletion still owned come back in both layers. The sibling whose own re-pin // write threw never moved its buffer; the two whose re-pins landed are replayed back together // with their stored pins and their own overlays. expect(durablePin("stable-first-view")).toBe("old-profile") expect(first["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(first["viewLocalState"].apiConfiguration).toEqual(deletedSettings) expect(durablePin("stable-second-view")).toBe("old-profile") expect(second["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(durablePin("stable-third-view")).toBe("old-profile") expect(third["viewLocalState"].currentApiConfigName).toBe("old-profile") // N5: the deletion still rejects with the sibling write failure it hit, not with a repair. await expect(deletion).rejects.toThrow("sibling re-pin write down") // N6: nothing is left unreconciled: every view the durable leg rewrote either came back or was // left on the profile its own newer write named. expect(rollbackLogLines.some((line) => line.includes("incomplete view-pin rollback"))).toBe(false) } finally { // Release the held mutation first, then settle the released work under the still-installed fake // clock, then restore the clock, drain the durable write queue and dispose every view the setup // built. Draining before the release would await a queue the held mutation never entered. releaseGateWrite?.() for (const cleanup of cleanups.reverse()) { cleanup() } await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved await gateWriteSettled await originatorSaveSettled vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await disposeBuiltProvidersAndReportCleanupErrors(built) } }) it("keeps a closed editor own selection out of the failed profile deletion rollback", async () => { // Review comment 4749102052: an editor can select the replacement while this deletion still awaits a // sibling re-pin. Its own write moves the pin claim onto itself, and while the view is live the // rollback reads that claim and leaves the entry alone. Close the view inside the same window and the // claim goes with it: the durable entry stays behind, the rollback finds no live owner, falls back to // matching the profile name - the very name this deletion wrote into that entry - and pushes the // deleted profile back into the layer a reload reads, undoing a selection the user had already // completed. This cell pins the outcome where the review puts it, in durable storage, and keeps the // sibling that never selected anything of its own restored, so the fix cannot be to restore nobody. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] let deletion: Promise | undefined let deletionObserved: Promise | undefined let heldRePinEntered = 0 let releaseHeldRePin: (() => void) | undefined // The held sibling re-pin parks on this promise before it reaches the serialized durable write queue, // so the deleting view stays inside the window this review describes while the other editor selects, // commits that selection to storage and closes. Declared outside the protected scope below so its // finally block can still release it when an assertion threw first. const heldRePin = new Promise((resolveHeld) => { releaseHeldRePin = () => { releaseHeldRePin = undefined resolveHeld() } }) try { vi.useFakeTimers() for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(provider) const editor = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(editor) const held = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(held) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "old-profile-key", id: "old-id", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", id: "keeper-id", } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.contextProxy.setProviderSettings(keeperSettings) await provider.setViewStateId("stable-sidebar-view") await provider.saveViewState("currentApiConfigName", "keeper-profile") await provider.saveViewState("apiConfiguration", keeperSettings) await editor.setViewStateId("stable-editor-view") await editor.saveViewState("currentApiConfigName", "old-profile") await held.setViewStateId("stable-held-view") await held.saveViewState("currentApiConfigName", "old-profile") // A third view that was never live in this session: its entry is planted straight into durable // storage, so no write of this session ever claimed its pin and the claim record has nothing to // say about it. The deletion re-points the entry (its view is not live, so nothing is recorded // for it either) and the rollback decides it on the profile name alone. const seededStates = mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > await mockContext.globalState.update("viewStates", { ...seededStates, "stable-legacy-view": { ...seededStates["stable-held-view"], currentApiConfigName: "old-profile", }, }) const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName // The instance registry is environment, and a view that closes leaves it. Review comment // 4749512297: this cell kept a stand-in list and edited that list itself, so it could pass even // if disposal left the editor registered. Nothing here replaces the registry any more - the // rollback below reads the real one, and the editor leaves it by disposing. const liveViews = [provider, editor, held] for (const instance of liveViews) { const postSpy = vi.spyOn(instance, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => postSpy.mockRestore()) } const rollbackLogLines: string[] = [] const logSpy = vi.spyOn(provider, "log").mockImplementation((line: string) => { rollbackLogLines.push(String(line)) }) cleanups.push(() => logSpy.mockRestore()) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("restored") vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", ...deletedSettings } : { name: "keeper-profile", ...keeperSettings }, ) // Hold the last sibling re-pin before it touches durable storage: the deletion stays waiting, and // the re-pin pass has already committed the other editor own re-pin in both layers. const heldSink = held["_saveViewLocalStateFromMutation"].bind(held) held["_saveViewLocalStateFromMutation"] = async () => { heldRePinEntered++ await heldRePin throw new Error("held sibling re-pin write down") } cleanups.push(() => { held["_saveViewLocalStateFromMutation"] = heldSink }) deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) for (let pumped = 0; pumped < 200 && heldRePinEntered === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P1: the deletion is parked on the held sibling re-pin, and the other editor re-pin already // committed - durable storage and that view own buffer both name the replacement. expect(heldRePinEntered).toBe(1) expect(durablePin("stable-editor-view")).toBe("keeper-profile") expect(editor["viewLocalState"].currentApiConfigName).toBe("keeper-profile") // P2: the user of that editor finishes a selection of the very profile this deletion had applied. // The write is its own, so it carries no deletion token and the view owns its pin from here on. await editor.saveViewState("currentApiConfigName", "keeper-profile") expect(durablePin("stable-editor-view")).toBe("keeper-profile") // P3: the editor closes inside the same window. Its entry stays in storage; only the live view - // and with it the record of who wrote that pin - goes away, by disposal, out of the registry the // rollback itself reads (review comment 4749512297). await editor.dispose() expect(ClineProvider.getAllInstances().includes(editor)).toBe(false) releaseHeldRePin?.() for (let pumped = 0; pumped < 200; pumped++) { await vi.advanceTimersByTimeAsync(0) } await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // N1 (review comment 4749102052): the selection the user completed while the deletion waited is // still what durable storage carries for that view. The view is gone, so a rollback that has lost // the ownership record cannot read the choice anywhere else: matching on the profile name here // matches the name this deletion wrote, and the reload would hand that user the deleted profile. expect(durablePin("stable-editor-view")).toBe("keeper-profile") // N2: the sibling that never selected anything of its own is still rolled back: this deletion wrote // that pin, nothing newer moved it, and the fix must not turn into restoring nobody. expect(durablePin("stable-held-view")).toBe("old-profile") // N3: the same deletion, one closed view whose pin no write of this session ever claimed: there // is no record to follow, so the profile-name rule decides it and the pin this deletion moved // there comes back. N1 above and N3 here are the two states the fix has to tell apart - a // recorded absence of claim (a selection the user completed) is not the same fact as no record // at all - and both are read in durable storage, where a reload reads them too. expect(durablePin("stable-legacy-view")).toBe("old-profile") // N4: the deletion rejects with the sibling failure it hit, not with a repair of its own. await expect(deletion).rejects.toThrow("held sibling re-pin write down") // The semantic core, read where it lives: stable-editor-view carries a recorded claim that the // user own selection then cleared - a record whose value is none - while stable-legacy-view // carries the claim this deletion own re-point wrote into it (review comment 4749512310): a // whole-map re-point records the writer on every entry it rewrote, the closed view own // included, so the merge leg no longer has to fall back on the profile name for it. The // compensation follows the cleared record in the first case and this deletion own record in // the second. These reads sit after the behavioral asserts above on purpose: a build that // records nobody, or records a writer that never wrote, fails first on the durable outcome // they are meant to explain. const pinClaims = ClineProvider["durableViewPinWriteOwnersByViewId"] // The record-layer assertions below follow the new requirement from review // 4750462846 - capture the prior claim with each re-point and restore it with // the pin - so a legacy view whose prior claim was never recorded goes back to // no record at all. The pin-layer assertions above this line are unchanged. expect(pinClaims.has("stable-editor-view")).toBe(true) expect(pinClaims.get("stable-editor-view")).toBeUndefined() expect(pinClaims.has("stable-legacy-view")).toBe(false) expect(pinClaims.get("stable-legacy-view")).toBeUndefined() } finally { releaseHeldRePin?.() try { await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved } finally { for (const cleanup of cleanups.reverse()) { cleanup() } vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await disposeBuiltProvidersAndReportCleanupErrors(built) } } }) it("restores the first overlapping deletion pin claim together with the closed view pin", async () => { const first = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const closed = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const claims = ClineProvider["durableViewPinWriteOwnersByViewId"] const pinOf = (viewId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewId]?.currentApiConfigName const originalProfile: ProviderSettingsEntry = { name: "overlap-original-profile", id: "overlap-original-id", apiProvider: providerIdentifiers.anthropic, } const replacementProfile: ProviderSettingsEntry = { name: "overlap-replacement-profile", id: "overlap-replacement-id", apiProvider: providerIdentifiers.anthropic, } const keeperProfile: ProviderSettingsEntry = { name: "overlap-keeper-profile", id: "overlap-keeper-id", apiProvider: providerIdentifiers.anthropic, } const manager = first.providerSettingsManager for (const entry of [originalProfile, replacementProfile, keeperProfile]) { await manager.saveConfig(entry.name, { apiProvider: providerIdentifiers.anthropic, apiKey: "overlap-" + entry.id + "-key", id: entry.id, }) } await manager.activateProfile({ name: keeperProfile.name }) const seedSurfaces = async (instance: ClineProvider) => { await instance.contextProxy.setValue("listApiConfigMeta", [ originalProfile, replacementProfile, keeperProfile, ]) await instance.contextProxy.setValue("currentApiConfigName", replacementProfile.name) } // Each provider reads these surfaces through its own proxy, which caches what globalState // held when it loaded: a proxy that never saw an active profile reports no profile to // activate and refuses the deletion instead of reaching the re-point. await seedSurfaces(first) await seedSurfaces(closed) await closed.setViewStateId("overlap-closed-view") await closed.saveViewState("currentApiConfigName", originalProfile.name) const priorClaim = claims.get("overlap-closed-view") const priorClaimWasRecorded = claims.has("overlap-closed-view") await closed.dispose() // Review comment 4753606226: what this row needs released, drained, restored and disposed is // tracked as it is created, and the finally below does all of it, so an assertion failing in // the middle cannot leave the first deletion waiting on an activation gate that nobody is // left to open while the spies stay mocked and the providers stay alive. const built: ClineProvider[] = [first, closed] const cleanups: Array<() => void> = [] const startedDeletions: Array> = [] const firstPost = vi.spyOn(first, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => firstPost.mockRestore()) let releaseFirstActivation: () => void = () => {} const firstHold = new Promise((resolve) => { releaseFirstActivation = resolve }) const firstActivation = vi .spyOn(first.providerSettingsManager, "activateProfile") .mockImplementation(async () => { await firstHold throw new Error("overlap first activation down") }) cleanups.push(() => firstActivation.mockRestore()) const firstDeletion = first.deleteProviderProfile(originalProfile) startedDeletions.push(firstDeletion) try { // The second deletion starts while the first waits for its activation step, and only // after the first re-point landed: its view now names the replacement the second // deletion removes, which is the overlap the reviewer describes. for ( let attempt = 0; attempt < 50 && pinOf("overlap-closed-view") !== replacementProfile.name; attempt++ ) { await new Promise((resolve) => setImmediate(resolve)) } expect(pinOf("overlap-closed-view")).toBe(replacementProfile.name) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await seedSurfaces(second) built.push(second) const secondPost = vi.spyOn(second, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => secondPost.mockRestore()) const secondActivation = vi .spyOn(second.providerSettingsManager, "activateProfile") .mockRejectedValue(new Error("overlap second activation down")) cleanups.push(() => secondActivation.mockRestore()) const secondDeletion = second.deleteProviderProfile(replacementProfile) startedDeletions.push(secondDeletion) // Both re-points landed before either deletion failed, so the second re-point replaced // the first deletion claim on the closed view - the overwrite the reviewer points at. await expect(secondDeletion).rejects.toThrow("overlap second activation down") await ClineProvider["persistedViewStateWriteQueue"] expect(pinOf("overlap-closed-view")).toBe(replacementProfile.name) expect(claims.get("overlap-closed-view")).not.toBe(priorClaim) releaseFirstActivation() await expect(firstDeletion).rejects.toThrow("overlap first activation down") await ClineProvider["persistedViewStateWriteQueue"] // The first rollback puts the pin it wrote back together with the claim its own re-point // replaced on the id-keyed record - not the token the second deletion left behind - so // the closed view ends where it stood before either deletion, and the record describes // the writer that pin actually had. expect(pinOf("overlap-closed-view")).toBe(originalProfile.name) expect(claims.has("overlap-closed-view")).toBe(priorClaimWasRecorded) expect(claims.get("overlap-closed-view")).toBe(priorClaim) } finally { releaseFirstActivation() // Drain every deletion this row started first: a deletion whose gate is opened only here // still rejects and still runs its rollback inside this row, so the mutation resumes while // the row can still see it instead of after the row had ended. await Promise.all(startedDeletions.map((deletion) => deletion.catch(() => undefined))) await ClineProvider["persistedViewStateWriteQueue"] for (const cleanup of cleanups.reverse()) { cleanup() } await disposeBuiltProvidersAndReportCleanupErrors(built) } }) it("leaves a newer live selection alone while restoring the overlapping deletion pin", async () => { const first = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const closed = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const live = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Review comment 4753606237: the control view named above, built here so its pin, its claim and its // disposal follow the same bookkeeping as the two views the row already had. const silentOpen = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const claims = ClineProvider["durableViewPinWriteOwnersByViewId"] const pinOf = (viewId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewId]?.currentApiConfigName const originalProfile: ProviderSettingsEntry = { name: "overlap-original-profile", id: "overlap-original-id", apiProvider: providerIdentifiers.anthropic, } const replacementProfile: ProviderSettingsEntry = { name: "overlap-replacement-profile", id: "overlap-replacement-id", apiProvider: providerIdentifiers.anthropic, } const keeperProfile: ProviderSettingsEntry = { name: "overlap-keeper-profile", id: "overlap-keeper-id", apiProvider: providerIdentifiers.anthropic, } const manager = first.providerSettingsManager for (const entry of [originalProfile, replacementProfile, keeperProfile]) { await manager.saveConfig(entry.name, { apiProvider: providerIdentifiers.anthropic, apiKey: "overlap-" + entry.id + "-key", id: entry.id, }) } await manager.activateProfile({ name: keeperProfile.name }) const seedSurfaces = async (instance: ClineProvider) => { await instance.contextProxy.setValue("listApiConfigMeta", [ originalProfile, replacementProfile, keeperProfile, ]) await instance.contextProxy.setValue("currentApiConfigName", replacementProfile.name) } // Each provider reads these surfaces through its own proxy, which caches what globalState // held when it loaded: a proxy that never saw an active profile reports no profile to // activate and refuses the deletion instead of reaching the re-point. await seedSurfaces(first) await seedSurfaces(closed) await seedSurfaces(live) await seedSurfaces(silentOpen) await live.setViewStateId("overlap-live-view") await live.saveViewState("currentApiConfigName", originalProfile.name) await silentOpen.setViewStateId("overlap-silent-open-view") await silentOpen.saveViewState("currentApiConfigName", originalProfile.name) // Review comment 4753606237 control view: an open editor that pins the deleted profile and never // selects anything after that, so the only writer its pin ever had is its own selection and then // whatever the deletions stamped on it. await closed.setViewStateId("overlap-closed-view") await closed.saveViewState("currentApiConfigName", originalProfile.name) const priorClaim = claims.get("overlap-closed-view") const priorClaimWasRecorded = claims.has("overlap-closed-view") await closed.dispose() // Review comment 4753606226: what this row needs released, drained, restored and disposed is // tracked as it is created, and the finally below does all of it, so an assertion failing in // the middle cannot leave the first deletion waiting on an activation gate that nobody is // left to open while the spies stay mocked and the providers stay alive. const built: ClineProvider[] = [first, closed, live, silentOpen] const cleanups: Array<() => void> = [] const startedDeletions: Array> = [] const firstPost = vi.spyOn(first, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => firstPost.mockRestore()) let releaseFirstActivation: () => void = () => {} const firstHold = new Promise((resolve) => { releaseFirstActivation = resolve }) const firstActivation = vi .spyOn(first.providerSettingsManager, "activateProfile") .mockImplementation(async () => { await firstHold throw new Error("overlap first activation down") }) cleanups.push(() => firstActivation.mockRestore()) const firstDeletion = first.deleteProviderProfile(originalProfile) startedDeletions.push(firstDeletion) try { // The second deletion starts while the first waits for its activation step, and only // after the first re-point landed: its view now names the replacement the second // deletion removes, which is the overlap the reviewer describes. for ( let attempt = 0; attempt < 50 && pinOf("overlap-closed-view") !== replacementProfile.name; attempt++ ) { await new Promise((resolve) => setImmediate(resolve)) } expect(pinOf("overlap-closed-view")).toBe(replacementProfile.name) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await seedSurfaces(second) built.push(second) const secondPost = vi.spyOn(second, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => secondPost.mockRestore()) const secondActivation = vi .spyOn(second.providerSettingsManager, "activateProfile") .mockRejectedValue(new Error("overlap second activation down")) cleanups.push(() => secondActivation.mockRestore()) const secondDeletion = second.deleteProviderProfile(replacementProfile) startedDeletions.push(secondDeletion) // Both re-points landed before either deletion failed, so the second re-point replaced // the first deletion claim on the closed view - the overwrite the reviewer points at. await expect(secondDeletion).rejects.toThrow("overlap second activation down") await ClineProvider["persistedViewStateWriteQueue"] expect(pinOf("overlap-closed-view")).toBe(replacementProfile.name) expect(claims.get("overlap-closed-view")).not.toBe(priorClaim) // Review comment 4753606237: the live view selects for itself after the second rollback, and it // selects the very name the first deletion had just written into this pin. The name therefore // cannot say whose write it is - only the writer token can - so this is the selection the // ownership guard has to stop, not one a name comparison would have skipped on its own. await live.saveViewState("currentApiConfigName", replacementProfile.name) releaseFirstActivation() await expect(firstDeletion).rejects.toThrow("overlap first activation down") await ClineProvider["persistedViewStateWriteQueue"] expect(pinOf("overlap-live-view")).toBe(replacementProfile.name) // Direct private access: the same view own buffer behind that pin, so a rollback that skipped only // the durable entry cannot hide behind the stored name. expect(live["viewLocalState"].currentApiConfigName).toBe(replacementProfile.name) // The first rollback puts the pin it wrote back together with the claim its own re-point // replaced on the id-keyed record - not the token the second deletion left behind - so // the closed view ends where it stood before either deletion, and the record describes // the writer that pin actually had. expect(pinOf("overlap-closed-view")).toBe(originalProfile.name) expect(claims.has("overlap-closed-view")).toBe(priorClaimWasRecorded) expect(claims.get("overlap-closed-view")).toBe(priorClaim) // Review comment 4753606237 control: the open editor that never selected for itself comes back too, // stored entry and buffer both. A rollback that skipped every open editor - the shape the row // describes - fails here even though it passes the live check above. expect(pinOf("overlap-silent-open-view")).toBe(originalProfile.name) // Direct private access: the buffer behind that pin, so the live replay leg is measured and not // only the stored name. expect(silentOpen["viewLocalState"].currentApiConfigName).toBe(originalProfile.name) } finally { releaseFirstActivation() // Drain every deletion this row started first: a deletion whose gate is opened only here // still rejects and still runs its rollback inside this row, so the mutation resumes while // the row can still see it instead of after the row had ended. await Promise.all(startedDeletions.map((deletion) => deletion.catch(() => undefined))) await ClineProvider["persistedViewStateWriteQueue"] for (const cleanup of cleanups.reverse()) { cleanup() } await disposeBuiltProvidersAndReportCleanupErrors(built) } }) it("rolls back a closed view pin this deletion re-pointed instead of leaving it on the replacement", async () => { // Review comment 4749512310: a whole-map re-point hands the pin claim to the writer that // committed it, but only for a view that is still alive - the record is copied onto the live // instance, and the record keyed by the persisted view id is left to whatever that view own // last write said. A view that closed inside the deletion window therefore keeps the claim its // own selection left, which for an ordinary selection is the cleared value, and the durable // merge leg reads that as "somebody else wrote this pin" and skips the entry. The user own // consequence: after a failed deletion a closed view stays pinned to the replacement in the // layer a reload reads, although this deletion was the last writer on that entry and the // rollback is undoing its own change. This cell closes a view that pinned the deleted profile, // lets the deletion re-point it, fails a sibling re-pin so the deletion compensates, and reads // the closed entry back out of storage. Profiles, ids and error text are unique to this cell // because the doubles in this suite keep state between cells. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] let deletion: Promise | undefined let deletionObserved: Promise | undefined let triggerRejected = 0 let releaseHeldWrite: (() => void) | undefined const goneView = "closedfix-gone-view" const heldView = "closedfix-held-view" const heldWriteGate = new Promise((resolveGate) => { releaseHeldWrite = () => { releaseHeldWrite = undefined resolveGate() } }) const pinOf = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName const claims = ClineProvider["durableViewPinWriteOwnersByViewId"] const oldProfile: ProviderSettingsEntry = { name: "closedfix-old-profile", id: "closedfix-old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "closedfix-keeper-profile", id: "closedfix-keeper-id", apiProvider: providerIdentifiers.anthropic, } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "closedfix-keeper-key", id: "closedfix-keeper-id", } try { vi.useFakeTimers() for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const held = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const gone = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(provider, held, gone) await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", keeperProfile.name) await provider.contextProxy.setProviderSettings(keeperSettings) await provider.setViewStateId("closedfix-sidebar-view") await provider.saveViewState("currentApiConfigName", keeperProfile.name) await provider.saveViewState("apiConfiguration", keeperSettings) await held.setViewStateId(heldView) await held.saveViewState("currentApiConfigName", oldProfile.name) await gone.setViewStateId(goneView) await gone.saveViewState("currentApiConfigName", oldProfile.name) // The view this cell is about closes for good before the deletion starts: its entry stays in // storage, the instance leaves the registry the rollback reads, and the claim left on that // entry is the one its own selection recorded. await gone.dispose() built.splice(built.indexOf(gone), 1) expect(ClineProvider.getAllInstances().includes(gone)).toBe(false) expect(pinOf(goneView)).toBe("closedfix-old-profile") const claimBeforeDeletion = claims.get(goneView) const claimKeyBeforeDeletion = claims.has(goneView) const proxy = held.contextProxy const issueToStorage = proxy.setValue.bind(proxy) const writeIssuer = new WeakMap() // Double assertion: setValue is generic over the state key and the wrapper only ever forwards // one key/value pair through it, so the wrapper is re-typed to that pair shape. const setValueSpy = vi.spyOn(proxy, "setValue").mockImplementation(((key: string, value: unknown) => { if (key === "viewStates" && value && typeof value === "object") { writeIssuer.set(value as object, "held-sibling") } return issueToStorage(key as never, value as never) }) as typeof proxy.setValue) cleanups.push(() => setValueSpy.mockRestore()) const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update cleanups.push(() => { storageSeam.update = durableUpdate }) storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } const states = value as Record const heldPin = states[heldView]?.currentApiConfigName if ( heldPin === keeperProfile.name && writeIssuer.get(value as object) === "held-sibling" && triggerRejected === 0 ) { // The held sibling own re-pin write, parked and then rejected: that rejection is what opens // the compensation whose rollback this cell reads. triggerRejected++ return heldWriteGate.then(() => Promise.reject(new Error("closedfix held re-pin write down"))) } return durableUpdate(key, value) } for (const instance of [provider, held]) { const postSpy = vi.spyOn(instance, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => postSpy.mockRestore()) } const manager = provider.providerSettingsManager // Reviewer 4750462837: the profile store here is the real ProviderSettingsManager; only // the secret storage is mocked (the mock extension context backs secrets with a plain // object), so the delete, the restore and the ids all come from the manager itself. // Both profiles are seeded through saveConfig and the keeper is activated through the // manager, so the selection the deletion reads is the stored one. await manager.saveConfig(oldProfile.name, { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "closedfix-old-router-key", id: "closedfix-old-id", }) await manager.saveConfig(keeperProfile.name, keeperSettings) await manager.activateProfile({ name: keeperProfile.name }) deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) for (let pumped = 0; pumped < 200 && triggerRejected === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P1: the re-point has landed for both views and the held sibling own write is still in flight, // so the writer this deletion used is readable on a view that is live. The closed entry was // re-pointed by that very same write. expect(triggerRejected).toBe(1) expect(pinOf(heldView)).toBe("closedfix-keeper-profile") expect(pinOf(goneView)).toBe("closedfix-keeper-profile") const deletionToken = held["durableViewPinWriteOwner"] expect(deletionToken).toBeDefined() expect(claimBeforeDeletion).not.toBe(deletionToken) // While the held write is pending the real store must already be without the deleted // record: the mocked deleteConfig used to report success without removing anything, // which is what this anchor points at. await expect(manager.hasConfig(oldProfile.name)).resolves.toBe(false) await expect( manager.listConfig().then((entries) => entries.map((entry) => entry.name)), ).resolves.not.toContain(oldProfile.name) releaseHeldWrite?.() for (let pumped = 0; pumped < 200; pumped++) { await vi.advanceTimersByTimeAsync(0) } await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // N1: the rollback put the deleted profile back for the live sibling that never selected anything // of its own, so the repair is not a rollback that restores nobody. expect(pinOf(heldView)).toBe("closedfix-old-profile") // N2: the closed view own entry comes back too. Today it stays on the replacement: the re-point // recorded this deletion on no record that survives the view, so the merge leg reads the cleared // claim its own selection left and calls a pin this deletion moved somebody else own. expect(pinOf(goneView)).toBe("closedfix-old-profile") // N3: read where the review puts it - the record on that entry goes back to what it // was before this deletion re-pointed it. The closed view own selection write // recorded an undefined claim, so the key is present here with an undefined // value; presence and value are asserted apart because a claim restored as an // absent key is a different state from a claim recorded as undefined. expect(claims.has(goneView)).toBe(claimKeyBeforeDeletion) expect(claims.get(goneView)).toBe(claimBeforeDeletion) // N4: the deletion rejects with the failure that opened the compensation. await expect(deletion).rejects.toThrow("closedfix held re-pin write down") // Reviewer 4750462837 asked what the store holds once the rollback settles: the // restored record comes back under its original id, not the fresh id a mocked // saveConfig used to invent. Measured on the real store the restored record carries // name, id and provider but not the apiKey the deletion read - the credential gap // is reported separately rather than pinned as intended behavior. await expect(manager.getProfile({ id: "closedfix-old-id" })).resolves.toMatchObject({ name: "closedfix-old-profile", id: "closedfix-old-id", openRouterApiKey: "closedfix-old-router-key", }) } finally { releaseHeldWrite?.() try { await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved } finally { for (const cleanup of cleanups.reverse()) { cleanup() } vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await disposeBuiltProvidersAndReportCleanupErrors(built) } } }) it("restores a rolled back pin from the id-keyed claim over the open view own token", async () => { // Review comment 4753606247: the durable merge leg asked the open view own field who wrote a pin, // but that field is the record for replaying a pin into an open view, not the record for deciding // what storage should hold. Two deletions on one stored pin: the second rollback restores the pin the // second deletion moved and puts the first deletion claim back on the id-keyed record, while the open // view own field keeps the second deletion token. The first rollback then skipped a pin its own record // called its own, so the editor - whose live buffer never moved, because both activations failed // before any live re-pin step - stayed pinned to the middle replacement in the layer a reload reads: // what was on screen still served the original profile while reopening selected the replacement. // This cell keeps the editor open, fails the second deletion first, and reads the stored pin and the // claim back. Profiles, view ids and error text are unique to this cell because the doubles in this // suite keep state between cells. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] let firstDeletion: Promise | undefined let secondDeletion: Promise | undefined let releaseFirstActivation: () => void = () => {} const firstHold = new Promise((resolve) => { releaseFirstActivation = resolve }) const editorView = "claimopen-editorView-view" const pinOf = (viewId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewId]?.currentApiConfigName const claims = ClineProvider["durableViewPinWriteOwnersByViewId"] const deferred = ClineProvider["deferredViewPinRollbacksByViewId"] const originalProfile: ProviderSettingsEntry = { name: "claimopen-original-profile", id: "claimopen-original-id", apiProvider: providerIdentifiers.anthropic, } const replacementProfile: ProviderSettingsEntry = { name: "claimopen-replacement-profile", id: "claimopen-replacement-id", apiProvider: providerIdentifiers.anthropic, } const thirdProfile: ProviderSettingsEntry = { name: "claimopen-third-profile", id: "claimopen-third-id", apiProvider: providerIdentifiers.anthropic, } const keeperProfile: ProviderSettingsEntry = { name: "claimopen-keeper-profile", id: "claimopen-keeper-id", apiProvider: providerIdentifiers.anthropic, } try { for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const first = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const editor = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(first, second, editor) const manager = first.providerSettingsManager for (const entry of [originalProfile, replacementProfile, thirdProfile, keeperProfile]) { await manager.saveConfig(entry.name, { apiProvider: providerIdentifiers.anthropic, apiKey: "claimopen-" + entry.id + "-key", id: entry.id, }) } await manager.activateProfile({ name: replacementProfile.name }) const seedSurfaces = async (instance: ClineProvider) => { await instance.contextProxy.setValue("listApiConfigMeta", [ thirdProfile, originalProfile, replacementProfile, keeperProfile, ]) await instance.contextProxy.setValue("currentApiConfigName", replacementProfile.name) } await seedSurfaces(first) await seedSurfaces(second) await seedSurfaces(editor) await editor.setViewStateId(editorView) await editor.saveViewState("currentApiConfigName", originalProfile.name) const priorClaimWasRecorded = claims.has(editorView) const priorClaim = claims.get(editorView) const firstActivation = vi.spyOn(first.providerSettingsManager, "activateProfile") const secondActivation = vi.spyOn(second.providerSettingsManager, "activateProfile") cleanups.push(() => { firstActivation.mockRestore() secondActivation.mockRestore() }) firstActivation.mockImplementation(async () => { await firstHold throw new Error("claimopen first activation down") }) secondActivation.mockRejectedValue(new Error("claimopen second activation down")) firstDeletion = first.deleteProviderProfile(originalProfile) for (let attempt = 0; attempt < 50 && pinOf(editorView) !== replacementProfile.name; attempt++) { await new Promise((resolve) => setImmediate(resolve)) } expect(pinOf(editorView)).toBe(replacementProfile.name) secondDeletion = second.deleteProviderProfile(replacementProfile) await expect(secondDeletion).rejects.toThrow("claimopen second activation down") await ClineProvider["persistedViewStateWriteQueue"] // The second rollback landed: the pin sits on the middle replacement and the claim the first // deletion wrote is back on the record, while the open view own field still names the second // deletion token. expect(pinOf(editorView)).toBe(replacementProfile.name) releaseFirstActivation() await expect(firstDeletion).rejects.toThrow("claimopen first activation down") await ClineProvider["persistedViewStateWriteQueue"] expect(editor["viewLocalState"].currentApiConfigName).toBe(originalProfile.name) expect(pinOf(editorView)).toBe(originalProfile.name) expect(claims.has(editorView)).toBe(priorClaimWasRecorded) expect(claims.get(editorView)).toBe(priorClaim) expect(deferred.has(editorView)).toBe(false) } finally { releaseFirstActivation() try { await firstDeletion?.catch(() => {}) await secondDeletion?.catch(() => {}) await ClineProvider["persistedViewStateWriteQueue"] } finally { for (const cleanup of cleanups.reverse()) { cleanup() } await disposeBuiltProvidersAndReportCleanupErrors(built) } } }) it("unwinds a pin past the deletion that blocked it once that deletion rolls back", async () => { // Review comment 4753606259 (and its TLA model over the same restore legs): a deletion that found its // re-pointed name gone gave up for good, so when a later deletion restored the pin to the middle // profile the earlier failure stayed uncompensated. Both deletions failed here, yet the stored pin // still named the profile the second deletion re-pointed it to, so reopening the closed view selected // that profile instead of the one it pinned before either deletion. A second view in the same write // group selects a profile of its own while the first deletion is still in flight, because the reviewer // asks that any newer user selection survive the unwind: that view owes nothing and has to stay where // its user left it. Profiles, view ids and error text are unique to this cell because the doubles in // this suite keep state between cells. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] let firstDeletion: Promise | undefined let secondDeletion: Promise | undefined let releaseFirstActivation: () => void = () => {} const firstHold = new Promise((resolve) => { releaseFirstActivation = resolve }) let releaseSecondActivation: () => void = () => {} const secondHold = new Promise((resolve) => { releaseSecondActivation = resolve }) const goneView = "chainclosed-goneView-view" const chosenView = "chainclosed-chosenView-view" const pinOf = (viewId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewId]?.currentApiConfigName const claims = ClineProvider["durableViewPinWriteOwnersByViewId"] const deferred = ClineProvider["deferredViewPinRollbacksByViewId"] const originalProfile: ProviderSettingsEntry = { name: "chainclosed-original-profile", id: "chainclosed-original-id", apiProvider: providerIdentifiers.anthropic, } const replacementProfile: ProviderSettingsEntry = { name: "chainclosed-replacement-profile", id: "chainclosed-replacement-id", apiProvider: providerIdentifiers.anthropic, } const thirdProfile: ProviderSettingsEntry = { name: "chainclosed-third-profile", id: "chainclosed-third-id", apiProvider: providerIdentifiers.anthropic, } const keeperProfile: ProviderSettingsEntry = { name: "chainclosed-keeper-profile", id: "chainclosed-keeper-id", apiProvider: providerIdentifiers.anthropic, } try { for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const first = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const gone = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const chosen = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(first, second, gone, chosen) const manager = first.providerSettingsManager for (const entry of [originalProfile, replacementProfile, thirdProfile, keeperProfile]) { await manager.saveConfig(entry.name, { apiProvider: providerIdentifiers.anthropic, apiKey: "chainclosed-" + entry.id + "-key", id: entry.id, }) } await manager.activateProfile({ name: replacementProfile.name }) const seedSurfaces = async (instance: ClineProvider) => { await instance.contextProxy.setValue("listApiConfigMeta", [ thirdProfile, originalProfile, replacementProfile, keeperProfile, ]) await instance.contextProxy.setValue("currentApiConfigName", replacementProfile.name) } await seedSurfaces(first) await seedSurfaces(second) await seedSurfaces(gone) await seedSurfaces(chosen) await gone.setViewStateId(goneView) await gone.saveViewState("currentApiConfigName", originalProfile.name) await chosen.setViewStateId(chosenView) await chosen.saveViewState("currentApiConfigName", originalProfile.name) const priorClaimWasRecorded = claims.has(goneView) const priorClaim = claims.get(goneView) await gone.dispose() const firstActivation = vi.spyOn(first.providerSettingsManager, "activateProfile") const secondActivation = vi.spyOn(second.providerSettingsManager, "activateProfile") cleanups.push(() => { firstActivation.mockRestore() secondActivation.mockRestore() }) firstActivation.mockImplementation(async () => { await firstHold throw new Error("chainclosed first activation down") }) secondActivation.mockImplementation(async () => { await secondHold throw new Error("chainclosed second activation down") }) firstDeletion = first.deleteProviderProfile(originalProfile) for (let attempt = 0; attempt < 50 && pinOf(goneView) !== replacementProfile.name; attempt++) { await new Promise((resolve) => setImmediate(resolve)) } expect(pinOf(goneView)).toBe(replacementProfile.name) secondDeletion = second.deleteProviderProfile(replacementProfile) for (let attempt = 0; attempt < 50 && pinOf(goneView) !== thirdProfile.name; attempt++) { await new Promise((resolve) => setImmediate(resolve)) } expect(pinOf(goneView)).toBe(thirdProfile.name) // A newer selection of its own while both deletions are in flight: this view is nobody else deferred // unwind, and the rollback below has to leave it where its user left it. await chosen.saveViewState("currentApiConfigName", keeperProfile.name) releaseFirstActivation() await expect(firstDeletion).rejects.toThrow("chainclosed first activation down") await ClineProvider["persistedViewStateWriteQueue"] releaseSecondActivation() await expect(secondDeletion).rejects.toThrow("chainclosed second activation down") await ClineProvider["persistedViewStateWriteQueue"] expect(pinOf(goneView)).toBe(originalProfile.name) expect(claims.has(goneView)).toBe(priorClaimWasRecorded) expect(claims.get(goneView)).toBe(priorClaim) expect(pinOf(chosenView)).toBe(keeperProfile.name) expect(deferred.has(goneView)).toBe(false) expect(deferred.has(chosenView)).toBe(false) } finally { releaseFirstActivation() releaseSecondActivation() try { await firstDeletion?.catch(() => {}) await secondDeletion?.catch(() => {}) await ClineProvider["persistedViewStateWriteQueue"] } finally { for (const cleanup of cleanups.reverse()) { cleanup() } await disposeBuiltProvidersAndReportCleanupErrors(built) } } }) it("drops a deferred pin rollback once a newer writer claims the pin", async () => { // Review comment 4753606259 asks that retained rollback state keep any newer user selection, and an // obligation that outlives the deletion it waited on is a newer selection a later rollback would still // undo. The blocking deletion here succeeds, so the pin stays on its replacement and the earlier // failure owes the pin it moved; the open view then selects a profile of its own. The obligation has // to go with the claim it waited on, so the view ends where its user left it and nothing is left for a // later rollback to rewrite. Profiles, view ids and error text are unique to this cell because the // doubles in this suite keep state between cells. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] let firstDeletion: Promise | undefined let secondDeletion: Promise | undefined let releaseFirstActivation: () => void = () => {} const firstHold = new Promise((resolve) => { releaseFirstActivation = resolve }) const staleView = "chainstale-staleView-view" const pinOf = (viewId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewId]?.currentApiConfigName const claims = ClineProvider["durableViewPinWriteOwnersByViewId"] const deferred = ClineProvider["deferredViewPinRollbacksByViewId"] const originalProfile: ProviderSettingsEntry = { name: "chainstale-original-profile", id: "chainstale-original-id", apiProvider: providerIdentifiers.anthropic, } const replacementProfile: ProviderSettingsEntry = { name: "chainstale-replacement-profile", id: "chainstale-replacement-id", apiProvider: providerIdentifiers.anthropic, } const thirdProfile: ProviderSettingsEntry = { name: "chainstale-third-profile", id: "chainstale-third-id", apiProvider: providerIdentifiers.anthropic, } const keeperProfile: ProviderSettingsEntry = { name: "chainstale-keeper-profile", id: "chainstale-keeper-id", apiProvider: providerIdentifiers.anthropic, } try { for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const first = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const pinned = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(first, second, pinned) const manager = first.providerSettingsManager for (const entry of [originalProfile, replacementProfile, thirdProfile, keeperProfile]) { await manager.saveConfig(entry.name, { apiProvider: providerIdentifiers.anthropic, apiKey: "chainstale-" + entry.id + "-key", id: entry.id, }) } await manager.activateProfile({ name: replacementProfile.name }) const seedSurfaces = async (instance: ClineProvider) => { await instance.contextProxy.setValue("listApiConfigMeta", [ thirdProfile, originalProfile, replacementProfile, keeperProfile, ]) await instance.contextProxy.setValue("currentApiConfigName", replacementProfile.name) } await seedSurfaces(first) await seedSurfaces(second) await seedSurfaces(pinned) await pinned.setViewStateId(staleView) await pinned.saveViewState("currentApiConfigName", originalProfile.name) const firstActivation = vi.spyOn(first.providerSettingsManager, "activateProfile") cleanups.push(() => { firstActivation.mockRestore() }) firstActivation.mockImplementation(async () => { await firstHold throw new Error("chainstale first activation down") }) firstDeletion = first.deleteProviderProfile(originalProfile) for (let attempt = 0; attempt < 50 && pinOf(staleView) !== replacementProfile.name; attempt++) { await new Promise((resolve) => setImmediate(resolve)) } expect(pinOf(staleView)).toBe(replacementProfile.name) secondDeletion = second.deleteProviderProfile(replacementProfile) // The blocking deletion succeeds this time through the real manager activation, so the pin // lands on its replacement and the claim that activation stamped stays there. await secondDeletion await ClineProvider["persistedViewStateWriteQueue"] expect(pinOf(staleView)).toBe(thirdProfile.name) releaseFirstActivation() await expect(firstDeletion).rejects.toThrow("chainstale first activation down") await ClineProvider["persistedViewStateWriteQueue"] expect(deferred.has(staleView)).toBe(true) expect(deferred.get(staleView)?.entry?.currentApiConfigName).toBe(originalProfile.name) expect(deferred.get(staleView)?.hadPriorClaim).toBe(true) // A newer selection of its own now takes the pin: the obligation that waited on the succeeded // deletion has to go with the claim it waited on. await pinned.saveViewState("currentApiConfigName", keeperProfile.name) expect(pinOf(staleView)).toBe(keeperProfile.name) expect(claims.has(staleView)).toBe(true) expect(deferred.has(staleView)).toBe(false) } finally { try { await firstDeletion?.catch(() => {}) await secondDeletion?.catch(() => {}) await ClineProvider["persistedViewStateWriteQueue"] } finally { for (const cleanup of cleanups.reverse()) { cleanup() } await disposeBuiltProvidersAndReportCleanupErrors(built) } } }) it("keeps the pin claim whose durable entry is still stored when the claim bound is crossed", async () => { // Review comment 4749512304: the pin claims keyed by the persisted view id are dropped oldest // inserted first once the record passes the bound the durable map is kept to, so the claim that // goes can be one that still describes a pin in storage while the claims that stay describe // entries no reload will ever read. A closed view has no other record, so losing that claim puts // it back under the profile-name rule the record exists to replace. This cell fills the record to // the bound with real durable pin writes, leaves exactly one of those entries in storage - the // one the oldest claim describes - and crosses the bound with one more write. The durable map is // set directly here, so nothing this cell asserts depends on how the viewStates pruning rule // keeps entries: the stored content is written out in full below. The claims are ordinary // selections, whose recorded value is the cleared one, so what this cell pins is which record // survives the bound. Profile and view ids are unique to this cell. const maxClaims = ClineProvider["MAX_PERSISTED_VIEW_STATES"] const ledger = ClineProvider["durableViewPinWriteOwnersByViewId"] const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] // The record is module-level and this file shares it between cells: snapshot it and put it back // exactly, so filling it past the bound here cannot decide what a later cell reads. const ledgerBefore = new Map(ledger) cleanups.push(() => { ledger.clear() for (const [viewId, owner] of ledgerBefore) { ledger.set(viewId, owner) } }) try { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(provider) await provider.contextProxy.setValue("listApiConfigMeta", [ { name: "claim-keeper-profile", id: "claim-keeper-id", apiProvider: providerIdentifiers.anthropic }, ]) await provider.setViewStateId("claim-home-view") const claimIds = Array.from({ length: maxClaims }, (_unused, index) => `claim-view-${index}`) const guardedView = claimIds[0] // Each claim is a real durable pin write by a real view: the view moves to the id, saves the // profile, and the write records the claim under that id, oldest claim first. for (const viewId of claimIds) { await provider.setViewStateId(viewId) await provider.saveViewState("currentApiConfigName", "claim-keeper-profile") } expect(ledger.size).toBe(maxClaims) // Exactly one stored entry is left, and it is the one the oldest claim describes. await provider.contextProxy.setValue("viewStates", { [guardedView]: { currentApiConfigName: "claim-keeper-profile", updatedAt: 1700000000000, }, }) // Crossing the bound with one more claim: under an oldest-first rule the record that goes is the // guarded one - the only claim still describing a pin a reload will read - while every claim // that describes a removed entry stays. await provider.setViewStateId("claim-newest-view") await provider.saveViewState("currentApiConfigName", "claim-keeper-profile") // N1: the claim whose durable entry is still in the stored map survives the bound. expect(ledger.has(guardedView)).toBe(true) // N2: the bound is still honored, and what left the record is a claim whose entry is gone. expect(ledger.size).toBeLessThanOrEqual(maxClaims) expect(ledger.has("claim-newest-view")).toBe(true) const staleClaimsLeft = [...ledger.keys()].filter( (viewId) => viewId.startsWith("claim-view-") && viewId !== guardedView, ).length expect(staleClaimsLeft).toBe(maxClaims - 2) } finally { for (const cleanup of cleanups.reverse()) { cleanup() } await ClineProvider["persistedViewStateWriteQueue"] await disposeBuiltProvidersAndReportCleanupErrors(built) } }) it("restores the secrets-backed profile record through the real manager when a sibling re-pin fails", async () => { // Review comment 4749102045: the deletion cells around this one replace the manager own record // operations with spies - deleteConfig, saveConfig, getProfile - so a build that skipped either // record write would still pass their pin assertions: a spy reports success without touching the // record. This cell keeps the real manager over the secrets store this file already seeds: the // record is written by saveConfig, removed by the deletion own deleteConfig, and put back by the // compensation through the same real write path. Only the VS Code storage doubles the whole file // already replaces are replaced here. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] let deletion: Promise | undefined let deletionObserved: Promise | undefined let heldRePinEntered = 0 let releaseHeldRePin: (() => void) | undefined // The sibling re-pin parks on this gate before it reaches the serialized durable write queue, so // the deletion can be observed after its own record delete committed and before any compensation // leg ran. The gate is declared outside the protected scope below so its finally can release it. const heldRePin = new Promise((resolveHeld) => { releaseHeldRePin = () => { releaseHeldRePin = undefined resolveHeld() } }) // Profiles live in one secrets blob under the manager own key, and the shared doubles keep state // between cells: the profile names and view ids below are unique to this cell so no other view // in the registry can follow them. const profilesKey = "roo_cline_config_api_config" const storedProfileNames = (): string[] => { // Double assertion: the shared secrets double resolves synchronously behind the Thenable type, // and this is the exact blob the manager re-reads on a reload. const stored = mockContext.secrets.get(profilesKey) as unknown as string | undefined const parsed = stored ? (JSON.parse(stored) as { apiConfigs?: Record }) : undefined return Object.keys(parsed?.apiConfigs ?? {}) } const profilesBefore = mockContext.secrets.get(profilesKey) as unknown as string | undefined cleanups.push(() => { // The shared secrets double resolves synchronously behind the Thenable types: this puts the // profiles blob back exactly as this cell found it, seeded profiles included. if (profilesBefore === undefined) { void mockContext.secrets.delete(profilesKey) } else { void mockContext.secrets.store(profilesKey, profilesBefore) } }) try { vi.useFakeTimers() for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(provider) const held = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) built.push(held) const oldProfile: ProviderSettingsEntry = { name: "record-old-profile", id: "record-old-id", apiProvider: providerIdentifiers.anthropic, } const keeperProfile: ProviderSettingsEntry = { name: "record-keeper-profile", id: "record-keeper-id", apiProvider: providerIdentifiers.anthropic, } const oldSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "record-old-key", id: "record-old-id", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "record-keeper-key", id: "record-keeper-id", } // The manager instance below is the one the deletion uses, so the seed is the production write // path itself: saveConfig stores under the id given, the blob is rewritten, and a later read // re-parses those bytes. const manager = provider.providerSettingsManager await manager.saveConfig(oldProfile.name, oldSettings) await manager.saveConfig(keeperProfile.name, keeperSettings) await manager.activateProfile({ name: keeperProfile.name }) expect(storedProfileNames()).toContain(oldProfile.name) await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", keeperProfile.name) await provider.contextProxy.setProviderSettings(keeperSettings) await provider.setViewStateId("record-sidebar-view") await provider.saveViewState("currentApiConfigName", keeperProfile.name) await provider.saveViewState("apiConfiguration", keeperSettings) await held.setViewStateId("record-held-view") await held.saveViewState("currentApiConfigName", oldProfile.name) for (const instance of [provider, held]) { const postSpy = vi.spyOn(instance, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => postSpy.mockRestore()) } const rollbackLogLines: string[] = [] const logSpy = vi.spyOn(provider, "log").mockImplementation((line: string) => { rollbackLogLines.push(String(line)) }) cleanups.push(() => logSpy.mockRestore()) // Hold the sibling re-pin before it touches durable storage: the deletion waits inside it, and // the compensation legs - the record restore included - only start when this write settles. const heldSink = held["_saveViewLocalStateFromMutation"].bind(held) held["_saveViewLocalStateFromMutation"] = async () => { heldRePinEntered++ await heldRePin throw new Error("held sibling re-pin write down") } cleanups.push(() => { held["_saveViewLocalStateFromMutation"] = heldSink }) deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) for (let pumped = 0; pumped < 200 && heldRePinEntered === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P1: the deletion is parked inside the sibling re-pin, and the record delete has already // committed for real: the profile is gone from the stored blob, not merely reported as gone, // and no compensation leg has run yet - so an absence observed here is the deletion own doing. expect(heldRePinEntered).toBe(1) expect(await manager.hasConfig(oldProfile.name)).toBe(false) expect(storedProfileNames()).not.toContain(oldProfile.name) expect( rollbackLogLines.filter((line) => line.includes("failed to restore the manager record")), ).toHaveLength(0) releaseHeldRePin?.() for (let pumped = 0; pumped < 200; pumped++) { await vi.advanceTimersByTimeAsync(0) } await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // N1: the deletion still rejects with the failure it hit, and the compensation put the record // back through the real manager: hasConfig and getProfile below re-read the stored bytes. await expect(deletion).rejects.toThrow("held sibling re-pin write down") expect(await manager.hasConfig(oldProfile.name)).toBe(true) // N2: restored with its original id, the one the mode mappings and any task pin still name. // A restore that minted a new id would leave the record present but unreachable, and only the // durable read below can see the difference. const restored = await manager.getProfile({ name: oldProfile.name }) expect(restored.name).toBe(oldProfile.name) expect(restored.id).toBe("record-old-id") expect(restored.apiKey).toBe("record-old-key") expect(storedProfileNames()).toContain(oldProfile.name) // N3: the record restore leg reported nothing: it ran on the real manager and landed. expect( rollbackLogLines.filter((line) => line.includes("failed to restore the manager record")), ).toHaveLength(0) } finally { releaseHeldRePin?.() try { await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved } finally { for (const cleanup of cleanups.reverse()) { cleanup() } vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await disposeBuiltProvidersAndReportCleanupErrors(built) } } }) // Rows for the helper above. No provider a cell in this describe builds rejects its dispose() // today - every cell above would fail in its finally block if one did - so the difference the // three review items describe is only visible under an injected rejection. These rows call // the helper directly with doubles that name their view, so the sidebar the reviewers name // is asserted by name, and each double records the attempt it received. it("attempts every provider cleanup when a rejected dispose comes first in the reverse order", async () => { const attempted: string[] = [] const cleanupFirstEditorDown = new Error("cleanup-first-editor-down") const cleanupSecondEditorDown = new Error("cleanup-second-editor-down") // Review comment 4754554479: the sidebar cleanup stays pending. Doubles that resolve at // once cannot tell a helper that awaits each disposal from one that calls dispose and moves // on: the attempt order, the collected rejections and the reported AggregateError all look // the same. Holding the gate makes the pending leg observable, and finally releases it. let releaseSidebar: () => void = () => {} const sidebarGate = new Promise((resolve) => { releaseSidebar = resolve }) const sidebar = { view: "sidebar", dispose: async () => { attempted.push("sidebar") await sidebarGate }, } const firstEditor = { view: "first-editor", dispose: async () => { attempted.push("first-editor") throw cleanupFirstEditorDown }, } const secondEditor = { view: "second-editor", dispose: async () => { attempted.push("second-editor") throw cleanupSecondEditorDown }, } let reported: unknown let cleanupPromise: Promise | undefined let cleanupOutcome: Promise | undefined try { cleanupPromise = disposeBuiltProvidersAndReportCleanupErrors([sidebar, firstEditor, secondEditor]) // Settles to a word either way: the race below never sees a rejection, and the // rejection stays handled even when an assertion above throws before the await. cleanupOutcome = cleanupPromise.then( () => "fulfilled", () => "rejected", ) for (let attempt = 0; attempt < 50 && attempted.length < 3; attempt++) { await new Promise((resolve) => setImmediate(resolve)) } // Mid-flight measure: every provider was attempted and the helper own promise is still // unsettled because it waits on the sidebar cleanup. A helper that called dispose // without awaiting it settles here instead, and this race answers "rejected". expect(attempted).toEqual(["second-editor", "first-editor", "sidebar"]) const settled = await Promise.race([ cleanupOutcome, new Promise((resolve) => setImmediate(() => resolve("pending"))), ]) expect(settled).toBe("pending") releaseSidebar() try { await cleanupPromise } catch (cleanupReport: unknown) { reported = cleanupReport } } finally { releaseSidebar() await cleanupOutcome } expect(reported).toBeInstanceOf(AggregateError) if (!(reported instanceof AggregateError)) { throw new Error("cleanup reported something other than an AggregateError") } // Both rejections are reported, in the order they were attempted, and the message names how // many cleanups failed. The last-built editor is attempted first, so its failure leads. expect(reported.errors).toHaveLength(2) expect(reported.errors[0]).toBe(cleanupSecondEditorDown) expect(reported.errors[1]).toBe(cleanupFirstEditorDown) expect(reported.message).toBe("2 of 3 provider cleanups failed") expect(attempted).toEqual(["second-editor", "first-editor", "sidebar"]) }) it("rethrows one rejected provider cleanup unchanged after attempting the rest", async () => { // One rejected dispose must still reach the runner as itself: the cells above dispose every // provider they built, and a cleanup that wrapped or swallowed the rejection would hide the // failure the cell used to fail with. The sidebar is built first, so the reverse walk // attempts the editor first and the sidebar second - the case the reviewer describes. const attempted: string[] = [] const cleanupEditorDown = new Error("cleanup-editor-down") const sidebar = { view: "sidebar", dispose: async () => { attempted.push("sidebar") }, } const editor = { view: "editor", dispose: async () => { attempted.push("editor") throw cleanupEditorDown }, } let reported: unknown try { await disposeBuiltProvidersAndReportCleanupErrors([sidebar, editor]) } catch (cleanupReport: unknown) { reported = cleanupReport } expect(reported).toBe(cleanupEditorDown) expect(attempted).toEqual(["editor", "sidebar"]) }) it("reports no cleanup error when every built provider disposes in the reverse creation order", async () => { // The shape the cells above rely on today: nothing rejects, so the cleanup reports nothing // and the runner sees only the cell own assertion. The attempt order is pinned because the // reviewers ask for the reverse order to stay. const attempted: string[] = [] const makeView = (view: string) => ({ view, dispose: async () => { attempted.push(view) }, }) // Review comment 4754554494: awaited directly, so a rejection fails this row by itself. The // earlier shape captured whatever the helper threw into a variable and compared it with // undefined, which also passes for a helper that reports cleanupErrors[0] whatever the walk // collected: after a clean walk that value is undefined too, so the capture could not tell // "reported nothing" from "reported something". await disposeBuiltProvidersAndReportCleanupErrors([ makeView("sidebar"), makeView("first-editor"), makeView("second-editor"), ]) // The reverse creation order stays pinned because the review asks for it to stay. expect(attempted).toEqual(["second-editor", "first-editor", "sidebar"]) }) it("replays a rolled-back sibling live pin only where its stored pin came back too", async () => { // Review comment 4746420955 asks the live replay to follow the durable outcome: the durable merge // leg and the live repair leg roll the same views back in two layers, and today they decide // independently. This cell puts the two layers at odds - the re-pin had committed on a sibling // while its own storage restore threw - and pins the single rule the rollback applies to both // legs: undo only what this deletion still owns, and report what it could not undo. // Defensive: the doubles in this suite can leave console writes pending at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) // The mutation timeout is the provider own 30-second clock: this cell never reaches it, but the // pending timers stay fake so a failed write cannot hold the worker for 30 real seconds. vi.useFakeTimers() const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const first = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "old-profile-key", id: "old-id", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", id: "keeper-id", } // Seeded through the real view-state writes before the write seam below is installed, so the seam // can only ever touch the writes this deletion and its compensation make. await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") // The deleting view pins a survivor of its own: the deletion reaches the sibling re-pin through // the branch that leaves its own pin alone, so the only two views whose state the rollback has to // reconcile are the two below. await provider.contextProxy.setProviderSettings(keeperSettings) await provider.setViewStateId("stable-sidebar-view") await provider.saveViewState("currentApiConfigName", "keeper-profile") await provider.saveViewState("apiConfiguration", keeperSettings) // The view whose re-pin this cell expects to stay put: pinned on the deleted profile with no // overlay of its own, so its re-pin writes the replacement name and settings on both layers. await first.setViewStateId("stable-first-view") await first.saveViewState("currentApiConfigName", "old-profile") // The view whose re-pin write this cell fails: that failure is what drives the compensation, and // because persistence precedes the buffer, its own live state never took the replacement. await second.setViewStateId("stable-second-view") await second.saveViewState("currentApiConfigName", "old-profile") await second.saveViewState("apiConfiguration", deletedSettings) const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName // Declared before the try below so its finally block can name every handle: a failed assertion must // not leave the deletion unobserved or the fake clock running for the later tests. let deletion: Promise | undefined let deletionObserved: Promise | undefined let deletionSettled = 0 let secondWriteRejectedAtStorage = 0 let mergeWriteRejectedAtStorage = 0 let viewStatesWrites = 0 const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") // Double assertion: the mock seam declares its own value type, while this seam has to see the raw // key/value pair to fail two different writes and count the rest. ContextProxy assigns its // in-memory cache before the durable attempt, so the map handed to the seam is identity-equal to // the cache of the view that issued the write: that names the sibling write. The compensation // durable merge is told apart by content instead - it is the only write that hands back the // deleted profile name for the view whose stored pin still reads the replacement. const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } viewStatesWrites++ const written = value as Record const stored = mockContext.globalState.get("viewStates") as Record | undefined if (second.contextProxy.getValue("viewStates") === value && secondWriteRejectedAtStorage === 0) { secondWriteRejectedAtStorage++ return Promise.reject(new Error("second sibling write down")) } if ( written["stable-first-view"]?.currentApiConfigName === "old-profile" && stored?.["stable-first-view"]?.currentApiConfigName === "keeper-profile" && mergeWriteRejectedAtStorage === 0 ) { mergeWriteRejectedAtStorage++ return Promise.reject(new Error("rollback merge write down")) } return durableUpdate(key, value) } try { // The instance registry is environment: the re-pin must see exactly these three views. instancesSpy.mockReturnValue([provider, first, second]) const firstPostSpy = vi.spyOn(first, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(second, "postStateToWebview").mockResolvedValue(undefined) // The rollback logs every leg it could not complete through this one method: spying on it reads // the report the review asks for without touching the console the doubles already mock. const rollbackLogSpy = vi.spyOn(provider, "log").mockImplementation(() => {}) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A gate this deletion never moved: the manager-gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("restored") vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", ...deletedSettings } : { name: "keeper-profile", ...keeperSettings }, ) // Observe at once: the deletion can reject while this row is still pumping the fake clock, and an // unhandled rejection by then is reported even though the rows below await this very promise. deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) void deletionObserved.then(() => { deletionSettled++ }) for (let pumped = 0; pumped < 200 && deletionSettled === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(deletionSettled).toBe(1) await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // P1: both writes this cell arms had reached storage - the sibling re-pin write that drives the // compensation, and the compensation own durable pin merge that this cell makes fail. expect(secondWriteRejectedAtStorage).toBe(1) expect(mergeWriteRejectedAtStorage).toBe(1) // N1: the view whose re-pin had committed stays on the replacement on BOTH layers. Its stored pin // never came back, so the live leg has nothing to undo here: replaying its buffer back onto // storage that still names the replacement would put the two layers on different profiles, // which is exactly the divergence the rollback exists to remove. expect(first["viewLocalState"].currentApiConfigName).toBe("keeper-profile") expect(first["viewLocalState"].apiConfiguration).toEqual(keeperSettings) expect(durablePin("stable-first-view")).toBe("keeper-profile") // N2: what the deletion could not undo is reported instead of quietly left behind, and the report // names this view. It is a log, not a second failure: the caller still sees the original. const rollbackLogs = rollbackLogSpy.mock.calls.map((call) => String(call[0])) expect( rollbackLogs.some( (line) => line.includes("incomplete view-pin rollback") && line.includes("stable-first-view"), ), ).toBe(true) // N3: the view whose own write failed is in that report too. Its buffer never took the // replacement, so nothing of its own is left stranded on it - but its stored pin still holds // the replacement, and the check that decides what to report now runs before the check that // asks what the view pins, so a view the durable leg could not bring back is named whichever // way its buffer moved. expect(rollbackLogs.some((line) => line.includes("stable-second-view"))).toBe(true) expect(second["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(second["viewLocalState"].apiConfiguration).toEqual(deletedSettings) // N4: the storage leg reports its own failure and keeps the original deletion failure for the // caller: a merge that threw adds its own log line, it does not replace the error this deletion // rejects with. expect(rollbackLogs.some((line) => line.includes("failed to restore the persisted view pins"))).toBe( true, ) await expect(deletion).rejects.toThrow("second sibling write down") // N5: the repair queues no durable write of its own: the only durable viewStates writes this // deletion and its rollback issue are the durable re-point of the pins, the re-pin writes, the // failed merge and the cache read-back that follows a rejected write. expect(viewStatesWrites).toBe(5) // N6: the repair refreshes state only: it posts nothing, and the failure path posts nothing. expect(firstPostSpy).not.toHaveBeenCalled() } finally { instancesSpy.mockRestore() storageSeam.update = durableUpdate // Settle the deletion under the still-installed fake clock, then restore the clock, drain the // durable queue and dispose every view. await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await first.dispose() await second.dispose() await provider.dispose() } }) it("keeps a committed profile deletion committed when only its final state refresh throws", async () => { // Review comment 4746420947 asks the deleting view last refresh to be post-commit work: by the // time it runs, every write the deletion can still put back has committed, so a refresh that // throws must not roll the deletion back. The re-pin above it is still compensated, so this // cell runs the deletion twice: once with only the refresh failing, once with a sibling // re-pin write failing, and pins the two different outcomes the two positions imply. // Defensive: the doubles in this suite can leave console writes pending at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) // The mutation timeout is the provider own 30-second clock: neither phase reaches it, but the // pending timers stay fake so a failed write cannot hold the worker for 30 real seconds. vi.useFakeTimers() const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const first = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "old-profile-key", id: "old-id", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", id: "keeper-id", } // Seeded through the real view-state writes before the write seam below is installed, so the // seam can only ever touch the writes the two deletions and their rollback make. await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.contextProxy.setProviderSettings(keeperSettings) await provider.setViewStateId("stable-sidebar-view") await provider.saveViewState("currentApiConfigName", "keeper-profile") await provider.saveViewState("apiConfiguration", keeperSettings) // Both siblings start pinned on the profile under deletion, one with an overlay of its own and // one without, so the re-pin has two different kinds of work to do. await first.setViewStateId("stable-first-view") await first.saveViewState("currentApiConfigName", "old-profile") await second.setViewStateId("stable-second-view") await second.saveViewState("currentApiConfigName", "old-profile") await second.saveViewState("apiConfiguration", deletedSettings) const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName // Declared before the try below so its finally block can name every handle: a failed assertion // must not leave either deletion unobserved or the fake clock running for the later tests. let deletionA: Promise | undefined let deletionAObserved: Promise | undefined let deletionB: Promise | undefined let deletionBObserved: Promise | undefined let deletionASettled = 0 let deletionBSettled = 0 let failFinalRefresh = 0 let armSecondSiblingWrite = 0 let secondWriteRejectedAtStorage = 0 let deletingViewPosts = 0 const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") // Double assertion: the mock seam declares its own value type, while this seam has to fail the // sibling write by identity and count the rest. ContextProxy assigns its in-memory cache // before the durable attempt, so the map handed to the seam is identity-equal to the cache of // the view that issued the write. const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update storageSeam.update = (key: string, value: unknown) => { if ( key === "viewStates" && armSecondSiblingWrite === 1 && secondWriteRejectedAtStorage === 0 && second.contextProxy.getValue("viewStates") === value ) { secondWriteRejectedAtStorage++ return Promise.reject(new Error("second sibling write down")) } return durableUpdate(key, value) } try { // The instance registry is environment: each re-pin must see exactly these three views. instancesSpy.mockReturnValue([provider, first, second]) // The deleting view own refresh, armed to fail once. The counter doubles as the witness that // the refresh still runs on the success path: it is moved out of the compensated region, not // dropped from it. vi.spyOn(provider, "postStateToWebview").mockImplementation(() => { deletingViewPosts++ if (failFinalRefresh === 1) { failFinalRefresh = 0 return Promise.reject(new Error("final state refresh down")) } return Promise.resolve() }) vi.spyOn(first, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(second, "postStateToWebview").mockResolvedValue(undefined) // The rollback logs every leg it could not complete through this one method: spying on it reads // what each path reports without touching the console the doubles already mock. const rollbackLogSpy = vi.spyOn(provider, "log").mockImplementation(() => {}) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A gate this deletion never moved: the manager-gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) // Only the compensation record-restore leg calls saveConfig: its call count is the witness that // a failed refresh starts no compensation at all. const recordRestoreSpy = vi .spyOn(provider.providerSettingsManager, "saveConfig") .mockResolvedValue("restored") vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", ...deletedSettings } : { name: "keeper-profile", ...keeperSettings }, ) // Phase A: nothing fails but the deleting view final state refresh. failFinalRefresh = 1 deletionA = provider.deleteProviderProfile(oldProfile) deletionAObserved = deletionA.catch(() => {}) void deletionAObserved.then(() => { deletionASettled++ }) for (let pumped = 0; pumped < 200 && deletionASettled === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(deletionASettled).toBe(1) // P1: the armed failure reached the refresh it names - the deleting view posted exactly once, // and nothing else in this phase failed. expect(deletingViewPosts).toBe(1) // A1: the deletion had already committed, so a refresh that throws does not turn it into a // failed deletion: the caller sees a deletion that succeeded. await expect(deletionA).resolves.toBeUndefined() // A2: and no compensation leg ran at all. The record restore is the first leg of the // rollback, so zero calls means the rollback never started: the deletion is not undone in // the manager, in the shared surfaces, or in the view pins. expect(recordRestoreSpy.mock.calls.length).toBe(0) // A3: the durable pins stay where the committed deletion put them. This reads the stored map // directly: a rollback would have written the deleted profile back into both sibling entries. expect(durablePin("stable-first-view")).toBe("keeper-profile") expect(durablePin("stable-second-view")).toBe("keeper-profile") expect(first["viewLocalState"].currentApiConfigName).toBe("keeper-profile") // A4: the failed refresh is reported instead of silently swallowed: the webview is left // showing the state before the deletion, and that is the only cost this path should pay. const phaseALogs = rollbackLogSpy.mock.calls.map((call) => String(call[0])) expect( phaseALogs.some( (line) => line.includes("final state refresh failed") && line.includes("final state refresh down"), ), ).toBe(true) // Phase B: the same deletion again, this time with a sibling re-pin write failing at storage. // Both siblings are re-seeded onto the deleted profile through the real write path so the // re-pin has the same work to do as in phase A, and only the position of the failure moves. await first.saveViewState("currentApiConfigName", "old-profile") await second.saveViewState("currentApiConfigName", "old-profile") await second.saveViewState("apiConfiguration", deletedSettings) armSecondSiblingWrite = 1 deletionB = provider.deleteProviderProfile(oldProfile) deletionBObserved = deletionB.catch(() => {}) void deletionBObserved.then(() => { deletionBSettled++ }) for (let pumped = 0; pumped < 200 && deletionBSettled === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(deletionBSettled).toBe(1) // P2: the failure this phase arms landed in storage, on the sibling re-pin write. expect(secondWriteRejectedAtStorage).toBe(1) // B1: a failed re-pin write is still compensated. The re-pin is the last write this deletion // can put back, so unlike the refresh its failure rejects the deletion with the original // write error. await expect(deletionB).rejects.toThrow("second sibling write down") // B2: and the rollback actually rolled the pins back, in storage and in the sibling buffers: // the compensation this cell keeps is the one that puts the deleted profile back. expect(durablePin("stable-first-view")).toBe("old-profile") expect(durablePin("stable-second-view")).toBe("old-profile") expect(first["viewLocalState"].currentApiConfigName).toBe("old-profile") // B3: the post-commit refresh belongs to the success path only. Counting the deleting view // posts across both phases says so: the compensated deletion never reaches the refresh at // all, so the total is still the single phase A one. expect(deletingViewPosts).toBe(1) // B4: and the compensated path adds no report of its own: every leg that had to run did run, // so the only log line this cell produced in either phase is the refresh failure above. expect(rollbackLogSpy.mock.calls.length).toBe(1) } finally { instancesSpy.mockRestore() storageSeam.update = durableUpdate // Settle both deletions under the still-installed fake clock, then restore the clock, drain // the durable queue and dispose every view. await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionAObserved await deletionBObserved vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await first.dispose() await second.dispose() await provider.dispose() } }) it("keeps the deletion waiting for the stored task pin its live replay restores", async () => { // Review comment 4746420929 asks this scenario for a task whose history is actually stored, and for // the deletion to be observed while the restore-side task write is still pending. The sticky // profile name a re-pin writes into a task history is the one durable value the rollback puts // back through a file write instead of through the view-state write queue, and every cell above // re-pins views that have no stored history item at all: this is the first place in this file // where production reaches that write, so a rollback that dropped it, never awaited it, or // pointed it at the wrong name would pass this file unnoticed. // Defensive: the doubles in this suite can leave console writes pending at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) // The mutation timeout is the provider own 30-second clock: this cell never reaches it, but the // pending timers stay fake so a held write cannot hold the worker for 30 real seconds. vi.useFakeTimers() const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const first = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const second = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "old-profile-key", id: "old-id", } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", id: "keeper-id", } // Seeded through the real view-state writes before the write seams below are installed, so the // seams can only ever touch the writes this deletion and its compensation make. await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") // The deleting view pins a survivor of its own: the deletion reaches the sibling re-pin through // the branch that leaves its own pin alone, so the only views whose state the rollback has to // reconcile are the two below. await provider.contextProxy.setProviderSettings(keeperSettings) await provider.setViewStateId("stable-sidebar-view") await provider.saveViewState("currentApiConfigName", "keeper-profile") await provider.saveViewState("apiConfiguration", keeperSettings) // The view this cell watches: pinned on the deleted profile, and its re-pin write commits, so // both its own layers and the task it runs move onto the replacement. await first.setViewStateId("stable-first-view") await first.saveViewState("currentApiConfigName", "old-profile") // The view whose re-pin write this cell fails: that failure is what drives the compensation, // and because persistence precedes the buffer, its own live state never took the replacement. await second.setViewStateId("stable-second-view") await second.saveViewState("currentApiConfigName", "old-profile") await second.saveViewState("apiConfiguration", deletedSettings) // The task the first view runs, built from the deleted profile exactly as the re-pin finds it, // and kept in step with the calls the way a real task is: the repair re-checks the task own // sticky name before replaying it, and a frozen double would hide the re-pin own change from // that guard. Double assertion: the double carries only the members the re-pin and the repair // touch, and the structural cast is the one the task fixtures in this suite already use. const firstTaskSettings: ProviderSettings = deletedSettings const firstTask = { apiConfiguration: firstTaskSettings, taskApiConfigName: "old-profile", taskId: "stored-first-task", setTaskApiConfigName: vi.fn((name: string) => { firstTask.taskApiConfigName = name }), updateApiConfiguration: vi.fn((settings: ProviderSettings) => { firstTask.apiConfiguration = settings }), persistStickyProviderProfileToCurrentTask: vi.fn(), } vi.spyOn(first, "getCurrentTask").mockReturnValue( firstTask as unknown as ReturnType, ) // A task WITH stored history, which is the part the review comment asks for: the durable task // write only happens at all when getTaskHistoryItem answers for the running task, so without // this record the rollback has no task-history write to make. Seeded the way the getTaskWithId // cells seed it - into the map getTaskHistoryItem reads, plus the flag that makes that store // authoritative over the legacy global-state fallback. const storedTask = { id: "stored-first-task", task: "first conversation", ts: 1, number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, apiConfigName: "old-profile", } first.taskHistoryStore["cache"].set(storedTask.id, storedTask) first["taskHistoryStoreInitialized"] = true // Read the stored name back through the store own accessor - the same one the provider reads // before it writes - so every claim below is about the durable value, never about a copy this // cell kept. const storedTaskPin = (): string | undefined => first.taskHistoryStore.get(storedTask.id)?.apiConfigName const durablePin = (viewStateId: string): string | undefined => ( mockContext.globalState.get("viewStates") as Record< string, { currentApiConfigName?: string } | undefined > )[viewStateId]?.currentApiConfigName // Declared before the try below so its finally block can name every handle: a failed assertion // must not leave the deletion parked on a write nobody will release, or the fake clock running // for the later tests. let releaseRestoreWrite!: () => void const pendingRestoreWrite = new Promise((resolve) => { releaseRestoreWrite = resolve }) let deletion: Promise | undefined let deletionObserved: Promise | undefined let deletionSettled = 0 let restoreWritesAtSeam = 0 let secondWriteRejectedAtStorage = 0 const instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") // The task-history store seam. The real write is captured before the spy replaces it and called // through for every write that is not held, so the held one is the only write this cell delays // and the store still performs the write itself. The name inside the item says which write it // is - the applied side carries the replacement, the rollback carries the deleted profile back // - so no production code is touched to tell the two apart. const upsertThrough = first.taskHistoryStore.upsert.bind(first.taskHistoryStore) const taskWriteSpy = vi.spyOn(first.taskHistoryStore, "upsert") taskWriteSpy.mockImplementation((item) => { if (item.apiConfigName === "old-profile" && restoreWritesAtSeam === 0) { restoreWritesAtSeam++ return pendingRestoreWrite.then(() => upsertThrough(item)) } return upsertThrough(item) }) // Double assertion: the mock seam declares its own value type, while this seam has to see the raw // key/value pair to fail one write and count the rest; the seam implementation is called through // for every write that is not failed, so those writes are still the ones production reaches // through ContextProxy. ContextProxy assigns its in-memory cache before the durable attempt, so // the map handed to the seam is identity-equal to the cache of the view that issued the write: // that names the sibling write without touching production, and the earlier durable re-point of // the pins arrives through a different cache and stays unblocked. const storageSeam = mockContext.globalState as unknown as { update: (key: string, value: unknown) => unknown } const durableUpdate = storageSeam.update storageSeam.update = (key: string, value: unknown) => { if (key !== "viewStates") { return durableUpdate(key, value) } if (second.contextProxy.getValue("viewStates") === value && secondWriteRejectedAtStorage === 0) { secondWriteRejectedAtStorage++ return Promise.reject(new Error("second sibling write down")) } return durableUpdate(key, value) } try { // The instance registry is environment: the re-pin must see exactly these three views. instancesSpy.mockReturnValue([provider, first, second]) const firstPostSpy = vi.spyOn(first, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(second, "postStateToWebview").mockResolvedValue(undefined) // The rollback reports what it could not undo through this one method: spying on it reads the // report without touching the console the doubles already mock. const rollbackLogSpy = vi.spyOn(provider, "log").mockImplementation(() => {}) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeperProfile]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) // A manager gate this deletion never moved: the gate restore legs stay inert here. vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("restored") vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", ...deletedSettings } : { name: "keeper-profile", ...keeperSettings }, ) // Observe at once: the deletion can reject while this row is still pumping the fake clock, and // an unhandled rejection by then is reported even though the rows below await this very promise. deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) void deletionObserved.then(() => { deletionSettled++ }) // Pump until the rollback durable task write reaches the store seam. The bound is generous and // the premise below is what turns this loop from a wait into a check: if that write never // arrives, restoreWritesAtSeam stays 0 and this row fails instead of passing on a loop that ran // to nothing. for (let pumped = 0; pumped < 200 && restoreWritesAtSeam === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } // P1 (the observation the review comment asks for): the rollback write for the stored task is // sitting on the store seam, and while it waits this deletion has settled on nothing at all - it // has not resolved, and it has not rejected with its original failure either. The sibling write // that drives the compensation had to reach storage first, so the compensation is what is parked // here. expect(restoreWritesAtSeam).toBe(1) expect(deletionSettled).toBe(0) expect(secondWriteRejectedAtStorage).toBe(1) // P2: the layers this rollback reaches before that write, each read from its own store. The // durable pin merge and the buffer replay have both come back for this view, its task already // runs under the deleted profile again and with the deleted profile handler, while the stored // history of that same task still names the replacement: four layers agree and the fifth is the // one still in flight, which is the state the review comment asks to observe. expect(durablePin("stable-first-view")).toBe("old-profile") expect(first["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(firstTask.taskApiConfigName).toBe("old-profile") expect(firstTask.updateApiConfiguration).toHaveBeenLastCalledWith(deletedSettings) expect(storedTaskPin()).toBe("keeper-profile") // Release the held write and pump until this deletion settles. releaseRestoreWrite() for (let pumped = 0; pumped < 200 && deletionSettled === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } expect(deletionSettled).toBe(1) await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // A1: the check the review comment asks for once the write is allowed to finish: the stored // profile name of the running task is the profile this deletion removed, not the replacement the // re-pin had pointed it at. expect(storedTaskPin()).toBe("old-profile") // A2: and that value agrees with the two view layers, one read from the durable map and one from // the view own buffer: this view, its storage and its conversation name one profile again. expect(durablePin("stable-first-view")).toBe("old-profile") expect(first["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(firstTask.taskApiConfigName).toBe("old-profile") // A3: the write this cell held is the rollback own write, in the order the two legs take it: // the re-pin points the stored task at the replacement while its own storage move is still in // flight, and the rollback points it back afterwards. expect(taskWriteSpy.mock.calls.map((call) => call[0]?.apiConfigName)).toEqual([ "keeper-profile", "old-profile", ]) // A4: the caller still sees the deletion failure it was getting before: the task write is // repaired here, not added to what the caller has to handle. await expect(deletion).rejects.toThrow("second sibling write down") // A5: nothing is left stranded on the replacement, so the rollback has no incomplete recovery to // report for this scenario. const rollbackLogs = rollbackLogSpy.mock.calls.map((call) => String(call[0])) expect(rollbackLogs.some((line) => line.includes("incomplete view-pin rollback"))).toBe(false) // A6: the repair refreshes state only: it posts nothing to the view it repaired, and the failure // path posts nothing either. expect(firstPostSpy).not.toHaveBeenCalled() } finally { // Release first: an assertion above can fail while the write is still held, and the deletion // awaits that write through its compensation, so the settlement below would never arrive. releaseRestoreWrite() instancesSpy.mockRestore() taskWriteSpy.mockRestore() storageSeam.update = durableUpdate // Settle the deletion under the still-installed fake clock, then restore the clock, drain the // durable queue and dispose every view. await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] await first.dispose() await second.dispose() await provider.dispose() } }) it("returns the deleting view, its task and its stored profile name when the read-back fails", async () => { // Review comment 4503736848: the activation of the deleting view moves its own buffer, its task // handler and the profile name stored with that conversation onto the replacement, and the live // replay in the compensation rewound only the views the sibling re-pin recorded - which never // includes this view. The read-back of the replacement settings is what makes the gap observable: // it fails, so the re-pin refuses to re-point the sibling without settings and rejects, and the // rollback restored storage while this view and its conversation stayed on the replacement. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] const rollbackLogLines: string[] = [] let deletion: Promise | undefined let deletionObserved: Promise | undefined let instancesSpy: ReturnType | undefined try { vi.useFakeTimers() // Defensive: the doubles in this suite can leave console writes pending at worker teardown. for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const newView = (view: "sidebar" | "editor") => new ClineProvider( mockContext, mockOutputChannel, view, new ContextProxy(mockContext), new WebviewFocusTracker(), ) const provider = newView("sidebar") built.push(provider) const sibling = newView("editor") built.push(sibling) const oldProfile = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter } const keeper = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "old-profile-key" } // Seeded through the real write paths, so a double below can only ever touch the writes this // deletion and its compensation make. Both views pin the profile that is about to go. await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeper]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.contextProxy.setProviderSettings(deletedSettings) await provider.setViewStateId("deleting-sidebar-view") await provider.saveViewState("currentApiConfigName", "old-profile") await provider.saveViewState("apiConfiguration", deletedSettings) await sibling.setViewStateId("rival-sibling-view") await sibling.saveViewState("currentApiConfigName", "old-profile") await sibling.saveViewState("apiConfiguration", deletedSettings) type PinMap = Record const viewStates = () => mockContext.globalState.get("viewStates") as PinMap const durablePin = (viewStateId: string) => viewStates()[viewStateId]?.currentApiConfigName instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") instancesSpy.mockReturnValue([provider, sibling]) for (const instance of [provider, sibling]) { const postSpy = vi.spyOn(instance, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => postSpy.mockRestore()) } const logSpy = vi.spyOn(provider, "log").mockImplementation((logLine: string) => { rollbackLogLines.push(String(logLine)) }) cleanups.push(() => logSpy.mockRestore()) const saveConfigSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig") cleanups.push(() => saveConfigSpy.mockRestore()) saveConfigSpy.mockResolvedValue("restored") vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeper]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(false) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) // The read-back seam: the deleted record reads fine and every read of the replacement fails. const getProfileSpy = vi.spyOn(provider.providerSettingsManager, "getProfile") getProfileSpy.mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", ...deletedSettings } : Promise.reject(new Error("replacement read-back down")), ) cleanups.push(() => getProfileSpy.mockRestore()) // The task this view runs, built from the deleted profile and kept in step with the calls the way // a real task is: the repair re-checks the task own sticky name before replaying it. Double // assertion: the cast is the one the task fixtures in this suite already use. const deletingTask = { apiConfiguration: deletedSettings as ProviderSettings, // the field holds the full settings union taskApiConfigName: "old-profile", taskId: "deleting-task", setTaskApiConfigName: vi.fn((name: string) => { deletingTask.taskApiConfigName = name }), updateApiConfiguration: vi.fn((settings: ProviderSettings) => { deletingTask.apiConfiguration = settings }), } const taskSpy = vi .spyOn(provider, "getCurrentTask") .mockReturnValue(deletingTask as unknown as ReturnType) cleanups.push(() => taskSpy.mockRestore()) const storedTask = { id: "deleting-task", task: "deleting conversation", ts: 1, number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, apiConfigName: "old-profile", } await provider.taskHistoryStore.initialized // seeding before that reconcile drops it again provider.taskHistoryStore["cache"].set(storedTask.id, storedTask) provider["taskHistoryStoreInitialized"] = true // Read the stored name back through the store own accessor: the claims below are about storage. const storedPin = (): string | undefined => provider.taskHistoryStore.get(storedTask.id)?.apiConfigName // The store seam: the real write is captured before the spy replaces it and called through. const upsertThrough = provider.taskHistoryStore.upsert.bind(provider.taskHistoryStore) const taskWriteSpy = vi.spyOn(provider.taskHistoryStore, "upsert") taskWriteSpy.mockImplementation((item) => upsertThrough(item)) cleanups.push(() => taskWriteSpy.mockRestore()) deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) for (let pumped = 0; pumped < 200; pumped++) { await vi.advanceTimersByTimeAsync(0) } await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] // P1: the premise the review comment describes really happened: the replacement read-back failed, // and the re-pin refused to re-point the sibling without the replacement settings. expect(rollbackLogLines.some((logLine) => logLine.includes("Unable to resolve API profile"))).toBe(true) await expect(deletion).rejects.toThrow("to re-point 1 live view(s) after deleting") // P2: the deletion did reach its compensation: the record restore ran with the deleted profile own // settings, so what follows is a rollback and not a path that never touched this view. expect(saveConfigSpy).toHaveBeenCalledWith("old-profile", deletedSettings) // A1: the deleting view own buffer agrees with its own storage again instead of staying on the // replacement, with its own overlay back rather than the replacement settings. expect(provider["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(provider["viewLocalState"].apiConfiguration).toEqual(deletedSettings) expect(sibling["viewLocalState"].currentApiConfigName).toBe("old-profile") expect(sibling["viewLocalState"].apiConfiguration).toEqual(deletedSettings) // A2: storage came back for both views, which is the half that already worked and the half that // made the divergence visible: this view stored pin names the profile this deletion removed again. expect(durablePin("deleting-sidebar-view")).toBe("old-profile") expect(durablePin("rival-sibling-view")).toBe("old-profile") // A3: the conversation that ran under the deleted profile comes back with the view - its sticky name // and its API handler are the deleted profile own again. expect(deletingTask.taskApiConfigName).toBe("old-profile") expect(deletingTask.updateApiConfiguration).toHaveBeenLastCalledWith(deletedSettings) // A4: and so is the name stored with it, read back through the store own accessor. The only two // stored writes are the activation own and the rollback own, in that order. expect(storedPin()).toBe("old-profile") expect(taskWriteSpy.mock.calls.map((call) => call[0]?.apiConfigName)).toEqual([ "keeper-profile", "old-profile", ]) // A5: coming back is not an incomplete recovery, so nothing reports this view as stranded. expect(rollbackLogLines.some((logLine) => logLine.includes("incomplete view-pin rollback"))).toBe(false) } finally { instancesSpy?.mockRestore() for (const cleanup of cleanups.reverse()) { cleanup() } await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] for (const instance of built) { await instance.dispose() } } }) it("leaves the deleting view on the replacement when it selected it during the rollback", async () => { // Review comment 4503736848 asks for the restoration without overwriting what came after it. This // view selects the replacement itself while the deletion is inside its own compensation, and that // write is owned by the view, not by the deletion token: the rollback leaves the buffer, the // conversation and the stored profile name on the choice the user made, and still brings back the // views it does own. const built: ClineProvider[] = [] const cleanups: Array<() => void> = [] const rollbackLogLines: string[] = [] let deletion: Promise | undefined let deletionObserved: Promise | undefined let instancesSpy: ReturnType | undefined let selectionStarted = 0 let selectionLanded = 0 let ownSelectionObserved: Promise | undefined try { vi.useFakeTimers() // Defensive: the doubles in this suite can leave console writes pending at worker teardown. for (const level of ["log", "warn", "error"] as const) { const consoleSpy = vi.spyOn(console, level).mockImplementation(() => {}) cleanups.push(() => consoleSpy.mockRestore()) } const newView = (view: "sidebar" | "editor") => new ClineProvider( mockContext, mockOutputChannel, view, new ContextProxy(mockContext), new WebviewFocusTracker(), ) const provider = newView("sidebar") built.push(provider) const sibling = newView("editor") built.push(sibling) const oldProfile = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter } const keeper = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic } const deletedSettings = { apiProvider: providerIdentifiers.openrouter, apiKey: "old-profile-key" } const keeperSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key" } // Seeded through the real write paths, so a double below can only ever touch the writes this // deletion and its compensation make. Both views pin the profile that is about to go. await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeper]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.contextProxy.setProviderSettings(deletedSettings) await provider.setViewStateId("deleting-sidebar-view") await provider.saveViewState("currentApiConfigName", "old-profile") await provider.saveViewState("apiConfiguration", deletedSettings) await sibling.setViewStateId("rival-sibling-view") await sibling.saveViewState("currentApiConfigName", "old-profile") await sibling.saveViewState("apiConfiguration", deletedSettings) type PinMap = Record const viewStates = () => mockContext.globalState.get("viewStates") as PinMap const durablePin = (viewStateId: string) => viewStates()[viewStateId]?.currentApiConfigName instancesSpy = vi.spyOn(ClineProvider, "getAllInstances") instancesSpy.mockReturnValue([provider, sibling]) for (const instance of [provider, sibling]) { const postSpy = vi.spyOn(instance, "postStateToWebview").mockResolvedValue(undefined) cleanups.push(() => postSpy.mockRestore()) } const logSpy = vi.spyOn(provider, "log").mockImplementation((logLine: string) => { rollbackLogLines.push(String(logLine)) }) cleanups.push(() => logSpy.mockRestore()) const saveConfigSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig") cleanups.push(() => saveConfigSpy.mockRestore()) // The deleting view commits a selection of the replacement itself, through its own mutation queue, // while this deletion is parked restoring the manager record inside the shared section. That write // is tokenless: it is this view choosing a profile, not the deletion writing one. saveConfigSpy.mockImplementation(async () => { selectionStarted++ const pending = provider["enqueueProviderProfileMutation"](async () => { await provider["_saveViewLocalStateFromMutation"]({ currentApiConfigName: "keeper-profile", apiConfiguration: keeperSettings, }) selectionLanded++ }) ownSelectionObserved = pending.catch(() => {}) for (let pumped = 0; pumped < 300 && selectionLanded === 0; pumped++) { await vi.advanceTimersByTimeAsync(0) } return "restored" }) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([keeper]) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(false) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-key", }) vi.spyOn(provider.providerSettingsManager, "getSelectionAndModeConfigs").mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }) // The read-back seam: the deleted record reads fine and every read of the replacement fails. const getProfileSpy = vi.spyOn(provider.providerSettingsManager, "getProfile") getProfileSpy.mockImplementation(async (params) => "name" in params && params.name === "old-profile" ? { name: "old-profile", ...deletedSettings } : Promise.reject(new Error("replacement read-back down")), ) cleanups.push(() => getProfileSpy.mockRestore()) // The task this view runs, built from the deleted profile and kept in step with the calls the way // a real task is: the repair re-checks the task own sticky name before replaying it. Double // assertion: the cast is the one the task fixtures in this suite already use. const deletingTask = { apiConfiguration: deletedSettings as ProviderSettings, // the field holds the full settings union taskApiConfigName: "old-profile", taskId: "deleting-task", setTaskApiConfigName: vi.fn((name: string) => { deletingTask.taskApiConfigName = name }), updateApiConfiguration: vi.fn((settings: ProviderSettings) => { deletingTask.apiConfiguration = settings }), } const taskSpy = vi .spyOn(provider, "getCurrentTask") .mockReturnValue(deletingTask as unknown as ReturnType) cleanups.push(() => taskSpy.mockRestore()) const storedTask = { id: "deleting-task", task: "deleting conversation", ts: 1, number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, apiConfigName: "old-profile", } await provider.taskHistoryStore.initialized // seeding before that reconcile drops it again provider.taskHistoryStore["cache"].set(storedTask.id, storedTask) provider["taskHistoryStoreInitialized"] = true // Read the stored name back through the store own accessor: the claims below are about storage. const storedPin = (): string | undefined => provider.taskHistoryStore.get(storedTask.id)?.apiConfigName deletion = provider.deleteProviderProfile(oldProfile) deletionObserved = deletion.catch(() => {}) for (let pumped = 0; pumped < 200; pumped++) { await vi.advanceTimersByTimeAsync(0) } await deletionObserved await vi.advanceTimersByTimeAsync(0) await ClineProvider["persistedViewStateWriteQueue"] await ownSelectionObserved // P1: the premise the review comment describes really happened: the replacement read-back failed, // and the re-pin refused to re-point the sibling without the replacement settings. expect(rollbackLogLines.some((logLine) => logLine.includes("Unable to resolve API profile"))).toBe(true) await expect(deletion).rejects.toThrow("to re-point 1 live view(s) after deleting") // P2: the newer selection really landed, durably, while the deletion was still restoring the record. expect(selectionStarted).toBe(1) expect(selectionLanded).toBe(1) // A1: the rollback does not stomp it. This view own write owns the pin, so the live replay leaves // the buffer, its overlay and the conversation on the profile the user chose. expect(provider["viewLocalState"].currentApiConfigName).toBe("keeper-profile") expect(provider["viewLocalState"].apiConfiguration).toEqual(keeperSettings) expect(deletingTask.taskApiConfigName).toBe("keeper-profile") expect(storedPin()).toBe("keeper-profile") // A2: storage holds that same choice, so the newer selection survives a reload as well. expect(durablePin("deleting-sidebar-view")).toBe("keeper-profile") // A3: the views this deletion still owns come back in both layers: leaving this view alone is not // the whole rollback standing down. expect(durablePin("rival-sibling-view")).toBe("old-profile") expect(sibling["viewLocalState"].currentApiConfigName).toBe("old-profile") // A4: a view whose own write owns its pin is not a stranded view, so the compensation has no // incomplete recovery to report for it. expect(rollbackLogLines.some((logLine) => logLine.includes("incomplete view-pin rollback"))).toBe(false) } finally { instancesSpy?.mockRestore() for (const cleanup of cleanups.reverse()) { cleanup() } await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1000) await deletionObserved await ownSelectionObserved vi.useRealTimers() await ClineProvider["persistedViewStateWriteQueue"] for (const instance of built) { await instance.dispose() } } }) it("leaves a sibling that chose another profile while the deletion waited to re-pin views", async () => { // Defensive: the doubles in this suite can leave console writes pending // at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Declared before the try below so its finally block can name them: a failed // assertion must not leave the sibling mutation queue held for every later test. let releaseChosenSelection!: () => void const chosenSelectionGate = new Promise((resolve) => { releaseChosenSelection = resolve }) // Same reason: the finally has to be able to await the work the released gate // unblocks instead of disposing over it. let siblingChoseProfile!: Promise let deletion: Promise | undefined try { const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") // A stable id keys the sibling's durable entry, so the assertion below names the // entry under test instead of sweeping every view's pin. await sibling.setViewStateId("stable-sibling-view") // The sibling pins the profile being deleted, so the deletion below selects it // for re-pinning onto the surviving profile. sibling["viewLocalState"].currentApiConfigName = "old-profile" sibling["viewLocalState"].apiConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "deleted-profile-secret", } vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, }) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined) // The sibling has queued a selection of a third profile of its own: this is the // mutation the deletion must not overwrite, and it stays queued - holding the // sibling mutation queue - until the deletion has had its turn at the sibling. const chosenSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "chosen-profile-key" } siblingChoseProfile = sibling["enqueueProviderProfileMutation"](async () => { await chosenSelectionGate await sibling["_saveViewLocalStateFromMutation"]({ currentApiConfigName: "chosen-profile", apiConfiguration: chosenSettings, }) }) deletion = provider.deleteProviderProfile(oldProfile) // The surviving profile is resolved immediately before the live views are // re-pinned: once that read has happened, hand the deletion the event-loop turns // its own write path needs while the sibling choice is still queued. await vi.waitFor(() => expect(provider.providerSettingsManager.getProfile).toHaveBeenCalled()) await new Promise((resolve) => setImmediate(resolve)) await new Promise((resolve) => setImmediate(resolve)) // The sibling choice is still in flight: the re-pin may not push the surviving // profile onto that view, so its buffer still names the profile it holds. expect(sibling["viewLocalState"].currentApiConfigName).not.toBe("keeper-profile") expect(sibling["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "deleted-profile-secret", }) releaseChosenSelection() await deletion await siblingChoseProfile // The newer choice survives the deletion: the live buffer and the sibling's own // durable entry both follow that selection instead of the surviving profile. expect(sibling["viewLocalState"].currentApiConfigName).toBe("chosen-profile") expect(sibling["viewLocalState"].apiConfiguration).toEqual(chosenSettings) const durableStates = sibling.contextProxy.getValue("viewStates") expect(durableStates?.["stable-sibling-view"]?.currentApiConfigName).toBe("chosen-profile") // Wait on the serialized view-state write queue that every // viewStates mutation goes through, so queued persistence finishes // while the console spies are still installed and teardown has no // pending writes. await ClineProvider["persistedViewStateWriteQueue"] } finally { releaseChosenSelection() // Ordering, not a race this suite showed: once the gate opens the queued choice // writes through the serialized view-state queue and the deletion may still be // re-pinning, so settle both and drain that queue before disposing. // Instrumented failure-path runs (scratch/1565f-w1-instr2-N-*) found the // disposed-over window never opens at the current interleaving. await deletion?.catch(() => {}) await siblingChoseProfile await ClineProvider["persistedViewStateWriteQueue"] await sibling.dispose() await provider.dispose() } }) it("leaves the view buffer untouched when the deleted profile is neither globally active nor view-pinned", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const otherProfile: ProviderSettingsEntry = { name: "other-profile", id: "other-id", apiProvider: providerIdentifiers.openrouter, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile, otherProfile]) // The global selection and this view's pin both name surviving profiles: // the deletion must not reconfigure this view's settings, and the // pinned view's nested overlay must survive byte-for-byte. await provider.contextProxy.setValue("currentApiConfigName", "other-profile") provider["viewLocalState"].currentApiConfigName = "keeper-profile" provider["viewLocalState"].apiConfiguration = { apiProvider: providerIdentifiers.anthropic, apiKey: "pinned-profile-secret", } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getProfile: vi.fn().mockResolvedValue({ name: "other-profile", id: "other-id", apiProvider: providerIdentifiers.openrouter, }), deleteConfig: vi.fn().mockResolvedValue(undefined), // The delete compensation snapshots the manager gate (its selection and mode map) before // committing; this double reports a gate the deletion never moved, so the gated restore // legs stay inert here. getSelectionAndModeConfigs: vi .fn() .mockResolvedValue({ currentApiConfigName: "default", modeApiConfigs: {} }), } const setProviderSettingsSpy = vi .spyOn(provider.contextProxy, "setProviderSettings") .mockResolvedValue(undefined) await provider.deleteProviderProfile(oldProfile) // No reconfiguration: the guard must stay false when neither the global // selection nor the view pin names the deleted profile, so the view // keeps its own pin and its nested overlay while the shared store // reports the global selection. expect(setProviderSettingsSpy).not.toHaveBeenCalled() expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("other-profile") expect(provider.getValues().currentApiConfigName).toBe("keeper-profile") expect(provider["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic, apiKey: "pinned-profile-secret", }) await provider.dispose() }) it("prunes the stale list entry and re-points the pin when the secret is already gone", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "old-profile") await provider.contextProxy.setValue("viewStates", { "pinning-view": { currentApiConfigName: "old-profile", updatedAt: Date.now() }, }) // @ts-ignore - Replace providerSettingsManager with a double whose deletion // reports the secret as already gone: an idempotent no-op that must still prune // the stale list entry and re-point the pin. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, deleteConfig: vi.fn().mockRejectedValue(new ProviderSettingsNotFoundError("missing")), activateProfile: vi.fn().mockResolvedValue(keeperProfile), listConfig: vi.fn().mockResolvedValue([keeperProfile]), setModeConfig: vi.fn(), // The settled delete classifies record absence with hasConfig rather than by // message text, snapshots the manager's own selection/mode gate before the // delete commits, and restores through saveConfig, so the double answers all // three reads. getProfile: vi.fn().mockRejectedValue(new Error("profile not found")), hasConfig: vi.fn().mockResolvedValue(false), getSelectionAndModeConfigs: vi.fn().mockResolvedValue({ currentApiConfigName: undefined, modeApiConfigs: {}, }), saveConfig: vi.fn().mockResolvedValue("old-id"), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) await provider["setViewStateId"]("pinning-view") expect(provider["viewLocalState"].currentApiConfigName).toBe("old-profile") await provider.deleteProviderProfile(oldProfile) // The not-found rejection is an idempotent success: the compensating writes run, // and the log records that the stale list entry was pruned only. expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("keeper-profile") expect(provider.contextProxy.getValue("listApiConfigMeta")).toEqual([keeperProfile]) expect(mockContext.globalState.get("viewStates")).toMatchObject({ "pinning-view": { currentApiConfigName: "keeper-profile" }, }) expect(mockOutputChannel.appendLine).toHaveBeenCalledWith(expect.stringContaining("not found")) await provider.dispose() }) it("leaves the durable pin and the shared list untouched when the settings deletion fails", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "old-profile") // Persist this view's pin under the profile being deleted so a failed deletion // must leave it intact. await provider.contextProxy.setValue("viewStates", { "pinning-view": { currentApiConfigName: "old-profile", updatedAt: Date.now() }, }) // @ts-ignore - Replace providerSettingsManager with a double whose deletion fails. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, deleteConfig: vi.fn().mockRejectedValue(new Error("storage down")), activateProfile: vi.fn().mockResolvedValue(keeperProfile), listConfig: vi.fn().mockResolvedValue([keeperProfile]), setModeConfig: vi.fn(), // Same settled delete reads as above: the record is present here, so the // classification read never runs and the gate snapshot resolves. getProfile: vi.fn().mockResolvedValue(oldProfile), hasConfig: vi.fn().mockResolvedValue(true), getSelectionAndModeConfigs: vi.fn().mockResolvedValue({ currentApiConfigName: undefined, modeApiConfigs: {}, }), saveConfig: vi.fn().mockResolvedValue("old-id"), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) await provider["setViewStateId"]("pinning-view") expect(provider["viewLocalState"].currentApiConfigName).toBe("old-profile") await expect(provider.deleteProviderProfile(oldProfile)).rejects.toThrow("storage down") // The deletion rejected, so no compensating write may have landed: the durable // pin still names the profile that still exists, the shared list is intact, and // the shared selection is untouched. expect(mockContext.globalState.get("viewStates")).toMatchObject({ "pinning-view": { currentApiConfigName: "old-profile" }, }) expect(provider.contextProxy.getValue("listApiConfigMeta")).toEqual([oldProfile, keeperProfile]) expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile") await provider.dispose() }) it("should keep an unrelated view-local pin when the shared selection points at the deleted profile", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const deletedProfile: ProviderSettingsEntry = { name: "shared-victim", id: "victim-id", apiProvider: providerIdentifiers.openrouter, } const replacementProfile: ProviderSettingsEntry = { name: "replacement-profile", id: "replacement-id", apiProvider: providerIdentifiers.anthropic, } const pinnedProfile: ProviderSettingsEntry = { name: "view-pin", id: "pin-id", apiProvider: providerIdentifiers.zai, } // The shared selection points at the profile being deleted while this view pins // an unrelated profile that must survive the deletion. await provider.contextProxy.setValue("listApiConfigMeta", [ deletedProfile, replacementProfile, pinnedProfile, ]) await provider.contextProxy.setValue("currentApiConfigName", "shared-victim") // Persist this view's pin through the durable map so the load applies it to the // buffer without touching the shared slot. await provider.contextProxy.setValue("viewStates", { "pinning-view": { currentApiConfigName: "view-pin", updatedAt: Date.now() }, }) // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, deleteConfig: vi.fn().mockResolvedValue(undefined), activateProfile: vi.fn().mockResolvedValue(replacementProfile), listConfig: vi.fn().mockResolvedValue([replacementProfile, pinnedProfile]), setModeConfig: vi.fn(), getProfile: vi.fn().mockResolvedValue(pinnedProfile), // The settled delete also snapshots the manager's selection/mode gate before // committing and can restore through saveConfig; the double answers both. hasConfig: vi.fn().mockResolvedValue(true), getSelectionAndModeConfigs: vi.fn().mockResolvedValue({ currentApiConfigName: undefined, modeApiConfigs: {}, }), saveConfig: vi.fn().mockResolvedValue("victim-id"), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) await provider["setViewStateId"]("pinning-view") expect(provider["viewLocalState"].currentApiConfigName).toBe("view-pin") await provider.deleteProviderProfile(deletedProfile) // The pin survives in the buffer: the deletion must not route through the // replacement activation for an unrelated view pin. The shared slot is // repaired to the replacement so sibling views stop reading the deleted // name, while this view's buffer keeps its pin. expect(provider.getValues().currentApiConfigName).toBe("view-pin") expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("replacement-profile") // The shared list sync drops the deleted entry. expect(provider.contextProxy.getValue("listApiConfigMeta")).toEqual([replacementProfile, pinnedProfile]) await provider.dispose() }) }) // The two deletions an unpinned view can meet, measured separately rather than averaged. // This one removes a profile the shared selection does not name, so nothing this view // resolves through disappears; the deletion still hands the view the selection through // activation, and the durable record gains a pin the view never authored. it("anchors a view with no pin of its own on the shared selection when an unrelated profile is deleted", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile") await provider.contextProxy.setProviderSettings({ apiProvider: providerIdentifiers.anthropic, apiKey: "keeper-shared", }) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) const keeperSettings = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const activateProfile = vi.fn().mockResolvedValue(keeperSettings) // @ts-ignore - Replace the manager with a structural double for this deletion. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, activateProfile, listConfig: vi.fn().mockResolvedValue([keeperProfile]), setModeConfig: vi.fn(), deleteConfig: vi.fn().mockResolvedValue(undefined), getProfile: vi .fn() .mockImplementation(async ({ name }: { name: string }) => name === "keeper-profile" ? keeperSettings : { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter }, ), hasConfig: vi.fn().mockResolvedValue(false), getSelectionAndModeConfigs: vi.fn().mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }), } await provider.deleteProviderProfile(oldProfile) const served = await provider.getState({ includeTaskHistory: false }) // Measured on the current head: the deletion still takes the activation path here, so the // view comes back anchored to the selection it was following. What it serves is unchanged - // the shared store already held that profile's settings - but the pin is new. The case // below isolates the deletion the activation path is actually for. expect(activateProfile).toHaveBeenCalledWith({ name: "keeper-profile" }) expect(provider.pinnedProfileName).toBe("keeper-profile") expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("keeper-profile") expect(served.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) expect(served.currentApiConfigName).toBe("keeper-profile") await provider.dispose() }) // The matching leg for the same unpinned view: when the deleted profile is the shared // selection this view resolves through, the replacement must be activated for it - the // shared store still carries the deleted profile's settings until this path replaces // them. Measured identical before and after the tightened condition below. it("activates the replacement for a view with no pin when the deleted profile is the shared selection", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const oldProfile: ProviderSettingsEntry = { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter, } const keeperProfile: ProviderSettingsEntry = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } await provider.contextProxy.setValue("listApiConfigMeta", [oldProfile, keeperProfile]) await provider.contextProxy.setValue("currentApiConfigName", "old-profile") await provider.contextProxy.setProviderSettings({ apiProvider: providerIdentifiers.openrouter, apiKey: "old-shared", }) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) const keeperSettings = { name: "keeper-profile", id: "keeper-id", apiProvider: providerIdentifiers.anthropic, } const activateProfile = vi.fn().mockResolvedValue(keeperSettings) // @ts-ignore - Replace the manager with a structural double for this deletion. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, activateProfile, listConfig: vi.fn().mockResolvedValue([keeperProfile]), setModeConfig: vi.fn(), deleteConfig: vi.fn().mockResolvedValue(undefined), getProfile: vi .fn() .mockImplementation(async ({ name }: { name: string }) => name === "keeper-profile" ? keeperSettings : { name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.openrouter }, ), hasConfig: vi.fn().mockResolvedValue(false), getSelectionAndModeConfigs: vi.fn().mockResolvedValue({ currentApiConfigName: "keeper-profile", modeApiConfigs: {}, }), } await provider.deleteProviderProfile(oldProfile) const served = await provider.getState({ includeTaskHistory: false }) expect(activateProfile).toHaveBeenCalledWith({ name: "keeper-profile" }) expect(provider.pinnedProfileName).toBe("keeper-profile") expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("keeper-profile") expect(served.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) await provider.dispose() }) describe("local state isolation", () => { it("should isolate mode state between instances", async () => { const provider1 = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const provider2 = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider2.saveViewState("mode", "debugger") await provider1.saveViewState("mode", "architect") const state1 = await provider1.getState() const state2 = await provider2.getState() expect(state1.mode).toBe("architect") expect(state2.mode).toBe("debugger") await provider1.dispose() await provider2.dispose() }) it("should isolate currentApiConfigName between instances", async () => { const provider1 = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const provider2 = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const saveViewState1 = provider1.saveViewState.bind(provider1) const saveViewState2 = provider2.saveViewState.bind(provider2) await saveViewState1("currentApiConfigName", "profile-a") await saveViewState2("currentApiConfigName", "profile-b") const state1 = await provider1.getState() const state2 = await provider2.getState() expect(state1.currentApiConfigName).toBe("profile-a") expect(state2.currentApiConfigName).toBe("profile-b") await provider1.dispose() await provider2.dispose() }) }) describe("getState merging", () => { it("should merge viewLocalState on top of global state", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Initially, getState should return values from contextProxy (global state) let state = await provider.getState() expect(state.mode).toBe("code") // After saveViewState, viewLocalState should take precedence await provider.saveViewState("mode", "architect") state = await provider.getState() expect(state.mode).toBe("architect") await provider.dispose() }) it("should preserve global state values not overridden by viewLocalState", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.saveViewState("mode", "architect") const state = await provider.getState() // mode should come from viewLocalState expect(state.mode).toBe("architect") // Other values should still come from global state / contextProxy: the fixture's // vscode.env.language is "en" and no custom modes are persisted. expect(state.language).toBe("en") expect(state.customModes).toEqual([]) await provider.dispose() }) it("should let viewLocalState apiConfiguration override provider settings", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "local-key", }) const state = await provider.getState() expect(state.apiConfiguration.apiProvider).toBe("openrouter") expect(state.apiConfiguration.openRouterApiKey).toBe("local-key") await provider.dispose() }) it("reports the fresh global apiConfiguration after a profile activation followed by a global settings write", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const savedForReadBack3: Record> = {} // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, saveConfig: vi.fn(async (name: string, settings: Record) => { savedForReadBack3[name] = settings return "activated-id" }), getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: "activated-id", ...savedForReadBack3[name], })), listConfig: vi .fn() .mockResolvedValue([ { name: "activated-profile", id: "activated-id", apiProvider: providerIdentifiers.anthropic }, ]), setModeConfig: vi.fn().mockResolvedValue(undefined), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) await provider.upsertProviderProfile( "activated-profile", { apiProvider: providerIdentifiers.anthropic }, true, ) // Simulate api.setConfiguration (src/extension/api.ts): a global-only // write that does not refresh the view-local buffer. await provider.contextProxy.setValues({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", }) const state = await provider.getState({ includeTaskHistory: false }) // The fresh global selection must win: the activation's buffer write must // not mask the later shared update (regression guard for the e2e // provider-probe suites, which start tasks after a profile activation). expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.openrouter) await provider.dispose() }) it("clears this view's buffered apiConfiguration when activating a different profile", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Seed the per-view buffer with profile A's settings, as loadViewState would // after a restart with a pinned profile. await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "profile-a-key", }) const savedForReadBack4: Record> = {} // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, saveConfig: vi.fn(async (name: string, settings: Record) => { savedForReadBack4[name] = settings return "profile-b-id" }), getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: "profile-b-id", ...savedForReadBack4[name], })), listConfig: vi .fn() .mockResolvedValue([ { name: "profile-b", id: "profile-b-id", apiProvider: providerIdentifiers.anthropic }, ]), setModeConfig: vi.fn().mockResolvedValue(undefined), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) await provider.upsertProviderProfile("profile-b", { apiProvider: providerIdentifiers.anthropic }, true) const state = await provider.getState({ includeTaskHistory: false }) // Activating profile B must clear profile A's buffered overlay so the shared // settings (written by setProviderSettings) win; otherwise getState would // report profile B's name with profile A's provider. expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) await provider.dispose() }) it("restores the cached viewStates map when a persisted view-state write fails durably", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("stable-sidebar-view") await provider.contextProxy.setValue("viewStates", { "other-view": { mode: "code", updatedAt: 1 }, }) // The next durable write fails; the cache was already updated optimistically. const updateSpy = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { throw new Error("durable write failed") }) await expect(provider["savePersistedViewState"]({ mode: "architect", updatedAt: 2 })).rejects.toThrow( "durable write failed", ) // The in-memory cache must match durable storage: an entry that never // reached disk cannot stay visible through getValue. expect(provider.contextProxy.getValue("viewStates")).toEqual({ "other-view": { mode: "code", updatedAt: 1 }, }) updateSpy.mockRestore() await provider.dispose() }) it("restores the cached viewStates map when a re-key write fails durably", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Seed a pre-launch entry under the temporary id through the real write // path, so the re-key has a real entry to move and this instance authored it. await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) // The re-key's durable write fails; the cache was already updated optimistically. const updateSpy = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { throw new Error("durable write failed") }) await expect(provider["rekeyPersistedViewStateEntry"]("stable-sidebar-view")).rejects.toThrow( "durable write failed", ) // The cache must match durable storage: the stable entry never reached disk, // and the retry path depends on the temporary entry still being visible. expect(provider.contextProxy.getValue("viewStates")).toEqual({ [provider.viewId]: { mode: "architect", updatedAt: 1 }, }) // Authorship survives the failure so a later registration can re-key again. expect(provider["wroteUnderTemporaryViewStateId"]).toBe(true) updateSpy.mockRestore() await provider.dispose() }) it("upserts activation writes from the stored normalized record, not the raw payload", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("profile-id") vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true) // The stored record is the normalized shape saveConfig persists: the schema // parse strips the stray cross-provider field and keeps the stored model. vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ id: "profile-id", name: "profile-a", apiProvider: providerIdentifiers.anthropic, apiModelId: "stored-model", }) const setProviderSettingsSpy = vi.spyOn(provider.contextProxy, "setProviderSettings") vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) await provider.upsertProviderProfile("profile-a", { apiProvider: providerIdentifiers.anthropic, apiModelId: "raw-model", openRouterApiKey: "cross-provider-stray", }) // The shared store receives the stored record: the raw payload's stray // cross-provider field must not reach it (or the sibling overlays and // task handler refreshed from the same value). expect(setProviderSettingsSpy).toHaveBeenCalledWith({ apiProvider: providerIdentifiers.anthropic, apiModelId: "stored-model", }) await provider.dispose() }) it("restores the cached viewStates map when a clear write fails durably", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("stable-sidebar-view") await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) // The clear's durable write fails; the cache was already updated optimistically. const updateSpy = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { throw new Error("durable write failed") }) await expect(provider["clearPersistedViewState"]()).rejects.toThrow("durable write failed") // The cache must match durable storage: the entry was never removed on // disk, so it must stay visible through getValue. expect(provider.contextProxy.getValue("viewStates")).toEqual({ "stable-sidebar-view": { mode: "architect", updatedAt: 1 }, }) updateSpy.mockRestore() await provider.dispose() }) it("restores the cached viewStates map when a persisted re-point write fails durably", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.contextProxy.setValue("viewStates", { "stable-sidebar-view": { currentApiConfigName: "profile-old", updatedAt: 1 }, "other-view": { mode: "code", currentApiConfigName: "profile-keep", updatedAt: 2 }, }) // The re-point's durable write fails; the cache was already updated optimistically. const updateSpy = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => { throw new Error("durable write failed") }) await expect(provider["repointPersistedViewStates"]("profile-old", "profile-new")).rejects.toThrow( "durable write failed", ) // The cache must match durable storage: the re-pointed pins never reached disk, // so the pre-re-point map must stay visible. expect(provider.contextProxy.getValue("viewStates")).toEqual({ "stable-sidebar-view": { currentApiConfigName: "profile-old", updatedAt: 1 }, "other-view": { mode: "code", currentApiConfigName: "profile-keep", updatedAt: 2 }, }) updateSpy.mockRestore() await provider.dispose() }) it("re-points live views pinned to a renamed profile onto the new name", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("stable-sidebar-view") await provider.saveViewState("currentApiConfigName", "profile-old") await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "old-key", }) await provider["repointViewLocalStateAfterProfileRename"]("profile-old", "profile-new", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "renamed-key", }) expect(provider["viewLocalState"].currentApiConfigName).toBe("profile-new") expect(provider["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "renamed-key", }) const viewStates = mockContext.globalState.get("viewStates") as Record> expect(viewStates["stable-sidebar-view"].currentApiConfigName).toBe("profile-new") await provider.dispose() }) it("keeps the applied profile mutation when a sibling's state post fails", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const postError = new Error("sibling post failed") const sibling = { viewId: "sibling-view", pinnedProfileName: "profile-new", _saveViewLocalStateFromMutation: vi.fn().mockResolvedValue(undefined), getCurrentTask: vi.fn().mockReturnValue(undefined), postStateToWebview: vi.fn().mockRejectedValue(postError), } const logSpy = vi.spyOn(provider, "log") const instancesSpy = vi .spyOn(ClineProvider, "getAllInstances") .mockReturnValue([provider, sibling] as unknown as ClineProvider[]) try { // A sibling whose UI refresh fails must not reject the applied mutation; the // failure is logged and the remaining siblings still refresh. await expect( provider["refreshViewLocalStateForUpdatedProfile"]("profile-new", { apiProvider: providerIdentifiers.openrouter, }), ).resolves.toBeUndefined() expect(sibling._saveViewLocalStateFromMutation).toHaveBeenCalledOnce() expect(logSpy).toHaveBeenCalledWith( expect.stringContaining("failed to post state to sibling view sibling-view"), ) } finally { instancesSpy.mockRestore() logSpy.mockRestore() } await provider.dispose() }) it("re-points persisted pins of closed views onto the renamed profile", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // A closed view's durable pin names the profile about to be renamed; no // live instance carries it, so only the persisted map can repair it. await provider.contextProxy.setValue("viewStates", { "closed-view": { currentApiConfigName: "profile-old", mode: "code", updatedAt: 1 }, }) await provider["setViewStateId"]("stable-sidebar-view") await provider.saveViewState("currentApiConfigName", "profile-old") await provider["repointViewLocalStateAfterProfileRename"]("profile-old", "profile-new", { apiProvider: providerIdentifiers.openrouter, }) const viewStates = mockContext.globalState.get("viewStates") as Record> // The closed view must launch onto the renamed profile instead of dangling at // the deleted name and being repaired to whatever the shared selection became // in the meantime. expect(viewStates["closed-view"].currentApiConfigName).toBe("profile-new") expect(viewStates["stable-sidebar-view"].currentApiConfigName).toBe("profile-new") await provider.dispose() }) it("clears this view's buffered apiConfiguration when directly activating a profile", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Seed the per-view buffer with profile A's settings, as loadViewState would // after a restart with a pinned profile. await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "profile-a-key", }) // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, activateProfile: vi.fn().mockResolvedValue({ name: "profile-b", id: "profile-b-id", apiProvider: providerIdentifiers.anthropic, }), listConfig: vi .fn() .mockResolvedValue([ { name: "profile-b", id: "profile-b-id", apiProvider: providerIdentifiers.anthropic }, ]), setModeConfig: vi.fn().mockResolvedValue(undefined), } vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // The direct-activation path (activateProviderProfileUnlocked) carries its own // overlay-clearing call, distinct from upsertProviderProfile's. await provider.activateProviderProfile({ name: "profile-b" }) const state = await provider.getState({ includeTaskHistory: false }) expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) await provider.dispose() }) it("should merge getValues from ContextProxy with view-local values taking precedence", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const contextProxyAccess = provider.contextProxy as { setValues: (values: Partial) => Promise } await contextProxyAccess.setValues({ mode: "debugger", currentApiConfigName: "shared-profile", apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "shared-key", }, customModePrompts: { code: { roleDefinition: "shared" } }, }) await provider.saveViewState("mode", "architect") await provider.saveViewState("currentApiConfigName", "view-profile") await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "view-key", }) const values = provider.getValues() expect(values.mode).toBe("architect") expect(values.currentApiConfigName).toBe("view-profile") expect(values.apiConfiguration).toEqual({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "view-key", }) expect(values.customModePrompts).toEqual({ code: { roleDefinition: "shared" } }) await provider.dispose() }) it("should keep flat provider settings out of the view-local buffer", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "openrouter/old-model", }) await provider.setValues({ apiProvider: providerIdentifiers.bedrock, awsUseApiKey: true, awsApiKey: "mock-key", awsRegion: "us-east-1", apiModelId: "anthropic.claude-opus-4-8-20261215-v1:0", awsBedrockEndpoint: "http://127.0.0.1:4567", awsBedrockEndpointEnabled: true, }) // Flat provider-settings keys are shared settings: they must flow through // the ContextProxy only and must not be merged into the view-local buffer, // which would turn them into a per-view override masking later shared // updates from other views. The pre-existing overlay is older than this // shared write, so the flat write drops it instead of being masked by it. expect(provider["viewLocalState"].apiConfiguration).toBeUndefined() expect(provider.contextProxy.getValue("apiProvider")).toBe(providerIdentifiers.bedrock) expect(provider.contextProxy.getValue("awsBedrockEndpoint")).toBe("http://127.0.0.1:4567") await provider.dispose() }) it("drops the view-local apiConfiguration overlay when setValues receives flat provider settings", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "view-key", }) await provider.setValues({ apiProvider: providerIdentifiers.anthropic, apiKey: "flat-key" }) // The overlay is removed, not merely out-shadowed: the merged read serves this view's // flat write and carries no per-view apiConfiguration left behind, so a later shared // update from another view cannot be hidden behind an older copy of this view's own. expect(provider["viewLocalState"].apiConfiguration).toBeUndefined() expect(provider.getValues().apiConfiguration).toBeUndefined() expect(provider.getValues().apiProvider).toBe(providerIdentifiers.anthropic) expect(provider.getValues().apiKey).toBe("flat-key") await provider.dispose() }) it("pins a sibling's overlay before a flat provider write in setValues", async () => { const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await sibling["setViewStateId"]("flat-write-view") await sibling.saveViewState("currentApiConfigName", "pinned-profile") const siblingPostSpy = vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ name: "pinned-profile", id: "pinned-id", apiProvider: providerIdentifiers.openrouter, apiKey: "pinned-key", }) await provider.setValues({ apiProvider: providerIdentifiers.anthropic, apiKey: "caller-key" }) // The sibling keeps serving its own profile's credentials instead of // reading the caller's flat write back from the shared store. expect(sibling["viewLocalState"].apiConfiguration).toMatchObject({ apiProvider: providerIdentifiers.openrouter, apiKey: "pinned-key", }) expect(siblingPostSpy).toHaveBeenCalled() await sibling.dispose() await provider.dispose() }) it("refreshes siblings pinned to the profile a setValues payload saves", async () => { const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await sibling["setViewStateId"]("saved-profile-view") await sibling.saveViewState("currentApiConfigName", "saved-profile") await sibling.saveViewState("apiConfiguration", { apiProvider: providerIdentifiers.anthropic, apiKey: "stale-key", }) const siblingPostSpy = vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.setValues( { apiProvider: providerIdentifiers.anthropic, apiKey: "fresh-key" }, { savedProfileName: "saved-profile" }, ) // The payload saves the sibling's own profile: the sibling serves the // fresh copy rather than a snapshot of the pre-save settings. expect(sibling["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic, apiKey: "fresh-key", }) expect(siblingPostSpy).toHaveBeenCalled() await sibling.dispose() await provider.dispose() }) }) it("drops the sibling overlay snapshot when the sibling re-pins before the commit", async () => { const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await sibling["setViewStateId"]("repin-view") await sibling.saveViewState("currentApiConfigName", "pinned-profile") vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) vi.spyOn(sibling.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "other-profile", apiProvider: providerIdentifiers.anthropic, }) vi.spyOn(sibling.providerSettingsManager, "listConfig").mockResolvedValue([]) vi.spyOn(sibling.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) vi.spyOn(sibling.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) // The sibling activates a different profile while the snapshot's profile // read is in flight: the captured overlay must not land on the new pin. let flipped = false vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async () => { const settings = { name: "pinned-profile", id: "pinned-id", apiProvider: providerIdentifiers.openrouter, apiKey: "pinned-key", } if (!flipped) { flipped = true await sibling.activateProviderProfile({ name: "other-profile" }) } return settings }) await provider.setValues({ apiProvider: providerIdentifiers.anthropic, apiKey: "caller-key" }) // The commit-time pin re-check skipped the stale snapshot: the sibling // keeps serving the profile it activated, not the captured overlay. expect(sibling["viewLocalState"].apiConfiguration).toBeUndefined() expect(sibling["pinnedProfileName"]).toBe("other-profile") await sibling.dispose() await provider.dispose() }) describe("persisted view state", () => { it("should persist setValue mutations for view-local mode", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("stable-sidebar-view") await provider.setValue("mode", "architect") expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ "stable-sidebar-view": { mode: "architect" }, }) await provider.dispose() }) it("should persist setValues mutations for view-local API profile", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("stable-sidebar-view") await provider.setValues({ currentApiConfigName: "profile-from-set-values" }) expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ "stable-sidebar-view": { currentApiConfigName: "profile-from-set-values" }, }) await provider.dispose() }) it("should drop an unknown mode from setValues while keeping valid modes", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // This file's getModeBySlug mock resolves every slug. Stand in the production lookup instead, // so "not-a-real-mode" is rejected because no mode definition names it and "architect" is // accepted because a built-in does. const actualModes = await vi.importActual("../../../shared/modes") const modesModule = vi.mocked(await import("../../../shared/modes")) const originalMode = modesModule.getModeBySlug("code") modesModule.getModeBySlug.mockImplementation(actualModes.getModeBySlug) try { await provider.setValues({ mode: "not-a-real-mode" }) expect(provider.contextProxy.getValue("mode")).toBeUndefined() expect(provider["viewLocalState"].mode).toBeUndefined() await provider.setValues({ mode: "architect" }) expect(provider.contextProxy.getValue("mode")).toBe("architect") expect(provider["viewLocalState"].mode).toBe("architect") } finally { modesModule.getModeBySlug.mockReturnValue(originalMode) } await provider.dispose() }) it("should keep a mode whose custom definition arrives in the same setValues payload", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // createTask and setConfiguration call setValues(configuration) before // registering configuration.customModes: the payload's own modes must count // as valid even though the manager has not registered them yet. vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) // The production lookup already prefers the custom modes it is handed over the built-ins, so // the payload's own mode definitions are what make "new-mode" valid here. const actualModes = await vi.importActual("../../../shared/modes") const modesModule = vi.mocked(await import("../../../shared/modes")) const originalMode = modesModule.getModeBySlug("code") modesModule.getModeBySlug.mockImplementation(actualModes.getModeBySlug) try { await provider.setValues({ customModes: [{ slug: "new-mode", name: "New Mode", roleDefinition: "test", groups: ["read"] }], mode: "new-mode", }) expect(provider.contextProxy.getValue("mode")).toBe("new-mode") expect(provider["viewLocalState"].mode).toBe("new-mode") } finally { modesModule.getModeBySlug.mockReturnValue(originalMode) } await provider.dispose() }) it("restores the previous mode when custom-mode registration fails during createTask", async () => { await provider.setValues({ mode: "architect" }) // setValues mirrors the write into the view buffer; drop it so this case // models a view that never pinned a mode of its own. delete provider["viewLocalState"].mode provider["customModesManager"].updateCustomMode = vi.fn().mockRejectedValue(new Error("registration down")) await expect( provider.createTask( undefined, undefined, undefined, {}, { mode: "reviewer", customModes: [ { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, ], }, ), ).rejects.toThrow("registration down") // The payload's mode reached shared + per-view state through setValues // before registration failed; the failure path must roll both back. expect(provider.getValues().mode).toBe("architect") // The view had no pin before, and an unset pin must stay unset rather // than becoming an explicit copy of the shared value. expect(provider["viewLocalState"].mode).toBeUndefined() }) it("restores the view's own mode pin separately when custom-mode registration fails", async () => { await provider.setValues({ mode: "code" }) provider["viewLocalState"].mode = "architect" provider["customModesManager"].updateCustomMode = vi.fn().mockRejectedValue(new Error("registration down")) await expect( provider.createTask( undefined, undefined, undefined, {}, { mode: "reviewer", customModes: [ { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, ], }, ), ).rejects.toThrow("registration down") // Shared and per-view selections roll back to their own prior values: // the view keeps its architect pin, the shared store keeps code. expect(provider["viewLocalState"].mode).toBe("architect") expect(provider.contextProxy.getValue("mode")).toBe("code") expect(provider.getValues().mode).toBe("architect") }) it("restores the mode pin the settings write itself found, not the one read before validation", async () => { // While setValues awaits the custom-mode lookup, this same view switches its own selection, // so the value read before the wait is no longer the value the write replaced. The rollback // must follow the write, not the earlier read. await provider["setViewStateId"]("stable-write-time-view") await provider.setValues({ mode: "code" }) let releaseValidation!: () => void const validationGate = new Promise((resolve) => { releaseValidation = resolve }) const getCustomModesSpy = vi .spyOn(provider.customModesManager, "getCustomModes") .mockImplementation(async () => { await validationGate return [] }) const originalUpdateCustomMode = provider["customModesManager"].updateCustomMode let releaseRegistration!: () => void const registrationGate = new Promise((resolve) => { releaseRegistration = resolve }) const updateCustomModeStub = vi.fn().mockImplementation(async () => { await registrationGate throw new Error("registration down") }) provider["customModesManager"].updateCustomMode = updateCustomModeStub const persistedMode = (viewStateId: string): string | undefined => (provider.contextProxy.getValue("viewStates") as Record)[ viewStateId ]?.mode // Declared before the try so the finally can name and settle this creation, the // promise 861 says teardown must not leave waiting. let creation: Promise | undefined try { creation = provider.createTask( undefined, undefined, undefined, {}, { mode: "reviewer", customModes: [ { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, ], }, ) // Subscribe to the rejection before driving the rest of the scenario: the failure surfaces // while this test is still moving state around. const creationResult = expect(creation).rejects.toThrow("registration down") // Window witness: the validation lookup is in flight and the write has not run yet, so both // layers still hold the values seeded above. for (let spun = 0; spun < 20 && getCustomModesSpy.mock.calls.length === 0; spun++) { await new Promise((resolve) => setTimeout(resolve, 0)) } expect(getCustomModesSpy.mock.calls.length).toBeGreaterThan(0) expect(provider["viewLocalState"].mode).toBe("code") expect(provider.contextProxy.getValue("mode")).toBe("code") await provider.contextProxy.setValue("mode", "debug") await provider.saveViewState("mode", "debug") releaseValidation() // Write-decision witness: registration is attempted only after setValues returned, so both // layers hold the payload mode by now - this write group carried reviewer into shared // storage and into this view's durable record. Without these pins the assertions below // cannot tell "wrote reviewer, then rolled back to this view's debug choice" from "the // mode was never written at all": both paths end in the same final state. for (let spun = 0; spun < 40 && updateCustomModeStub.mock.calls.length === 0; spun++) { await new Promise((resolve) => setTimeout(resolve, 0)) } expect(updateCustomModeStub.mock.calls.length).toBeGreaterThan(0) expect(provider.contextProxy.getValue("mode")).toBe("reviewer") expect(persistedMode("stable-write-time-view")).toBe("reviewer") releaseRegistration() await creationResult // Both layers roll back to what the write group itself found: the debug selection this view // made while validation waited. Restoring the pre-validation read (code) would undo that // selection, mask it in getValues(), and survive a reload. expect(provider["viewLocalState"].mode).toBe("debug") expect(provider.contextProxy.getValue("mode")).toBe("debug") expect(provider.getValues().mode).toBe("debug") expect(persistedMode("stable-write-time-view")).toBe("debug") } finally { // The finally releases both gates and settles the creation before restoring the // stubs: with only the restores below, a failed check leaves the stub chain // waiting on a gate forever - 861's window. Paired failure-path runs // (scratch/1565f-w6-instr2-*) carry how that dangling shows up. releaseValidation() releaseRegistration() await creation?.catch(() => {}) await ClineProvider["persistedViewStateWriteQueue"] provider["customModesManager"].updateCustomMode = originalUpdateCustomMode getCustomModesSpy.mockRestore() } }) it("keeps a mode pin this view acquired while the settings write awaited validation", async () => { // The opposite polarity of the same bug: the view had no pin at all when createTask read the // layers, and picked one up while setValues awaited the mode lookup. Restoring the earlier // read would clear a pin that legitimately appeared during the wait. await provider["setViewStateId"]("stable-acquired-pin-view") await provider.contextProxy.setValue("mode", "code") expect(provider["viewLocalState"].mode).toBeUndefined() let releaseValidation!: () => void const validationGate = new Promise((resolve) => { releaseValidation = resolve }) const getCustomModesSpy = vi .spyOn(provider.customModesManager, "getCustomModes") .mockImplementation(async () => { await validationGate return [] }) const originalUpdateCustomMode = provider["customModesManager"].updateCustomMode let releaseRegistration!: () => void const registrationGate = new Promise((resolve) => { releaseRegistration = resolve }) const updateCustomModeStub = vi.fn().mockImplementation(async () => { await registrationGate throw new Error("registration down") }) provider["customModesManager"].updateCustomMode = updateCustomModeStub const persistedMode = (viewStateId: string): string | undefined => (provider.contextProxy.getValue("viewStates") as Record)[ viewStateId ]?.mode // Declared before the try so the finally can name and settle this creation, the // promise 861 says teardown must not leave waiting. let creation: Promise | undefined try { creation = provider.createTask( undefined, undefined, undefined, {}, { mode: "reviewer", customModes: [ { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, ], }, ) const creationResult = expect(creation).rejects.toThrow("registration down") // Window witness: the validation lookup is in flight and the write has not run yet. for (let spun = 0; spun < 20 && getCustomModesSpy.mock.calls.length === 0; spun++) { await new Promise((resolve) => setTimeout(resolve, 0)) } // The lookup has been entered and the gate is still held, so no write has run yet. expect(getCustomModesSpy.mock.calls.length).toBeGreaterThan(0) expect(provider["viewLocalState"].mode).toBeUndefined() expect(provider.contextProxy.getValue("mode")).toBe("code") // The view chooses its own mode while validation waits. await provider.saveViewState("mode", "debug") releaseValidation() // Write-decision witness: the payload mode reached both layers before registration failed, // so the debug pin restored below is the value this write group found - not the only // value this view ever held. Without these pins the cell cannot tell "wrote reviewer, then // rolled back to debug" from "never wrote the mode at all": both end in the same state. for (let spun = 0; spun < 40 && updateCustomModeStub.mock.calls.length === 0; spun++) { await new Promise((resolve) => setTimeout(resolve, 0)) } expect(updateCustomModeStub.mock.calls.length).toBeGreaterThan(0) expect(provider.contextProxy.getValue("mode")).toBe("reviewer") expect(persistedMode("stable-acquired-pin-view")).toBe("reviewer") releaseRegistration() await creationResult // The per-view layer goes back to the pin the write group found - the debug choice - not to // the unset state read before validation. The shared layer keeps its own snapshot (code), // because the two layers are restored from their own reports. expect(provider["viewLocalState"].mode).toBe("debug") expect(persistedMode("stable-acquired-pin-view")).toBe("debug") expect(provider.contextProxy.getValue("mode")).toBe("code") } finally { // The finally releases both gates and settles the creation before restoring the // stubs: with only the restores below, a failed check leaves the stub chain // waiting on a gate forever - 861's window. Paired failure-path runs // (scratch/1565f-w6-instr2-*) carry how that dangling shows up. releaseValidation() releaseRegistration() await creation?.catch(() => {}) await ClineProvider["persistedViewStateWriteQueue"] provider["customModesManager"].updateCustomMode = originalUpdateCustomMode getCustomModesSpy.mockRestore() } }) it("leaves the mode pin unset when the settings write found no earlier pin", async () => { // Positive control: an unset pin is not an owned value. The rollback leaves the view unpinned // instead of writing an explicit copy of the shared value into the view record. await provider["setViewStateId"]("stable-unset-pin-view") await provider.contextProxy.setValue("mode", "code") expect(provider["viewLocalState"].mode).toBeUndefined() let releaseValidation!: () => void const validationGate = new Promise((resolve) => { releaseValidation = resolve }) const getCustomModesSpy = vi .spyOn(provider.customModesManager, "getCustomModes") .mockImplementation(async () => { await validationGate return [] }) const originalUpdateCustomMode = provider["customModesManager"].updateCustomMode let releaseRegistration!: () => void const registrationGate = new Promise((resolve) => { releaseRegistration = resolve }) const updateCustomModeStub = vi.fn().mockImplementation(async () => { await registrationGate throw new Error("registration down") }) provider["customModesManager"].updateCustomMode = updateCustomModeStub const persistedMode = (viewStateId: string): string | undefined => (provider.contextProxy.getValue("viewStates") as Record)[ viewStateId ]?.mode // Declared before the try so the finally can name and settle this creation, the // promise 861 says teardown must not leave waiting. let creation: Promise | undefined try { creation = provider.createTask( undefined, undefined, undefined, {}, { mode: "reviewer", customModes: [ { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, ], }, ) const creationResult = expect(creation).rejects.toThrow("registration down") // Window witness: the validation lookup is in flight and the write has not run yet. for (let spun = 0; spun < 20 && getCustomModesSpy.mock.calls.length === 0; spun++) { await new Promise((resolve) => setTimeout(resolve, 0)) } // The lookup has been entered and the gate is still held, so no write has run yet. expect(getCustomModesSpy.mock.calls.length).toBeGreaterThan(0) expect(provider["viewLocalState"].mode).toBeUndefined() releaseValidation() // Write-decision witness: the payload mode reached shared storage and this view's durable // record before registration failed, so the unset state asserted below is a restore to // "no pin" - evidence the write group owned nothing here - not evidence that the mode // was never written at all. for (let spun = 0; spun < 40 && updateCustomModeStub.mock.calls.length === 0; spun++) { await new Promise((resolve) => setTimeout(resolve, 0)) } expect(updateCustomModeStub.mock.calls.length).toBeGreaterThan(0) expect(provider.contextProxy.getValue("mode")).toBe("reviewer") expect(persistedMode("stable-unset-pin-view")).toBe("reviewer") releaseRegistration() await creationResult expect(provider["viewLocalState"].mode).toBeUndefined() expect(persistedMode("stable-unset-pin-view")).toBeUndefined() expect(provider.contextProxy.getValue("mode")).toBe("code") } finally { // The finally releases both gates and settles the creation before restoring the // stubs: with only the restores below, a failed check leaves the stub chain // waiting on a gate forever - 861's window. Paired failure-path runs // (scratch/1565f-w6-instr2-*) carry how that dangling shows up. releaseValidation() releaseRegistration() await creation?.catch(() => {}) await ClineProvider["persistedViewStateWriteQueue"] provider["customModesManager"].updateCustomMode = originalUpdateCustomMode getCustomModesSpy.mockRestore() } }) it("leaves a mode the layers picked up on their own when validation dropped the payload mode", async () => { // The write group never accepted this payload: validation dropped the unknown slug before // either store was touched, so this call owns no mode in either layer. Meanwhile a path // without mode validation (setValue / saveViewState, as the webview handler uses) wrote that // very slug into both layers. A rollback keyed to the requested value would undo a selection // this call never made. await provider["setViewStateId"]("stable-dropped-mode-view") await provider.setValues({ mode: "code" }) // This file mocks getModeBySlug to accept every slug; stand in the production lookup so // not-a-real-mode is rejected because no mode definition names it. const actualModes = await vi.importActual("../../../shared/modes") const modesModule = vi.mocked(await import("../../../shared/modes")) const originalLookup = modesModule.getModeBySlug("code") modesModule.getModeBySlug.mockImplementation(actualModes.getModeBySlug) let releaseValidation!: () => void const validationGate = new Promise((resolve) => { releaseValidation = resolve }) const getCustomModesSpy = vi .spyOn(provider.customModesManager, "getCustomModes") .mockImplementation(async () => { await validationGate return [] }) const originalUpdateCustomMode = provider["customModesManager"].updateCustomMode provider["customModesManager"].updateCustomMode = vi.fn().mockRejectedValue(new Error("registration down")) // Records what ClineProvider#setValues forwards into shared storage: the createTask payload // is identified by its customModes key, and the check below pins that the forwarded payload // never carried the mode that validation dropped. const setValuesOriginal = provider.contextProxy.setValues.bind(provider.contextProxy) const forwardedPayloads: RooCodeSettings[] = [] const setValuesSpy = vi.spyOn(provider.contextProxy, "setValues").mockImplementation(async (values) => { forwardedPayloads.push({ ...values }) return setValuesOriginal(values) }) const persistedMode = (viewStateId: string): string | undefined => (provider.contextProxy.getValue("viewStates") as Record)[ viewStateId ]?.mode // Declared before the try so the finally can name and settle this creation, the // promise 861 says teardown must not leave waiting. let creation: Promise | undefined try { creation = provider.createTask( undefined, undefined, undefined, {}, { mode: "not-a-real-mode", customModes: [{ slug: "other-mode", name: "Other Mode", roleDefinition: "test", groups: [] }], }, ) const creationResult = expect(creation).rejects.toThrow("registration down") // Window witness: the validation lookup is in flight and the write has not run yet. for (let spun = 0; spun < 20 && getCustomModesSpy.mock.calls.length === 0; spun++) { await new Promise((resolve) => setTimeout(resolve, 0)) } // The lookup has been entered and the gate is still held, so no write has run yet. expect(getCustomModesSpy.mock.calls.length).toBeGreaterThan(0) expect(provider.contextProxy.getValue("mode")).toBe("code") // Another writer puts this payload exact slug into both layers while validation waits. await provider.contextProxy.setValue("mode", "not-a-real-mode") await provider.saveViewState("mode", "not-a-real-mode") releaseValidation() await creationResult // Decision witness: the forwarded write omitted the payload mode - validation dropped // the unknown slug before shared storage was touched - so the surviving value below is // the competing writer's selection, not this call having written the same string and // "restored" it. Without this pin the cell passes even in the world where validation // accepted the slug: the rollback then restores exactly what the competing write // carried, and every other assertion here still holds. const writeGroupPayloads = forwardedPayloads.filter((payload) => "customModes" in payload) expect(writeGroupPayloads.length).toBe(1) expect(Object.prototype.hasOwnProperty.call(writeGroupPayloads[0], "mode")).toBe(false) // Nothing is rolled back: the payload mode never reached either store, so the selection that // landed during the wait survives in the buffer, on disk, and in the merged view. expect(provider.contextProxy.getValue("mode")).toBe("not-a-real-mode") expect(provider["viewLocalState"].mode).toBe("not-a-real-mode") expect(provider.getValues().mode).toBe("not-a-real-mode") expect(persistedMode("stable-dropped-mode-view")).toBe("not-a-real-mode") } finally { // The finally releases the validation gate and settles the creation before // restoring the stubs: with only the restores below, a failed check leaves // the lookup awaiting the gate forever - 861's window. Paired failure-path // runs (scratch/1565f-w6-instr2-*) carry how that dangling shows up. releaseValidation() await creation?.catch(() => {}) await ClineProvider["persistedViewStateWriteQueue"] modesModule.getModeBySlug.mockReturnValue(originalLookup) provider["customModesManager"].updateCustomMode = originalUpdateCustomMode getCustomModesSpy.mockRestore() setValuesSpy.mockRestore() } }) it("should sanitize raw viewStateId before using it as persisted viewStates key", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("tab panel/with.dots and spaces") await provider.setValue("mode", "architect") expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ tab_panel_with_dots_and_spaces: { mode: "architect" }, }) expect(provider.contextProxy.getValue("viewStates")).not.toHaveProperty("tab panel/with.dots and spaces") await provider.dispose() }) it("should persist queued writes under the viewStateId active when the change was made", async () => { // Hold the first *viewStates* write specifically. The constructor writes other // global-state keys synchronously (codebaseIndexModels at ClineProvider.ts:509), // so an unqualified once-only mock is consumed by that write: the viewStates // write then resolves immediately and is never held across the id switch, which // is the in-flight behaviour this test claims to prove. let releaseFirstViewStatesWrite!: () => void let viewStatesWriteHeld = false let markFirstWriteStarted!: () => void const firstWriteStarted = new Promise((resolve) => { markFirstWriteStarted = resolve }) mockContext.globalState.update = vi.fn().mockImplementation((key: string, value: unknown) => { mockContext.globalState.get = vi .fn() .mockImplementation((lookupKey: string) => (lookupKey === key ? value : undefined)) if (key !== "viewStates" || viewStatesWriteHeld) { return Promise.resolve() } viewStatesWriteHeld = true markFirstWriteStarted() return new Promise((writeResolve) => { releaseFirstViewStatesWrite = writeResolve }) }) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("view-a") // The first write is held, so the second one is captured under "view-a" but only // executes after the id switch: that is the interleaving this test names. const heldSave = provider.saveViewState("currentApiConfigName", "cfg-a") await firstWriteStarted const queuedSave = provider.saveViewState("mode", "architect") const idSwitch = provider["setViewStateId"]("view-b") releaseFirstViewStatesWrite() await heldSave await queuedSave await idSwitch // Both writes stay under the id active when each change was made, even though the // second one ran after "view-b" had been registered. expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ "view-a": { mode: "architect", currentApiConfigName: "cfg-a" }, }) expect(provider.contextProxy.getValue("viewStates")).not.toHaveProperty("view-b") await provider.dispose() }) it("should preserve persisted viewStates entry when an editor provider is disposed during teardown", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("tab-to-preserve") await provider.saveViewState("mode", "architect") expect(provider.contextProxy.getValue("viewStates")).toHaveProperty("tab-to-preserve") await provider.dispose() expect(provider.contextProxy.getValue("viewStates")).toHaveProperty("tab-to-preserve") }) it("should read viewStates fresh from storage so out-of-proxy writes are not clobbered", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider["setViewStateId"]("view-a") await provider.saveViewState("mode", "architect") // Simulate a concurrent writer (another view's provider) updating the shared // map directly in storage, bypassing this proxy's cache. const stored = (await mockContext.globalState.get>("viewStates")) ?? {} await mockContext.globalState.update("viewStates", { ...stored, "view-b": { mode: "debug", updatedAt: 1 }, }) await provider.saveViewState("mode", "code") // The serialized write must have merged on top of the fresh storage value, not // on top of this proxy's stale cache. expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ "view-a": { mode: "code" }, "view-b": { mode: "debug" }, }) await provider.dispose() }) it("should re-key durable viewStates entries from the temporary pre-launch view id", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // A change made before the stable id is registered persists under the // temporary id so it is not lost; registration re-keys it to the stable id. await provider.saveViewState("mode", "architect") expect(provider["viewLocalState"].mode).toBe("architect") expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ [provider.viewId]: { mode: "architect" }, }) await provider["setViewStateId"]("stable-sidebar-view") await provider.saveViewState("mode", "debugger") const viewStates = provider.contextProxy.getValue("viewStates") as Record expect(viewStates["stable-sidebar-view"]).toMatchObject({ mode: "debugger" }) expect(viewStates[provider.viewId]).toBeUndefined() await provider.dispose() }) it("should drop the temporary viewStates entry when a stable entry already exists", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // A stable entry already exists (e.g. persisted by an earlier registration); // it must win over this instance's temporary entry. await provider.contextProxy.setValue("viewStates", { "stable-sidebar-view": { mode: "debugger", updatedAt: 2 }, }) // Author the temporary entry through the real write path so this instance // owns it: unowned entries are never re-keyed. await provider.saveViewState("mode", "architect") await provider["setViewStateId"]("stable-sidebar-view") const viewStates = provider.contextProxy.getValue("viewStates") as Record expect(viewStates["stable-sidebar-view"]).toMatchObject({ mode: "debugger" }) expect(viewStates[provider.viewId]).toBeUndefined() expect(provider["viewLocalState"].mode).toBe("debugger") await provider.dispose() }) it("should discard a stale loadViewState when a newer view id is registered during the load", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Seed persisted entries under both ids through the proxy so the loads // observe them via the cached read path: the temporary entry holds a // pre-registration selection, the stable entry the post-registration one. await provider.contextProxy.setValue("viewStates", { [provider.viewId]: { mode: "architect", currentApiConfigName: "ghost-profile", updatedAt: 1 }, "stable-sidebar-view": { mode: "debug", updatedAt: 2 }, }) // Hang the temporary entry's profile lookup so that load is still in flight // when the stable id is registered. let releaseGhost!: () => void const ghostLoad = new Promise((resolve) => { releaseGhost = resolve }) vi.spyOn(provider.providerSettingsManager, "getProfile").mockReturnValue( ghostLoad.then(() => Object.assign({} as Awaited>, { name: "ghost-profile", id: "ghost-id", apiProvider: providerIdentifiers.anthropic, }), ), ) const staleLoad = provider["loadViewState"]() // Register the stable id without awaiting its load: the re-key drops the // temporary entry (the stable one already exists) and the registration's own // load settles on the stable entry immediately. const register = provider["setViewStateId"]("stable-sidebar-view") await register releaseGhost() await staleLoad // The stale (temporary-id) load must not overwrite the stable id's load. expect(provider["viewLocalState"]).toEqual({ mode: "debug" }) await provider.dispose() }) it("deregisters the provider when an early cleanup step throws during dispose", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // The first cleanup step throwing used to skip the deregistration below // it: the provider stayed in activeInstances while _disposed was already // set, so no later retry could repair the registration. The finally now // covers the whole disposal operation. provider["taskScheduler"] = { cancelQueued: vi.fn(() => { throw new Error("early cleanup boom") }), } as unknown as ClineProvider["taskScheduler"] expect(ClineProvider.getAllInstances()).toContain(provider) await expect(provider.dispose()).rejects.toThrow("early cleanup boom") expect(ClineProvider.getAllInstances()).not.toContain(provider) }) it("keeps a newer view pin written during custom-mode registration when rollback runs", async () => { await provider.setValues({ mode: "code" }) provider["viewLocalState"].mode = "code" // Another view moves this view's pin while registration is in flight; // the rollback must not overwrite that newer per-view choice. provider["customModesManager"].updateCustomMode = vi.fn().mockImplementation(async () => { await provider.saveViewState("mode", "architect") throw new Error("registration down") }) await expect( provider.createTask( undefined, undefined, undefined, {}, { mode: "reviewer", customModes: [ { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, ], }, ), ).rejects.toThrow("registration down") // The view layer no longer holds this call's "reviewer", so the rollback // leaves the newer architect pin alone; the shared layer still does and // rolls back to its own prior value. expect(provider["viewLocalState"].mode).toBe("architect") expect(provider.contextProxy.getValue("mode")).toBe("code") }) it("does not touch the shared mode on rollback when the configuration omitted mode", async () => { await provider.setValues({ mode: "code" }) delete provider["viewLocalState"].mode provider["customModesManager"].updateCustomMode = vi.fn().mockImplementation(async () => { await provider.contextProxy.setValue("mode", "architect") throw new Error("registration down") }) await expect( provider.createTask( undefined, undefined, undefined, {}, { customModes: [ { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, ], }, ), ).rejects.toThrow("registration down") // This call never wrote a mode, so the rollback must leave the shared // store alone even though the captured previous value differs. expect(provider.contextProxy.getValue("mode")).toBe("architect") }) it("keeps a newer shared mode written by another view when custom-mode registration fails", async () => { await provider.setValues({ mode: "code" }) delete provider["viewLocalState"].mode // updateCustomMode awaits queued file I/O: while it is in flight another // view moves the shared mode, and only then does registration fail. provider["customModesManager"].updateCustomMode = vi.fn().mockImplementation(async () => { await provider.contextProxy.setValue("mode", "architect") throw new Error("registration down") }) await expect( provider.createTask( undefined, undefined, undefined, {}, { mode: "reviewer", customModes: [ { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, ], }, ), ).rejects.toThrow("registration down") // The rollback owns the shared layer only while it still holds the value // this call wrote; the other view's newer choice must survive. expect(provider.contextProxy.getValue("mode")).toBe("architect") // The view layer still held this call's value, so its own rollback ran: // the pre-call absence is restored rather than left as "reviewer". expect(provider["viewLocalState"].mode).toBeUndefined() }) it("restores the mode that stood when setValues wrote after custom-mode registration fails", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // This file mocks getModeBySlug to resolve every slug. Stand in the production lookup so the // payload own definition is what makes reviewer valid, exactly as createTask hands it over. const actualModes = await vi.importActual("../../../shared/modes") const modesModule = vi.mocked(await import("../../../shared/modes")) const originalMode = modesModule.getModeBySlug("code") modesModule.getModeBySlug.mockImplementation(actualModes.getModeBySlug) try { await provider.setValues({ mode: "code" }) delete provider["viewLocalState"].mode // setValues awaits the registered custom-mode list while it validates the mode the payload // asks for. Another view completes a shared-mode write inside that wait, so the value this // call owns is the one standing at its own write - debug - not the code it read before. let competingWriteRan = false vi.spyOn(provider.customModesManager, "getCustomModes").mockImplementation(async () => { if (!competingWriteRan) { competingWriteRan = true await provider.contextProxy.setValue("mode", "debug") } return [] }) provider.customModesManager.updateCustomMode = vi.fn().mockRejectedValue(new Error("registration down")) await expect( provider.createTask( undefined, undefined, undefined, {}, { mode: "reviewer", customModes: [ { slug: "reviewer", name: "Reviewer", roleDefinition: "Reviews code", groups: [] }, ], }, ), ).rejects.toThrow("registration down") // The shared store must land on the mode the other view wrote, not on the value this call // read before it awaited validation. expect(provider.contextProxy.getValue("mode")).toBe("debug") } finally { modesModule.getModeBySlug.mockReturnValue(originalMode) } await provider.dispose() }) it("deregisters the provider even when MCP cleanup rejects during dispose", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // An MCP client whose disposal rejects used to abort dispose() before // the registry cleanup below it: the provider stayed in activeInstances // while _disposed was already set, so no later retry could repair the // registration. Deregistration now runs in a finally path. // The constructor resolves McpServerManager.getInstance asynchronously and // assigns this.mcpHub in its .then, so let that settle first: installing the // double before the hub lands would have it overwritten before dispose reads it. await new Promise((resolve) => setImmediate(resolve)) // Structural double: dispose() only ever calls unregisterClient on mcpHub. provider["mcpHub"] = { unregisterClient: vi.fn().mockRejectedValue(new Error("mcp disposal down")), } as unknown as ClineProvider["mcpHub"] expect(ClineProvider.getAllInstances()).toContain(provider) await expect(provider.dispose()).rejects.toThrow("mcp disposal down") expect(ClineProvider.getAllInstances()).not.toContain(provider) }) }) describe("getState default values", () => { it("should fall back to defaults for unset state values", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) const state = await provider.getState() expect(state.mode).toBe("code") expect(state.currentApiConfigName).toBe("default") expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) expect(state.alwaysAllowReadOnly).toBe(false) expect(state.alwaysAllowReadOnlyOutsideWorkspace).toBe(false) expect(state.alwaysAllowWrite).toBe(false) expect(state.alwaysAllowWriteOutsideWorkspace).toBe(false) expect(state.alwaysAllowWriteProtected).toBe(false) expect(state.alwaysAllowExecute).toBe(false) expect(state.alwaysAllowMcp).toBe(false) expect(state.alwaysAllowModeSwitch).toBe(false) expect(state.alwaysAllowSubtasks).toBe(false) expect(state.alwaysAllowFollowupQuestions).toBe(false) expect(state.followupAutoApproveTimeoutMs).toBe(60000) expect(state.diagnosticsEnabled).toBe(true) expect(state.soundEnabled).toBe(false) expect(state.ttsEnabled).toBe(false) expect(state.ttsSpeed).toBe(1) expect(state.enableCheckpoints).toBe(true) expect(state.checkpointTimeout).toBe(DEFAULT_CHECKPOINT_TIMEOUT_SECONDS) expect(state.terminalPowershellCounter).toBe(false) expect(state.terminalZshClearEolMark).toBe(true) expect(state.terminalZshOhMy).toBe(false) expect(state.terminalZshP10k).toBe(false) expect(state.terminalZdotdir).toBe(false) expect(state.mcpEnabled).toBe(true) expect(state.listApiConfigMeta).toEqual([]) expect(state.pinnedApiConfigs).toEqual({}) expect(state.modeApiConfigs).toEqual({}) expect(state.customSupportPrompts).toEqual({}) expect(state.experiments).toEqual(experimentDefault) expect(state.autoApprovalEnabled).toBe(false) expect(state.maxOpenTabsContext).toBe(20) expect(state.maxWorkspaceFiles).toBe(200) expect(state.telemetrySetting).toBe("unset") expect(state.enableSubfolderRules).toBe(false) expect(state.maxImageFileSize).toBe(5) expect(state.maxTotalImageSize).toBe(20) expect(state.historyPreviewCollapsed).toBe(false) expect(state.reasoningBlockCollapsed).toBe(true) expect(state.enterBehavior).toBe("send") expect(state.codebaseIndexModels).toEqual(EMBEDDING_MODEL_PROFILES) expect(state.codebaseIndexConfig).toEqual({ codebaseIndexEnabled: false, codebaseIndexQdrantUrl: "http://localhost:6333", codebaseIndexEmbedderProvider: providerIdentifiers.openai, codebaseIndexEmbedderBaseUrl: "", codebaseIndexEmbedderModelId: "", }) expect(state.profileThresholds).toEqual({}) expect(state.includeDiagnosticMessages).toBe(true) expect(state.maxDiagnosticMessages).toBe(50) expect(state.includeTaskHistoryInEnhance).toBe(true) expect(state.includeCurrentTime).toBe(true) expect(state.includeCurrentCost).toBe(true) expect(state.maxGitStatusFiles).toBe(0) expect(state.language).toBe("en") await provider.dispose() }) it("should report a non-retired apiProvider from state instead of the anthropic fallback", async () => { const contextProxy = new ContextProxy(mockContext) await contextProxy.setValues({ apiProvider: providerIdentifiers.openrouter }) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", contextProxy, new WebviewFocusTracker(), ) const state = await provider.getState() expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.openrouter) await provider.dispose() }) it("should fill the apiConfiguration apiProvider from the raw state value when provider settings sanitize it away", async () => { // "bogus-provider" is neither an active nor a retired provider, so // ContextProxy.sanitizeProviderValues drops it from the provider // settings; the raw state value still reaches apiConfiguration via // the getState fill-in, which is what this assertion pins. const contextProxy = new ContextProxy(mockContext) // A single structural cast: the raw-state write must carry an // un-sanitizable apiProvider value, which the typed setValues(RooCodeSettings) // signature deliberately rejects. const contextProxyAccess = contextProxy as { setValues: (values: Record) => Promise } await contextProxyAccess.setValues({ apiProvider: "bogus-provider" }) const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", contextProxy, new WebviewFocusTracker(), ) const state = await provider.getState() expect(state.apiConfiguration.apiProvider).toBe("bogus-provider") await provider.dispose() }) it("should serve the embedding model profiles default when the stored value is cleared", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // The constructor seeds codebaseIndexModels into the context; with a truthy // stored value the ?? default is unobservable (both ?? and && forms return // the same profiles object). Clear the stored value so the read-time default // is the one under test. await provider.contextProxy.setValue("codebaseIndexModels", undefined) const state = await provider.getState() expect(state.codebaseIndexModels).toBe(EMBEDDING_MODEL_PROFILES) await provider.dispose() }) }) describe("postStateToWebviewThrottled", () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(async () => { await provider.dispose() vi.useRealTimers() }) test("posts on the leading edge and coalesces a burst into one trailing post", async () => { const postStateSpy = vi.spyOn(provider, "postStateToWebviewWithoutTaskHistory").mockResolvedValue(undefined) await provider.postStateToWebviewThrottled() await provider.postStateToWebviewThrottled() await provider.postStateToWebviewThrottled() expect(postStateSpy).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(499) expect(postStateSpy).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(1) expect(postStateSpy).toHaveBeenCalledTimes(2) }) test("does not starve state posts during continuous updates", async () => { const postStateSpy = vi.spyOn(provider, "postStateToWebviewWithoutTaskHistory").mockResolvedValue(undefined) await provider.postStateToWebviewThrottled() await vi.advanceTimersByTimeAsync(400) await provider.postStateToWebviewThrottled() await vi.advanceTimersByTimeAsync(400) await provider.postStateToWebviewThrottled() await vi.advanceTimersByTimeAsync(199) expect(postStateSpy).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(1) expect(postStateSpy).toHaveBeenCalledTimes(2) }) // Characterization test for the semantics that made #1078's throttle a no-op in practice: // flushing right after a leading-edge post has no pending trailing invocation to run, so it // only cancels the trailing timer — and the next call then hits the leading edge again. // Callers on a hot path (see Task#addToClineMessages) must therefore not flush per message. test("flushing after every post defeats coalescing entirely", async () => { const postStateSpy = vi.spyOn(provider, "postStateToWebviewWithoutTaskHistory").mockResolvedValue(undefined) for (let i = 0; i < 5; i++) { await provider.postStateToWebviewThrottled() await provider.flushPostStateToWebviewThrottled() await vi.advanceTimersByTimeAsync(100) } // One full-state post per call: no coalescing at all. expect(postStateSpy).toHaveBeenCalledTimes(5) // The same burst without the interleaved flush coalesces into far fewer posts. postStateSpy.mockClear() for (let i = 0; i < 5; i++) { await provider.postStateToWebviewThrottled() await vi.advanceTimersByTimeAsync(100) } await vi.advanceTimersByTimeAsync(500) expect(postStateSpy.mock.calls.length).toBeLessThan(5) }) test("flushes a pending trailing post exactly once and waits for it", async () => { let releasePost!: () => void const pendingPost = new Promise((resolve) => { releasePost = resolve }) const postStateSpy = vi .spyOn(provider, "postStateToWebviewWithoutTaskHistory") .mockResolvedValueOnce(undefined) .mockReturnValueOnce(pendingPost) await provider.postStateToWebviewThrottled() await provider.postStateToWebviewThrottled() expect(postStateSpy).toHaveBeenCalledTimes(1) let flushSettled = false const flushPromise = provider.flushPostStateToWebviewThrottled() void flushPromise.then(() => { flushSettled = true }) await Promise.resolve() expect(postStateSpy).toHaveBeenCalledTimes(2) expect(flushSettled).toBe(false) releasePost() await flushPromise expect(flushSettled).toBe(true) await vi.advanceTimersByTimeAsync(1000) expect(postStateSpy).toHaveBeenCalledTimes(2) }) test("does not duplicate an idle leading post when flushed", async () => { const postStateSpy = vi.spyOn(provider, "postStateToWebviewWithoutTaskHistory").mockResolvedValue(undefined) await provider.postStateToWebviewThrottled() await provider.flushPostStateToWebviewThrottled() await vi.advanceTimersByTimeAsync(1000) expect(postStateSpy).toHaveBeenCalledOnce() }) test("handles state post failures inside the debounced callback", async () => { const error = new Error("state post failed") const logSpy = vi.spyOn(provider, "log").mockImplementation(() => {}) vi.spyOn(provider, "postStateToWebviewWithoutTaskHistory").mockRejectedValue(error) await expect(provider.postStateToWebviewThrottled()).resolves.toBeUndefined() expect(logSpy).toHaveBeenCalledWith( "[ClineProvider#postStateToWebviewThrottled] Failed to post state: state post failed", ) }) test("stringifies non-Error state post failures inside the debounced callback", async () => { const logSpy = vi.spyOn(provider, "log").mockImplementation(() => {}) vi.spyOn(provider, "postStateToWebviewWithoutTaskHistory").mockRejectedValue("state post failed") await expect(provider.postStateToWebviewThrottled()).resolves.toBeUndefined() expect(logSpy).toHaveBeenCalledWith( "[ClineProvider#postStateToWebviewThrottled] Failed to post state: state post failed", ) }) test("handles state post failures while flushing a pending trailing post", async () => { const error = new Error("state post failed") const logSpy = vi.spyOn(provider, "log").mockImplementation(() => {}) const postStateSpy = vi .spyOn(provider, "postStateToWebviewWithoutTaskHistory") .mockResolvedValueOnce(undefined) .mockRejectedValueOnce(error) await provider.postStateToWebviewThrottled() await provider.postStateToWebviewThrottled() await expect(provider.flushPostStateToWebviewThrottled()).resolves.toBeUndefined() expect(postStateSpy).toHaveBeenCalledTimes(2) expect(logSpy).toHaveBeenCalledWith( "[ClineProvider#postStateToWebviewThrottled] Failed to post state: state post failed", ) }) test("cancels pending work on dispose and ignores later schedule or flush calls", async () => { const postStateSpy = vi.spyOn(provider, "postStateToWebviewWithoutTaskHistory").mockResolvedValue(undefined) await provider.postStateToWebviewThrottled() await provider.postStateToWebviewThrottled() expect(postStateSpy).toHaveBeenCalledTimes(1) await provider.dispose() await vi.advanceTimersByTimeAsync(1000) await provider.postStateToWebviewThrottled() await provider.flushPostStateToWebviewThrottled() expect(postStateSpy).toHaveBeenCalledTimes(1) }) }) test("postMessageToWebview skips postMessage after dispose", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.dispose() mockPostMessage.mockClear() const message: ExtensionMessage = { type: "action", action: "chatButtonClicked" } await provider.postMessageToWebview(message) expect(mockPostMessage).not.toHaveBeenCalled() }) test("postMessageToWebview logs a delivery that resolves false", async () => { await provider.resolveWebviewView(mockWebviewView) mockPostMessage.mockResolvedValue(false) const message: ExtensionMessage = { type: "action", action: "chatButtonClicked" } await provider.postMessageToWebview(message) // A resolved false is a drop (the page is not deliverable), not a success: it must // reach the log so a wedged channel is diagnosable. await vi.waitFor(() => { expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( expect.stringContaining("[postMessageToWebview] undelivered message type=action"), ) }) }) test("dispose is idempotent — second call is a no-op", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.dispose() await provider.dispose() // dispose body runs only once: log "Disposing ClineProvider..." appears once const disposeCalls = (mockOutputChannel.appendLine as ReturnType).mock.calls.filter( ([msg]) => typeof msg === "string" && msg.includes("Disposing ClineProvider..."), ) expect(disposeCalls).toHaveLength(1) }) test("dispose still deregisters the provider when task eviction fails", async () => { await provider.resolveWebviewView(mockWebviewView) Object.assign(provider, { taskRegistry: new TaskRegistry() }) provider["taskRegistry"].push({ taskId: "stuck-task", instanceId: "stuck-instance", emit: vi.fn(), abortTask: vi.fn(), dispose: vi.fn(), } as unknown as Task) // Bracket notation keeps the private member accessible without a cast. provider["evictCurrentTask"] = vi.fn().mockRejectedValue(new Error("eviction failed")) await expect(provider.dispose()).rejects.toThrow("eviction failed") // _disposed is already set, so a second dispose() returns early: a teardown failure // must deregister the provider instead of stranding a live-looking entry that // setViewStateId would keep treating as a claim on its viewStateId. expect(ClineProvider.getAllInstances()).not.toContain(provider) }) test("dispose drains every task in abort-then-cleanup order", async () => { let resolveCurrentAbort!: () => void let resolveCurrentCleanup!: () => void let resolveRemainingAbort!: () => void let resolveRemainingCleanup!: () => void const currentTask = { taskId: "current-task", instanceId: "current-instance", emit: vi.fn(), abortTask: vi.fn().mockReturnValue( new Promise((resolve) => { resolveCurrentAbort = resolve }), ), dispose: vi.fn().mockReturnValue( new Promise((resolve) => { resolveCurrentCleanup = resolve }), ), } const remainingTask = { taskId: "remaining-task", instanceId: "remaining-instance", emit: vi.fn(), abortTask: vi.fn().mockReturnValue( new Promise((resolve) => { resolveRemainingAbort = resolve }), ), dispose: vi.fn().mockReturnValue( new Promise((resolve) => { resolveRemainingCleanup = resolve }), ), } Object.assign(provider, { taskRegistry: new TaskRegistry() }) provider["taskRegistry"].push(remainingTask as unknown as Task) provider["taskRegistry"].push(currentTask as unknown as Task) let shutdownComplete = false const shutdown = provider.dispose() void shutdown .then(() => { shutdownComplete = true }) .catch(() => {}) await vi.waitFor(() => expect(currentTask.abortTask).toHaveBeenCalledOnce()) expect(currentTask.dispose).not.toHaveBeenCalled() expect(remainingTask.abortTask).not.toHaveBeenCalled() resolveCurrentAbort() await vi.waitFor(() => expect(currentTask.dispose).toHaveBeenCalledOnce()) expect(remainingTask.abortTask).not.toHaveBeenCalled() resolveCurrentCleanup() await vi.waitFor(() => expect(remainingTask.abortTask).toHaveBeenCalledOnce()) expect(remainingTask.dispose).not.toHaveBeenCalled() resolveRemainingAbort() await vi.waitFor(() => expect(remainingTask.dispose).toHaveBeenCalledOnce()) expect(shutdownComplete).toBe(false) resolveRemainingCleanup() await shutdown expect(shutdownComplete).toBe(true) }) test("dispose continues draining tasks after cleanup rejects", async () => { const cleanupError = new Error("cleanup failed") const logSpy = vi.spyOn(provider, "log") const remainingTask = { taskId: "remaining-task", instanceId: "remaining-instance", emit: vi.fn(), abortTask: vi.fn().mockResolvedValue(undefined), dispose: vi.fn().mockResolvedValue(undefined), } const currentTask = { taskId: "current-task", instanceId: "current-instance", emit: vi.fn(), abortTask: vi.fn().mockResolvedValue(undefined), dispose: vi.fn().mockRejectedValue(cleanupError), } Object.assign(provider, { taskRegistry: new TaskRegistry() }) provider["taskRegistry"].push(remainingTask as unknown as Task) provider["taskRegistry"].push(currentTask as unknown as Task) await expect(provider.dispose()).resolves.toBeUndefined() expect(currentTask.dispose).toHaveBeenCalledOnce() expect(remainingTask.dispose).toHaveBeenCalledOnce() expect(logSpy).toHaveBeenCalledWith( "[ClineProvider#dispose] Task cleanup failed for current-task.current-instance: cleanup failed", ) }) test("dispose continues draining tasks after abort rejects", async () => { const abortError = new Error("abort failed") const remainingTask = { taskId: "remaining-task", instanceId: "remaining-instance", emit: vi.fn(), abortTask: vi.fn().mockResolvedValue(undefined), dispose: vi.fn().mockResolvedValue(undefined), } const currentTask = { taskId: "current-task", instanceId: "current-instance", emit: vi.fn(), abortTask: vi.fn().mockRejectedValue(abortError), dispose: vi.fn().mockResolvedValue(undefined), } Object.assign(provider, { taskRegistry: new TaskRegistry() }) provider["taskRegistry"].push(remainingTask as unknown as Task) provider["taskRegistry"].push(currentTask as unknown as Task) await expect(provider.dispose()).resolves.toBeUndefined() expect(currentTask.abortTask).toHaveBeenCalledOnce() expect(currentTask.dispose).toHaveBeenCalledOnce() expect(remainingTask.abortTask).toHaveBeenCalledOnce() expect(remainingTask.dispose).toHaveBeenCalledOnce() }) test("handles webviewDidLaunch message", async () => { await provider.resolveWebviewView(mockWebviewView) // Get the message handler from onDidReceiveMessage const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as ReturnType).mock .calls[0][0] // Simulate webviewDidLaunch message await messageHandler({ type: "webviewDidLaunch" }) // Should post state and theme to webview expect(mockPostMessage).toHaveBeenCalled() }) test("receives the launch message that the webview posts as soon as its HTML loads", async () => { // The webview posts webviewDidLaunch when it mounts. VS Code drops a message // that arrives before a listener exists, so the listener must exist first. let launch: Promise | undefined Object.defineProperty(mockWebviewView.webview, "html", { configurable: true, get: () => "", set: () => { const listener = vi.mocked(mockWebviewView.webview.onDidReceiveMessage).mock.calls.at(-1)?.[0] launch = listener?.({ type: "webviewDidLaunch" }) }, }) await provider.resolveWebviewView(mockWebviewView) expect(launch).toBeDefined() await launch expect(mockPostMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "state" })) }) it("should re-pin the view to a valid global selection when the first listed profile has no name", async () => { const provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // @ts-ignore - Replace providerSettingsManager with a test double: the view's pinned config no // longer exists, the shared global selection is still valid, and the only listed profile is a // legacy entry without a name. provider.providerSettingsManager = { hasConfig: vi.fn(async (name: string) => name === "global-valid"), listConfig: vi.fn(async () => [{ id: "legacy-id", apiProvider: providerIdentifiers.openai }]), saveConfig: vi.fn(async () => "legacy-id"), dispose: vi.fn(), } // @ts-ignore - Replace customModesManager with a test double (no custom modes). provider.customModesManager = { getCustomModes: vi.fn().mockResolvedValue([]), dispose: vi.fn() } // The view's own pin points at a deleted profile; the shared global selection is still valid. await provider.saveViewState("currentApiConfigName", "gone-pin") await provider.contextProxy.setValue("currentApiConfigName", "global-valid") const postMessageSpy = vi.spyOn(provider, "postMessageToWebview") const contextProxySetValueSpy = vi.spyOn(provider.contextProxy, "setValue") await webviewMessageHandler(provider, { type: "webviewDidLaunch" }) // The launch flow's profile-list sync is fire-and-forget; wait for its final post. await vi.waitFor(() => expect(postMessageSpy).toHaveBeenCalledWith(expect.objectContaining({ type: "listApiConfig" })), ) // The valid shared selection is adopted by this view only: the view-local pin switches to it // while the shared global selection is left untouched for the other views. expect(provider["viewLocalState"].currentApiConfigName).toBe("global-valid") expect(mockContext.globalState.get("currentApiConfigName")).toBe("global-valid") // A nameless first listed profile must never clear the shared selection with undefined. expect(contextProxySetValueSpy).not.toHaveBeenCalledWith("currentApiConfigName", undefined) await provider.dispose() }) test("logs detached workspace initialization failures", async () => { await provider.resolveWebviewView(mockWebviewView) let rejectInitialization!: (error: Error) => void const initializationPromise = new Promise((_, reject) => { rejectInitialization = reject }) const initializeSpy = vi .spyOn(provider.workspaceTracker!, "initializeFilePaths") .mockReturnValue(initializationPromise) const logSpy = vi.spyOn(provider, "log") const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await expect(messageHandler({ type: "webviewDidLaunch" })).resolves.toBeUndefined() expect(initializeSpy).toHaveBeenCalledOnce() rejectInitialization(new Error("workspace boom")) await Promise.resolve() await Promise.resolve() expect(logSpy).toHaveBeenCalledWith("Workspace initialization error: Error: workspace boom") }) test("clearTask aborts current task", async () => { // Setup Cline instance with auto-mock from the top of the file const mockCline = new Task(defaultTaskOptions) // Create a new mocked instance // add the mock object to the stack await provider.addClineToStack(mockCline) // get the stack size before the abort call const stackSizeBeforeAbort = provider.getTaskStackSize() // call the removeClineFromStack method so it will call the current cline abort and remove it from the stack await provider.removeClineFromStack() // get the stack size after the abort call const stackSizeAfterAbort = provider.getTaskStackSize() // check if the abort method was called expect(mockCline.abortTask).toHaveBeenCalled() // check if the stack size was decreased expect(stackSizeBeforeAbort - stackSizeAfterAbort).toBe(1) }) describe("clearTask message handler", () => { beforeEach(async () => { await provider.resolveWebviewView(mockWebviewView) }) test("calls clearTask (delegation handled via metadata)", async () => { // Setup a single task without parent const mockCline = new Task(defaultTaskOptions) // Mock the provider methods const clearTaskSpy = vi.spyOn(provider, "clearTask").mockResolvedValue(undefined) const postStateToWebviewSpy = vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // Add task to stack await provider.addClineToStack(mockCline) // Get the message handler const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Trigger clearTask message await messageHandler({ type: "clearTask" }) // Verify clearTask was called expect(clearTaskSpy).toHaveBeenCalled() expect(postStateToWebviewSpy).toHaveBeenCalled() }) test("calls clearTask even with parent task (delegation via metadata)", async () => { // Setup parent and child tasks const parentTask = new Task(defaultTaskOptions) const childTask = new Task(defaultTaskOptions) // Set up parent-child relationship ;(childTask as any).parentTask = parentTask ;(childTask as any).rootTask = parentTask // Mock the provider methods const clearTaskSpy = vi.spyOn(provider, "clearTask").mockResolvedValue(undefined) const postStateToWebviewSpy = vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // Add both tasks to stack (parent first, then child) await provider.addClineToStack(parentTask) await provider.addClineToStack(childTask) // Get the message handler const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Trigger clearTask message await messageHandler({ type: "clearTask" }) // Verify clearTask was called (delegation happens via metadata, not finishSubTask) expect(clearTaskSpy).toHaveBeenCalled() expect(postStateToWebviewSpy).toHaveBeenCalled() }) test("handles case when no current task exists", async () => { // Don't add any tasks to the stack // Mock the provider methods const clearTaskSpy = vi.spyOn(provider, "clearTask").mockResolvedValue(undefined) const postStateToWebviewSpy = vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // Get the message handler const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Trigger clearTask message await messageHandler({ type: "clearTask" }) // When there's no current task, clearTask is still called (it handles the no-task case internally) expect(clearTaskSpy).toHaveBeenCalled() expect(postStateToWebviewSpy).toHaveBeenCalled() }) test("correctly identifies task scenario for issue #4602", async () => { // This test validates the fix for issue #4602 // where canceling during API retry correctly uses clearTask const mockCline = new Task(defaultTaskOptions) // Mock the provider methods const clearTaskSpy = vi.spyOn(provider, "clearTask").mockResolvedValue(undefined) // Add only one task to stack await provider.addClineToStack(mockCline) // Verify stack size is 1 expect(provider.getTaskStackSize()).toBe(1) // Get the message handler const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Trigger clearTask message (simulating cancel during API retry) await messageHandler({ type: "clearTask" }) // clearTask should be called (delegation handled via metadata) expect(clearTaskSpy).toHaveBeenCalled() }) }) test("addClineToStack adds multiple Cline instances to the stack", async () => { // Setup Cline instance with auto-mock from the top of the file const mockCline1 = new Task(defaultTaskOptions) // Create a new mocked instance const mockCline2 = new Task(defaultTaskOptions) // Create a new mocked instance Object.defineProperty(mockCline1, "taskId", { value: "test-task-id-1", writable: true }) Object.defineProperty(mockCline2, "taskId", { value: "test-task-id-2", writable: true }) // add Cline instances to the stack await provider.addClineToStack(mockCline1) await provider.addClineToStack(mockCline2) // verify cline instances were added to the stack expect(provider.getTaskStackSize()).toBe(2) // verify current cline instance is the last one added expect(provider.getCurrentTask()).toBe(mockCline2) }) test("getState returns correct initial state", async () => { const state = await provider.getState() expect(state).toHaveProperty("apiConfiguration") expect(state.apiConfiguration).toHaveProperty("apiProvider") expect(state).toHaveProperty("customInstructions") expect(state).toHaveProperty("alwaysAllowReadOnly") expect(state).toHaveProperty("alwaysAllowWrite") expect(state).toHaveProperty("alwaysAllowExecute") expect(state).toHaveProperty("taskHistory") expect(state).toHaveProperty("soundEnabled") expect(state).toHaveProperty("ttsEnabled") expect(state).toHaveProperty("writeDelayMs") }) test("getState and getStateToPostToWebview return the complete NanoGPT configuration", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setProviderSettings({ apiProvider: providerIdentifiers.nanogpt, nanoGptApiKey: "nanogpt-secret", nanoGptModelId: "openai/model", nanoGptRoutingPreference: "latency", }) const state = await provider.getState() const postedState = await provider.getStateToPostToWebview() const expectedConfiguration = { apiProvider: providerIdentifiers.nanogpt, nanoGptApiKey: "nanogpt-secret", nanoGptModelId: "openai/model", nanoGptRoutingPreference: "latency", } expect(state.apiConfiguration).toMatchObject(expectedConfiguration) expect(postedState.apiConfiguration).toMatchObject(expectedConfiguration) }) test.each([true, false, undefined])( "returns saved OpenAI-compatible reasoning and Responses settings to the webview when enabled is %s", async (enableReasoningEffort) => { await provider.resolveWebviewView(mockWebviewView) const configuration: ProviderSettings = { apiProvider: providerIdentifiers.openai, openAiModelId: "custom-model", enableReasoningEffort, openAiUseResponsesApi: enableReasoningEffort, reasoningEffort: "low", openAiCustomModelInfo: { ...openAiModelInfoSaneDefaults, reasoningEffort: "max" }, } await provider.contextProxy.setProviderSettings(configuration) expect(provider.contextProxy.getProviderSettings()).toMatchObject(configuration) expect((await provider.getState()).apiConfiguration).toMatchObject(configuration) expect((await provider.getStateToPostToWebview()).apiConfiguration).toMatchObject(configuration) }, ) describe("display settings written through setValues and a task's configuration", () => { const hand = (values: Record) => values as unknown as RooCodeSettings it("stores valid values as they are", async () => { const setValues = vi.spyOn(provider.contextProxy, "setValues").mockResolvedValue(undefined) await provider.setValues({ timeFormat: "24h", dateFormat: "ymd", showRelativeTimes: false }) expect(setValues).toHaveBeenCalledWith({ timeFormat: "24h", dateFormat: "ymd", showRelativeTimes: false }) }) it("ignores an invalid value, keeps the others, and logs which", async () => { const setValues = vi.spyOn(provider.contextProxy, "setValues").mockResolvedValue(undefined) const log = vi.spyOn(provider, "log").mockImplementation(() => {}) await provider.setValues(hand({ timeFormat: "13h", dateFormat: "dmy", mode: "code" })) expect(setValues).toHaveBeenCalledWith({ dateFormat: "dmy", mode: "code" }) expect(log).toHaveBeenCalledWith("[setValues] Ignored an invalid value for timeFormat") }) it("applies the same check to the configuration of a new task", async () => { const setValues = vi.spyOn(provider.contextProxy, "setValues").mockResolvedValue(undefined) vi.spyOn(provider, "log").mockImplementation(() => {}) await provider .createTask("hello", undefined, undefined, {}, hand({ showRelativeTimes: "yes", mode: "code" })) .catch(() => undefined) // what happens after the configuration is written is not under test expect(setValues).toHaveBeenCalledWith({ mode: "code" }) }) }) test.each([ ["true", true, true], ["false", false, false], ["unset", undefined, true], ])( "task title generation setting %s round-trips through getState and the webview state", async (_label, saved, expected) => { await provider.contextProxy.setValue("taskTitleGenerationEnabled", saved) await provider.contextProxy.setValue( "taskTitleApiConfigId", saved === undefined ? undefined : "title-profile", ) const state = await provider.getState() const webviewState = await provider.getStateToPostToWebview({ includeTaskHistory: false }) expect(state.taskTitleGenerationEnabled).toBe(expected) expect(webviewState.taskTitleGenerationEnabled).toBe(expected) expect(state.taskTitleApiConfigId).toBe(saved === undefined ? undefined : "title-profile") expect(webviewState.taskTitleApiConfigId).toBe(saved === undefined ? undefined : "title-profile") }, ) test("getState returns the saved destructive command guard setting", async () => { await provider.contextProxy.setValue("destructiveCommandGuardEnabled", true) const state = await provider.getState() expect(state.destructiveCommandGuardEnabled).toBe(true) }) test("getState returns the saved blanket auto-deny setting", async () => { await provider.contextProxy.setValue("alwaysDenyUnapprovedCommands", true) const state = await provider.getState() expect(state.alwaysDenyUnapprovedCommands).toBe(true) }) test("getState defaults blanket auto-deny to false", async () => { const state = await provider.getState() expect(state.alwaysDenyUnapprovedCommands).toBe(false) }) test("getState returns the saved allowed read files", async () => { await provider.contextProxy.setValue("allowedReadFiles", ["notes.md"]) const state = await provider.getState() expect(state.allowedReadFiles).toEqual(["notes.md"]) }) test("getState defaults allowed read files to an empty list", async () => { const state = await provider.getState() expect(state.allowedReadFiles).toEqual([]) }) test("getStateToPostToWebview returns the saved allowed read files", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("allowedReadFiles", ["notes.md"]) const state = await provider.getStateToPostToWebview() expect(state.allowedReadFiles).toEqual(["notes.md"]) }) describe("prompt cache TTL round trip", () => { // The provider-settings route: the knob rides `apiConfiguration`, so the // round trip is the profile write plus the state post, with no dedicated // message type and no settings-specific branch in the message handler. test("a saved 1h survives a fresh getStateToPostToWebview payload", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.upsertProviderProfile("ttl-profile", { apiProvider: providerIdentifiers.anthropic, apiModelId: "claude-sonnet-4-5", apiKey: "test-key", promptCacheTtl: "1h", }) // A fresh read, not the in-memory value the save path just wrote: this is // the "saved control reverts visually" case the checklist calls out. const posted = await provider.getStateToPostToWebview() expect(posted.apiConfiguration.promptCacheTtl).toBe("1h") expect((await provider.getState()).apiConfiguration.promptCacheTtl).toBe("1h") }) test("an unset knob stays absent rather than becoming an explicit 5m", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.upsertProviderProfile("default-ttl-profile", { apiProvider: providerIdentifiers.anthropic, apiModelId: "claude-sonnet-4-5", apiKey: "test-key", }) const posted = await provider.getStateToPostToWebview() // Consumers apply the vendor default, so the stored value must be absent // rather than a literal "5m" that would look like a user choice. expect(posted.apiConfiguration.promptCacheTtl).toBeUndefined() expect(posted.apiConfiguration).not.toHaveProperty("promptCacheTtl", "5m") }) test("a hand-edited 1h for a model without the capability is stored, not silently rewritten", async () => { await provider.resolveWebviewView(mockWebviewView) // MiniMax caches prompts but advertises no TTL class. The profile can only // have been written by hand or imported, and the save path must keep what // the user stored: capability is enforced where the request is built (the // emitter fails closed), so a save-time rewrite would be a second, silent // source of truth for the same rule. await provider.upsertProviderProfile("hand-edited-profile", { apiProvider: providerIdentifiers.minimax, apiKey: "test-key", promptCacheTtl: "1h", }) const posted = await provider.getStateToPostToWebview() expect(posted.apiConfiguration.promptCacheTtl).toBe("1h") }) }) test("getStateToPostToWebview defaults allowed read files to an empty list", async () => { await provider.resolveWebviewView(mockWebviewView) const state = await provider.getStateToPostToWebview() expect(state.allowedReadFiles).toEqual([]) }) describe("date and time display settings", () => { const defaults = { timeFormat: "auto", dateFormat: "auto", showRelativeTimes: true } /** Saves through the real `updateSettings` handler, as the settings view does. */ const save = async (updatedSettings: Record) => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = vi.mocked(mockWebviewView.webview.onDidReceiveMessage).mock.calls[0][0] await messageHandler({ type: "updateSettings", updatedSettings }) } test.each(Object.entries(defaults))("%s is %j when it was never saved", async (key, expected) => { await provider.resolveWebviewView(mockWebviewView) expect(await provider.getState()).toMatchObject({ [key]: expected }) expect(await provider.getStateToPostToWebview()).toMatchObject({ [key]: expected }) }) test.each([ ["timeFormat", "12h"], ["timeFormat", "24h"], ["timeFormat", "auto"], ["dateFormat", "mdy"], ["dateFormat", "dmy"], ["dateFormat", "ymd"], ["dateFormat", "auto"], ["showRelativeTimes", true], ["showRelativeTimes", false], ])("a saved %s of %j is stored and returned to the webview", async (key, value) => { mockPostMessage.mockClear() await save({ [key]: value }) expect(mockContext.globalState.update).toHaveBeenCalledWith(key, value) expect(await provider.getState()).toMatchObject({ [key]: value }) expect(await provider.getStateToPostToWebview()).toMatchObject({ [key]: value }) // The open webview is told, so the saved value does not revert on screen. expect(mockPostMessage).toHaveBeenCalledWith( expect.objectContaining({ type: "state", state: expect.objectContaining({ [key]: value }) }), ) }) test("the state refresh after a save reaches the active webview with the saved time format", async () => { mockPostMessage.mockClear() await save({ timeFormat: "24h" }) const posted: unknown[][] = mockPostMessage.mock.calls const states = posted .map(([message]) => message as { type?: string; state?: { timeFormat?: string } }) .filter((message) => message.type === "state") expect(states.length).toBeGreaterThan(0) expect(states.at(-1)?.state?.timeFormat).toBe("24h") }) test("an explicit false is kept, not replaced by the default of true", async () => { await save({ showRelativeTimes: false }) expect((await provider.getState()).showRelativeTimes).toBe(false) expect((await provider.getStateToPostToWebview()).showRelativeTimes).toBe(false) }) test("all three are saved together and returned together", async () => { await save({ timeFormat: "24h", dateFormat: "dmy", showRelativeTimes: false }) const expected = { timeFormat: "24h", dateFormat: "dmy", showRelativeTimes: false } expect(await provider.getState()).toMatchObject(expected) expect(await provider.getStateToPostToWebview()).toMatchObject(expected) }) test("saving one setting leaves the others at their defaults", async () => { await save({ timeFormat: "12h" }) expect(await provider.getStateToPostToWebview()).toMatchObject({ ...defaults, timeFormat: "12h" }) }) }) test("getState returns the saved allowed write files", async () => { await provider.contextProxy.setValue("allowedWriteFiles", ["notes.md"]) const state = await provider.getState() expect(state.allowedWriteFiles).toEqual(["notes.md"]) }) test("getState defaults allowed write files to an empty list", async () => { const state = await provider.getState() expect(state.allowedWriteFiles).toEqual([]) }) test("getStateToPostToWebview returns the saved allowed write files", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("allowedWriteFiles", ["notes.md"]) const state = await provider.getStateToPostToWebview() expect(state.allowedWriteFiles).toEqual(["notes.md"]) }) test("getStateToPostToWebview defaults allowed write files to an empty list", async () => { await provider.resolveWebviewView(mockWebviewView) const state = await provider.getStateToPostToWebview() expect(state.allowedWriteFiles).toEqual([]) }) test("getStateToPostToWebview returns the saved destructive command guard setting", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("destructiveCommandGuardEnabled", true) const state = await provider.getStateToPostToWebview() expect(state.destructiveCommandGuardEnabled).toBe(true) }) test("getStateToPostToWebview disables destructive command guard by default", async () => { await provider.resolveWebviewView(mockWebviewView) const state = await provider.getStateToPostToWebview() expect(state.destructiveCommandGuardEnabled).toBe(false) }) test("getStateToPostToWebview returns the saved dynamicThinkingEffort experiment when enabled", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("experiments", { ...experimentDefault, dynamicThinkingEffort: true, }) const state = await provider.getStateToPostToWebview() expect(state.experiments).toEqual({ ...experimentDefault, dynamicThinkingEffort: true }) }) test("getStateToPostToWebview returns the saved dynamicThinkingEffort experiment when explicitly disabled", async () => { await provider.resolveWebviewView(mockWebviewView) // A second experiment is enabled on purpose: a projection that fell back to // experimentDefault whenever the flag was false would still satisfy a // fixture-equals-default assertion, and it would discard this enabled // experiment on the way. await provider.contextProxy.setValue("experiments", { ...experimentDefault, preventFocusDisruption: true, dynamicThinkingEffort: false, }) const state = await provider.getStateToPostToWebview() expect(state.experiments).toEqual({ ...experimentDefault, preventFocusDisruption: true, dynamicThinkingEffort: false, }) }) test("getStateToPostToWebview defaults dynamicThinkingEffort to false when experiments are unset", async () => { await provider.resolveWebviewView(mockWebviewView) const state = await provider.getStateToPostToWebview() expect(state.experiments).toEqual({ ...experimentDefault, dynamicThinkingEffort: false }) }) test("getStateToPostToWebview returns the saved blanket auto-deny setting", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("alwaysDenyUnapprovedCommands", true) const state = await provider.getStateToPostToWebview() expect(state.alwaysDenyUnapprovedCommands).toBe(true) }) test("getStateToPostToWebview disables blanket auto-deny by default", async () => { await provider.resolveWebviewView(mockWebviewView) const state = await provider.getStateToPostToWebview() expect(state.alwaysDenyUnapprovedCommands).toBe(false) }) test("language is set to VSCode language", async () => { // Mock VSCode language as Spanish ;(vscode.env as any).language = "pt-BR" const state = await provider.getState() expect(state.language).toBe("pt-BR") }) test("writeDelayMs defaults to DEFAULT_WRITE_DELAY_MS", async () => { // Mock globalState.get to return undefined for writeDelayMs (typed reassignment, // same pattern as the customModePrompts test below — Memento.get has no mock type) mockContext.globalState.get = vi.fn((key: string) => { return key === "writeDelayMs" ? undefined : null }) const state = await provider.getState() expect(state.writeDelayMs).toBe(DEFAULT_WRITE_DELAY_MS) }) test("getStateToPostToWebview returns the persisted writeDelayMs value", async () => { await provider.resolveWebviewView(mockWebviewView) // Simulate the updateSettings handler storing the value. await provider.contextProxy.setValue("writeDelayMs", 500) const state = await provider.getStateToPostToWebview() expect(state.writeDelayMs).toBe(500) }) test("getStateToPostToWebview defaults writeDelayMs to DEFAULT_WRITE_DELAY_MS when unset", async () => { await provider.resolveWebviewView(mockWebviewView) // Ensure the setting is not persisted. await provider.contextProxy.setValue("writeDelayMs", undefined) const state = await provider.getStateToPostToWebview() expect(state.writeDelayMs).toBe(DEFAULT_WRITE_DELAY_MS) }) test.each([true, false, undefined])( "returns the saved output collapse preference (%s) to the webview", async (value) => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("collapseCommandOutputByDefault", value) expect((await provider.getState()).collapseCommandOutputByDefault).toBe(value ?? false) expect((await provider.getStateToPostToWebview()).collapseCommandOutputByDefault).toBe(value ?? false) }, ) test("getState applies fallback defaults for write, diff, and terminal settings", async () => { // Mock globalState.get to return undefined for the fallback settings // (typed reassignment — Memento.get has no mock type, same pattern as the // writeDelayMs default test above) mockContext.globalState.get = vi.fn((key: string) => { if ( [ "writeDelayMs", "diffFuzzyThreshold", "terminalShellIntegrationTimeout", "terminalShellIntegrationDisabled", "terminalCommandDelay", ].includes(key) ) { return undefined } return null }) const state = await provider.getState() expect(state.writeDelayMs).toBe(DEFAULT_WRITE_DELAY_MS) expect(state.diffFuzzyThreshold).toBe(DEFAULT_DIFF_FUZZY_THRESHOLD) expect(state.terminalShellIntegrationTimeout).toBe(Terminal.defaultShellIntegrationTimeout) expect(state.terminalShellIntegrationDisabled).toBe(true) expect(state.terminalCommandDelay).toBe(0) }) test("getState passes through defined write/diff/terminal values instead of defaults", async () => { await provider.contextProxy.setValue("writeDelayMs", 500) await provider.contextProxy.setValue("diffFuzzyThreshold", 0.5) await provider.contextProxy.setValue("terminalShellIntegrationTimeout", 99999) await provider.contextProxy.setValue("terminalShellIntegrationDisabled", false) await provider.contextProxy.setValue("terminalCommandDelay", 1234) const state = await provider.getState() expect(state.writeDelayMs).toBe(500) expect(state.diffFuzzyThreshold).toBe(0.5) expect(state.terminalShellIntegrationTimeout).toBe(99999) expect(state.terminalShellIntegrationDisabled).toBe(false) expect(state.terminalCommandDelay).toBe(1234) }) test("handles writeDelayMs message", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "updateSettings", updatedSettings: { writeDelayMs: 2000 } }) expect(updateGlobalStateSpy).toHaveBeenCalledWith("writeDelayMs", 2000) expect(mockContext.globalState.update).toHaveBeenCalledWith("writeDelayMs", 2000) expect(mockPostMessage).toHaveBeenCalled() }) test("updates sound utility when sound setting changes", async () => { await provider.resolveWebviewView(mockWebviewView) // Get the message handler from onDidReceiveMessage const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Simulate setting sound to enabled await messageHandler({ type: "updateSettings", updatedSettings: { soundEnabled: true } }) expect(updateGlobalStateSpy).toHaveBeenCalledWith("soundEnabled", true) expect(mockContext.globalState.update).toHaveBeenCalledWith("soundEnabled", true) expect(mockPostMessage).toHaveBeenCalled() // Simulate setting sound to disabled await messageHandler({ type: "updateSettings", updatedSettings: { soundEnabled: false } }) expect(mockContext.globalState.update).toHaveBeenCalledWith("soundEnabled", false) expect(mockPostMessage).toHaveBeenCalled() // Simulate setting tts to enabled await messageHandler({ type: "updateSettings", updatedSettings: { ttsEnabled: true } }) expect(setTtsEnabled).toHaveBeenCalledWith(true) expect(mockContext.globalState.update).toHaveBeenCalledWith("ttsEnabled", true) expect(mockPostMessage).toHaveBeenCalled() // Simulate setting tts to disabled await messageHandler({ type: "updateSettings", updatedSettings: { ttsEnabled: false } }) expect(setTtsEnabled).toHaveBeenCalledWith(false) expect(mockContext.globalState.update).toHaveBeenCalledWith("ttsEnabled", false) expect(mockPostMessage).toHaveBeenCalled() }) test("autoCondenseContext defaults to true", async () => { // Mock globalState.get to return undefined for autoCondenseContext ;(mockContext.globalState.get as any).mockImplementation((key: string) => { return key === "autoCondenseContext" ? undefined : null }) const state = await provider.getState() expect(state.autoCondenseContext).toBe(true) }) test("handles autoCondenseContext message", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "updateSettings", updatedSettings: { autoCondenseContext: false } }) expect(updateGlobalStateSpy).toHaveBeenCalledWith("autoCondenseContext", false) expect(mockContext.globalState.update).toHaveBeenCalledWith("autoCondenseContext", false) expect(mockPostMessage).toHaveBeenCalled() }) test("autoCondenseContextPercent defaults to 100", async () => { // Mock globalState.get to return undefined for autoCondenseContextPercent ;(mockContext.globalState.get as any).mockImplementation((key: string) => { return key === "autoCondenseContextPercent" ? undefined : null }) const state = await provider.getState() expect(state.autoCondenseContextPercent).toBe(100) }) test("handles autoCondenseContextPercent message", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "updateSettings", updatedSettings: { autoCondenseContextPercent: 75 } }) expect(updateGlobalStateSpy).toHaveBeenCalledWith("autoCondenseContextPercent", 75) expect(mockContext.globalState.update).toHaveBeenCalledWith("autoCondenseContextPercent", 75) expect(mockPostMessage).toHaveBeenCalled() }) describe("auto-close settings are included in posted state", () => { it("getStateToPostToWebview returns saved autoCloseZooOpenedFiles value", async () => { await provider.resolveWebviewView(mockWebviewView) // Simulate the updateSettings handler storing the value. await provider.contextProxy.setValue("autoCloseZooOpenedFiles", false) await provider.contextProxy.setValue("autoCloseZooOpenedFilesAfterUserEdited", true) await provider.contextProxy.setValue("autoCloseZooOpenedNewFiles", true) const state = await provider.getStateToPostToWebview() // The saved values must be present in the state posted to the webview. expect(state.autoCloseZooOpenedFiles).toBe(false) expect(state.autoCloseZooOpenedFilesAfterUserEdited).toBe(true) expect(state.autoCloseZooOpenedNewFiles).toBe(true) }) it("getStateToPostToWebview defaults autoCloseZooOpenedFiles to false when unset", async () => { await provider.resolveWebviewView(mockWebviewView) // Ensure the settings are not set. await provider.contextProxy.setValue("autoCloseZooOpenedFiles", undefined) await provider.contextProxy.setValue("autoCloseZooOpenedFilesAfterUserEdited", undefined) await provider.contextProxy.setValue("autoCloseZooOpenedNewFiles", undefined) const state = await provider.getStateToPostToWebview() // Unset values should default to their documented defaults (opt-in). expect(state.autoCloseZooOpenedFiles).toBe(false) expect(state.autoCloseZooOpenedFilesAfterUserEdited).toBe(false) expect(state.autoCloseZooOpenedNewFiles).toBe(false) }) it("getState returns saved autoCloseZooOpenedFiles value for DiffViewProvider", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("autoCloseZooOpenedFiles", false) await provider.contextProxy.setValue("autoCloseZooOpenedFilesAfterUserEdited", true) await provider.contextProxy.setValue("autoCloseZooOpenedNewFiles", true) const state = await provider.getState() // DiffViewProvider reads from getState(); all three fields must be present // so a regression that drops any of them is caught. expect(state.autoCloseZooOpenedFiles).toBe(false) expect(state.autoCloseZooOpenedFilesAfterUserEdited).toBe(true) expect(state.autoCloseZooOpenedNewFiles).toBe(true) }) }) it("getStateToPostToWebview passes through defined diffFuzzyThreshold value", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("diffFuzzyThreshold", 0.5) const state = await provider.getStateToPostToWebview() expect(state.diffFuzzyThreshold).toBe(0.5) }) it("loads saved API config when switching modes", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] const profile: ProviderSettingsEntry = { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic, } provider["initialModeConfigIds"] = Promise.resolve({ architect: "test-id" }) // The double carries only the manager methods this test drives; Object.assign keeps // the whole-manager replacement semantics of the original cast without an any hole. Object.assign(provider, { providerSettingsManager: { getModeConfigId: vi.fn().mockResolvedValue("test-id"), listConfig: vi.fn().mockResolvedValue([profile]), activateProfile: vi.fn().mockResolvedValue(profile), setModeConfig: vi.fn(), getProfile: vi.fn().mockResolvedValue(profile), }, }) // Switch to architect mode await messageHandler({ type: "mode", text: "architect" }) // Should load the saved config for architect mode expect(provider.providerSettingsManager.getModeConfigId).not.toHaveBeenCalled() expect(provider.providerSettingsManager.activateProfile).toHaveBeenCalledWith({ name: "test-config" }) expect(mockContext.globalState.update).toHaveBeenCalledWith("currentApiConfigName", "test-config") }) it("prefers this window's mode profile over one another window saved in shared storage", async () => { await provider.resolveWebviewView(mockWebviewView) const manager = provider.providerSettingsManager vi.spyOn(manager, "getModeConfigId").mockResolvedValue("other-window-id") vi.spyOn(manager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(manager, "listConfig").mockResolvedValue([{ name: "local", id: "this-window-id" }]) await provider["setModeConfig"]("code", "this-window-id") expect(manager.setModeConfig).toHaveBeenCalledWith("code", "this-window-id") await expect(provider["getModeConfigId"]("code")).resolves.toBe("this-window-id") // An unmapped mode keeps this provider's current profile. await expect(provider["getModeConfigId"]("architect")).resolves.toBeUndefined() }) describe("mode profile initialization and imports", () => { const profiles = { currentApiConfigName: "first", apiConfigs: { first: { id: "id1" }, second: { id: "id2" }, imported: { id: "id3" } }, modeApiConfigs: { code: "id1", architect: "id1" }, } let createdProviders: ClineProvider[] const newProvider = () => { const created = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) createdProviders.push(created) return created } beforeEach(async () => { createdProviders = [] await provider.providerSettingsManager.import(profiles) }) afterEach(async () => { for (const created of createdProviders) { await created.dispose() } vi.restoreAllMocks() }) it("captures the opening snapshot during construction and waits for it on lookup", async () => { let resolveSnapshot!: (value: Record) => void const snapshot = new Promise>((resolve) => { resolveSnapshot = resolve }) const getSnapshot = vi .spyOn(ProviderSettingsManager.prototype, "getModeConfigIds") .mockReturnValue(snapshot) const created = newProvider() expect(getSnapshot).toHaveBeenCalledOnce() let settled = false const lookup = created["getModeConfigId"]("code").then((id) => { settled = true return id }) // Flush the real manager's initialization while the opening snapshot is pending. await created.providerSettingsManager.listConfig() expect(settled).toBe(false) resolveSnapshot({ code: "id2" }) await expect(lookup).resolves.toBe("id2") expect(getSnapshot).toHaveBeenCalledOnce() }) it("isolates two providers using the same shared profile store", async () => { const first = newProvider() const second = newProvider() await Promise.all([first["initialModeConfigIds"], second["initialModeConfigIds"]]) await first.setModeConfig("code", "id2") await expect(second.providerSettingsManager.getModeConfigId("code")).resolves.toBe("id2") await expect(first["getModeConfigId"]("code")).resolves.toBe("id2") await expect(second["getModeConfigId"]("code")).resolves.toBe("id1") }) it("keeps an unmapped mode local when another provider saves a mapping later", async () => { await provider.providerSettingsManager.saveConfig("first", { id: "id1", apiProvider: providerIdentifiers.openrouter, }) const first = newProvider() const second = newProvider() await Promise.all([first["initialModeConfigIds"], second["initialModeConfigIds"]]) await second.setModeConfig("new-mode", "id2") await expect(first.providerSettingsManager.getModeConfigId("new-mode")).resolves.toBe("id2") await expect(first["getModeConfigId"]("new-mode")).resolves.toBeUndefined() await expect(second["getModeConfigId"]("new-mode")).resolves.toBe("id2") await first.contextProxy.setValue("currentApiConfigName", "first") await first.handleModeSwitch("new-mode") await first.handleModeSwitch("code") await first.handleModeSwitch("new-mode") await expect(first["getModeConfigId"]("new-mode")).resolves.toBe("id1") await expect(second.providerSettingsManager.getModeConfigId("new-mode")).resolves.toBe("id2") await expect(newProvider()["getModeConfigId"]("new-mode")).resolves.toBe("id2") }) it.each(["success", "profile write fails", "later settings write fails"])( "refreshes imported local and snapshot choices only after profiles persist: %s", async (outcome) => { const first = newProvider() const second = newProvider() await Promise.all([first["initialModeConfigIds"], second["initialModeConfigIds"]]) await first.setModeConfig("code", "id2") vi.mocked(fsPromises.readFile).mockResolvedValueOnce( JSON.stringify({ providerProfiles: { ...profiles, modeApiConfigs: { code: "id3", architect: "id3" } }, globalSettings: {}, }), ) if (outcome === "profile write fails") { vi.spyOn(mockContext.secrets, "store").mockRejectedValueOnce(new Error("profile write failed")) } else if (outcome === "later settings write fails") { vi.spyOn(first.contextProxy, "setValues").mockRejectedValueOnce(new Error("settings write failed")) } const result = await importSettingsFromPath("/test/settings.json", { providerSettingsManager: first.providerSettingsManager, contextProxy: first.contextProxy, customModesManager: first.customModesManager, }) expect(result.success).toBe(outcome === "success") await expect(first["getModeConfigId"]("code")).resolves.toBe( outcome === "profile write fails" ? "id2" : "id3", ) await expect(first["getModeConfigId"]("architect")).resolves.toBe( outcome === "profile write fails" ? "id1" : "id3", ) await expect(second["getModeConfigId"]("code")).resolves.toBe("id1") if (outcome !== "profile write fails") { await second.setModeConfig("code", "id2") await second.setModeConfig("architect", "id2") await expect(first["getModeConfigId"]("code")).resolves.toBe("id3") await expect(first["getModeConfigId"]("architect")).resolves.toBe("id3") } }, ) }) describe("mode profile snapshot", () => { beforeEach(() => { vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue( ["opened-with-id", "chosen-id", "reset-id"].map((id) => ({ name: id, id })), ) }) it("keeps the prior choice when the shared write fails", async () => { provider["initialModeConfigIds"] = Promise.resolve({ code: "opened-with-id" }) const error = new Error("write failed") vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockRejectedValue(error) await expect(provider.setModeConfig("code", "failed-id")).rejects.toBe(error) await expect(provider["getModeConfigId"]("code")).resolves.toBe("opened-with-id") }) it("returns undefined when no mapping exists", async () => { vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) await expect(provider["getModeConfigId"]("new-custom-mode")).resolves.toBeUndefined() }) it.each(["local", "snapshot"])("ignores a stale %s ID after another window resets profiles", async (source) => { if (source === "local") { provider["localModeConfigIds"].set("code", "removed-id") } else { provider["initialModeConfigIds"] = Promise.resolve({ code: "removed-id" }) } vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("reset-id") await expect(provider["getModeConfigId"]("code")).resolves.toBe("reset-id") }) it("keeps the choice this window opened with when another window changes the shared value", async () => { provider["initialModeConfigIds"] = Promise.resolve({ architect: "opened-with-id" }) vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("other-window-id") await expect(provider["getModeConfigId"]("architect")).resolves.toBe("opened-with-id") // A mode created after this window opened keeps this provider's current profile. await expect(provider["getModeConfigId"]("new-custom-mode")).resolves.toBeUndefined() }) it("prefers an explicit local choice over the snapshot", async () => { provider["initialModeConfigIds"] = Promise.resolve({ architect: "opened-with-id" }) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) await provider["setModeConfig"]("architect", "chosen-id") await expect(provider["getModeConfigId"]("architect")).resolves.toBe("chosen-id") }) it("keeps the current profile when the snapshot cannot be read", async () => { vi.spyOn(provider.providerSettingsManager, "getModeConfigIds").mockRejectedValue(new Error("unreadable")) vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("shared-id") provider["captureInitialModeConfigIds"]() await expect(provider["getModeConfigId"]("architect")).resolves.toBeUndefined() }) it("drops local choices and re-reads the mapping when state is reset", async () => { const { t } = await import("../../../i18n") vi.mocked(vscode.window.showInformationMessage).mockResolvedValueOnce(t("common:answers.yes") as never) vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "resetAllConfigs").mockResolvedValue(undefined) vi.spyOn(provider.contextProxy, "resetAllState").mockResolvedValue(undefined) // The shared custom-modes mock does not implement reset. Object.assign(provider.customModesManager, { resetCustomModes: vi.fn().mockResolvedValue(undefined) }) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "getModeConfigIds").mockResolvedValue({ code: "reset-id" }) vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined) await provider["setModeConfig"]("code", "removed-profile-id") await provider.resetState() await expect(provider["getModeConfigId"]("code")).resolves.toBe("reset-id") }) }) it("keeps the current config locally when switching to a mode without a config", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = vi.mocked(mockWebviewView.webview.onDidReceiveMessage).mock.calls[0][0] ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getModeConfigId: vi.fn().mockResolvedValue(undefined), listConfig: vi .fn() .mockResolvedValue([ { name: "current-config", id: "current-id", apiProvider: providerIdentifiers.anthropic }, ]), setModeConfig: vi.fn(), } as any await provider.setValue("currentApiConfigName", "current-config") // Switch to architect mode await messageHandler({ type: "mode", text: "architect" }) await expect(provider["getModeConfigId"]("architect")).resolves.toBe("current-id") expect(provider.providerSettingsManager.setModeConfig).not.toHaveBeenCalled() }) it("saves config as default for current mode when loading config", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] const profile: ProviderSettingsEntry = { apiProvider: providerIdentifiers.anthropic, id: "new-id", name: "new-config", } ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, activateProfile: vi.fn().mockResolvedValue(profile), listConfig: vi.fn().mockResolvedValue([profile]), setModeConfig: vi.fn(), getModeConfigId: vi.fn().mockResolvedValue(undefined), } as any // First set the mode await messageHandler({ type: "mode", text: "architect" }) // Then load the config await messageHandler({ type: "loadApiConfiguration", text: "new-config" }) // Should save new config as default for architect mode expect(provider.providerSettingsManager.setModeConfig).toHaveBeenCalledWith("architect", "new-id") }) it("load API configuration by ID works and updates mode config", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] const profile: ProviderSettingsEntry = { name: "config-by-id", id: "config-id-123", apiProvider: providerIdentifiers.anthropic, } ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, activateProfile: vi.fn().mockResolvedValue(profile), listConfig: vi.fn().mockResolvedValue([profile]), setModeConfig: vi.fn(), getModeConfigId: vi.fn().mockResolvedValue(undefined), } as any // First set the mode await messageHandler({ type: "mode", text: "architect" }) // Then load the config by ID await messageHandler({ type: "loadApiConfigurationById", text: "config-id-123" }) // Should save new config as default for architect mode expect(provider.providerSettingsManager.setModeConfig).toHaveBeenCalledWith("architect", "config-id-123") // Ensure the `activateProfile` method was called with the correct ID expect(provider.providerSettingsManager.activateProfile).toHaveBeenCalledWith({ id: "config-id-123" }) }) test("handles showRooIgnoredFiles setting", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Default value should be false expect((await provider.getState()).showRooIgnoredFiles).toBe(false) // Test showRooIgnoredFiles with true await messageHandler({ type: "updateSettings", updatedSettings: { showRooIgnoredFiles: true } }) expect(mockContext.globalState.update).toHaveBeenCalledWith("showRooIgnoredFiles", true) expect(mockPostMessage).toHaveBeenCalled() expect((await provider.getState()).showRooIgnoredFiles).toBe(true) // Test showRooIgnoredFiles with false await messageHandler({ type: "updateSettings", updatedSettings: { showRooIgnoredFiles: false } }) expect(mockContext.globalState.update).toHaveBeenCalledWith("showRooIgnoredFiles", false) expect(mockPostMessage).toHaveBeenCalled() expect((await provider.getState()).showRooIgnoredFiles).toBe(false) }) test("handles updatePrompt message correctly", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Mock existing prompts const existingPrompts = { code: { roleDefinition: "existing code role", customInstructions: "existing code prompt", }, architect: { roleDefinition: "existing architect role", customInstructions: "existing architect prompt", }, } await provider.setValue("customModePrompts", existingPrompts) // Test updating a prompt await messageHandler({ type: "updatePrompt", promptMode: "code", customPrompt: "new code prompt", }) // Verify state was updated correctly expect(mockContext.globalState.update).toHaveBeenCalledWith("customModePrompts", { ...existingPrompts, code: "new code prompt", }) // Verify state was posted to webview expect(mockPostMessage).toHaveBeenCalledWith( expect.objectContaining({ type: "state", state: expect.objectContaining({ customModePrompts: { ...existingPrompts, code: "new code prompt", }, }), }), ) }) test("customModePrompts defaults to empty object", async () => { // Mock globalState.get to return undefined for customModePrompts ;(mockContext.globalState.get as any).mockImplementation((key: string) => { if (key === "customModePrompts") { return undefined } return null }) const state = await provider.getState() expect(state.customModePrompts).toEqual({}) }) test("handles maxWorkspaceFiles message", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "updateSettings", updatedSettings: { maxWorkspaceFiles: 300 } }) expect(updateGlobalStateSpy).toHaveBeenCalledWith("maxWorkspaceFiles", 300) expect(mockContext.globalState.update).toHaveBeenCalledWith("maxWorkspaceFiles", 300) expect(mockPostMessage).toHaveBeenCalled() }) test("handles mode-specific custom instructions updates", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Mock existing prompts const existingPrompts = { code: { roleDefinition: "Code role", customInstructions: "Old instructions", }, } mockContext.globalState.get = vi.fn((key: string) => { if (key === "customModePrompts") { return existingPrompts } return undefined }) // Update custom instructions for code mode await messageHandler({ type: "updatePrompt", promptMode: "code", customPrompt: { roleDefinition: "Code role", customInstructions: "New instructions", }, }) // Verify state was updated correctly expect(mockContext.globalState.update).toHaveBeenCalledWith("customModePrompts", { code: { roleDefinition: "Code role", customInstructions: "New instructions", }, }) }) it("saves mode config when updating API configuration", async () => { // Setup mock context with mode and config name mockContext = { ...mockContext, globalState: { ...mockContext.globalState, get: vi.fn((key: string) => { if (key === "mode") { return "code" } else if (key === "currentApiConfigName") { return "test-config" } return undefined }), update: vi.fn(), keys: vi.fn().mockReturnValue([]), }, } as unknown as vscode.ExtensionContext // Create new provider with updated mock context provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] const savedForReadBack5: Record> = {} ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, listConfig: vi .fn() .mockResolvedValue([ { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic }, ]), saveConfig: vi.fn(async (name: string, settings: Record) => { savedForReadBack5[name] = settings return "test-id" }), getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: "test-id", ...savedForReadBack5[name], })), setModeConfig: vi.fn(), } as any // Update API configuration await messageHandler({ type: "upsertApiConfiguration", text: "test-config", apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, }) // Should save config as default for current mode expect(provider.providerSettingsManager.setModeConfig).toHaveBeenCalledWith("code", "test-id") }) test("file content includes line numbers", async () => { const { extractTextFromFile } = await import("../../../integrations/misc/extract-text") const result = await extractTextFromFile("test.js") expect(result).toBe("1 | const x = 1;\n2 | const y = 2;\n3 | const z = 3;") }) describe("deleteMessage", () => { beforeEach(async () => { await provider.resolveWebviewView(mockWebviewView) }) test("handles deletion with confirmation dialog", async () => { // Setup mock messages const mockMessages = [ { ts: 1000, type: "say", say: "user_feedback" }, // User message 1 { ts: 2000, type: "say", say: "tool" }, // Tool message { ts: 3000, type: "say", say: "text" }, // Message before delete { ts: 4000, type: "say", say: "tool" }, // Message to delete { ts: 5000, type: "say", say: "user_feedback" }, // Next user message { ts: 6000, type: "say", say: "user_feedback" }, // Final message ] as ClineMessage[] const mockApiHistory = [ { ts: 1000 }, { ts: 2000 }, { ts: 3000 }, { ts: 4000 }, { ts: 5000 }, { ts: 6000 }, ] as (Anthropic.MessageParam & { ts?: number })[] // Setup Task instance with auto-mock from the top of the file const mockCline = new Task(defaultTaskOptions) // Create a new mocked instance mockCline.clineMessages = mockMessages // Set test-specific messages mockCline.apiConversationHistory = mockApiHistory // Set API history await provider.addClineToStack(mockCline) // Add the mocked instance to the stack // Mock getTaskWithId ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) // Mock createTaskWithHistoryItem ;(provider as any).createTaskWithHistoryItem = vi.fn() // Trigger message deletion const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "deleteMessage", value: 4000 }) // Verify that the dialog message was sent to webview expect(mockPostMessage).toHaveBeenCalledWith({ type: "showDeleteMessageDialog", messageTs: 4000, hasCheckpoint: false, }) // Simulate user confirming deletion through the dialog await messageHandler({ type: "deleteMessageConfirm", messageTs: 4000 }) // Verify only messages before the deleted message were kept expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([ mockMessages[0], mockMessages[1], mockMessages[2], ]) // Verify only API messages before the deleted message were kept expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([ mockApiHistory[0], mockApiHistory[1], mockApiHistory[2], ]) // createTaskWithHistoryItem is only called when restoring checkpoints or aborting tasks expect((provider as any).createTaskWithHistoryItem).not.toHaveBeenCalled() }) test("handles case when no current task exists", async () => { // Clear the cline stack Object.assign(provider, { taskRegistry: new TaskRegistry() }) // Trigger message deletion const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "deleteMessage", value: 2000 }) // Verify no dialog was shown since there's no current cline expect(mockPostMessage).not.toHaveBeenCalledWith( expect.objectContaining({ type: "showDeleteMessageDialog", }), ) }) }) describe("editMessage", () => { beforeEach(async () => { await provider.resolveWebviewView(mockWebviewView) }) test("handles edit with confirmation dialog", async () => { // Setup mock messages const mockMessages = [ { ts: 1000, type: "say", say: "user_feedback" }, // User message 1 { ts: 2000, type: "say", say: "tool" }, // Tool message { ts: 3000, type: "say", say: "text" }, // Message before edit { ts: 4000, type: "say", say: "tool" }, // Message to edit { ts: 5000, type: "say", say: "user_feedback" }, // Next user message { ts: 6000, type: "say", say: "user_feedback" }, // Final message ] as ClineMessage[] const mockApiHistory = [ { ts: 1000 }, { ts: 2000 }, { ts: 3000 }, { ts: 4000 }, { ts: 5000 }, { ts: 6000 }, ] as (Anthropic.MessageParam & { ts?: number })[] // Setup Task instance with auto-mock from the top of the file const mockCline = new Task(defaultTaskOptions) // Create a new mocked instance mockCline.clineMessages = mockMessages // Set test-specific messages mockCline.apiConversationHistory = mockApiHistory // Set API history // Explicitly mock the overwrite methods since they're not being called in the tests mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() mockCline.handleWebviewAskResponse = vi.fn() await provider.addClineToStack(mockCline) // Add the mocked instance to the stack // Mock getTaskWithId ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) // Trigger message edit // Get the message handler function that was registered with the webview const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Call the message handler with a submitEditedMessage message await messageHandler({ type: "submitEditedMessage", value: 4000, editedMessageContent: "Edited message content", }) // Verify that the dialog message was sent to webview expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 4000, text: "Edited message content", hasCheckpoint: false, images: undefined, }) // Simulate user confirming edit through the dialog await messageHandler({ type: "editMessageConfirm", messageTs: 4000, text: "Edited message content", }) // Verify correct messages were kept - delete from the preceding user message to truly replace it expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([]) // Verify correct API messages were kept expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([]) // The new flow calls webviewMessageHandler recursively with askResponse // We need to verify the recursive call happened by checking if the handler was called again expect((mockWebviewView.webview.onDidReceiveMessage as any).mock.calls.length).toBeGreaterThanOrEqual(1) }) }) describe("getSystemPrompt", () => { beforeEach(async () => { mockPostMessage.mockClear() await provider.resolveWebviewView(mockWebviewView) // Reset and setup mock mockAddCustomInstructions.mockClear() mockAddCustomInstructions.mockImplementation( (modeInstructions: string, globalInstructions: string, _cwd: string) => { return Promise.resolve(modeInstructions || globalInstructions || "") }, ) }) const getMessageHandler = () => { const mockCalls = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls expect(mockCalls.length).toBeGreaterThan(0) return mockCalls[0][0] } test("handles mcpEnabled setting correctly", async () => { await provider.resolveWebviewView(mockWebviewView) const handler = getMessageHandler() expect(typeof handler).toBe("function") // Test with mcpEnabled: true vi.spyOn(provider, "getState").mockResolvedValueOnce({ apiConfiguration: { apiProvider: providerIdentifiers.openrouter, }, mcpEnabled: true, mode: "code" as const, experiments: experimentDefault, } as any) await handler({ type: "getSystemPrompt", mode: "code" }) // Verify system prompt was generated and sent expect(mockPostMessage).toHaveBeenCalledWith( expect.objectContaining({ type: "systemPrompt", text: expect.any(String), mode: "code", }), ) // Reset for second test mockPostMessage.mockClear() // Test with mcpEnabled: false vi.spyOn(provider, "getState").mockResolvedValueOnce({ apiConfiguration: { apiProvider: providerIdentifiers.openrouter, }, mcpEnabled: false, mode: "code" as const, experiments: experimentDefault, } as any) await handler({ type: "getSystemPrompt", mode: "code" }) // Verify system prompt was generated and sent expect(mockPostMessage).toHaveBeenCalledWith( expect.objectContaining({ type: "systemPrompt", text: expect.any(String), mode: "code", }), ) }) test("handles errors gracefully", async () => { // Mock SYSTEM_PROMPT to throw an error const { SYSTEM_PROMPT } = await import("../../prompts/system") vi.mocked(SYSTEM_PROMPT).mockRejectedValueOnce(new Error("Test error")) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "getSystemPrompt", mode: "code" }) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.get_system_prompt") }) test("uses code mode custom instructions", async () => { await provider.resolveWebviewView(mockWebviewView) // Mock getState to return custom instructions for code mode vi.spyOn(provider, "getState").mockResolvedValue({ apiConfiguration: { apiProvider: providerIdentifiers.openrouter, }, customModePrompts: { code: { customInstructions: "Code mode specific instructions" }, }, mode: "code" as const, experiments: experimentDefault, } as any) // Trigger getSystemPrompt const handler = getMessageHandler() await handler({ type: "getSystemPrompt", mode: "code" }) // Verify system prompt was generated and sent expect(mockPostMessage).toHaveBeenCalledWith( expect.objectContaining({ type: "systemPrompt", text: expect.any(String), mode: "code", }), ) }) test("uses correct mode-specific instructions when mode is specified", async () => { await provider.resolveWebviewView(mockWebviewView) // Mock getState to return architect mode instructions vi.spyOn(provider, "getState").mockResolvedValue({ apiConfiguration: { apiProvider: providerIdentifiers.openrouter, }, customModePrompts: { architect: { customInstructions: "Architect mode instructions" }, }, mode: "architect", mcpEnabled: false, experiments: experimentDefault, } as any) // Trigger getSystemPrompt for architect mode const handler = getMessageHandler() await handler({ type: "getSystemPrompt", mode: "architect" }) // Verify system prompt was generated and sent expect(mockPostMessage).toHaveBeenCalledWith( expect.objectContaining({ type: "systemPrompt", text: expect.any(String), mode: "architect", }), ) }) }) describe("handleModeSwitch", () => { beforeEach(async () => { // Set up webview for each test await provider.resolveWebviewView(mockWebviewView) }) it("loads saved API config when switching modes", async () => { const profile: ProviderSettingsEntry = { name: "saved-config", id: "saved-config-id", apiProvider: providerIdentifiers.anthropic, } provider["initialModeConfigIds"] = Promise.resolve({ architect: "saved-config-id" }) ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getModeConfigId: vi.fn().mockResolvedValue("saved-config-id"), listConfig: vi.fn().mockResolvedValue([profile]), activateProfile: vi.fn().mockResolvedValue(profile), setModeConfig: vi.fn(), getProfile: vi.fn().mockResolvedValue(profile), } as any // Register a stable view id so the durable per-view write is persisted await provider["setViewStateId"]("stable-test-view") // Switch to architect mode await provider.handleModeSwitch("architect") // Verify mode was updated in durable per-view state expect(mockContext.globalState.update).toHaveBeenCalledWith( "viewStates", expect.objectContaining({ ["stable-test-view"]: expect.objectContaining({ mode: "architect" }), }), ) // Verify saved config was loaded expect(provider.providerSettingsManager.getModeConfigId).not.toHaveBeenCalled() expect(provider.providerSettingsManager.activateProfile).toHaveBeenCalledWith({ name: "saved-config" }) expect(mockContext.globalState.update).toHaveBeenCalledWith("currentApiConfigName", "saved-config") // Verify state was posted to webview expect(mockPostMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "state" })) }) test("keeps the current config locally when switching to a mode without a config", async () => { ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getModeConfigId: vi.fn().mockResolvedValue(undefined), listConfig: vi .fn() .mockResolvedValue([ { name: "current-config", id: "current-id", apiProvider: providerIdentifiers.anthropic }, ]), setModeConfig: vi.fn(), } as any // Seed the shared current config name: the mode-default recording reads the // view's effective profile, which falls back to the shared slot when this // view pins no profile of its own. const contextProxy = provider.contextProxy await contextProxy.setValue("currentApiConfigName", "current-config") // Register a stable view id so the durable per-view write is persisted await provider["setViewStateId"]("stable-test-view") // Switch to architect mode await provider.handleModeSwitch("architect") // Verify mode was updated in durable per-view state expect(mockContext.globalState.update).toHaveBeenCalledWith( "viewStates", expect.objectContaining({ ["stable-test-view"]: expect.objectContaining({ mode: "architect" }), }), ) await expect(provider["getModeConfigId"]("architect")).resolves.toBe("current-id") expect(provider.providerSettingsManager.setModeConfig).not.toHaveBeenCalled() // Verify state was posted to webview expect(mockPostMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "state" })) }) }) describe("createTaskWithHistoryItem mode validation", () => { test("validates and falls back to default mode when restored mode no longer exists", async () => { await provider.resolveWebviewView(mockWebviewView) // Mock custom modes that don't include the saved mode const mockCustomModesManager = { getCustomModes: vi.fn().mockResolvedValue([ { slug: "existing-mode", name: "Existing Mode", roleDefinition: "Test role", groups: ["read"] as const, }, ]), dispose: vi.fn(), } ;(provider as any).customModesManager = mockCustomModesManager // Mock getModeBySlug to return undefined for non-existent mode const { getModeBySlug } = await import("../../../shared/modes") vi.mocked(getModeBySlug) .mockReturnValueOnce(undefined) // First call returns undefined (mode doesn't exist) .mockReturnValue({ slug: "code", name: "Code Mode", roleDefinition: "You are a code assistant", groups: ["read", "edit"], }) // Subsequent calls return default mode // Mock provider settings manager ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getModeConfigId: vi.fn().mockResolvedValue(undefined), listConfig: vi.fn().mockResolvedValue([]), } // Spy on log method to verify warning was logged const logSpy = vi.spyOn(provider, "log") // Create history item with non-existent mode const historyItem = { id: "test-id", ts: Date.now(), task: "Test task", mode: "non-existent-mode", // This mode doesn't exist number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, } // Initialize with history item await provider.createTaskWithHistoryItem(historyItem) // Verify mode validation occurred expect(mockCustomModesManager.getCustomModes).toHaveBeenCalled() expect(getModeBySlug).toHaveBeenCalledWith("non-existent-mode", expect.any(Array)) // Verify fallback to default mode, view-locally: history restore no longer // writes the shared global mode expect(provider["viewLocalState"].mode).toBe("code") expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "code") expect(logSpy).toHaveBeenCalledWith( "Mode 'non-existent-mode' from history no longer exists. Falling back to default mode 'code'.", ) // Verify history item was updated with default mode expect(historyItem.mode).toBe("code") }) test("preserves mode when it exists in custom modes", async () => { provider["initialModeConfigIds"] = Promise.resolve({ "custom-mode": "config-id" }) await provider.resolveWebviewView(mockWebviewView) // Mock custom modes that include the saved mode const mockCustomModesManager = { getCustomModes: vi.fn().mockResolvedValue([ { slug: "custom-mode", name: "Custom Mode", roleDefinition: "Custom role", groups: ["read", "edit"] as const, }, ]), dispose: vi.fn(), } ;(provider as any).customModesManager = mockCustomModesManager // Mock getModeBySlug to return the custom mode const { getModeBySlug } = await import("../../../shared/modes") vi.mocked(getModeBySlug).mockReturnValue({ slug: "custom-mode", name: "Custom Mode", roleDefinition: "Custom role", groups: ["read", "edit"], }) // Mock provider settings manager ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getModeConfigId: vi.fn().mockResolvedValue("config-id"), listConfig: vi .fn() .mockResolvedValue([ { name: "test-config", id: "config-id", apiProvider: providerIdentifiers.anthropic }, ]), activateProfile: vi.fn().mockResolvedValue({ name: "test-config", id: "config-id", apiProvider: providerIdentifiers.anthropic, }), } // Spy on log method to verify no warning was logged const logSpy = vi.spyOn(provider, "log") // Create history item with existing custom mode const historyItem = { id: "test-id", ts: Date.now(), task: "Test task", mode: "custom-mode", number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, } // Initialize with history item await provider.createTaskWithHistoryItem(historyItem) // Verify mode validation occurred expect(mockCustomModesManager.getCustomModes).toHaveBeenCalled() expect(getModeBySlug).toHaveBeenCalledWith("custom-mode", expect.any(Array)) // Verify mode was preserved view-locally (no shared global mode write) expect(provider["viewLocalState"].mode).toBe("custom-mode") expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "custom-mode") expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining("no longer exists")) // Verify history item mode was not changed expect(historyItem.mode).toBe("custom-mode") }) test("preserves mode when it exists in built-in modes", async () => { await provider.resolveWebviewView(mockWebviewView) // Mock no custom modes const mockCustomModesManager = { getCustomModes: vi.fn().mockResolvedValue([]), dispose: vi.fn(), } ;(provider as any).customModesManager = mockCustomModesManager // Mock getModeBySlug to return built-in architect mode const { getModeBySlug } = await import("../../../shared/modes") vi.mocked(getModeBySlug).mockReturnValue({ slug: "architect", name: "Architect Mode", roleDefinition: "You are an architect", groups: ["read", "edit"], }) // Mock provider settings manager ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getModeConfigId: vi.fn().mockResolvedValue(undefined), listConfig: vi.fn().mockResolvedValue([]), } // Create history item with built-in mode const historyItem = { id: "test-id", ts: Date.now(), task: "Test task", mode: "architect", number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, } // Initialize with history item await provider.createTaskWithHistoryItem(historyItem) // Verify mode was preserved view-locally (no shared global mode write) expect(provider["viewLocalState"].mode).toBe("architect") expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "architect") // Verify history item mode was not changed expect(historyItem.mode).toBe("architect") }) test("handles history items without mode property", async () => { await provider.resolveWebviewView(mockWebviewView) // Mock provider settings manager ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getModeConfigId: vi.fn().mockResolvedValue(undefined), listConfig: vi.fn().mockResolvedValue([]), } // Create history item without mode const historyItem = { id: "test-id", ts: Date.now(), task: "Test task", // No mode property number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, } // Initialize with history item await provider.createTaskWithHistoryItem(historyItem) // Verify no mode validation occurred (mode update not called) expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", expect.any(String)) }) test("continues with task restoration even if mode config loading fails", async () => { provider["initialModeConfigIds"] = Promise.resolve({ code: "config-id" }) await provider.resolveWebviewView(mockWebviewView) // Mock custom modes const mockCustomModesManager = { getCustomModes: vi.fn().mockResolvedValue([]), dispose: vi.fn(), } ;(provider as any).customModesManager = mockCustomModesManager // Mock getModeBySlug to return built-in mode const { getModeBySlug } = await import("../../../shared/modes") vi.mocked(getModeBySlug).mockReturnValue({ slug: "code", name: "Code Mode", roleDefinition: "You are a code assistant", groups: ["read", "edit"], }) // Mock provider settings manager to throw error ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, getModeConfigId: vi.fn().mockResolvedValue("config-id"), listConfig: vi .fn() .mockResolvedValue([ { name: "test-config", id: "config-id", apiProvider: providerIdentifiers.anthropic }, ]), activateProfile: vi.fn().mockRejectedValue(new Error("Failed to load config")), } // Spy on log method const logSpy = vi.spyOn(provider, "log") // Create history item const historyItem = { id: "test-id", ts: Date.now(), task: "Test task", mode: "code", number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, } // Initialize with history item - should not throw await expect(provider.createTaskWithHistoryItem(historyItem)).resolves.not.toThrow() // Verify error was logged but task restoration continued expect(logSpy).toHaveBeenCalledWith( expect.stringContaining("Failed to restore API configuration for mode 'code'"), ) }) }) describe("updateCustomMode", () => { test("updates both file and state when updating custom mode", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Mock CustomModesManager methods ;(provider as any).customModesManager = { updateCustomMode: vi.fn().mockResolvedValue(undefined), getCustomModes: vi.fn().mockResolvedValue([ { slug: "test-mode", name: "Test Mode", roleDefinition: "Updated role definition", groups: ["read"] as const, }, ]), dispose: vi.fn(), } as any // Test updating a custom mode await messageHandler({ type: "updateCustomMode", modeConfig: { slug: "test-mode", name: "Test Mode", roleDefinition: "Updated role definition", groups: ["read"] as const, }, }) // Verify CustomModesManager.updateCustomMode was called expect(provider.customModesManager.updateCustomMode).toHaveBeenCalledWith( "test-mode", expect.objectContaining({ slug: "test-mode", roleDefinition: "Updated role definition", }), ) // Verify state was updated expect(mockContext.globalState.update).toHaveBeenCalledWith("customModes", [ { groups: ["read"], name: "Test Mode", roleDefinition: "Updated role definition", slug: "test-mode" }, ]) // Verify state was posted to webview // Verify state was posted to webview with correct format expect(mockPostMessage).toHaveBeenCalledWith( expect.objectContaining({ type: "state", state: expect.objectContaining({ customModes: [ expect.objectContaining({ slug: "test-mode", roleDefinition: "Updated role definition", }), ], }), }), ) }) }) // A custom-mode deletion or save writes "mode" straight into the shared store, so this // view's durable pin keeps the slug the call just wrote away from it: a view pinned to a // deleted mode goes on reporting a slug that no longer exists. The pinned and the // unpinned view are held apart here instead of averaged into one case. describe("custom-mode deletion and the mode pin", () => { // The file-level shared/modes double answers getModeBySlug with one fixed truthy object whatever it // is asked about, so every deleted slug would still read as resolving. This block needs the real // lookup - installed here and restored afterwards the way the mode-switch tests do - because the // deletion handler now asks whether the slug survives the deletion. let restoreGetModeBySlug: (() => void) | undefined beforeEach(async () => { const modesModule = vi.mocked(await import("../../../shared/modes")) const actualModes = await vi.importActual("../../../shared/modes") // The stub answers every question with the same object, so reading it once is enough // to be able to put it back afterwards (the mode-switch tests capture it the same way). const stubbedReturn = modesModule.getModeBySlug("code") modesModule.getModeBySlug.mockImplementation(actualModes.getModeBySlug) restoreGetModeBySlug = () => modesModule.getModeBySlug.mockReturnValue(stubbedReturn) }) afterEach(() => restoreGetModeBySlug?.()) beforeEach(() => { // The harness CustomModesManager double has no deleteCustomMode member, so it is // installed on the instance the way the mutation-queue test installs it. The list is mutable // and the delete removes from it, because the handler reads the list again after the deletion // to decide whether the slug still resolves: a static list would report a deleted mode as // still available. const modes = [ { slug: "gone-mode", name: "Gone Mode", roleDefinition: "A mode that is about to be deleted", groups: ["read"] as const, }, ] Object.assign(provider.customModesManager, { deleteCustomMode: vi.fn(async (slug: string) => { for (let i = modes.length - 1; i >= 0; i--) { if (modes[i].slug === slug) { modes.splice(i, 1) } } }), getCustomModes: vi.fn(async () => [...modes]), }) }) const handlerForView = async (viewStateId: string) => { await provider.resolveWebviewView(mockWebviewView) await provider["setViewStateId"](viewStateId) return vi.mocked(mockWebviewView.webview.onDidReceiveMessage).mock.calls[0][0] } // getState() is what the fan-out serializes for this view: it merges the view's pin // over the shared store, so it is the mode the webview actually renders. const servedMode = async () => (await provider.getState()).mode // Both slugs the cases below name, so the mode the provider validates against always // carries the mode the view under test is pinned to. const seedTwoModes = () => { // Same mutable list as the beforeEach: the second read must reflect the deletion. const modes = [ { slug: "gone-mode", name: "Gone Mode", roleDefinition: "A mode that is about to be deleted", groups: ["read"] as const, }, { slug: "keep-mode", name: "Keep Mode", roleDefinition: "A mode this view is pinned to", groups: ["read"] as const, }, ] Object.assign(provider.customModesManager, { deleteCustomMode: vi.fn(async (slug: string) => { for (let i = modes.length - 1; i >= 0; i--) { if (modes[i].slug === slug) { modes.splice(i, 1) } } }), getCustomModes: vi.fn(async () => [...modes]), }) } it("moves a view pinned to the deleted mode onto the default mode", async () => { const messageHandler = await handlerForView("pinned-deleted-view") await provider.saveViewState("mode", "gone-mode") await messageHandler({ type: "deleteCustomMode", slug: "gone-mode" }) expect(provider.customModesManager.deleteCustomMode).toHaveBeenCalledWith("gone-mode") // Before the routing fix the shared store moved to the default slug while this view // kept pinning the deleted one, so the webview was shown "gone-mode" and the next // task would record a slug no mode list contains. expect(await servedMode()).toBe("code") expect(provider["viewLocalState"].mode).toBe("code") expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ "pinned-deleted-view": { mode: "code" }, }) }) it("reports the default mode to a view that has no pin of its own", async () => { const messageHandler = await handlerForView("unpinned-deleted-view") // The shared selection is the slug being deleted - the selection this reset exists // for - and the view has no pin of its own to keep it away from it. await provider.contextProxy.setValue("mode", "gone-mode") await messageHandler({ type: "deleteCustomMode", slug: "gone-mode" }) // An unpinned view follows the shared store either way; what routing adds is the // record. A mode write through the provider pins this view's copy to the slug the // shared store now holds, which is the rule the updateSettings path already follows. expect(await servedMode()).toBe("code") expect(provider.contextProxy.getValue("mode")).toBe("code") expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ "unpinned-deleted-view": { mode: "code" }, }) }) // Deleting one mode must not move a view that is pinned to a different one: the reset // keys off the mode this view actually resolves to - its pin, or the shared selection // when it has no pin of its own. it("keeps a view pinned to another mode on that mode when a different mode is deleted", async () => { const messageHandler = await handlerForView("pinned-other-view") seedTwoModes() await provider.saveViewState("mode", "keep-mode") await messageHandler({ type: "deleteCustomMode", slug: "gone-mode" }) expect(await servedMode()).toBe("keep-mode") expect(provider["viewLocalState"].mode).toBe("keep-mode") // The shared selection was never the deleted slug, so nothing writes over it here. expect(provider.contextProxy.getValue("mode")).toBeUndefined() }) it("resets the shared selection without moving a view pinned to another mode", async () => { const messageHandler = await handlerForView("pinned-other-shared-view") seedTwoModes() // The shared selection is the mode being deleted while this view pins another one: // the shared layer must move so unpinned views stop resolving to the deleted slug, // while this view keeps its own pin. await provider.contextProxy.setValue("mode", "gone-mode") await provider.saveViewState("mode", "keep-mode") await messageHandler({ type: "deleteCustomMode", slug: "gone-mode" }) expect(provider.contextProxy.getValue("mode")).toBe("code") expect(provider["viewLocalState"].mode).toBe("keep-mode") expect(await servedMode()).toBe("keep-mode") }) it("moves the pin onto the mode a pinned view just saved", async () => { const messageHandler = await handlerForView("pinned-saved-view") await provider.saveViewState("mode", "gone-mode") Object.assign(provider.customModesManager, { getCustomModes: vi.fn().mockResolvedValue([ { slug: "new-mode", name: "New Mode", roleDefinition: "A custom mode this view just saved", groups: ["read"] as const, }, ]), }) await messageHandler({ type: "updateCustomMode", modeConfig: { slug: "new-mode", name: "New Mode", roleDefinition: "A custom mode this view just saved", groups: ["read"] as const, }, }) // Saving a mode makes this view use it; a view pinned elsewhere must follow, not // stay on the earlier slug while the shared store moved on. expect(await servedMode()).toBe("new-mode") expect(provider["viewLocalState"].mode).toBe("new-mode") expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ "pinned-saved-view": { mode: "new-mode" }, }) }) }) describe("upsertApiConfiguration", () => { test("handles error in upsertApiConfiguration gracefully", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, setModeConfig: vi.fn().mockRejectedValue(new Error("Failed to update mode config")), listConfig: vi .fn() .mockResolvedValue([ { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic }, ]), } as any // Mock getState to provide necessary data vi.spyOn(provider, "getState").mockResolvedValue({ mode: "code", currentApiConfigName: "test-config", } as any) // Trigger upsertApiConfiguration await messageHandler({ type: "upsertApiConfiguration", text: "test-config", apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "test-key" }, }) // Verify error was logged and user was notified expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( expect.stringContaining("Error create new api configuration"), ) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.create_api_config") }) test("handles successful upsertApiConfiguration", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] const savedForReadBack6: Record> = {} ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, setModeConfig: vi.fn(), saveConfig: vi.fn(async (name: string, settings: Record) => { savedForReadBack6[name] = settings return undefined }), getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: undefined, ...savedForReadBack6[name], })), listConfig: vi .fn() .mockResolvedValue([ { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic }, ]), } as any const testApiConfig = { apiProvider: providerIdentifiers.anthropic, apiKey: "test-key", } // Trigger upsertApiConfiguration await messageHandler({ type: "upsertApiConfiguration", text: "test-config", apiConfiguration: testApiConfig, }) // Verify config was saved expect(provider.providerSettingsManager.saveConfig).toHaveBeenCalledWith("test-config", testApiConfig) // Verify state updates expect(mockContext.globalState.update).toHaveBeenCalledWith("listApiConfigMeta", [ { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic }, ]) expect(mockContext.globalState.update).toHaveBeenCalledWith("currentApiConfigName", "test-config") // Verify state was posted to webview expect(mockPostMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "state" })) }) test("handles buildApiHandler error in updateApiConfiguration", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Mock buildApiHandler to throw an error const { buildApiHandler } = await import("../../../api") ;(buildApiHandler as any).mockImplementationOnce(() => { throw new Error("API handler error") }) const savedForReadBack7: Record> = {} ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, setModeConfig: vi.fn(), saveConfig: vi.fn(async (name: string, settings: Record) => { savedForReadBack7[name] = settings return undefined }), getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: undefined, ...savedForReadBack7[name], })), listConfig: vi .fn() .mockResolvedValue([ { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic }, ]), } as any // Setup Task instance with auto-mock from the top of the file const mockCline = new Task(defaultTaskOptions) // Create a new mocked instance await provider.addClineToStack(mockCline) const testApiConfig = { apiProvider: providerIdentifiers.anthropic, apiKey: "test-key", } // Trigger upsertApiConfiguration await messageHandler({ type: "upsertApiConfiguration", text: "test-config", apiConfiguration: testApiConfig, }) // Verify error handling expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( expect.stringContaining("Error create new api configuration"), ) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.create_api_config") // Verify state was still updated expect(mockContext.globalState.update).toHaveBeenCalledWith("listApiConfigMeta", [ { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic }, ]) expect(mockContext.globalState.update).toHaveBeenCalledWith("currentApiConfigName", "test-config") }) test("handles successful saveApiConfiguration", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] const savedForReadBack8: Record> = {} ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, setModeConfig: vi.fn(), saveConfig: vi.fn(async (name: string, settings: Record) => { savedForReadBack8[name] = settings return undefined }), getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: undefined, ...savedForReadBack8[name], })), listConfig: vi .fn() .mockResolvedValue([ { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic }, ]), } as any const testApiConfig = { apiProvider: providerIdentifiers.anthropic, apiKey: "test-key", } // Trigger upsertApiConfiguration await messageHandler({ type: "saveApiConfiguration", text: "test-config", apiConfiguration: testApiConfig, }) // Verify config was saved expect(provider.providerSettingsManager.saveConfig).toHaveBeenCalledWith("test-config", testApiConfig) // Verify state updates expect(mockContext.globalState.update).toHaveBeenCalledWith("listApiConfigMeta", [ { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic }, ]) expect(updateGlobalStateSpy).toHaveBeenCalledWith("listApiConfigMeta", [ { name: "test-config", id: "test-id", apiProvider: providerIdentifiers.anthropic }, ]) }) }) }) describe("webviewMessageHandler no-floating-promises coverage", () => { const createProvider = (overrides: Record = {}) => Object.assign( { context: { secrets: { get: vi.fn().mockResolvedValue(undefined), }, }, contextProxy: { getValue: vi.fn(), setValue: vi.fn().mockResolvedValue(undefined), }, postMessageToWebview: vi.fn().mockResolvedValue(true), postStateToWebview: vi.fn().mockResolvedValue(undefined), getCurrentTask: vi.fn(), getCurrentWorkspaceCodeIndexScope: vi.fn(), getMcpHub: vi.fn().mockReturnValue({ getMcpSettingsFilePath: vi.fn().mockResolvedValue("/test/mcp.json"), }), providerSettingsManager: { listConfig: vi.fn().mockResolvedValue([]), }, customModesManager: { getCustomModesFilePath: vi.fn().mockResolvedValue("/test/custom-modes.yaml"), exportModeWithRules: vi.fn(), importModeWithRules: vi.fn(), getCustomModes: vi.fn().mockResolvedValue([]), checkRulesDirectoryHasContent: vi.fn().mockResolvedValue(true), }, exportTaskWithId: vi.fn().mockResolvedValue(undefined), showTaskWithId: vi.fn().mockResolvedValue(undefined), condenseTaskContext: vi.fn().mockResolvedValue(undefined), deleteTaskWithId: vi.fn().mockResolvedValue(undefined), log: vi.fn(), cwd: "/test/workspace", }, overrides, ) as unknown as ClineProvider const createIndexManager = (overrides: Record = {}) => Object.assign( { setWorkspaceEnabled: vi.fn().mockResolvedValue(undefined), setAutoEnableDefault: vi.fn().mockResolvedValue(undefined), isFeatureEnabled: true, isFeatureConfigured: true, isWorkspaceEnabled: true, initialize: vi.fn().mockResolvedValue(undefined), state: "Standby", isInitialized: true, startIndexing: vi.fn().mockResolvedValue(undefined), stopIndexing: vi.fn(), clearIndexData: vi.fn().mockResolvedValue(undefined), getCurrentStatus: vi.fn().mockReturnValue({ systemStatus: "Standby" }), }, overrides, ) beforeEach(() => { vi.clearAllMocks() }) it("logs a detached indexing rejection without rejecting the handler", async () => { let rejectIndexing!: (error: Error) => void const indexingPromise = new Promise((_, reject) => { rejectIndexing = reject }) const manager = createIndexManager({ startIndexing: vi.fn().mockReturnValue(indexingPromise), }) const provider = createProvider({ getCurrentWorkspaceCodeIndexScope: vi.fn().mockReturnValue({ codeIndexManager: manager }), }) await expect(webviewMessageHandler(provider, { type: "startIndexing" })).resolves.toBeUndefined() expect(provider.getCurrentWorkspaceCodeIndexScope).toHaveBeenCalledOnce() expect(manager.startIndexing).toHaveBeenCalledOnce() rejectIndexing(new Error("boom")) await Promise.resolve() await Promise.resolve() expect(provider.log).toHaveBeenCalledWith("Indexing error: Error: boom") }) it("covers the changed task-operation happy paths", async () => { const task = { taskId: "task-1", handleTerminalOperation: vi.fn().mockResolvedValue(undefined), } const provider = createProvider({ getCurrentTask: vi.fn().mockReturnValue(task) }) await webviewMessageHandler(provider, { type: "terminalOperation", terminalOperation: "continue" }) await webviewMessageHandler(provider, { type: "exportCurrentTask" }) await webviewMessageHandler(provider, { type: "showTaskWithId", text: "task-2" }) await webviewMessageHandler(provider, { type: "condenseTaskContextRequest", text: "task-2" }) await webviewMessageHandler(provider, { type: "deleteTaskWithId", text: "task-2" }) await webviewMessageHandler(provider, { type: "exportTaskWithId", text: "task-2" }) expect(task.handleTerminalOperation).toHaveBeenCalledWith("continue") expect(provider.exportTaskWithId).toHaveBeenCalledTimes(2) expect(provider.showTaskWithId).toHaveBeenCalledWith("task-2") expect(provider.condenseTaskContext).toHaveBeenCalledWith("task-2") expect(provider.deleteTaskWithId).toHaveBeenCalledWith("task-2") }) it("covers changed file, image, mention, settings, and TTS dispatch paths", async () => { const { openFile } = await import("../../../integrations/misc/open-file") const { openImage, saveImage } = await import("../../../integrations/misc/image-handler") const { openMention } = await import("../../mentions") const { playTts } = await import("../../../utils/tts") const provider = createProvider() await webviewMessageHandler(provider, { type: "openImage", text: "/test/image.png" }) await webviewMessageHandler(provider, { type: "saveImage", dataUri: "invalid" }) await webviewMessageHandler(provider, { type: "openFile", text: "/test/file.ts" }) await webviewMessageHandler(provider, { type: "openMention", text: "file.ts" }) await webviewMessageHandler(provider, { type: "openCustomModesSettings" }) await webviewMessageHandler(provider, { type: "openMcpSettings" }) await webviewMessageHandler(provider, { type: "playTts", text: "hello" }) expect(openImage).toHaveBeenCalledWith("/test/image.png", { values: undefined }) expect(saveImage).toHaveBeenCalledOnce() expect(openFile).toHaveBeenCalledTimes(3) expect(openMention).toHaveBeenCalledWith("/test/workspace", "file.ts") expect(playTts).toHaveBeenCalledOnce() }) it("covers changed configuration and rules response paths", async () => { const provider = createProvider() await webviewMessageHandler(provider, { type: "getListApiConfiguration" }) await webviewMessageHandler(provider, { type: "checkRulesDirectory", slug: "mode-1" }) expect(provider.postMessageToWebview).toHaveBeenCalledWith({ type: "listApiConfig", listApiConfig: [] }) expect(provider.postMessageToWebview).toHaveBeenCalledWith({ type: "checkRulesDirectoryResult", slug: "mode-1", hasContent: true, }) }) it("covers all changed export-mode response paths", async () => { const provider = createProvider() const exportModeWithRules = provider.customModesManager.exportModeWithRules as ReturnType const showSaveDialog = vi.mocked(vscode.window.showSaveDialog) exportModeWithRules.mockResolvedValueOnce({ success: true, yaml: "mode: one" }) showSaveDialog.mockResolvedValueOnce({ fsPath: "/test/mode.yaml" } as vscode.Uri) await webviewMessageHandler(provider, { type: "exportMode", slug: "mode-1" }) exportModeWithRules.mockResolvedValueOnce({ success: true, yaml: "mode: one" }) showSaveDialog.mockResolvedValueOnce(undefined) await webviewMessageHandler(provider, { type: "exportMode", slug: "mode-1" }) exportModeWithRules.mockResolvedValueOnce({ success: false, error: "invalid mode" }) await webviewMessageHandler(provider, { type: "exportMode", slug: "mode-1" }) exportModeWithRules.mockRejectedValueOnce(new Error("export failed")) await webviewMessageHandler(provider, { type: "exportMode", slug: "mode-1" }) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "exportModeResult", success: true }), ) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "exportModeResult", error: "Export cancelled" }), ) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "exportModeResult", error: "invalid mode" }), ) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "exportModeResult", error: "export failed" }), ) }) it("covers all changed import-mode response paths", async () => { const provider = createProvider() const importModeWithRules = provider.customModesManager.importModeWithRules as ReturnType const showOpenDialog = vi.mocked(vscode.window.showOpenDialog) const selectedFile = [{ fsPath: "/test/mode.yaml" } as vscode.Uri] showOpenDialog.mockResolvedValueOnce(selectedFile) importModeWithRules.mockResolvedValueOnce({ success: true, slug: "mode-1" }) await webviewMessageHandler(provider, { type: "importMode", source: "project" }) showOpenDialog.mockResolvedValueOnce(selectedFile) importModeWithRules.mockResolvedValueOnce({ success: false, error: "invalid mode" }) await webviewMessageHandler(provider, { type: "importMode", source: "project" }) showOpenDialog.mockResolvedValueOnce(undefined) await webviewMessageHandler(provider, { type: "importMode", source: "project" }) showOpenDialog.mockRejectedValueOnce(new Error("dialog failed")) await webviewMessageHandler(provider, { type: "importMode", source: "project" }) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "importModeResult", success: true }), ) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "importModeResult", error: "invalid mode" }), ) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "importModeResult", error: "cancelled" }), ) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "importModeResult", error: "dialog failed" }), ) }) it("covers changed cloud sign-out and rate-limit error responses", async () => { const { CloudService } = await import("@roo-code/cloud") const { openAiCodexOAuthManager } = await import("../../../integrations/openai-codex/oauth") const provider = createProvider() vi.mocked(CloudService.hasInstance).mockReturnValueOnce(false) await webviewMessageHandler(provider, { type: "rooCloudSignOut" }) await webviewMessageHandler(provider, { type: "rooCloudSignOut" }) vi.mocked(openAiCodexOAuthManager.getAccessToken).mockRejectedValueOnce(new Error("token failed")) await webviewMessageHandler(provider, { type: "requestOpenAiCodexRateLimits" }) expect(provider.postMessageToWebview).toHaveBeenCalledWith({ type: "openAiCodexRateLimits", error: "token failed", }) }) it("covers changed indexing status, secret, and missing-manager responses", async () => { const manager = createIndexManager() const getScope = vi.fn().mockReturnValueOnce(undefined).mockReturnValue({ codeIndexManager: manager }) const provider = createProvider({ getCurrentWorkspaceCodeIndexScope: getScope, }) await webviewMessageHandler(provider, { type: "requestIndexingStatus" }) expect(manager.getCurrentStatus).not.toHaveBeenCalled() expect(provider.postMessageToWebview).toHaveBeenCalledWith({ type: "indexingStatusUpdate", values: expect.objectContaining({ systemStatus: "Error", message: expect.any(String) }), }) await webviewMessageHandler(provider, { type: "requestIndexingStatus" }) expect(getScope).toHaveBeenCalledTimes(2) expect(manager.getCurrentStatus).toHaveBeenCalledOnce() expect(provider.postMessageToWebview).toHaveBeenLastCalledWith({ type: "indexingStatusUpdate", values: manager.getCurrentStatus.mock.results[0].value, }) await webviewMessageHandler(provider, { type: "requestCodeIndexSecretStatus" }) getScope.mockReturnValueOnce(undefined) await webviewMessageHandler(provider, { type: "startIndexing" }) expect(getScope).toHaveBeenCalledTimes(3) expect(manager.setWorkspaceEnabled).not.toHaveBeenCalled() expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "codeIndexSecretStatus" }), ) expect(provider.log).toHaveBeenCalledWith("Cannot start indexing: No workspace folder open") }) it("catches both start-indexing calls during error recovery", async () => { const manager = createIndexManager({ isInitialized: false, startIndexing: vi .fn() .mockRejectedValueOnce(new Error("first failure")) .mockRejectedValueOnce(new Error("second failure")), }) const provider = createProvider({ getCurrentWorkspaceCodeIndexScope: vi.fn().mockReturnValue({ codeIndexManager: manager }), }) await webviewMessageHandler(provider, { type: "startIndexing" }) await Promise.resolve() expect(manager.startIndexing).toHaveBeenCalledTimes(2) expect(provider.log).toHaveBeenCalledWith("Indexing error: Error: first failure") expect(provider.log).toHaveBeenCalledWith("Indexing error: Error: second failure") }) it("covers changed stop, toggle, and detached toggle rejection paths", async () => { const manager = createIndexManager({ startIndexing: vi.fn().mockRejectedValue(new Error("toggle failure")), }) const provider = createProvider({ getCurrentWorkspaceCodeIndexScope: vi.fn().mockReturnValue({ codeIndexManager: manager, workspaceIndexingEnablementManager: new WorkspaceIndexingEnablementManager(manager), }), }) await webviewMessageHandler(provider, { type: "stopIndexing" }) expect(provider.getCurrentWorkspaceCodeIndexScope).toHaveBeenCalledOnce() expect(provider.postMessageToWebview).toHaveBeenCalledExactlyOnceWith({ type: "indexingStatusUpdate", values: manager.getCurrentStatus(), }) await webviewMessageHandler(provider, { type: "toggleWorkspaceIndexing", bool: true }) await Promise.resolve() expect(manager.stopIndexing).toHaveBeenCalledOnce() expect(provider.log).toHaveBeenCalledWith("Indexing error: Error: toggle failure") expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "indexingStatusUpdate" }), ) }) it("does not toggle indexing or publish status without a workspace scope", async () => { const provider = createProvider() await webviewMessageHandler(provider, { type: "toggleWorkspaceIndexing", bool: true }) expect(provider.getCurrentWorkspaceCodeIndexScope).toHaveBeenCalledOnce() expect(provider.log).toHaveBeenCalledExactlyOnceWith( "Cannot toggle workspace indexing: No workspace folder open", ) expect(provider.postMessageToWebview).not.toHaveBeenCalled() }) it.each([ { bool: true, expected: true }, { bool: false, expected: false }, { bool: undefined, expected: false }, ])("delegates workspace enablement with bool=$bool as $expected", async ({ bool, expected }) => { const setEnabled = vi.fn().mockResolvedValue(undefined) const provider = createProvider({ getCurrentWorkspaceCodeIndexScope: vi.fn().mockReturnValue({ workspaceIndexingEnablementManager: { setEnabled }, }), }) const message: WebviewMessage = { type: "toggleWorkspaceIndexing" } if (bool !== undefined) { message.bool = bool } await webviewMessageHandler(provider, message) expect(setEnabled).toHaveBeenCalledExactlyOnceWith(expected, provider) // Status publication belongs to the enablement manager, not the handler. expect(provider.postMessageToWebview).not.toHaveBeenCalled() expect(provider.log).not.toHaveBeenCalled() }) it("does not stop indexing or publish status without a workspace scope", async () => { const provider = createProvider() await webviewMessageHandler(provider, { type: "stopIndexing" }) expect(provider.getCurrentWorkspaceCodeIndexScope).toHaveBeenCalledOnce() expect(provider.log).toHaveBeenCalledWith("Cannot stop indexing: No workspace folder open") expect(provider.postMessageToWebview).not.toHaveBeenCalled() }) it.each([true, false])("resolves the scope after saving index settings (workspace=%s)", async (hasWorkspace) => { const handleSettingsChange = vi.fn().mockResolvedValue(undefined) const manager = createIndexManager({ handleSettingsChange, isFeatureEnabled: false }) const provider = createProvider({ getCurrentWorkspaceCodeIndexScope: vi .fn() .mockReturnValue(hasWorkspace ? { codeIndexManager: manager } : undefined), }) await webviewMessageHandler(provider, { type: "saveCodeIndexSettingsAtomic", codeIndexSettings: { codebaseIndexEnabled: false, codebaseIndexQdrantUrl: "http://localhost:6333", codebaseIndexEmbedderProvider: providerIdentifiers.openai, codebaseIndexEmbedderModelId: "text-embedding-3-small", }, }) expect(provider.getCurrentWorkspaceCodeIndexScope).toHaveBeenCalledOnce() expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "codeIndexSettingsSaved", success: true }), ) if (hasWorkspace) { expect(handleSettingsChange).toHaveBeenCalledOnce() } else { expect(handleSettingsChange).not.toHaveBeenCalled() expect(provider.log).toHaveBeenCalledWith("Cannot save code index settings: No workspace folder open") } }) it("does not update auto-enable defaults without a workspace scope", async () => { const provider = createProvider() await webviewMessageHandler(provider, { type: "setAutoEnableDefault", bool: true }) expect(provider.getCurrentWorkspaceCodeIndexScope).toHaveBeenCalledOnce() expect(provider.log).toHaveBeenCalledWith("Cannot set auto-enable default: No workspace folder open") expect(provider.postMessageToWebview).not.toHaveBeenCalled() }) it("catches auto-enabled indexing failures and posts the resulting status", async () => { const { CodeIndexManagerRegistry } = await import("../../../services/code-index/code-index-manager-registry") let workspaceEnabled = false const manager = createIndexManager({ setAutoEnableDefault: vi.fn().mockImplementation(async () => { workspaceEnabled = true }), startIndexing: vi.fn().mockRejectedValue(new Error("auto-enable failure")), }) Object.defineProperty(manager, "isWorkspaceEnabled", { get: () => workspaceEnabled }) const getAllInstances = vi .spyOn(CodeIndexManagerRegistry, "getAllInstances") .mockReturnValue([manager] as unknown as ReturnType) const provider = createProvider({ getCurrentWorkspaceCodeIndexScope: vi.fn().mockReturnValue({ codeIndexManager: manager }), }) try { await webviewMessageHandler(provider, { type: "setAutoEnableDefault", bool: true }) await Promise.resolve() expect(provider.getCurrentWorkspaceCodeIndexScope).toHaveBeenCalledOnce() expect(manager.startIndexing).toHaveBeenCalledOnce() expect(provider.log).toHaveBeenCalledWith("Indexing error: Error: auto-enable failure") expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "indexingStatusUpdate" }), ) } finally { getAllInstances.mockRestore() } }) it("covers changed clear-index response paths", async () => { const manager = createIndexManager() const getScope = vi.fn().mockReturnValueOnce(undefined).mockReturnValue({ codeIndexManager: manager }) const provider = createProvider({ getCurrentWorkspaceCodeIndexScope: getScope }) await webviewMessageHandler(provider, { type: "clearIndexData" }) expect(manager.clearIndexData).not.toHaveBeenCalled() expect(provider.log).toHaveBeenCalledWith("Cannot clear index data: No workspace folder open") expect(provider.postMessageToWebview).toHaveBeenCalledExactlyOnceWith({ type: "indexCleared", values: { success: false, error: expect.any(String) }, }) await webviewMessageHandler(provider, { type: "clearIndexData" }) manager.clearIndexData.mockRejectedValueOnce(new Error("clear failed")) await webviewMessageHandler(provider, { type: "clearIndexData" }) expect(getScope).toHaveBeenCalledTimes(3) expect(manager.clearIndexData).toHaveBeenCalledTimes(2) expect(provider.postMessageToWebview).toHaveBeenCalledWith({ type: "indexCleared", values: { success: true }, }) expect(provider.postMessageToWebview).toHaveBeenCalledWith({ type: "indexCleared", values: { success: false, error: "clear failed" }, }) }) it("covers changed marketplace error and removal responses", async () => { const provider = createProvider() const item = { id: "item-1", name: "Item 1", description: "Test marketplace item", type: "mode", content: "slug: item-1", } satisfies NonNullable const options = { target: "project" } satisfies NonNullable const marketplaceManager = { installMarketplaceItem: vi.fn().mockRejectedValue(new Error("install failed")), removeInstalledMarketplaceItem: vi .fn() .mockResolvedValueOnce(undefined) .mockRejectedValueOnce(new Error("remove failed")), } const managerArgument = marketplaceManager as unknown as NonNullable< Parameters[2] > await webviewMessageHandler( provider, { type: "installMarketplaceItem", mpItem: item, mpInstallOptions: options }, managerArgument, ) await webviewMessageHandler( provider, { type: "removeInstalledMarketplaceItem", mpItem: item, mpInstallOptions: options }, managerArgument, ) await webviewMessageHandler( provider, { type: "removeInstalledMarketplaceItem", mpItem: item, mpInstallOptions: options }, managerArgument, ) await webviewMessageHandler(provider, { type: "removeInstalledMarketplaceItem", mpItem: item, mpInstallOptions: options, }) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "marketplaceInstallResult", success: false }), ) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "marketplaceRemoveResult", success: true }), ) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "marketplaceRemoveResult", error: "remove failed" }), ) expect(provider.postMessageToWebview).toHaveBeenCalledWith( expect.objectContaining({ type: "marketplaceRemoveResult", error: "Marketplace manager is not available" }), ) }) }) describe("Project MCP Settings", () => { let provider: ClineProvider let mockContext: vscode.ExtensionContext let mockOutputChannel: vscode.OutputChannel let mockWebviewView: any let mockPostMessage: any beforeEach(async () => { vi.clearAllMocks() const pathUtils = await import("../../../utils/path") vi.mocked(pathUtils.getWorkspacePath).mockReturnValue("") mockContext = { extensionPath: "/test/path", extensionUri: { fsPath: "/test/path" } as vscode.Uri, globalState: { get: vi.fn(), update: vi.fn(), keys: vi.fn().mockReturnValue([]), }, secrets: { get: vi.fn(), store: vi.fn(), delete: vi.fn(), }, workspaceState: { get: vi.fn().mockReturnValue(undefined), update: vi.fn().mockResolvedValue(undefined), keys: vi.fn().mockReturnValue([]), }, subscriptions: [], extension: { packageJSON: { version: "1.0.0" }, }, globalStorageUri: { fsPath: "/test/storage/path", }, } as unknown as vscode.ExtensionContext mockOutputChannel = { appendLine: vi.fn(), clear: vi.fn(), dispose: vi.fn(), } as unknown as vscode.OutputChannel mockPostMessage = vi.fn() mockWebviewView = { webview: { postMessage: mockPostMessage, html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), cspSource: "vscode-webview://test-csp-source", }, visible: true, onDidDispose: vi.fn(), onDidChangeVisibility: vi.fn(), } ;(vscode.window as any).activeTextEditor = undefined ;(vscode.workspace.getWorkspaceFolder as any).mockReset() provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) }) test("handles openProjectMcpSettings message", async () => { // Mock workspace folders first ;(vscode.workspace as any).workspaceFolders = [{ uri: { fsPath: "/test/workspace" } }] const pathUtils = await import("../../../utils/path") vi.mocked(pathUtils.getWorkspacePath).mockReturnValue("/test/workspace") // Mock fs functions const fs = await import("fs/promises") const mockedFs = vi.mocked(fs) mockedFs.mkdir.mockClear() mockedFs.mkdir.mockResolvedValue(undefined) mockedFs.writeFile.mockClear() mockedFs.writeFile.mockResolvedValue(undefined) // Mock fileExistsAtPath to return false (file doesn't exist) const fsUtils = await import("../../../utils/fs") vi.spyOn(fsUtils, "fileExistsAtPath").mockResolvedValue(false) // Mock openFile const openFileModule = await import("../../../integrations/misc/open-file") const openFileSpy = vi.spyOn(openFileModule, "openFile").mockClear().mockResolvedValue(undefined) // Set up the webview await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Ensure the message handler is properly set up expect(messageHandler).toBeDefined() expect(typeof messageHandler).toBe("function") // Trigger openProjectMcpSettings through the message handler await messageHandler({ type: "openProjectMcpSettings", }) const expectedRooDir = path.join("/test/workspace", ".roo") const expectedMcpPath = path.join(expectedRooDir, "mcp.json") // Check that fs.mkdir was called with the correct path expect(mockedFs.mkdir).toHaveBeenCalledWith(expectedRooDir, { recursive: true }) expect(pathUtils.getWorkspacePath).toHaveBeenCalled() // Verify file was created with default content expect(safeWriteJson).toHaveBeenCalledWith(expectedMcpPath, { mcpServers: {} }, { prettyPrint: true }) // Check that openFile was called expect(openFileSpy).toHaveBeenCalledWith(expectedMcpPath) }) test("handles openProjectMcpSettings when workspace is not open", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Mock no workspace folders ;(vscode.workspace as any).workspaceFolders = [] // Trigger openProjectMcpSettings await messageHandler({ type: "openProjectMcpSettings" }) // Verify error message was shown expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.no_workspace") }) test("handles openProjectMcpSettings file creation error", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Mock workspace folders ;(vscode.workspace as any).workspaceFolders = [{ uri: { fsPath: "/test/workspace" } }] const pathUtils = await import("../../../utils/path") vi.mocked(pathUtils.getWorkspacePath).mockReturnValue("/test/workspace") // Mock fs functions to fail const fs = await import("fs/promises") const mockedFs = vi.mocked(fs) mockedFs.mkdir.mockRejectedValue(new Error("Failed to create directory")) // Trigger openProjectMcpSettings await messageHandler({ type: "openProjectMcpSettings", }) // Verify the translated error key is surfaced in test mode expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.create_json") }) }) describe("getTelemetryProperties", () => { let defaultTaskOptions: TaskOptions let provider: ClineProvider let mockContext: vscode.ExtensionContext let mockOutputChannel: vscode.OutputChannel let mockCline: any beforeEach(() => { // Reset mocks vi.clearAllMocks() // Initialize TelemetryService if not already initialized if (!TelemetryService.hasInstance()) { TelemetryService.createInstance([]) } // Setup basic mocks mockContext = { globalState: { get: vi.fn().mockImplementation((key: string) => { if (key === "mode") return "code" if (key === "apiProvider") return "anthropic" return undefined }), update: vi.fn(), keys: vi.fn().mockReturnValue([]), }, workspaceState: { get: vi.fn().mockReturnValue(undefined), update: vi.fn().mockResolvedValue(undefined), keys: vi.fn().mockReturnValue([]), }, secrets: { get: vi.fn(), store: vi.fn(), delete: vi.fn() }, extensionUri: { fsPath: "/test/path" } as vscode.Uri, globalStorageUri: { fsPath: "/test/path" }, extension: { packageJSON: { version: "1.0.0" } }, } as unknown as vscode.ExtensionContext mockOutputChannel = { appendLine: vi.fn() } as unknown as vscode.OutputChannel provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) defaultTaskOptions = { provider, apiConfiguration: { apiProvider: providerIdentifiers.openrouter, }, } // Setup Task instance with mocked getModel method mockCline = new Task(defaultTaskOptions) mockCline.api = { getModel: vi.fn().mockReturnValue({ id: "claude-sonnet-4-20250514", info: { contextWindow: 200000 }, }), } }) test("includes basic properties in telemetry", async () => { const properties = await provider.getTelemetryProperties() expect(properties).toHaveProperty("vscodeVersion") expect(properties).toHaveProperty("platform") expect(properties).toHaveProperty("appVersion", "1.0.0") }) test("includes model ID from current Cline instance if available", async () => { // Add mock Cline to stack await provider.addClineToStack(mockCline) const properties = await provider.getTelemetryProperties() expect(properties).toHaveProperty("modelId", "claude-sonnet-4-20250514") }) describe("cloud authentication telemetry", () => { beforeEach(() => { // Reset all mocks before each test vi.clearAllMocks() }) test("includes cloud authentication property when user is authenticated", async () => { // Import the CloudService mock and update it const { CloudService } = await import("@roo-code/cloud") const mockCloudService = { isAuthenticated: vi.fn().mockReturnValue(true), // Provider dispose detaches the settings listener; later tests construct // and dispose providers against this surviving instance getter. on: vi.fn(), off: vi.fn(), } // Update the existing mock Object.defineProperty(CloudService, "instance", { get: vi.fn().mockReturnValue(mockCloudService), configurable: true, }) const properties = await provider.getTelemetryProperties() expect(properties).toHaveProperty("cloudIsAuthenticated", true) }) test("includes cloud authentication property when user is not authenticated", async () => { // Import the CloudService mock and update it const { CloudService } = await import("@roo-code/cloud") const mockCloudService = { isAuthenticated: vi.fn().mockReturnValue(false), // Provider dispose detaches the settings listener; later tests construct // and dispose providers against this surviving instance getter. on: vi.fn(), off: vi.fn(), } // Update the existing mock Object.defineProperty(CloudService, "instance", { get: vi.fn().mockReturnValue(mockCloudService), configurable: true, }) const properties = await provider.getTelemetryProperties() expect(properties).toHaveProperty("cloudIsAuthenticated", false) }) test("handles CloudService errors gracefully", async () => { // Import the CloudService mock and update it to throw an error const { CloudService } = await import("@roo-code/cloud") Object.defineProperty(CloudService, "instance", { get: vi.fn().mockImplementation(() => { throw new Error("CloudService not available") }), configurable: true, }) const properties = await provider.getTelemetryProperties() // Should still include basic telemetry properties expect(properties).toHaveProperty("vscodeVersion") expect(properties).toHaveProperty("platform") expect(properties).toHaveProperty("appVersion", "1.0.0") // Cloud property should be undefined when CloudService is not available expect(properties).toHaveProperty("cloudIsAuthenticated", undefined) }) test("handles CloudService method errors gracefully", async () => { // Import the CloudService mock and update it const { CloudService } = await import("@roo-code/cloud") const mockCloudService = { isAuthenticated: vi.fn().mockImplementation(() => { throw new Error("Authentication check error") }), // Provider dispose detaches the settings listener; later tests construct // and dispose providers against this surviving instance getter. on: vi.fn(), off: vi.fn(), } // Update the existing mock Object.defineProperty(CloudService, "instance", { get: vi.fn().mockReturnValue(mockCloudService), configurable: true, }) const properties = await provider.getTelemetryProperties() // Should still include basic telemetry properties expect(properties).toHaveProperty("vscodeVersion") expect(properties).toHaveProperty("platform") expect(properties).toHaveProperty("appVersion", "1.0.0") // Property that errored should be undefined expect(properties).toHaveProperty("cloudIsAuthenticated", undefined) }) }) }) describe("ClineProvider - Router Models", () => { let provider: ClineProvider let mockContext: vscode.ExtensionContext let mockOutputChannel: vscode.OutputChannel let mockWebviewView: any let mockPostMessage: any // One distinct handler double per provider, so assertions can prove that each getModels // call receives the handler built for its own provider rather than just any handler. let handlersByProvider: Map const handlerForProvider = (providerName: string) => { const handler = handlersByProvider.get(providerName) if (!handler) { throw new Error(`buildApiHandler was never called for provider "${providerName}"`) } return handler } beforeEach(async () => { vi.clearAllMocks() // An earlier test leaves a one-shot throwing implementation on buildApiHandler that // vi.clearAllMocks() does not remove. Reset it so the router-model fetches receive a // real handler double instead of throwing on the first provider. The double assertion // is required because the mock only needs the getModel member the tests exercise. const { buildApiHandler } = await import("../../../api") handlersByProvider = new Map() vi.mocked(buildApiHandler).mockReset() vi.mocked(buildApiHandler).mockImplementation((configuration) => { const providerName = configuration.apiProvider let handler = handlersByProvider.get(providerName) if (!handler) { handler = { providerName, getModel: vi.fn().mockReturnValue({ id: "claude-3-sonnet" }), } handlersByProvider.set(providerName, handler) } return handler as unknown as ReturnType }) const globalState: Record = {} const secrets: Record = {} mockContext = { extensionPath: "/test/path", extensionUri: { fsPath: "/test/path" } as vscode.Uri, globalState: { get: vi.fn().mockImplementation((key: string) => { return globalState[key] }), update: vi.fn().mockImplementation((key: string, value: string | undefined) => { return (globalState[key] = value) }), keys: vi.fn().mockImplementation(() => { return Object.keys(globalState) }), }, secrets: { get: vi.fn().mockImplementation((key: string) => { return secrets[key] }), store: vi.fn().mockImplementation((key: string, value: string | undefined) => { return (secrets[key] = value) }), delete: vi.fn().mockImplementation((key: string) => { return delete secrets[key] }), }, workspaceState: { get: vi.fn().mockReturnValue(undefined), update: vi.fn().mockResolvedValue(undefined), keys: vi.fn().mockReturnValue([]), }, subscriptions: [], extension: { packageJSON: { version: "1.0.0" }, }, globalStorageUri: { fsPath: "/test/storage/path", }, } as unknown as vscode.ExtensionContext mockOutputChannel = { appendLine: vi.fn(), clear: vi.fn(), dispose: vi.fn(), } as unknown as vscode.OutputChannel mockPostMessage = vi.fn() mockWebviewView = { webview: { postMessage: mockPostMessage, html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), }, visible: true, onDidDispose: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), onDidChangeVisibility: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), } if (!TelemetryService.hasInstance()) { TelemetryService.createInstance([]) } provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) }) test("handles requestRouterModels with successful responses", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Mock getState to return API configuration vi.spyOn(provider, "getState").mockResolvedValue({ apiConfiguration: { openRouterApiKey: "openrouter-key", requestyApiKey: "requesty-key", litellmApiKey: "litellm-key", litellmBaseUrl: "http://localhost:4000", }, } as any) const mockModels = { "model-1": { maxTokens: 4096, contextWindow: 8192, description: "Test model 1", supportsPromptCache: false, }, "model-2": { maxTokens: 8192, contextWindow: 16384, description: "Test model 2", supportsPromptCache: false, }, } const { getModels } = await import("../../../api/providers/fetchers/modelCache") vi.mocked(getModels).mockResolvedValue(mockModels) await messageHandler({ type: "requestRouterModels" }) // Verify getModels was called for each provider with correct options and that provider's handler. expect(getModels).toHaveBeenCalledWith( { provider: providerIdentifiers.openrouter }, handlerForProvider(providerIdentifiers.openrouter), ) expect(getModels).toHaveBeenCalledWith( { provider: providerIdentifiers.requesty, apiKey: "requesty-key" }, handlerForProvider(providerIdentifiers.requesty), ) expect(getModels).toHaveBeenCalledWith( { provider: providerIdentifiers.unbound }, handlerForProvider(providerIdentifiers.unbound), ) expect(getModels).toHaveBeenCalledWith( { provider: providerIdentifiers.vercelAiGateway }, handlerForProvider(providerIdentifiers.vercelAiGateway), ) expect(getModels).toHaveBeenCalledWith( { provider: providerIdentifiers.litellm, apiKey: "litellm-key", baseUrl: "http://localhost:4000", }, handlerForProvider(providerIdentifiers.litellm), ) // Opencode Go's /models endpoint is public, so it is fetched like the other no-auth routers. expect(getModels).toHaveBeenCalledWith( expect.objectContaining({ provider: providerIdentifiers.opencodeGo }), handlerForProvider(providerIdentifiers.opencodeGo), ) // Kenari's /models endpoint is public, so it is fetched like the other no-auth routers. expect(getModels).toHaveBeenCalledWith( expect.objectContaining({ provider: providerIdentifiers.kenari }), handlerForProvider(providerIdentifiers.kenari), ) // NanoGPT's detailed catalog is public and may be scoped by an optional key. expect(getModels).toHaveBeenCalledWith( { provider: providerIdentifiers.nanogpt, apiKey: undefined }, handlerForProvider(providerIdentifiers.nanogpt), ) // Every getModels call must receive the handler built for the provider it fetches. for (const [options, handler] of vi.mocked(getModels).mock.calls) { expect(handler).toBe(handlerForProvider(options.provider)) } // Verify response was sent expect(mockPostMessage).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, }) }) test("handles requestRouterModels with individual provider failures", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] vi.spyOn(provider, "getState").mockResolvedValue({ apiConfiguration: { openRouterApiKey: "openrouter-key", requestyApiKey: "requesty-key", litellmApiKey: "litellm-key", litellmBaseUrl: "http://localhost:4000", }, } as any) const mockModels = { "model-1": { maxTokens: 4096, contextWindow: 8192, description: "Test model", supportsPromptCache: false }, } const { getModels } = await import("../../../api/providers/fetchers/modelCache") // Mock some providers to succeed and others to fail vi.mocked(getModels) .mockResolvedValueOnce(mockModels) // openrouter success .mockRejectedValueOnce(new Error("Requesty API error")) // requesty fail .mockResolvedValueOnce(mockModels) // unbound success .mockResolvedValueOnce(mockModels) // vercel-ai-gateway success .mockResolvedValueOnce(mockModels) // zoo-gateway success .mockRejectedValueOnce(new Error("LiteLLM connection failed")) // litellm fail .mockResolvedValueOnce(mockModels) // opencode-go (public endpoint) .mockResolvedValueOnce(mockModels) // kenari (public endpoint) .mockResolvedValueOnce(mockModels) // nanogpt (public endpoint) .mockResolvedValueOnce(mockModels) // friendli (public endpoint) await messageHandler({ type: "requestRouterModels" }) // Verify main response includes successful providers and empty objects for failed ones expect(mockPostMessage).toHaveBeenCalledWith({ type: "routerModels", routerModels: { openrouter: mockModels, requesty: {}, unbound: mockModels, "vercel-ai-gateway": mockModels, "zoo-gateway": mockModels, ollama: {}, lmstudio: {}, litellm: {}, poe: {}, deepseek: {}, moonshot: {}, "opencode-go": mockModels, kenari: mockModels, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, }, values: undefined, }) // Verify error messages were sent for failed providers expect(mockPostMessage).toHaveBeenCalledWith({ type: "singleRouterModelFetchResponse", success: false, error: "Requesty API error", values: { provider: providerIdentifiers.requesty }, }) expect(mockPostMessage).toHaveBeenCalledWith({ type: "singleRouterModelFetchResponse", success: false, error: "LiteLLM connection failed", values: { provider: providerIdentifiers.litellm }, }) }) test("handles requestRouterModels with LiteLLM values from message", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Mock state without LiteLLM config vi.spyOn(provider, "getState").mockResolvedValue({ apiConfiguration: { openRouterApiKey: "openrouter-key", requestyApiKey: "requesty-key", // No litellm config }, } as any) const mockModels = { "model-1": { maxTokens: 4096, contextWindow: 8192, description: "Test model", supportsPromptCache: false }, } const { getModels } = await import("../../../api/providers/fetchers/modelCache") vi.mocked(getModels).mockResolvedValue(mockModels) await messageHandler({ type: "requestRouterModels", values: { litellmApiKey: "message-litellm-key", litellmBaseUrl: "http://message-url:4000", }, }) // Verify LiteLLM was called with values from message expect(getModels).toHaveBeenCalledWith( { provider: providerIdentifiers.litellm, apiKey: "message-litellm-key", baseUrl: "http://message-url:4000", }, handlerForProvider(providerIdentifiers.litellm), ) }) test("skips LiteLLM when neither config nor message values are provided", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] vi.spyOn(provider, "getState").mockResolvedValue({ apiConfiguration: { openRouterApiKey: "openrouter-key", requestyApiKey: "requesty-key", // No litellm config }, } as any) const mockModels = { "model-1": { maxTokens: 4096, contextWindow: 8192, description: "Test model", supportsPromptCache: false }, } const { getModels } = await import("../../../api/providers/fetchers/modelCache") vi.mocked(getModels).mockResolvedValue(mockModels) await messageHandler({ type: "requestRouterModels" }) // Verify LiteLLM was NOT called expect(getModels).not.toHaveBeenCalledWith( expect.objectContaining({ provider: providerIdentifiers.litellm, }), expect.anything(), ) // Verify response includes empty object for LiteLLM expect(mockPostMessage).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, }) }) test("handles requestLmStudioModels with proper response", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] vi.spyOn(provider, "getState").mockResolvedValue({ apiConfiguration: { lmStudioModelId: "model-1", lmStudioBaseUrl: "http://localhost:1234", }, } as any) const mockModels = { "model-1": { maxTokens: 4096, contextWindow: 8192, description: "Test model", supportsPromptCache: false }, } const { getModels } = await import("../../../api/providers/fetchers/modelCache") vi.mocked(getModels).mockResolvedValue(mockModels) await messageHandler({ type: "requestLmStudioModels", }) expect(getModels).toHaveBeenCalledWith( { provider: providerIdentifiers.lmstudio, baseUrl: "http://localhost:1234", }, handlerForProvider(providerIdentifiers.lmstudio), ) }) }) describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { let provider: ClineProvider let mockContext: vscode.ExtensionContext let mockOutputChannel: vscode.OutputChannel let mockWebviewView: any let mockPostMessage: any let defaultTaskOptions: TaskOptions beforeEach(() => { vi.clearAllMocks() if (!TelemetryService.hasInstance()) { TelemetryService.createInstance([]) } const globalState: Record = { mode: "code", currentApiConfigName: "current-config", } const secrets: Record = {} mockContext = { extensionPath: "/test/path", extensionUri: { fsPath: "/test/path" } as vscode.Uri, globalState: { get: vi.fn().mockImplementation((key: string) => { return globalState[key] }), update: vi.fn().mockImplementation((key: string, value: string | undefined) => { return (globalState[key] = value) }), keys: vi.fn().mockImplementation(() => { return Object.keys(globalState) }), }, secrets: { get: vi.fn().mockImplementation((key: string) => { return secrets[key] }), store: vi.fn().mockImplementation((key: string, value: string | undefined) => { return (secrets[key] = value) }), delete: vi.fn().mockImplementation((key: string) => { return delete secrets[key] }), }, workspaceState: { get: vi.fn().mockReturnValue(undefined), update: vi.fn().mockResolvedValue(undefined), keys: vi.fn().mockReturnValue([]), }, subscriptions: [], extension: { packageJSON: { version: "1.0.0" }, }, globalStorageUri: { fsPath: "/test/storage/path", }, } as unknown as vscode.ExtensionContext mockOutputChannel = { appendLine: vi.fn(), clear: vi.fn(), dispose: vi.fn(), } as unknown as vscode.OutputChannel mockPostMessage = vi.fn() mockWebviewView = { webview: { postMessage: mockPostMessage, html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), }, visible: true, onDidDispose: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), onDidChangeVisibility: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), } provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) defaultTaskOptions = { provider, apiConfiguration: { apiProvider: providerIdentifiers.openrouter, }, } // Mock getMcpHub method provider.getMcpHub = vi.fn().mockReturnValue({ listTools: vi.fn().mockResolvedValue([]), callTool: vi.fn().mockResolvedValue({ content: [] }), listResources: vi.fn().mockResolvedValue([]), readResource: vi.fn().mockResolvedValue({ contents: [] }), getAllServers: vi.fn().mockReturnValue([]), }) }) describe("Edit Messages with Images and Attachments", () => { beforeEach(async () => { await provider.resolveWebviewView(mockWebviewView) }) test("handles editing messages containing images", async () => { const mockMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message" }, { ts: 2000, type: "say", say: "user_feedback", text: "Message with image", images: [ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==", ], value: 3000, }, { ts: 3000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = mockMessages mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }, { ts: 3000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() mockCline.submitUserMessage = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "submitEditedMessage", value: 3000, editedMessageContent: "Edited message with preserved images", }) // Verify dialog was shown expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 3000, text: "Edited message with preserved images", hasCheckpoint: false, images: undefined, }) // Simulate confirmation await messageHandler({ type: "editMessageConfirm", messageTs: 3000, text: "Edited message with preserved images", }) // Verify messages were edited correctly - the ORIGINAL user message and all subsequent messages are removed expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([mockMessages[0]]) expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([{ ts: 1000 }]) // Verify submitUserMessage was called with the edited content expect(mockCline.submitUserMessage).toHaveBeenCalledWith( "Edited message with preserved images", [], undefined, undefined, [{ text: "Edited message with preserved images", source: "generated" }], ) }) test("handles editing messages with file attachments", async () => { const mockMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message" }, { ts: 2000, type: "say", say: "user_feedback", text: "Message with file", attachments: [{ path: "/path/to/file.txt", type: "file" }], value: 3000, }, { ts: 3000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = mockMessages mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }, { ts: 3000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() mockCline.submitUserMessage = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "submitEditedMessage", value: 3000, editedMessageContent: "Edited message with file attachment", }) // Verify dialog was shown expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 3000, text: "Edited message with file attachment", hasCheckpoint: false, images: undefined, }) // Simulate user confirming the edit await messageHandler({ type: "editMessageConfirm", messageTs: 3000, text: "Edited message with file attachment", }) expect(mockCline.overwriteClineMessages).toHaveBeenCalled() expect(mockCline.submitUserMessage).toHaveBeenCalledWith( "Edited message with file attachment", [], undefined, undefined, [{ text: "Edited message with file attachment", source: "generated" }], ) }) }) describe("Network Failure Scenarios", () => { beforeEach(async () => { ;(vscode.window.showInformationMessage as any) = vi.fn() await provider.resolveWebviewView(mockWebviewView) }) test("handles network timeout during edit submission", async () => { const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message", value: 2000 }, { ts: 2000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() mockCline.handleWebviewAskResponse = vi.fn().mockRejectedValue(new Error("Network timeout")) await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Should not throw error, but handle gracefully await expect( messageHandler({ type: "submitEditedMessage", value: 2000, editedMessageContent: "Edited message", }), ).resolves.toBeUndefined() // Verify dialog was shown expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 2000, text: "Edited message", hasCheckpoint: false, images: undefined, }) // Simulate user confirming the edit await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: "Edited message" }) expect(mockCline.overwriteClineMessages).toHaveBeenCalled() }) test("handles connection drops during edit operation", async () => { const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message", value: 2000 }, { ts: 2000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }] as any[] mockCline.overwriteClineMessages = vi.fn().mockRejectedValue(new Error("Connection lost")) mockCline.overwriteApiConversationHistory = vi.fn() mockCline.handleWebviewAskResponse = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Should handle connection error gracefully await expect( messageHandler({ type: "submitEditedMessage", value: 2000, editedMessageContent: "Edited message", }), ).resolves.toBeUndefined() // Verify dialog was shown expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 2000, text: "Edited message", hasCheckpoint: false, images: undefined, }) // Simulate user confirming the edit await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: "Edited message" }) // The error should be caught and shown expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.message.error_editing_message") }) }) describe("Concurrent Edit Operations", () => { beforeEach(async () => { ;(vscode.window.showInformationMessage as any) = vi.fn() await provider.resolveWebviewView(mockWebviewView) }) test("handles race conditions with simultaneous edits", async () => { const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Message 1", value: 2000 }, { ts: 2000, type: "say", say: "text", text: "AI response 1" }, { ts: 3000, type: "say", say: "user_feedback", text: "Message 2", value: 4000 }, { ts: 4000, type: "say", say: "text", text: "AI response 2" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }, { ts: 3000 }, { ts: 4000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() mockCline.handleWebviewAskResponse = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Simulate concurrent edit operations const edit1Promise = messageHandler({ type: "submitEditedMessage", value: 2000, editedMessageContent: "Edited message 1", }) const edit2Promise = messageHandler({ type: "submitEditedMessage", value: 4000, editedMessageContent: "Edited message 2", }) await Promise.all([edit1Promise, edit2Promise]) // Verify dialogs were shown for both edits expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 2000, text: "Edited message 1", hasCheckpoint: false, images: undefined, }) expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 4000, text: "Edited message 2", hasCheckpoint: false, images: undefined, }) // Simulate user confirming both edits await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: "Edited message 1" }) await messageHandler({ type: "editMessageConfirm", messageTs: 4000, text: "Edited message 2" }) // Both operations should complete without throwing expect(mockCline.overwriteClineMessages).toHaveBeenCalled() }) }) describe("Edit Permissions and Authorization", () => { beforeEach(async () => { ;(vscode.window.showInformationMessage as any) = vi.fn() await provider.resolveWebviewView(mockWebviewView) }) test("handles edit permission failures", async () => { // Mock no current cline (simulating permission failure) vi.spyOn(provider, "getCurrentTask").mockReturnValue(undefined) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "submitEditedMessage", value: 2000, editedMessageContent: "Edited message", }) // Should not show confirmation dialog when no current cline expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() }) test("handles authorization failures during edit", async () => { const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message", value: 2000 }, { ts: 2000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }] as any[] mockCline.overwriteClineMessages = vi.fn().mockRejectedValue(new Error("Unauthorized")) mockCline.overwriteApiConversationHistory = vi.fn() mockCline.handleWebviewAskResponse = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "submitEditedMessage", value: 2000, editedMessageContent: "Edited message", }) // Simulate confirmation await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: "Edited message", }) expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.message.error_editing_message") }) describe("Malformed Requests and Invalid Formats", () => { beforeEach(async () => { await provider.resolveWebviewView(mockWebviewView) }) test("handles malformed edit requests", async () => { const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Test with missing value await messageHandler({ type: "submitEditedMessage", editedMessageContent: "Edited message", }) // Test with invalid value type await messageHandler({ type: "submitEditedMessage", value: "invalid", editedMessageContent: "Edited message", }) // Test with missing editedMessageContent await messageHandler({ type: "submitEditedMessage", value: 2000, }) // Should not show confirmation dialog for malformed requests expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() }) test("handles invalid message formats", async () => { const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Test with null message - should throw error await expect(messageHandler(null)).rejects.toThrow() // Test with undefined message - should throw error await expect(messageHandler(undefined)).rejects.toThrow() // Test with message missing type await expect( messageHandler({ value: 2000, editedMessageContent: "Edited message", }), ).resolves.toBeUndefined() // Should handle gracefully without errors expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() }) test("handles invalid timestamp values", async () => { ;(vscode.window.showInformationMessage as any) = vi.fn() const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message" }, { ts: 2000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }] as any[] await provider.addClineToStack(mockCline) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Test with negative timestamp await messageHandler({ type: "deleteMessage", value: -1000, }) // Test with zero timestamp await messageHandler({ type: "deleteMessage", value: 0, }) // Invalid timestamps may still trigger confirmation dialog // This is expected behavior as the system tries to process the message }) }) describe("Operations on Deleted or Non-existent Messages", () => { beforeEach(async () => { ;(vscode.window.showInformationMessage as any) = vi.fn() await provider.resolveWebviewView(mockWebviewView) }) test("handles edit operations on deleted messages", async () => { const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Existing message" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() mockCline.handleWebviewAskResponse = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Try to edit a message that doesn't exist (timestamp 5000) await messageHandler({ type: "submitEditedMessage", value: 5000, editedMessageContent: "Edited non-existent message", }) // Should show edit dialog expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 5000, text: "Edited non-existent message", hasCheckpoint: false, images: undefined, }) // Simulate user confirming the edit await messageHandler({ type: "editMessageConfirm", messageTs: 5000, text: "Edited non-existent message", }) // Should not perform any operations since message doesn't exist expect(mockCline.overwriteClineMessages).not.toHaveBeenCalled() expect(mockCline.handleWebviewAskResponse).not.toHaveBeenCalled() }) test("handles delete operations on non-existent messages", async () => { const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Existing message" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] // Try to delete a message that doesn't exist (timestamp 5000) await messageHandler({ type: "deleteMessage", value: 5000, }) // Should show delete dialog expect(mockPostMessage).toHaveBeenCalledWith({ type: "showDeleteMessageDialog", messageTs: 5000, hasCheckpoint: false, }) // Simulate user confirming the delete await messageHandler({ type: "deleteMessageConfirm", messageTs: 5000 }) // Should not perform any operations since message doesn't exist expect(mockCline.overwriteClineMessages).not.toHaveBeenCalled() }) }) describe("Resource Cleanup During Failed Operations", () => { beforeEach(async () => { ;(vscode.window.showInformationMessage as any) = vi.fn() await provider.resolveWebviewView(mockWebviewView) }) test("validates proper cleanup during failed edit operations", async () => { const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message", value: 2000 }, { ts: 2000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }] as any[] // Mock cleanup tracking const cleanupSpy = vi.fn() mockCline.overwriteClineMessages = vi.fn().mockImplementation(() => { cleanupSpy() throw new Error("Operation failed") }) mockCline.overwriteApiConversationHistory = vi.fn() mockCline.handleWebviewAskResponse = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "submitEditedMessage", value: 2000, editedMessageContent: "Edited message", }) // Should show edit dialog expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 2000, text: "Edited message", hasCheckpoint: false, images: undefined, }) // Simulate user confirming the edit await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: "Edited message" }) // Verify cleanup was attempted before failure expect(cleanupSpy).toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.message.error_editing_message") }) test("validates proper cleanup during failed delete operations", async () => { const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Message to delete" }, { ts: 2000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }] as any[] // Mock cleanup tracking const cleanupSpy = vi.fn() mockCline.overwriteClineMessages = vi.fn().mockImplementation(() => { cleanupSpy() throw new Error("Delete operation failed") }) mockCline.overwriteApiConversationHistory = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "deleteMessage", value: 2000 }) // Should show delete dialog expect(mockPostMessage).toHaveBeenCalledWith({ type: "showDeleteMessageDialog", messageTs: 2000, hasCheckpoint: false, }) // Simulate user confirming the delete await messageHandler({ type: "deleteMessageConfirm", messageTs: 2000 }) // Verify cleanup was attempted before failure expect(cleanupSpy).toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.message.error_deleting_message") }) }) describe("Large Message Payloads", () => { beforeEach(async () => { ;(vscode.window.showInformationMessage as any) = vi.fn() await provider.resolveWebviewView(mockWebviewView) }) test("handles editing messages with large text content", async () => { // Create a large message (10KB of text) const largeText = "A".repeat(10000) const mockMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: largeText, value: 2000 }, { ts: 2000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = mockMessages mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() mockCline.submitUserMessage = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] const largeEditedContent = "B".repeat(15000) await messageHandler({ type: "submitEditedMessage", value: 2000, editedMessageContent: largeEditedContent, }) // Should show edit dialog expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: 2000, text: largeEditedContent, hasCheckpoint: false, images: undefined, }) // Simulate user confirming the edit await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: largeEditedContent }) expect(mockCline.overwriteClineMessages).toHaveBeenCalled() expect(mockCline.submitUserMessage).toHaveBeenCalledWith(largeEditedContent, [], undefined, undefined, [ { text: largeEditedContent, source: "generated" }, ]) }) test("handles deleting messages with large payloads", async () => { // Create messages with large payloads const largeText = "X".repeat(50000) const mockMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Small message" }, { ts: 2000, type: "say", say: "user_feedback", text: largeText }, { ts: 3000, type: "say", say: "text", text: "AI response" }, { ts: 4000, type: "say", say: "user_feedback", text: "Another large message: " + largeText }, ] as ClineMessage[] const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = mockMessages mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }, { ts: 3000 }, { ts: 4000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "deleteMessage", value: 3000 }) // Should show delete dialog expect(mockPostMessage).toHaveBeenCalledWith({ type: "showDeleteMessageDialog", messageTs: 3000, hasCheckpoint: false, }) // Simulate user confirming the delete await messageHandler({ type: "deleteMessageConfirm", messageTs: 3000 }) // Should handle large payloads without issues - keeps messages before the deleted one expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([mockMessages[0], mockMessages[1]]) expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([{ ts: 1000 }, { ts: 2000 }]) }) }) describe("Error Messaging and User Feedback", () => { beforeEach(async () => { await provider.resolveWebviewView(mockWebviewView) }) // Note: Error messaging test removed as the implementation may not have proper error handling in place test("provides user feedback for successful operations", async () => { const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Message to delete" }, { ts: 2000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) ;(provider as any).createTaskWithHistoryItem = vi.fn() const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "deleteMessage", value: 2000 }) // Should show delete dialog expect(mockPostMessage).toHaveBeenCalledWith({ type: "showDeleteMessageDialog", messageTs: 2000, hasCheckpoint: false, }) // Simulate user confirming the delete await messageHandler({ type: "deleteMessageConfirm", messageTs: 2000 }) // Verify successful operation completed expect(mockCline.overwriteClineMessages).toHaveBeenCalled() // createTaskWithHistoryItem is only called when restoring checkpoints or aborting tasks expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() }) test("handles user cancellation gracefully", async () => { // Test cancellation by not sending confirmation const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Message to edit" }, { ts: 2000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() mockCline.handleWebviewAskResponse = vi.fn() await provider.addClineToStack(mockCline) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "submitEditedMessage", value: 2000, editedMessageContent: "Edited message", }) // Verify no operations were performed when user canceled expect(mockCline.overwriteClineMessages).not.toHaveBeenCalled() expect(mockCline.overwriteApiConversationHistory).not.toHaveBeenCalled() expect(mockCline.handleWebviewAskResponse).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() }) }) describe("Edge Cases with Message Timestamps", () => { beforeEach(async () => { ;(vscode.window.showInformationMessage as any) = vi.fn() await provider.resolveWebviewView(mockWebviewView) }) test("handles messages with identical timestamps", async () => { const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Message 1" }, { ts: 1000, type: "say", say: "text", text: "Message 2 (same timestamp)" }, { ts: 1000, type: "say", say: "user_feedback", text: "Message 3 (same timestamp)" }, { ts: 2000, type: "say", say: "text", text: "Message 4" }, ] as ClineMessage[] mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 1000 }, { ts: 1000 }, { ts: 2000 }] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "deleteMessage", value: 1000 }) // Should show delete dialog expect(mockPostMessage).toHaveBeenCalledWith({ type: "showDeleteMessageDialog", messageTs: 1000, hasCheckpoint: false, }) // Simulate user confirming the delete await messageHandler({ type: "deleteMessageConfirm", messageTs: 1000 }) // Should handle identical timestamps gracefully expect(mockCline.overwriteClineMessages).toHaveBeenCalled() }) test("handles messages with future timestamps", async () => { const futureTimestamp = Date.now() + 100000 // Future timestamp const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Past message" }, { ts: futureTimestamp, type: "say", say: "user_feedback", text: "Future message", value: futureTimestamp + 1000, }, { ts: futureTimestamp + 1000, type: "say", say: "text", text: "AI response" }, ] as ClineMessage[] mockCline.apiConversationHistory = [ { ts: 1000 }, { ts: futureTimestamp }, { ts: futureTimestamp + 1000 }, ] as any[] mockCline.overwriteClineMessages = vi.fn() mockCline.overwriteApiConversationHistory = vi.fn() mockCline.submitUserMessage = vi.fn() await provider.addClineToStack(mockCline) ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ historyItem: { id: "test-task-id" }, }) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "submitEditedMessage", value: futureTimestamp + 1000, editedMessageContent: "Edited future message", }) // Should show edit dialog expect(mockPostMessage).toHaveBeenCalledWith({ type: "showEditMessageDialog", messageTs: futureTimestamp + 1000, text: "Edited future message", hasCheckpoint: false, images: undefined, }) // Simulate user confirming the edit await messageHandler({ type: "editMessageConfirm", messageTs: futureTimestamp + 1000, text: "Edited future message", }) // Should handle future timestamps correctly expect(mockCline.overwriteClineMessages).toHaveBeenCalled() expect(mockCline.submitUserMessage).toHaveBeenCalled() }) }) }) describe("getTaskWithId", () => { it("retries a transiently missing API history before returning an empty conversation", async () => { const historyItem = { id: "retry-api-history", task: "test task", ts: 1, number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, } provider.taskHistoryStore["cache"].set(historyItem.id, historyItem) provider["taskHistoryStoreInitialized"] = true const fsp = await import("fs/promises") let reads = 0 vi.mocked(fsp.readFile).mockImplementation(async (file) => { if (!String(file).endsWith("api_conversation_history.json")) return "" if (++reads === 1) throw Object.assign(new Error("Replacement in progress"), { code: "ENOENT" }) return JSON.stringify([{ role: "assistant", content: "committed" }]) }) const result = await provider.getTaskWithId(historyItem.id) expect(result.apiConversationHistory).toEqual([{ role: "assistant", content: "committed" }]) }) it.each(["ENOENT", "EACCES"])("returns empty history after %s without removing the task", async (code) => { const item = { id: "failed-api-read", task: "test", ts: 1, number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, } provider.taskHistoryStore["cache"].set(item.id, item) provider["taskHistoryStoreInitialized"] = true const fsp = await import("fs/promises") const read = vi.mocked(fsp.readFile) let reads = 0 read.mockImplementation(async (file) => { if (!String(file).endsWith("api_conversation_history.json")) return "" reads++ throw Object.assign(new Error("read failed"), { code }) }) const result = await provider.getTaskWithId(item.id) expect(result.apiConversationHistory).toEqual([]) expect(provider.taskHistoryStore.get(item.id)).toEqual(item) expect(reads).toBe(code === "ENOENT" ? 2 : 1) }) it("aggregates parent and child costs without reading API history", async () => { const parent = { id: "cost-parent", task: "test", ts: 1, number: 1, tokensIn: 0, tokensOut: 0, totalCost: 2, childIds: ["cost-child"], } provider.taskHistoryStore["cache"].set(parent.id, parent) provider.taskHistoryStore["cache"].set("cost-child", { ...parent, id: "cost-child", totalCost: 3, childIds: [], }) provider["taskHistoryStoreInitialized"] = true const read = vi.spyOn(provider, "getTaskWithId") const result = await provider.getTaskWithAggregatedCosts(parent.id) expect(result.aggregatedCosts.totalCost).toBe(5) expect(read).not.toHaveBeenCalled() }) it("does not restore a deleted file-backed task from legacy history", async () => { const historyItem = { id: "deleted-task", task: "legacy task", ts: Date.now(), number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, } vi.mocked(mockContext.globalState.get).mockImplementation((key: string) => { if (key === "taskHistory") { return [historyItem] } return undefined }) provider.taskHistoryStore["cache"].set(historyItem.id, historyItem) await provider.taskHistoryStore.delete(historyItem.id) provider["taskHistoryStoreInitialized"] = true await expect(provider.getTaskWithId(historyItem.id)).rejects.toThrow("Task not found") }) it("rejects a missing task before file-backed history initialization", async () => { provider["taskHistoryStoreInitialized"] = false vi.mocked(mockContext.globalState.get).mockReturnValue(undefined) await expect(provider.getTaskWithId("cold-start-missing-task")).rejects.toThrow("Task not found") }) it("returns empty apiConversationHistory when file is missing", async () => { const historyItem = { id: "missing-api-file-task", task: "test task", ts: Date.now() } vi.mocked(mockContext.globalState.get).mockImplementation((key: string) => { if (key === "taskHistory") { return [historyItem] } return undefined }) const deleteTaskSpy = vi.spyOn(provider, "deleteTaskFromState") const result = await (provider as any).getTaskWithId("missing-api-file-task") expect(result.historyItem).toEqual(historyItem) expect(result.apiConversationHistory).toEqual([]) expect(deleteTaskSpy).not.toHaveBeenCalled() }) it("returns empty apiConversationHistory when file contains invalid JSON", async () => { const historyItem = { id: "corrupt-api-task", task: "test task", ts: Date.now() } vi.mocked(mockContext.globalState.get).mockImplementation((key: string) => { if (key === "taskHistory") { return [historyItem] } return undefined }) // Make fileExistsAtPath return true so the read path is exercised const fsUtils = await import("../../../utils/fs") vi.spyOn(fsUtils, "fileExistsAtPath").mockResolvedValue(true) // Make readFile return corrupted JSON const fsp = await import("fs/promises") vi.mocked(fsp.readFile).mockResolvedValueOnce("{not valid json!!!" as never) const deleteTaskSpy = vi.spyOn(provider, "deleteTaskFromState") const result = await (provider as any).getTaskWithId("corrupt-api-task") expect(result.historyItem).toEqual(historyItem) expect(result.apiConversationHistory).toEqual([]) expect(deleteTaskSpy).not.toHaveBeenCalled() // Restore the spy vi.mocked(fsUtils.fileExistsAtPath).mockRestore() }) }) describe("Zoo Code auth profile sync", () => { beforeEach(async () => { const { getCachedZooCodeToken } = await import("../../../services/zoo-code-auth") vi.mocked(getCachedZooCodeToken).mockReturnValue("") }) describe("handleZooCodeCallback", () => { it("creates a Zoo Gateway profile when none exists", async () => { vi.spyOn(provider, "getState").mockResolvedValue({ apiConfiguration: { zooGatewayModelId: "anthropic/claude-sonnet-4" }, } as any) vi.spyOn(provider.contextProxy, "getProviderSettings").mockReturnValue({ apiProvider: providerIdentifiers.anthropic, } as any) vi.spyOn(provider.contextProxy, "getValues").mockReturnValue({ currentApiConfigName: "Anthropic", } as any) const upsertSpy = vi.spyOn(provider, "upsertProviderProfile").mockResolvedValue("profile-id") vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, listConfig: vi.fn().mockResolvedValue([]), } await provider.handleZooCodeCallback("zoo_ext_token") expect(postMessageSpy).toHaveBeenCalledWith({ type: "zooGatewayCredentialsReady" }) expect(upsertSpy).toHaveBeenCalledWith( "Zoo Gateway", expect.objectContaining({ apiProvider: providerIdentifiers.zooGateway, zooSessionToken: "zoo_ext_token", zooGatewayBaseUrl: "https://www.zoocode.dev/api/gateway/v1", }), false, ) }) it("updates every zoo-gateway profile and activates only the active one", async () => { vi.spyOn(provider, "getState").mockResolvedValue({ apiConfiguration: { zooGatewayModelId: "anthropic/claude-sonnet-4" }, } as any) vi.spyOn(provider.contextProxy, "getProviderSettings").mockReturnValue({ apiProvider: providerIdentifiers.zooGateway, } as any) vi.spyOn(provider.contextProxy, "getValues").mockReturnValue({ currentApiConfigName: "Zoo Gateway", } as any) const upsertSpy = vi.spyOn(provider, "upsertProviderProfile").mockResolvedValue("profile-id") const saveConfig = vi.fn().mockResolvedValue(undefined) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, listConfig: vi.fn().mockResolvedValue([ { name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }, { name: "Backup Zoo", apiProvider: providerIdentifiers.zooGateway }, ]), getProfile: vi .fn() .mockResolvedValueOnce({ apiProvider: providerIdentifiers.zooGateway, zooSessionToken: "old-token", zooGatewayBaseUrl: "https://old.example/api/gateway/v1", }) .mockResolvedValueOnce({ apiProvider: providerIdentifiers.zooGateway, zooSessionToken: "old-token", }), saveConfig, } await provider.handleZooCodeCallback("new-token") expect(upsertSpy).toHaveBeenCalledWith( "Zoo Gateway", expect.objectContaining({ zooSessionToken: "new-token", zooGatewayBaseUrl: "https://www.zoocode.dev/api/gateway/v1", }), true, ) // The non-active profile now goes through upsertProviderProfile so the views // pinned to it are refreshed, not just the file on disk. expect(upsertSpy).toHaveBeenCalledWith( "Backup Zoo", expect.objectContaining({ zooSessionToken: "new-token", zooGatewayBaseUrl: "https://www.zoocode.dev/api/gateway/v1", }), false, ) }) it("logs and posts state when profile persistence fails", async () => { vi.spyOn(provider, "getState").mockRejectedValue(new Error("state unavailable")) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, listConfig: vi.fn().mockResolvedValue([]), } await provider.handleZooCodeCallback("zoo_ext_token") expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( expect.stringContaining("[handleZooCodeCallback] Failed to save zoo-gateway profile"), ) // State must still be refreshed even when profile persistence fails. expect(provider.postStateToWebview).toHaveBeenCalled() }) }) describe("ensureZooGatewayProfileSeeded", () => { it("does nothing when no cached auth token exists", async () => { const handleSpy = vi.spyOn(provider, "handleZooCodeCallback").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, listConfig: vi.fn(), } await (provider as any).ensureZooGatewayProfileSeeded() expect(handleSpy).not.toHaveBeenCalled() }) it("skips seeding when every zoo-gateway profile already has the current token and base URL", async () => { const { getCachedZooCodeToken } = await import("../../../services/zoo-code-auth") vi.mocked(getCachedZooCodeToken).mockReturnValue("current-token") const handleSpy = vi.spyOn(provider, "handleZooCodeCallback").mockResolvedValue(undefined) const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, listConfig: vi .fn() .mockResolvedValue([{ name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }]), getProfile: vi.fn().mockResolvedValue({ zooSessionToken: "current-token", zooGatewayBaseUrl: "https://www.zoocode.dev/api/gateway/v1", }), } await (provider as any).ensureZooGatewayProfileSeeded() expect(handleSpy).not.toHaveBeenCalled() expect(postMessageSpy).toHaveBeenCalledWith({ type: "zooGatewayCredentialsReady" }) }) it("re-seeds when any zoo-gateway profile has a stale or missing token", async () => { const { getCachedZooCodeToken } = await import("../../../services/zoo-code-auth") vi.mocked(getCachedZooCodeToken).mockReturnValue("fresh-token") const handleSpy = vi.spyOn(provider, "handleZooCodeCallback").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, listConfig: vi .fn() .mockResolvedValue([{ name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }]), getProfile: vi.fn().mockResolvedValue({ zooSessionToken: "stale-token", zooGatewayBaseUrl: "https://www.zoocode.dev/api/gateway/v1", }), } await (provider as any).ensureZooGatewayProfileSeeded() expect(handleSpy).toHaveBeenCalledWith("fresh-token") }) it("re-seeds when any zoo-gateway profile has a stale base URL", async () => { const { getCachedZooCodeToken } = await import("../../../services/zoo-code-auth") vi.mocked(getCachedZooCodeToken).mockReturnValue("current-token") const handleSpy = vi.spyOn(provider, "handleZooCodeCallback").mockResolvedValue(undefined) ;(provider as any).providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, listConfig: vi .fn() .mockResolvedValue([{ name: "Zoo Gateway", apiProvider: providerIdentifiers.zooGateway }]), getProfile: vi.fn().mockResolvedValue({ zooSessionToken: "current-token", zooGatewayBaseUrl: "https://staging.zoocode.dev/api/gateway/v1", }), } await (provider as any).ensureZooGatewayProfileSeeded() expect(handleSpy).toHaveBeenCalledWith("current-token") }) }) }) describe("profile save without activation and overlay completeness", () => { it("refreshes views pinned to a profile saved without activation", async () => { // Defensive: the doubles in this suite can leave console writes pending // at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) try { // The sibling loaded the profile earlier: its buffer pins the name and // carries the settings snapshot taken at that load. sibling["viewLocalState"].currentApiConfigName = "saved-profile" sibling["viewLocalState"].apiConfiguration = { apiProvider: providerIdentifiers.anthropic, apiKey: "old-key", } vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) // The sibling has an active task built from the pre-save settings. // Task is a class; the double assertion is the only way to attach a // minimal double without the full provider/services graph. const siblingTask = { apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "old-key" }, taskApiConfigName: "saved-profile", updateApiConfiguration: vi.fn(), } vi.spyOn(sibling, "getCurrentTask").mockReturnValue( siblingTask as unknown as ReturnType, ) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) const savedForReadBack9: Record> = {} // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, saveConfig: vi.fn(async (name: string, settings: Record) => { savedForReadBack9[name] = settings return "saved-id" }), getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: "saved-id", ...savedForReadBack9[name], })), listConfig: vi.fn().mockResolvedValue([]), setModeConfig: vi.fn(), } await provider.upsertProviderProfile( "saved-profile", { apiProvider: providerIdentifiers.anthropic, apiKey: "new-key" }, false, ) // A save that does not activate still rewrites the profile; the pinned // sibling must not keep serving the pre-save snapshot. expect(sibling["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic, apiKey: "new-key", }) // The active task's handler must be rebuilt with the saved settings, // not just the view buffer. expect(siblingTask.updateApiConfiguration).toHaveBeenCalledWith({ apiProvider: providerIdentifiers.anthropic, apiKey: "new-key", }) // Wait on the serialized view-state write queue that every // viewStates mutation goes through, so queued persistence finishes // while the console spies are still installed and teardown has no // pending writes. await ClineProvider["persistedViewStateWriteQueue"] } finally { await sibling.dispose() } }) it("does not rebuild a pinned sibling's task that runs under another profile", async () => { // Defensive: the doubles in this suite can leave console writes pending // at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) try { // The sibling pins the saved profile, but its active task follows a // different sticky profile: the save must refresh the view overlay // without switching that conversation to the saved profile's settings. sibling["viewLocalState"].currentApiConfigName = "saved-profile" sibling["viewLocalState"].apiConfiguration = { apiProvider: providerIdentifiers.anthropic, apiKey: "old-key", } vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) const siblingTask = { apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key" }, taskApiConfigName: "other-profile", updateApiConfiguration: vi.fn(), } vi.spyOn(sibling, "getCurrentTask").mockReturnValue( siblingTask as unknown as ReturnType, ) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // The real profile manager over the seeded mockContext secrets store saves and reads // the profile: the sibling overlay below is the stored read-back record, not what // the caller passed in. await provider.upsertProviderProfile( "saved-profile", { apiProvider: providerIdentifiers.anthropic, apiKey: "new-key" }, false, ) // The pinned view's overlay still catches up with the saved settings... expect(sibling["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic, apiKey: "new-key", }) // ...but the task runs under another profile: its handler must not be // switched to the saved profile's settings. expect(siblingTask.updateApiConfiguration).not.toHaveBeenCalled() // Wait on the serialized view-state write queue that every // viewStates mutation goes through, so queued persistence finishes // while the console spies are still installed and teardown has no // pending writes. await ClineProvider["persistedViewStateWriteQueue"] } finally { await sibling.dispose() } }) it("refreshes the task of a view that follows the saved profile though its pin follows another", async () => { // Defensive: the doubles in this suite can leave console writes pending // at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) try { // The sibling's own view follows a different profile: its pin and its buffer // both belong there, and only its conversation follows the saved profile. sibling["viewLocalState"].currentApiConfigName = "other-profile" sibling["viewLocalState"].apiConfiguration = { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key", } const siblingPost = vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) // Its conversation was launched onto the saved profile, so its handler holds the // pre-save key. Task is a class; the double assertion is the only way to attach a // minimal double without the full provider/services graph. const siblingTask = { apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "old-key" }, taskApiConfigName: "saved-profile", updateApiConfiguration: vi.fn(), } vi.spyOn(sibling, "getCurrentTask").mockReturnValue( siblingTask as unknown as ReturnType, ) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // The real profile manager over the seeded mockContext secrets store saves and reads // the profile: the handler rebuild below runs on the stored read-back record, not on // whatever the caller passed in. await provider.upsertProviderProfile( "saved-profile", { apiProvider: providerIdentifiers.anthropic, apiKey: "new-key" }, false, ) // The conversation follows the saved profile, so its handler must catch up with the saved // key: skipping this view because of its own pin is what left the task sending a key the // save had just replaced. expect(siblingTask.updateApiConfiguration).toHaveBeenCalledWith({ apiProvider: providerIdentifiers.anthropic, apiKey: "new-key", }) // The view itself follows another profile, so its own buffer must keep that profile's // settings rather than taking the saved ones. expect(sibling["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic, apiKey: "other-key", }) // Nothing this view posts changed - its pin and its buffer both belong to the other // profile - so the task refresh must not drag a state post along with it. expect(siblingPost).not.toHaveBeenCalled() // Wait on the serialized view-state write queue that every // viewStates mutation goes through, so queued persistence finishes // while the console spies are still installed and teardown has no // pending writes. await ClineProvider["persistedViewStateWriteQueue"] } finally { await sibling.dispose() } }) it("leaves a view that follows the saved profile by neither its pin nor its task alone", async () => { // Defensive: the doubles in this suite can leave console writes pending // at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) try { // The sibling's own view follows a different profile: its pin and its buffer // both belong there, and only its conversation follows another profile. sibling["viewLocalState"].currentApiConfigName = "other-profile" sibling["viewLocalState"].apiConfiguration = { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key", } const siblingPost = vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) // Its conversation follows that other profile too. Task is a class; the double // assertion is the only way to attach a minimal double without the full // provider/services graph. const siblingTask = { apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key" }, taskApiConfigName: "other-profile", updateApiConfiguration: vi.fn(), } vi.spyOn(sibling, "getCurrentTask").mockReturnValue( siblingTask as unknown as ReturnType, ) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // The real profile manager over the seeded mockContext secrets store saves and reads // the profile: the queue's id and the read-back below are the stored record, not // whatever the caller passed in. const savedProfileId = await provider.upsertProviderProfile( "saved-profile", { apiProvider: providerIdentifiers.anthropic, apiKey: "new-key" }, false, ) // A save that fails inside the queue's error handling returns no id, and the real // store would then hold no record under that id: pin the queue's success confirmation // against a read-back by id from the real store first, and only then check that // nothing followed. if (typeof savedProfileId !== "string") { throw new Error(`upsertProviderProfile returned ${String(savedProfileId)} instead of a profile id`) } const landedRecord = await provider["providerSettingsManager"] .getProfile({ id: savedProfileId }) .catch(() => undefined) expect(landedRecord?.name).toBe("saved-profile") // Neither axis points at the saved profile: the save of an unrelated profile must leave // both the view's buffer and its conversation on the profile they already follow. expect(siblingTask.updateApiConfiguration).not.toHaveBeenCalled() expect(sibling["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic, apiKey: "other-key", }) expect(siblingPost).not.toHaveBeenCalled() // Wait on the serialized view-state write queue that every // viewStates mutation goes through, so queued persistence finishes // while the console spies are still installed and teardown has no // pending writes. await ClineProvider["persistedViewStateWriteQueue"] } finally { await sibling.dispose() } }) it("does not rebuild the acting view's task when it runs under another profile", async () => { // The acting view pins the saved profile while its own task follows a // different sticky profile: the non-activating save refreshes the view // overlay but must leave the task's handler alone. const task = { apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key" }, taskApiConfigName: "other-profile", updateApiConfiguration: vi.fn(), } vi.spyOn(provider, "getCurrentTask").mockReturnValue( task as unknown as ReturnType, ) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) provider["viewLocalState"].currentApiConfigName = "saved-profile" const savedForReadBack11: Record> = {} // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, saveConfig: vi.fn(async (name: string, settings: Record) => { savedForReadBack11[name] = settings return "saved-id" }), getProfile: vi.fn(async ({ name }: { name: string }) => ({ name, id: "saved-id", ...savedForReadBack11[name], })), listConfig: vi.fn().mockResolvedValue([]), setModeConfig: vi.fn(), } await provider.upsertProviderProfile( "saved-profile", { apiProvider: providerIdentifiers.anthropic, apiKey: "new-key" }, false, ) expect(provider["viewLocalState"].apiConfiguration).toEqual({ apiProvider: providerIdentifiers.anthropic, apiKey: "new-key", }) expect(task.updateApiConfiguration).not.toHaveBeenCalled() }) it("does not leak shared provider keys into a pinned view's api configuration", async () => { vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) // The shared store sits on a profile with keys the pinned profile never // sets; spreading the overlay over the shared keys would report a mixed // configuration (e.g. another profile's model id and region). await provider.contextProxy.setValue("apiProvider", providerIdentifiers.bedrock) await provider.contextProxy.setValue("apiModelId", "anthropic.claude-v1") await provider.contextProxy.setValue("awsRegion", "us-east-1") provider["viewLocalState"].currentApiConfigName = "pinned-profile" provider["viewLocalState"].apiConfiguration = { apiProvider: providerIdentifiers.anthropic, apiKey: "k", } // The cloud doubles in this suite make getState() log its defensive catch // branches; silence them so teardown has no pending console writes. vi.spyOn(console, "error").mockImplementation(() => {}) const state = await provider.getState() expect(state.apiConfiguration.apiProvider).toBe(providerIdentifiers.anthropic) expect(state.apiConfiguration.apiKey).toBe("k") expect(state.apiConfiguration.apiModelId).toBeUndefined() expect(state.apiConfiguration.awsRegion).toBeUndefined() // Let any deferred logging settle while the spies are installed. await new Promise((resolve) => setTimeout(resolve, 50)) }) it("leaves a task following another sticky profile untouched when an activation preserves foreign tasks", async () => { // Defensive: the doubles in this suite can leave console writes pending // at worker teardown. vi.spyOn(console, "log").mockImplementation(() => {}) vi.spyOn(console, "warn").mockImplementation(() => {}) vi.spyOn(console, "error").mockImplementation(() => {}) // The current task follows a different sticky profile than the one the // launch-time repair activates. const task = { apiConfiguration: { apiProvider: providerIdentifiers.openai, apiKey: "task-key" }, taskApiConfigName: "task-profile", updateApiConfiguration: vi.fn(), } vi.spyOn(provider, "getCurrentTask").mockReturnValue( task as unknown as ReturnType, ) vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) // @ts-ignore - Replace providerSettingsManager with a test double. provider.providerSettingsManager = { runExclusiveAcrossInstances: runManagerSectionInline, activateProfile: vi.fn().mockResolvedValue({ name: "shared-profile", id: "id-shared", apiProvider: providerIdentifiers.anthropic, apiKey: "shared-key", }), listConfig: vi.fn().mockResolvedValue([]), setModeConfig: vi.fn(), } await provider.activateProviderProfile( { name: "shared-profile" }, { persistModeConfig: false, persistTaskHistory: false, preserveForeignTask: true }, ) // The repair wrote the shared selection through the activation path but // left the foreign task's handler and captured settings alone. expect(task.updateApiConfiguration).not.toHaveBeenCalled() expect(task.apiConfiguration.apiProvider).toBe(providerIdentifiers.openai) // Control: the same activation without preserveForeignTask does switch // the task, so the skip above is attributable to the flag. await provider.activateProviderProfile( { name: "shared-profile" }, { persistModeConfig: false, persistTaskHistory: false }, ) expect(task.updateApiConfiguration).toHaveBeenCalledWith({ apiProvider: providerIdentifiers.anthropic, apiKey: "shared-key", }) }) }) })