import { createHash } from "node:crypto" import { WebviewFocusTracker } from "../WebviewFocusTracker" // npx vitest run core/webview/__tests__/ClineProvider.sticky-profile.spec.ts import * as vscode from "vscode" import { makeCompositeDisposable } from "../../../test-utils/vscode" import { TelemetryService } from "@roo-code/telemetry" import { ClineProvider } from "../ClineProvider" import type { Task } from "../../task/Task" import { ContextProxy } from "../../config/ContextProxy" import type { HistoryItem, ProviderSettings } from "@roo-code/types" import { providerIdentifiers, retiredProviderIdentifiers } from "@roo-code/types/provider-identifiers" // The spec mocks this module at module level (below); rows that need the production // factory reach it through vi.importActual and install it on this same spy. import { buildApiHandler } from "../../../api" vi.mock("vscode", () => ({ ExtensionContext: vi.fn(), OutputChannel: vi.fn(), WebviewView: vi.fn(), Disposable: { from: (...subscriptions: vscode.Disposable[]) => makeCompositeDisposable(...subscriptions) }, Uri: { joinPath: vi.fn(), file: vi.fn(), }, CodeActionKind: { QuickFix: { value: "quickfix" }, RefactorRewrite: { value: "refactor.rewrite" }, }, commands: { executeCommand: vi.fn().mockResolvedValue(undefined), }, window: { showInformationMessage: vi.fn(), showWarningMessage: vi.fn(), showErrorMessage: vi.fn(), onDidChangeActiveTextEditor: vi.fn(() => ({ dispose: vi.fn() })), // Loading the real Task pulls in the editor integration, whose decorations are created at // module scope (DecorationController.ts:3 and :9). createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn() }), }, workspace: { getConfiguration: vi.fn().mockReturnValue({ get: vi.fn().mockReturnValue([]), update: 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() })), // The real Task graph watches its own files through a workspace file watcher. createFileSystemWatcher: vi.fn(() => ({ onDidChange: vi.fn(() => ({ dispose: vi.fn() })), onDidCreate: vi.fn(() => ({ dispose: vi.fn() })), onDidDelete: vi.fn(() => ({ dispose: vi.fn() })), dispose: vi.fn(), })), }, env: { get machineId() { return "test-machine-id" }, uriScheme: "vscode", language: "en", appName: "Visual Studio Code", }, ExtensionMode: { Production: 1, Development: 2, Test: 3, }, // The real Task graph builds a RelativePattern for that watcher. RelativePattern: vi.fn().mockImplementation(function ( this: Record, base: unknown, pattern: unknown, ) { this.base = base this.pattern = pattern }), version: "1.85.0", })) // Create a counter for unique task IDs. let taskIdCounter = 0 vi.mock("../../task/Task", () => ({ Task: vi.fn().mockImplementation(function (options) { return { taskId: options.taskId || `test-task-id-${++taskIdCounter}`, saveClineMessages: vi.fn(), clineMessages: [], apiConversationHistory: [], overwriteClineMessages: vi.fn(), overwriteApiConversationHistory: vi.fn(), abortTask: vi.fn(), handleWebviewAskResponse: vi.fn(), getTaskNumber: vi.fn().mockReturnValue(0), setTaskNumber: vi.fn(), setParentTask: vi.fn(), setRootTask: vi.fn(), emit: vi.fn(), parentTask: options.parentTask, updateApiConfiguration: vi.fn(), setTaskApiConfigName: vi.fn(), _taskApiConfigName: options.historyItem?.apiConfigName, taskApiConfigName: options.historyItem?.apiConfigName, } }), })) vi.mock("../../prompts/sections/custom-instructions") vi.mock("../../../utils/safeWriteJson") vi.mock("../../../api", () => ({ buildApiHandler: vi.fn().mockReturnValue({ getModel: vi.fn().mockReturnValue({ id: "claude-3-sonnet", }), }), })) vi.mock("../../../integrations/workspace/WorkspaceTracker", () => ({ default: vi.fn().mockImplementation(function () { return { initializeFilePaths: vi.fn(), dispose: vi.fn(), } }), })) vi.mock("../../diff/strategies/multi-search-replace", () => ({ MultiSearchReplaceDiffStrategy: vi.fn().mockImplementation(function () { return { getName: () => "test-strategy", applyDiff: vi.fn(), } }), })) vi.mock("@roo-code/cloud", () => { // One stable double behind the getter: disposing a provider unsubscribes from the cloud // service, and a fresh object on every access would make those listeners impossible to // remove and unobservable to assert against. const cloudService = { isAuthenticated: vi.fn().mockReturnValue(false), on: vi.fn(), off: vi.fn(), } return { CloudService: { hasInstance: vi.fn().mockReturnValue(true), get instance() { return cloudService }, }, getRooCodeApiUrl: vi.fn().mockReturnValue("https://app.roocode.com"), } }) 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"], }, ], getModeBySlug: vi.fn().mockReturnValue({ slug: "code", name: "Code Mode", roleDefinition: "You are a code assistant", groups: ["read", "edit"], }), defaultModeSlug: "code", })) vi.mock("../../prompts/system", () => ({ SYSTEM_PROMPT: vi.fn().mockResolvedValue("mocked system prompt"), codeMode: "code", })) vi.mock("../../../api/providers/fetchers/modelCache", () => ({ getModels: vi.fn().mockResolvedValue({}), flushModels: vi.fn(), })) vi.mock("../../../integrations/misc/extract-text", () => ({ extractTextFromFile: vi.fn().mockResolvedValue("Mock file content"), })) vi.mock("p-wait-for", () => ({ default: vi.fn().mockImplementation(async () => Promise.resolve()), })) vi.mock("fs/promises", () => ({ mkdir: vi.fn().mockResolvedValue(undefined), writeFile: vi.fn().mockResolvedValue(undefined), readFile: vi.fn().mockResolvedValue(""), readdir: vi.fn().mockResolvedValue([]), unlink: vi.fn().mockResolvedValue(undefined), rmdir: vi.fn().mockResolvedValue(undefined), access: vi.fn().mockResolvedValue(undefined), rm: vi.fn().mockResolvedValue(undefined), })) vi.mock("../../../utils/storage", async (importOriginal) => { const actual = await importOriginal() return { ...actual, getStorageBasePath: vi.fn().mockImplementation((defaultPath: string) => { return defaultPath }), getSettingsDirectoryPath: vi.fn().mockResolvedValue("/test/settings/path"), getTaskDirectoryPath: vi.fn().mockResolvedValue("/test/task/path"), } }) vi.mock("@roo-code/telemetry", async (importOriginal) => { const actual = await importOriginal() return { // Keep the real hashDistinctId: getStateToPostToWebview hashes the machine ID // before posting it to the webview (issue #830). ...actual, TelemetryService: { hasInstance: vi.fn().mockReturnValue(true), createInstance: vi.fn(), get instance() { return { trackEvent: vi.fn(), trackError: vi.fn(), setProvider: vi.fn(), captureModeSwitch: vi.fn(), // The real Task constructor reports the task it just built. captureTaskCreated: vi.fn(), } }, }, } }) describe("ClineProvider - Sticky Provider Profile", () => { let provider: ClineProvider let mockContext: vscode.ExtensionContext let mockOutputChannel: vscode.OutputChannel let mockWebviewView: vscode.WebviewView let mockPostMessage: any let originalRooCliRuntimeEnv: string | undefined beforeEach(async () => { vi.clearAllMocks() taskIdCounter = 0 originalRooCliRuntimeEnv = process.env.ROO_CLI_RUNTIME delete process.env.ROO_CLI_RUNTIME if (!TelemetryService.hasInstance()) { TelemetryService.createInstance([]) } const globalState: Record = { mode: "code", currentApiConfigName: "default-profile", } 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) => { globalState[key] = value return Promise.resolve() }), 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) => { secrets[key] = value return Promise.resolve() }), delete: vi.fn().mockImplementation((key: string) => { delete secrets[key] return Promise.resolve() }), }, 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().mockImplementation(() => { return { dispose: vi.fn() } }), onDidChangeVisibility: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), } as unknown as vscode.WebviewView provider = new ClineProvider( mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Wait for the async TaskHistoryStore initialization to complete await new Promise((resolve) => setTimeout(resolve, 10)) // 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([]), }) }) afterEach(async () => { if (originalRooCliRuntimeEnv === undefined) { delete process.env.ROO_CLI_RUNTIME } else { process.env.ROO_CLI_RUNTIME = originalRooCliRuntimeEnv } // Every test in this file constructs a real ClineProvider, and nothing else closes it: an // instance stays in the static live set that profile operations sweep, and it keeps the // postStateToWebview stub of the test that built it. One test's double then decides another // test's fan-out - a rejecting stub makes an unrelated deletion fail for someone else's // setup. Disposing after each test covers every test, including the last one, which no // later hook would clean up. for (const stray of ( ClineProvider as unknown as { getAllInstances: () => ClineProvider[] } ).getAllInstances()) { await stray.dispose() } }) it("posts only the hashed identity for generated machine IDs", async () => { const ids = [ "", "someValue.machineId", "01234567-89ab-cdef-0123-456789abcdef", "机器-id", ...Array.from({ length: 32 }, (_, i) => "device-" + i.toString(16).repeat(i + 1)), ] for (const raw of ids) { vi.spyOn(vscode.env, "machineId", "get").mockReturnValue(raw) const state = await provider.getStateToPostToWebview() const expected = createHash("sha256").update(`zoo-code-telemetry-distinct-id-v1:${raw}`).digest("hex") expect(state.machineId).toBe(expected) expect(state.machineId).not.toBe(raw) } }) describe("activateProviderProfile", () => { beforeEach(async () => { await provider.resolveWebviewView(mockWebviewView) }) it("should save provider profile to task metadata when switching profiles", async () => { // Create a mock task const mockTask = { taskId: "test-task-id", _taskApiConfigName: "default-profile", setTaskApiConfigName: vi.fn(), emit: vi.fn(), saveClineMessages: vi.fn(), clineMessages: [], apiConversationHistory: [], updateApiConfiguration: vi.fn(), } // Add task to provider stack await provider.addClineToStack(mockTask as any) // Populate the store so persistStickyProviderProfileToCurrentTask finds the task await provider.taskHistoryStore.upsert({ id: mockTask.taskId, ts: Date.now(), task: "Test task", number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, }) // Mock updateTaskHistory to track calls const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { return Promise.resolve([]) }) // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.anthropic, }) // Mock providerSettingsManager.listConfig vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.anthropic }, ]) // Switch provider profile await provider.activateProviderProfile({ name: "new-profile" }) // Verify task history was updated with new provider profile expect(updateTaskHistorySpy).toHaveBeenCalledWith( expect.objectContaining({ id: mockTask.taskId, apiConfigName: "new-profile", }), ) // Verify task's setTaskApiConfigName was called expect(mockTask.setTaskApiConfigName).toHaveBeenCalledWith("new-profile") }) it.each([ { expectedCurrentTaskId: "test-task-id", applies: true }, { expectedCurrentTaskId: "other-task-id", applies: false }, ])( "expectedCurrentTaskId $expectedCurrentTaskId rebuilds and sticky-writes the current task: $applies", async ({ expectedCurrentTaskId, applies }) => { const currentTask = { taskId: "test-task-id", setTaskApiConfigName: vi.fn<(name: string) => void>(), updateApiConfiguration: vi.fn<(settings: unknown) => void>(), emit: vi.fn(), } // Supplies only the members that profile activation touches on the current task. vi.spyOn(provider, "getCurrentTask").mockReturnValue(currentTask as unknown as Task) await provider.taskHistoryStore.upsert({ id: currentTask.taskId, ts: Date.now(), task: "Test task", number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, }) const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([]) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.anthropic, }) await provider.activateProviderProfile({ name: "new-profile" }, { expectedCurrentTaskId }) expect(currentTask.updateApiConfiguration).toHaveBeenCalledTimes(applies ? 1 : 0) expect(currentTask.setTaskApiConfigName).toHaveBeenCalledTimes(applies ? 1 : 0) const stickyWrite = expect.objectContaining({ id: currentTask.taskId, apiConfigName: "new-profile" }) if (applies) { expect(updateTaskHistorySpy).toHaveBeenCalledWith(stickyWrite) } else { expect(updateTaskHistorySpy).not.toHaveBeenCalled() } }, ) it.each([true, false])( "writes the mode default only when persistModeConfig is %s", async (persistModeConfig) => { vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.anthropic, }) const setModeConfigSpy = vi.spyOn(provider.providerSettingsManager, "setModeConfig").mockResolvedValue() await provider.contextProxy.setValue("mode", "architect") await provider.activateProviderProfile( { name: "new-profile" }, { persistModeConfig, expectedCurrentTaskId: "test-task-id" }, ) if (persistModeConfig) { expect(setModeConfigSpy).toHaveBeenCalledExactlyOnceWith("architect", "new-profile-id") } else { expect(setModeConfigSpy).not.toHaveBeenCalled() } }, ) it("should update task's taskApiConfigName property when switching profiles", async () => { // Create a mock task with initial profile const mockTask = { taskId: "test-task-id", _taskApiConfigName: "default-profile", setTaskApiConfigName: vi.fn().mockImplementation(function (this: any, name: string) { this._taskApiConfigName = name }), emit: vi.fn(), saveClineMessages: vi.fn(), clineMessages: [], apiConversationHistory: [], updateApiConfiguration: vi.fn(), } // Add task to provider stack await provider.addClineToStack(mockTask as any) // Mock getGlobalState to return task history vi.spyOn(provider as any, "getGlobalState").mockReturnValue([ { id: mockTask.taskId, ts: Date.now(), task: "Test task", number: 1, tokensIn: 0, tokensOut: 0, cacheWrites: 0, cacheReads: 0, totalCost: 0, }, ]) // Mock updateTaskHistory vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { return Promise.resolve([]) }) // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.openrouter, }) // Mock providerSettingsManager.listConfig vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.openrouter }, ]) // Switch provider profile await provider.activateProviderProfile({ name: "new-profile" }) // Verify task's _taskApiConfigName property was updated expect(mockTask._taskApiConfigName).toBe("new-profile") }) it("should update in-memory task profile even if task history item does not exist yet", async () => { await provider.resolveWebviewView(mockWebviewView) const mockTask = { taskId: "test-task-id", _taskApiConfigName: "default-profile", setTaskApiConfigName: vi.fn().mockImplementation(function (this: any, name: string) { this._taskApiConfigName = name }), emit: vi.fn(), saveClineMessages: vi.fn(), clineMessages: [], apiConversationHistory: [], updateApiConfiguration: vi.fn(), } await provider.addClineToStack(mockTask as any) // No history item exists yet vi.spyOn(provider as any, "getGlobalState").mockReturnValue([]) const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { return Promise.resolve([]) }) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.openrouter, }) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.openrouter }, ]) await provider.activateProviderProfile({ name: "new-profile" }) // In-memory should still update, even without a history item. expect(mockTask._taskApiConfigName).toBe("new-profile") // No history item => no updateTaskHistory call. expect(updateTaskHistorySpy).not.toHaveBeenCalled() }) }) describe("createTaskWithHistoryItem", () => { it("should restore provider profile from history item when reopening task outside CLI runtime", async () => { await provider.resolveWebviewView(mockWebviewView) // Create a history item with saved provider profile const historyItem: HistoryItem = { id: "test-task-id", number: 1, ts: Date.now(), task: "Test task", tokensIn: 100, tokensOut: 200, cacheWrites: 0, cacheReads: 0, totalCost: 0.001, mode: "code", apiConfigName: "saved-profile", // Saved provider profile } // Mock activateProviderProfile to track calls const activateProviderProfileSpy = vi .spyOn(provider, "activateProviderProfile") .mockResolvedValue(undefined) // Mock providerSettingsManager.listConfig vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "saved-profile", id: "saved-profile-id", apiProvider: providerIdentifiers.anthropic }, ]) // Initialize task with history item await provider.createTaskWithHistoryItem(historyItem) // Verify provider profile was restored via activateProviderProfile (restore-only: don't persist mode config) expect(activateProviderProfileSpy).toHaveBeenCalledWith( { name: "saved-profile" }, { persistModeConfig: false, persistTaskHistory: false, expectedCurrentTaskId: historyItem.id }, ) }) it("should not restore an empty task apiConfigName profile from history", async () => { await provider.resolveWebviewView(mockWebviewView) const historyItem: HistoryItem = { id: "test-task-id", number: 1, ts: Date.now(), task: "Test task", tokensIn: 100, tokensOut: 200, cacheWrites: 0, cacheReads: 0, totalCost: 0.001, mode: "ask", apiConfigName: "default", } const activateProviderProfileSpy = vi .spyOn(provider, "activateProviderProfile") .mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "default", id: "default-id" }, ]) await provider.createTaskWithHistoryItem(historyItem) expect(activateProviderProfileSpy).not.toHaveBeenCalled() }) it("should skip restoring task apiConfigName from history in CLI runtime", async () => { await provider.resolveWebviewView(mockWebviewView) process.env.ROO_CLI_RUNTIME = "1" const historyItem: HistoryItem = { id: "test-task-id", number: 1, ts: Date.now(), task: "Test task", tokensIn: 100, tokensOut: 200, cacheWrites: 0, cacheReads: 0, totalCost: 0.001, apiConfigName: "saved-profile", } const activateProviderProfileSpy = vi .spyOn(provider, "activateProviderProfile") .mockResolvedValue(undefined) const logSpy = vi.spyOn(provider, "log") vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "saved-profile", id: "saved-profile-id", apiProvider: providerIdentifiers.anthropic }, ]) await provider.createTaskWithHistoryItem(historyItem) expect(activateProviderProfileSpy).not.toHaveBeenCalledWith({ name: "saved-profile" }, expect.anything()) expect(logSpy).toHaveBeenCalledWith( expect.stringContaining("Skipping restore of provider profile 'saved-profile'"), ) }) it("should skip restoring mode-based provider config from history in CLI runtime", async () => { await provider.resolveWebviewView(mockWebviewView) process.env.ROO_CLI_RUNTIME = "1" const historyItem: HistoryItem = { id: "test-task-id", number: 1, ts: Date.now(), task: "Test task", tokensIn: 100, tokensOut: 200, cacheWrites: 0, cacheReads: 0, totalCost: 0.001, mode: "code", } const activateProviderProfileSpy = vi .spyOn(provider, "activateProviderProfile") .mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("mode-config-id") vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "mode-profile", id: "mode-config-id", apiProvider: providerIdentifiers.anthropic }, ]) await provider.createTaskWithHistoryItem(historyItem) expect(activateProviderProfileSpy).not.toHaveBeenCalled() }) it("restores the mode-based profile without persisting it as a mode default or touching another task", async () => { provider["initialModeConfigIds"] = Promise.resolve({ code: "mode-config-id" }) await provider.resolveWebviewView(mockWebviewView) const historyItem: HistoryItem = { id: "test-task-id", number: 1, ts: Date.now(), task: "Test task", tokensIn: 0, tokensOut: 0, totalCost: 0, mode: "code", } const activateProviderProfileSpy = vi .spyOn(provider, "activateProviderProfile") .mockResolvedValue(undefined) vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("mode-config-id") vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "mode-profile", id: "mode-config-id", apiProvider: providerIdentifiers.anthropic }, ]) vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({ name: "mode-profile", id: "mode-config-id", apiProvider: providerIdentifiers.anthropic, }) await provider.createTaskWithHistoryItem(historyItem) expect(activateProviderProfileSpy).toHaveBeenCalledWith( { name: "mode-profile" }, { persistModeConfig: false, expectedCurrentTaskId: historyItem.id }, ) }) it("should use current profile if history item has no saved apiConfigName", async () => { await provider.resolveWebviewView(mockWebviewView) // Create a history item without saved provider profile const historyItem: HistoryItem = { id: "test-task-id", number: 1, ts: Date.now(), task: "Test task", tokensIn: 100, tokensOut: 200, cacheWrites: 0, cacheReads: 0, totalCost: 0.001, // No apiConfigName field } // Mock activateProviderProfile to track calls const activateProviderProfileSpy = vi .spyOn(provider, "activateProviderProfile") .mockResolvedValue(undefined) // Initialize task with history item await provider.createTaskWithHistoryItem(historyItem) // Verify activateProviderProfile was NOT called for apiConfigName restoration // (it might be called for mode-based config, but not for direct apiConfigName) const callsForApiConfigName = activateProviderProfileSpy.mock.calls.filter( (call) => call[0] && "name" in call[0] && call[0].name === historyItem.apiConfigName, ) expect(callsForApiConfigName.length).toBe(0) }) it("should override mode-based config with task's apiConfigName", async () => { await provider.resolveWebviewView(mockWebviewView) // Create a history item with both mode and apiConfigName const historyItem: HistoryItem = { id: "test-task-id", number: 1, ts: Date.now(), task: "Test task", tokensIn: 100, tokensOut: 200, cacheWrites: 0, cacheReads: 0, totalCost: 0.001, mode: "architect", // Mode has a different preferred profile apiConfigName: "task-specific-profile", // Task's actual profile } // Track all activateProviderProfile calls const activateCalls: string[] = [] vi.spyOn(provider, "activateProviderProfile").mockImplementation(async (args) => { if ("name" in args) { activateCalls.push(args.name) } }) // Mock providerSettingsManager methods vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("mode-config-id") vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "mode-preferred-profile", id: "mode-config-id", apiProvider: providerIdentifiers.anthropic }, { name: "task-specific-profile", id: "task-profile-id", apiProvider: providerIdentifiers.openai }, ]) // Initialize task with history item await provider.createTaskWithHistoryItem(historyItem) // Verify task's apiConfigName was activated LAST (overriding mode-based config) expect(activateCalls[activateCalls.length - 1]).toBe("task-specific-profile") }) it("should handle missing provider profile gracefully", async () => { await provider.resolveWebviewView(mockWebviewView) // Create a history item with a provider profile that no longer exists const historyItem: HistoryItem = { id: "test-task-id", number: 1, ts: Date.now(), task: "Test task", tokensIn: 100, tokensOut: 200, cacheWrites: 0, cacheReads: 0, totalCost: 0.001, apiConfigName: "deleted-profile", // Profile that doesn't exist } // Mock providerSettingsManager.listConfig to return empty (profile doesn't exist) vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([]) // Mock log to verify warning is logged const logSpy = vi.spyOn(provider, "log") // Initialize task with history item - should not throw await expect(provider.createTaskWithHistoryItem(historyItem)).resolves.not.toThrow() // Verify a warning was logged expect(logSpy).toHaveBeenCalledWith( expect.stringContaining("Provider profile 'deleted-profile' from history no longer exists"), ) }) }) describe("Task metadata persistence", () => { it("should include apiConfigName in task metadata when saving", async () => { await provider.resolveWebviewView(mockWebviewView) // Create a mock task with provider profile const mockTask = { taskId: "test-task-id", _taskApiConfigName: "test-profile", setTaskApiConfigName: vi.fn(), emit: vi.fn(), saveClineMessages: vi.fn(), clineMessages: [], apiConversationHistory: [], updateApiConfiguration: vi.fn(), } // Populate the store so persistStickyProviderProfileToCurrentTask finds the task await provider.taskHistoryStore.upsert({ id: mockTask.taskId, ts: Date.now(), task: "Test task", number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, }) // Mock updateTaskHistory to capture the updated history item let updatedHistoryItem: any vi.spyOn(provider, "updateTaskHistory").mockImplementation((item) => { updatedHistoryItem = item return Promise.resolve([item]) }) // Add task to provider stack await provider.addClineToStack(mockTask as any) // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.anthropic, }) // Mock providerSettingsManager.listConfig vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.anthropic }, ]) // Trigger a profile switch await provider.activateProviderProfile({ name: "new-profile" }) // Verify apiConfigName was included in the updated history item expect(updatedHistoryItem).toBeDefined() expect(updatedHistoryItem.apiConfigName).toBe("new-profile") }) }) describe("Multiple workspaces isolation", () => { it("should preserve task profile when switching profiles in another workspace", async () => { // This test verifies that each task retains its designated provider profile // so that switching profiles in one workspace doesn't alter other tasks await provider.resolveWebviewView(mockWebviewView) // Create task 1 with profile A const task1 = { taskId: "task-1", _taskApiConfigName: "profile-a", setTaskApiConfigName: vi.fn().mockImplementation(function (this: any, name: string) { this._taskApiConfigName = name }), emit: vi.fn(), saveClineMessages: vi.fn(), clineMessages: [], apiConversationHistory: [], updateApiConfiguration: vi.fn(), } // Add task 1 to stack await provider.addClineToStack(task1 as any) // Mock getGlobalState to return task history for both tasks const taskHistory = [ { id: "task-1", ts: Date.now(), task: "Task 1", number: 1, tokensIn: 0, tokensOut: 0, cacheWrites: 0, cacheReads: 0, totalCost: 0, apiConfigName: "profile-a", }, { id: "task-2", ts: Date.now(), task: "Task 2", number: 2, tokensIn: 0, tokensOut: 0, cacheWrites: 0, cacheReads: 0, totalCost: 0, apiConfigName: "profile-b", }, ] // Populate the store for (const item of taskHistory) { await provider.taskHistoryStore.upsert(item as any) } // Mock updateTaskHistory vi.spyOn(provider, "updateTaskHistory").mockImplementation((item) => { const index = taskHistory.findIndex((h) => h.id === item.id) if (index >= 0) { taskHistory[index] = { ...taskHistory[index], ...item } } return Promise.resolve(taskHistory) }) // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "profile-c", id: "profile-c-id", apiProvider: providerIdentifiers.anthropic, }) // Mock providerSettingsManager.listConfig vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "profile-a", id: "profile-a-id", apiProvider: providerIdentifiers.anthropic }, { name: "profile-b", id: "profile-b-id", apiProvider: providerIdentifiers.openai }, { name: "profile-c", id: "profile-c-id", apiProvider: providerIdentifiers.anthropic }, ]) // Switch task 1's profile to profile C await provider.activateProviderProfile({ name: "profile-c" }) // Verify task 1's profile was updated expect(task1._taskApiConfigName).toBe("profile-c") expect(taskHistory[0].apiConfigName).toBe("profile-c") // Verify task 2's profile remains unchanged expect(taskHistory[1].apiConfigName).toBe("profile-b") }) }) describe("Error handling", () => { it("should handle errors gracefully when saving profile fails", async () => { await provider.resolveWebviewView(mockWebviewView) // Create a mock task const mockTask = { taskId: "test-task-id", _taskApiConfigName: "default-profile", setTaskApiConfigName: vi.fn(), emit: vi.fn(), saveClineMessages: vi.fn(), clineMessages: [], apiConversationHistory: [], updateApiConfiguration: vi.fn(), } // Add task to provider stack await provider.addClineToStack(mockTask as any) // Populate the store await provider.taskHistoryStore.upsert({ id: mockTask.taskId, ts: Date.now(), task: "Test task", number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, }) // Mock updateTaskHistory to throw error vi.spyOn(provider, "updateTaskHistory").mockRejectedValue(new Error("Save failed")) // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.anthropic, }) // Mock providerSettingsManager.listConfig vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "new-profile", id: "new-profile-id", apiProvider: providerIdentifiers.anthropic }, ]) // Mock log to verify error is logged const logSpy = vi.spyOn(provider, "log") // Switch provider profile - should not throw await expect(provider.activateProviderProfile({ name: "new-profile" })).resolves.not.toThrow() // Verify error was logged expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to persist provider profile switch")) }) it("should handle null/undefined apiConfigName gracefully", async () => { await provider.resolveWebviewView(mockWebviewView) // Create a history item with null apiConfigName const historyItem: HistoryItem = { id: "test-task-id", number: 1, ts: Date.now(), task: "Test task", tokensIn: 100, tokensOut: 200, cacheWrites: 0, cacheReads: 0, totalCost: 0.001, apiConfigName: null as any, // Invalid apiConfigName } // Mock activateProviderProfile to track calls const activateProviderProfileSpy = vi .spyOn(provider, "activateProviderProfile") .mockResolvedValue(undefined) // Initialize task with history item - should not throw await expect(provider.createTaskWithHistoryItem(historyItem)).resolves.not.toThrow() // Verify activateProviderProfile was not called with null expect(activateProviderProfileSpy).not.toHaveBeenCalledWith({ name: null }) }) }) describe("Profile restoration with activateProfile failure", () => { it("should continue task restoration even if activateProviderProfile fails", async () => { await provider.resolveWebviewView(mockWebviewView) // Create a history item with saved provider profile const historyItem: HistoryItem = { id: "test-task-id", number: 1, ts: Date.now(), task: "Test task", tokensIn: 100, tokensOut: 200, cacheWrites: 0, cacheReads: 0, totalCost: 0.001, apiConfigName: "failing-profile", } // Mock providerSettingsManager.listConfig to return the profile vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ { name: "failing-profile", id: "failing-profile-id", apiProvider: providerIdentifiers.anthropic }, ]) // Mock activateProviderProfile to throw error vi.spyOn(provider, "activateProviderProfile").mockRejectedValue(new Error("Activation failed")) // Mock log to verify error is logged const logSpy = vi.spyOn(provider, "log") // Initialize task with history item - should not throw even though activation fails await expect(provider.createTaskWithHistoryItem(historyItem)).resolves.not.toThrow() // Verify error was logged expect(logSpy).toHaveBeenCalledWith( expect.stringContaining("Failed to restore API configuration 'failing-profile' for task"), ) }) }) describe("deleteProviderProfile", () => { // Every test in this file constructs a real ClineProvider, and the harness never // disposes them: they stay in the static live set that profile operations sweep, and a // stray from an earlier test still carries that test's mocked postStateToWebview - one of // them rejects, and a fan-out that reaches it makes an unrelated deletion fail for // someone else's stub. Close the strays before measuring this block's own deletion. beforeEach(async () => { const live = (ClineProvider as unknown as { getAllInstances: () => ClineProvider[] }).getAllInstances() for (const stray of live) { if (stray !== provider) { await stray.dispose() } } }) it("removes the stored profile so a dangling mode mapping can no longer re-activate it", async () => { await provider.resolveWebviewView(mockWebviewView) // Seed the stored profile settings: the default profile plus a child // profile (mirroring the cross-profile subtasks e2e scenario), with the // "ask" mode mapped to the child profile. const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const childId = await provider.providerSettingsManager.saveConfig("subtask-child-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1-mini", }) await provider.providerSettingsManager.setModeConfig("ask", childId) // The UI-facing list mirrors the store, as maintained by upsert/activate. await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "subtask-child-profile", id: childId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "subtask-child-profile", }) await provider.deleteProviderProfile({ name: "subtask-child-profile", id: childId, apiProvider: providerIdentifiers.openrouter, }) // The deleted profile's settings are gone from the manager store. const remaining = await provider.providerSettingsManager.listConfig() expect(remaining.some((config) => config.name === "subtask-child-profile")).toBe(false) await expect( provider.providerSettingsManager.getProfile({ name: "subtask-child-profile" }), ).rejects.toThrow(/subtask-child-profile.*not found/) // The mode mapping still points at the deleted id, but it no longer // resolves to a stored profile, so handleModeSwitch falls through to the // current configuration instead of re-activating the deleted profile. const savedConfigId = await provider.providerSettingsManager.getModeConfigId("ask") expect(savedConfigId).toBe(childId) expect(remaining.find(({ id }) => id === savedConfigId)).toBeUndefined() // The context was repointed at the surviving profile. const values = provider.contextProxy.getValues() expect(values.currentApiConfigName).toBe("default") expect(values.listApiConfigMeta?.map((entry) => entry.name)).toEqual(["default"]) }) it("treats an already-gone secret as success so the stale list entry is still pruned", async () => { await provider.resolveWebviewView(mockWebviewView) // Only the default profile exists in the store: the ghost profile's secret // was already gone (e.g. pruned by an earlier run) but its list entry // survived. const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "ghost-profile", id: "ghost-id", apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "ghost-profile", }) // The manager's "not found" rejection must not surface to the caller ... await expect( provider.deleteProviderProfile({ name: "ghost-profile", id: "ghost-id", apiProvider: providerIdentifiers.openrouter, }), ).resolves.not.toThrow() // ... it prunes the stale list entry and repoints the selection. const values = provider.contextProxy.getValues() expect(values.currentApiConfigName).toBe("default") expect(values.listApiConfigMeta?.map((entry) => entry.name)).toEqual(["default"]) }) it("reports failure when a sibling re-pin rejects without an error object", async () => { await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1-mini", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "default", }) // A rejection carries no reason when the value thrown was not an Error, and the re-pin sweep // reports exactly that as `[undefined]`. Reading the reason instead of counting the failed // writes let this through: the deletion reported success while a live sibling stayed pinned // to a profile that no longer resolves. The sweep itself stays real here - only the durable // view-state write underneath it is broken - so this row also proves the sweep collects the // rejection rather than only the guard reacting to a stubbed outcome. const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await sibling.activateProviderProfile({ name: "doomed-profile" }) const postSpy = vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) // Direct private access: the durable view-state write is the seam a real storage failure hits. sibling["savePersistedViewState"] = async () => { throw undefined } try { await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("re-pinning a live view away from the deleted profile failed with a non-error reason") // And the compensation ran: the record is back in the manager and the shared list carries it // again, so the reported failure is not a half-applied deletion. expect(await provider.providerSettingsManager.hasConfig("doomed-profile")).toBe(true) expect(provider.contextProxy.getValues().listApiConfigMeta?.map((entry) => entry.name)).toContain( "doomed-profile", ) // The sibling whose write failed was left exactly where it was: the durable write is awaited // before the local buffer updates, so a failed re-pin cannot leave the view showing a name // its storage never received, and it is not posted half-way either. expect(sibling.pinnedProfileName).toBe("doomed-profile") expect(sibling["viewLocalState"].currentApiConfigName).toBe("doomed-profile") expect(postSpy).not.toHaveBeenCalled() } finally { await sibling.dispose() } }) it("posts a compensated sibling only after the shared settings are restored", async () => { await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "default", }) // Seed the shared provider settings the way the doomed profile's activation leaves them, // so the rollback has a payload to put back and the read below has something to lose: // every profile here was stored with a different model id. await provider.contextProxy.setProviderSettings({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) // A view can pin a profile without an apiConfiguration overlay - activation alone leaves none - // and such a view reads the shared settings. Once the deletion hands it back its own name, the // moment of the post decides which model it advertises: posted before the shared restore it // pairs the restored profile's name with the survivor's model, and no later post corrects it. const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await sibling.activateProviderProfile({ name: "doomed-profile" }) // The reviewer's point is the message, not a read of the provider behind it: postStateToWebview // stays real and the record is taken from what actually leaves the view. Name and model come // out of one message, so a post that pairs the restored name with the survivor payload cannot // pass both checks. const postedNames: (string | undefined)[] = [] const postedModelIds: (string | undefined)[] = [] const sharedModelAtPost: (string | undefined)[] = [] const siblingPostMessage = vi.fn( (message: { type?: string state?: { currentApiConfigName?: string; apiConfiguration?: { openRouterModelId?: string } } }) => { // The shared store is read at the moment the message left this view, which is the ordering // the finding is about. sharedModelAtPost.push(provider.contextProxy.getProviderSettings().openRouterModelId) const state = message?.type === "state" ? message.state : undefined postedNames.push(state?.currentApiConfigName) postedModelIds.push(state?.apiConfiguration?.openRouterModelId) }, ) const siblingWebviewView = { webview: { postMessage: siblingPostMessage, html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), cspSource: "vscode-webview://test-csp-source", }, visible: true, onDidDispose: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), onDidChangeVisibility: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), } as unknown as vscode.WebviewView // The view has to exist for a message to leave: postMessageToWebview drops it when no view is // bound, which is what left the previous version of this row reading the provider cache // instead of the delivered state. await sibling.resolveWebviewView(siblingWebviewView) // Fail the deletion at its last step so the compensation path - and its posts - actually run. vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("webview gone")) try { await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("webview gone") // The sweep posted the sibling onto the survivor; the rollback posted it back. The last post // is the compensated one, and by then the shared store must already hold the restored // profile's own payload - not the survivor's. expect(sibling.pinnedProfileName).toBe("doomed-profile") const lastPost = postedNames.length - 1 expect(postedNames.length).toBeGreaterThan(1) // Both values are read out of one state message delivered to the mocked webview: the // compensated post has to carry the restored profile name and that profile model together. // Asserting the name alone passes a post that put the survivor payload under the restored // name; asserting the model alone passes one that kept the survivor name. expect(postedNames[lastPost]).toBe("doomed-profile") expect(postedModelIds[lastPost]).toBe("openai/gpt-4o") // And when that last message left the view, the shared store had already been put back // onto the restored profile - the ordering the finding asks for. expect(sharedModelAtPost[lastPost]).toBe("openai/gpt-4o") } finally { await sibling.dispose() } }) it("still refuses to delete the last stored profile when a stale list entry remains", async () => { await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) // A ghost list entry survives next to the only real profile, so the // provider-level "last profile" guard does not fire: the refusal must come // from the settings store itself. await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "ghost-profile", id: "ghost-id", apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "default", }) await expect( provider.deleteProviderProfile({ name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("Cannot delete the last remaining configuration") // Nothing was repointed or pruned. const values = provider.contextProxy.getValues() expect(values.currentApiConfigName).toBe("default") expect(values.listApiConfigMeta?.map((entry) => entry.name)).toEqual(["default", "ghost-profile"]) }) it("deletes a stored profile while the shared selection is unset", async () => { // The selection is unset on a store where nobody has picked a profile yet, while the // store holds several of them. Deleting one is an ordinary request; reading the unset // selection as "this must be the last profile" refused it. await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const extraId = await provider.providerSettingsManager.saveConfig("unset-selection-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1-mini", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "unset-selection-profile", id: extraId, apiProvider: providerIdentifiers.openrouter, }, ], currentApiConfigName: undefined, }) await expect( provider.deleteProviderProfile({ name: "unset-selection-profile", id: extraId, apiProvider: providerIdentifiers.openrouter, }), ).resolves.not.toThrow() const remaining = await provider.providerSettingsManager.listConfig() expect(remaining.some((config) => config.name === "unset-selection-profile")).toBe(false) const values = provider.contextProxy.getValues() expect(values.listApiConfigMeta?.map((entry) => entry.name)).toEqual(["default"]) // Nothing picked a profile on the user's behalf: an unset selection stays unset. expect(values.currentApiConfigName).toBeUndefined() }) it("still refuses an unset selection when the store holds no survivor", async () => { await provider.resolveWebviewView(mockWebviewView) const onlyId = await provider.providerSettingsManager.saveConfig("only-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) await provider.contextProxy.setValues({ listApiConfigMeta: [{ name: "only-profile", id: onlyId, apiProvider: providerIdentifiers.openrouter }], currentApiConfigName: undefined, }) await expect( provider.deleteProviderProfile({ name: "only-profile", id: onlyId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("You cannot delete the last profile") const values = provider.contextProxy.getValues() expect(values.listApiConfigMeta?.map((entry) => entry.name)).toEqual(["only-profile"]) }) it("moves the settings manager's own selection off a profile it was naming", async () => { // The settings manager keeps a current-profile selection of its own beside the // shared one, and deleting the profile it names leaves it holding a record that no // longer exists: every later rollback reads it, and a dangling name makes the next // restore skip silently. await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const activeId = await provider.providerSettingsManager.saveConfig("manager-selected-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1-mini", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "manager-selected-profile", id: activeId, apiProvider: providerIdentifiers.openrouter, }, ], currentApiConfigName: "manager-selected-profile", }) await provider.providerSettingsManager.activateProfile({ name: "manager-selected-profile" }) // Record every activation the deletion performs, while keeping the real store // behaviour intact so the assertions below read the manager's own state. const activations: ({ name: string } | { id: string })[] = [] const activateProfile = provider.providerSettingsManager.activateProfile.bind( provider.providerSettingsManager, ) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockImplementation((params) => { activations.push(params) return activateProfile(params) }) await provider.deleteProviderProfile({ name: "manager-selected-profile", id: activeId, apiProvider: providerIdentifiers.openrouter, }) expect(activations.some((params) => "name" in params && params.name === "default")).toBe(true) await expect(provider.providerSettingsManager.getCurrentProfileName()).resolves.toBe("default") }) it("leaves a newer manager selection alone when another profile is deleted", async () => { // The manager has already been moved by someone else: this deletion must not // overwrite a selection that is newer than it. await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const goneId = await provider.providerSettingsManager.saveConfig("deleted-elsewhere-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1-mini", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "deleted-elsewhere-profile", id: goneId, apiProvider: providerIdentifiers.openrouter, }, ], currentApiConfigName: "deleted-elsewhere-profile", }) await provider.providerSettingsManager.activateProfile({ name: "default" }) const activations: ({ name: string } | { id: string })[] = [] const activateProfile = provider.providerSettingsManager.activateProfile.bind( provider.providerSettingsManager, ) vi.spyOn(provider.providerSettingsManager, "activateProfile").mockImplementation((params) => { activations.push(params) return activateProfile(params) }) await provider.deleteProviderProfile({ name: "deleted-elsewhere-profile", id: goneId, apiProvider: providerIdentifiers.openrouter, }) expect(activations).toEqual([]) expect(provider.providerSettingsManager.activateProfile).not.toHaveBeenCalled() await expect(provider.providerSettingsManager.getCurrentProfileName()).resolves.toBe("default") const remaining = await provider.providerSettingsManager.listConfig() expect(remaining.some((config) => config.name === "deleted-elsewhere-profile")).toBe(false) }) it("restores the acting view and its task when a deletion rolls back", async () => { await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o-mini", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "default", }) // Act on the profile that is about to be deleted: this view pins it, the shared store // selects it, and the running task serves it. The deletion has to reconfigure all three, // and a rollback that undoes only the shared store leaves this view - the one the user // is looking at - on a profile that failed to delete. await provider.activateProviderProfile({ name: "doomed-profile" }) // The configuration this conversation was actually sending. It is deliberately a // different model from the settings stored under the doomed profile's name below: a // profile record can be saved again while the running task keeps the settings its // handler was built from, and a rollback that rebuilds from the restored record would // silently switch this conversation's model while looking like it restored it. const actingTaskConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", } const currentTask = { taskId: "doomed-task", _taskApiConfigName: "doomed-profile", get taskApiConfigName(): string { return this._taskApiConfigName }, setTaskApiConfigName: vi.fn(function (this: { _taskApiConfigName: string }, name: string) { this._taskApiConfigName = name }), apiConfiguration: actingTaskConfiguration, updateApiConfiguration: vi.fn<(settings: unknown) => void>(), emit: vi.fn(), } vi.spyOn(provider, "getCurrentTask").mockReturnValue(currentTask as unknown as Task) await provider.taskHistoryStore.upsert({ id: currentTask.taskId, ts: Date.now(), task: "Doomed task", number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, }) vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => Promise.resolve([])) // The failure lands after the re-pointing has already happened: the durable rewrites // succeeded and the last step of the deletion cannot report success. vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("webview gone")) await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("webview gone") // The view keeps the profile it was acting on. It had no overlay of its own before the // deletion (it served the shared store), so the rollback has to clear the survivor's // settings that the deletion pinned into its overlay rather than leave them there under // the restored pin. expect(provider["viewLocalState"].currentApiConfigName).toBe("doomed-profile") expect(provider["viewLocalState"].apiConfiguration).toBeUndefined() expect(provider.contextProxy.getValues().currentApiConfigName).toBe("doomed-profile") expect(provider.contextProxy.getProviderSettings().openRouterModelId).toBe("openai/gpt-4o-mini") // The task was moved onto the survivor by the deletion, so the rollback moves it back - // and the settings manager keeps its own selection beside the shared one, which the // deletion moved forward as well. expect(currentTask._taskApiConfigName).toBe("doomed-profile") await expect(provider.providerSettingsManager.getCurrentProfileName()).resolves.toBe("doomed-profile") const stored = await provider.providerSettingsManager.listConfig() expect(stored.some((config) => config.name === "doomed-profile")).toBe(true) // The rebuild order is the behavior this row is about: the deletion rebuilt the handler // with the survivor's settings, and the rollback handed back the configuration this // conversation was sending - the very object it started with, not the settings the // restored record carries. Asserting only the restored profile name would pass a // rollback that renamed the task and left it running another profile's model. expect(currentTask.updateApiConfiguration).toHaveBeenNthCalledWith( 1, expect.objectContaining({ openRouterModelId: "openai/gpt-4.1" }), ) expect(currentTask.updateApiConfiguration).toHaveBeenLastCalledWith(actingTaskConfiguration) }) it("re-points the selection when a sibling view activates the deleted profile mid-deletion", async () => { await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const childId = await provider.providerSettingsManager.saveConfig("subtask-child-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1-mini", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "subtask-child-profile", id: childId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "default", }) // A second view - a real provider instance with its own ContextProxy, its own pin and its // own overlay - activates the profile this deletion is about to remove while the deletion // pauses inside the record delete. Both views share the extension host's storage, so from // the moment the record is gone the shared selection genuinely names the deleted profile and // that view's own pin dangles: the deletion has to notice both instead of trusting what it // read at entry, and the re-pin has to reach a live view rather than a hand-written // selection write. const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Posting state to a webview this test never opens is not what is under test. vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) const manager = provider.providerSettingsManager const deleteStoredConfig = manager.deleteConfig.bind(manager) manager.deleteConfig = async (name: string) => { await sibling.activateProviderProfile({ name: "subtask-child-profile" }) return deleteStoredConfig(name) } try { await provider.deleteProviderProfile({ name: "subtask-child-profile", id: childId, apiProvider: providerIdentifiers.openrouter, }) const values = provider.contextProxy.getValues() expect(values.currentApiConfigName).toBe("default") // The shared provider keys still carried the deleted profile's settings when the selection // moved onto it, so they must be replaced with the profile the selection now names. expect(provider.contextProxy.getProviderSettings().openRouterModelId).toBe("openai/gpt-4.1") // The view that pinned itself onto the deleted profile is the one whose pin dangles, so the // re-pin has to give it both the survivor's name and the survivor's settings: a re-pin that // moves the name while the view keeps the deleted profile's configuration - or loses any // configuration of its own - pairs one profile's name with another profile's credentials. expect(sibling.pinnedProfileName).toBe("default") expect(sibling["viewLocalState"].apiConfiguration?.openRouterModelId).toBe("openai/gpt-4.1") expect((await sibling.getState()).apiConfiguration?.openRouterModelId).toBe("openai/gpt-4.1") } finally { // Every provider a test constructs joins the static live-provider set the re-pin sweeps, // so this one must not outlive the test that created it. await sibling.dispose() } }) it("follows a selection a sibling view moved onto another survivor mid-deletion", async () => { const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const otherId = await provider.providerSettingsManager.saveConfig("other-survivor", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) const childId = await provider.providerSettingsManager.saveConfig("subtask-child-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1-mini", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "other-survivor", id: otherId, apiProvider: providerIdentifiers.openrouter }, { name: "subtask-child-profile", id: childId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "subtask-child-profile", }) // Seed the shared provider settings the way a real activation leaves them: through the same // 'setProviderSettings' call an activation makes, holding the payload of the profile the // selection names once the sibling view has switched to 'other-survivor'. The assertion at the // bottom then has something to lose - every profile in this test was stored with a // different model id, so pairing the survivor name with another profile's settings shows up. await provider.contextProxy.setProviderSettings({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) await provider.resolveWebviewView(mockWebviewView) // This deletion selects the first survivor at entry, because that is what the shared // selection names then. A sibling view moves the selection onto a different survivor while // the record delete is in flight; that choice is the user's, and the deletion must follow it // instead of pushing the selection back onto its own pick. const manager = provider.providerSettingsManager const deleteStoredConfig = manager.deleteConfig.bind(manager) manager.deleteConfig = async (name: string) => { await provider.contextProxy.setValue("currentApiConfigName", "other-survivor") return deleteStoredConfig(name) } await provider.deleteProviderProfile({ name: "subtask-child-profile", id: childId, apiProvider: providerIdentifiers.openrouter, }) const values = provider.contextProxy.getValues() expect(values.currentApiConfigName).toBe("other-survivor") expect(values.listApiConfigMeta?.map((entry) => entry.name)).toEqual(["default", "other-survivor"]) // Invariant: no shared write may pair the survivor's name with another profile's settings. The shared // provider keys carry the settings of the profile the selection names, and the selection // moved onto 'other-survivor' mid-deletion, so the store must now hold that profile's payload - // "openai/gpt-4o", a model id no other profile in this test was stored with. expect(provider.contextProxy.getProviderSettings().openRouterModelId).toBe("openai/gpt-4o") }) it("restores a view that pinned itself onto the deleted profile mid-deletion", async () => { await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "default", }) // A second live view pins itself onto the profile being deleted while the deletion is // inside the record delete, so the re-pin sweep - not the pre-delete snapshot - is what // notices it. The deletion then fails at its last step, and the compensation has to undo // that view's re-pin as well: leaving it on the survivor while the record is restored is // a state no caller asked for, and the pre-delete snapshot cannot see this view at all. const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined) const manager = provider.providerSettingsManager const deleteStoredConfig = manager.deleteConfig.bind(manager) manager.deleteConfig = async (name: string) => { await sibling.activateProviderProfile({ name: "doomed-profile" }) // Seed it after the activation, because the activation itself writes no overlay: // a copy seeded before it would be erased by it. The deletion replaces this // buffer with the survivor's settings and the rollback has to hand it back - without // it the overlay half of the restore is unobservable. await sibling["_saveViewLocalStateFromMutation"]({ apiConfiguration: { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }, }) return deleteStoredConfig(name) } vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("webview gone")) try { await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("webview gone") // The record is back and the shared selection is where it was. expect(provider.contextProxy.getValues().currentApiConfigName).toBe("default") const stored = await provider.providerSettingsManager.listConfig() expect(stored.some((config) => config.name === "doomed-profile")).toBe(true) // The view that pinned itself on mid-deletion was re-pointed by the sweep, so the // rollback has to bring it back onto the restored profile together with the settings it // was serving before - both halves, because a name restored over another profile's // configuration pairs the two, and a cleared overlay leaves the restored pin with no // settings at all. expect(sibling.pinnedProfileName).toBe("doomed-profile") expect(sibling["viewLocalState"].apiConfiguration?.openRouterModelId).toBe("openai/gpt-4o") expect((await sibling.getState()).apiConfiguration?.openRouterModelId).toBe("openai/gpt-4o") } finally { await sibling.dispose() } }) it("leaves a replacement task instance alone when the deletion rolls back", async () => { await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "default", }) await provider.activateProviderProfile({ name: "doomed-profile" }) const actingTaskConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", } const actingTask = { taskId: "shared-task-id", _taskApiConfigName: "doomed-profile", get taskApiConfigName(): string { return this._taskApiConfigName }, setTaskApiConfigName: vi.fn(function (this: { _taskApiConfigName: string }, name: string) { this._taskApiConfigName = name }), apiConfiguration: actingTaskConfiguration, updateApiConfiguration: vi.fn<(settings: unknown) => void>(), emit: vi.fn(), } // Same task id, different conversation: restoring a task's history installs a new Task // object under the id the user still sees. The replacement is on the survivor and holds its // own settings, so it belongs to whoever opened it and this rollback must not touch it. const replacementTask = { taskId: "shared-task-id", _taskApiConfigName: "default", get taskApiConfigName(): string { return this._taskApiConfigName }, setTaskApiConfigName: vi.fn(function (this: { _taskApiConfigName: string }, name: string) { this._taskApiConfigName = name }), apiConfiguration: { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }, updateApiConfiguration: vi.fn<(settings: unknown) => void>(), emit: vi.fn(), } const getCurrentTask = vi.spyOn(provider, "getCurrentTask").mockReturnValue(actingTask as unknown as Task) await provider.taskHistoryStore.upsert({ id: actingTask.taskId, ts: Date.now(), task: "Acting task", number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, }) vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => Promise.resolve([])) vi.spyOn(provider, "postStateToWebview").mockImplementationOnce(async () => { getCurrentTask.mockReturnValue(replacementTask as unknown as Task) return Promise.reject(new Error("webview gone")) }) await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("webview gone") // The instance the deletion actually re-pointed is gone, so the rollback leaves the // conversation that replaced it exactly as it found it: comparing task ids alone would // rewrite the new conversation's sticky profile and rebuild its handler from a profile the // deletion never touched. expect(replacementTask.setTaskApiConfigName).not.toHaveBeenCalled() expect(replacementTask.updateApiConfiguration).not.toHaveBeenCalled() expect(replacementTask.taskApiConfigName).toBe("default") // The shared half of the rollback still ran: the selection is back on the profile this row // started with, so the surviving conversation is not stranded on a profile that failed to // delete. It is simply not this rollback's conversation to rewrite. expect(provider.contextProxy.getValues().currentApiConfigName).toBe("doomed-profile") const stored = await provider.providerSettingsManager.listConfig() expect(stored.some((config) => config.name === "doomed-profile")).toBe(true) }) it("restores the conversation the deletion re-pointed when a replacement lands before the re-point", async () => { await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "default", }) await provider.activateProviderProfile({ name: "doomed-profile" }) // The conversation open when the deletion starts follows the survivor, so what method entry records // about the acting task describes that conversation, not the one this deletion ends up re-pointing. const staleTaskConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", } const staleTask = { taskId: "shared-task-id", _taskApiConfigName: "default", get taskApiConfigName(): string { return this._taskApiConfigName }, setTaskApiConfigName: vi.fn(function (this: { _taskApiConfigName: string }, value: string) { this._taskApiConfigName = value }), apiConfiguration: staleTaskConfiguration, updateApiConfiguration: vi.fn<(settings: unknown) => void>(), emit: vi.fn(), } // Restoring a conversation's history installs a new Task object under the same id. This one runs the // profile being deleted, and it lands while the manager delete is in flight. const replacementTaskConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", } const replacementTask = { taskId: "shared-task-id", _taskApiConfigName: "doomed-profile", get taskApiConfigName(): string { return this._taskApiConfigName }, setTaskApiConfigName: vi.fn(function (this: { _taskApiConfigName: string }, value: string) { this._taskApiConfigName = value }), apiConfiguration: replacementTaskConfiguration, updateApiConfiguration: vi.fn<(settings: unknown) => void>(), emit: vi.fn(), } const getCurrentTask = vi.spyOn(provider, "getCurrentTask").mockReturnValue(staleTask as unknown as Task) await provider.taskHistoryStore.upsert({ id: staleTask.taskId, ts: Date.now(), task: "Acting conversation", number: 1, tokensIn: 0, tokensOut: 0, totalCost: 0, }) vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => Promise.resolve([])) // The replacement conversation installs itself after entry has recorded the acting task and before the // deletion re-points the running conversation. const deleteConfigUnspied = provider.providerSettingsManager.deleteConfig.bind( provider.providerSettingsManager, ) vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockImplementationOnce(async (name: string) => { getCurrentTask.mockReturnValue(replacementTask as unknown as Task) return deleteConfigUnspied(name) }) vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("webview gone")) await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("webview gone") // The rollback restores the conversation this deletion actually re-pointed. The guard has to compare the // profile with the task captured at the moment of re-pointing; entry-time values describe a conversation // that was never reconfigured, and a guard built from them skips the conversation that was. expect(replacementTask.setTaskApiConfigName).toHaveBeenCalledWith("doomed-profile") expect(replacementTask.taskApiConfigName).toBe("doomed-profile") // The conversation's own configuration goes back with its name: the re-point handed it the survivor's // settings, and the rollback must hand back what the conversation was actually sending. expect(replacementTask.updateApiConfiguration).toHaveBeenLastCalledWith(replacementTaskConfiguration) // The conversation that was open at entry was never reconfigured, so it stays untouched. expect(staleTask.setTaskApiConfigName).not.toHaveBeenCalled() expect(staleTask.taskApiConfigName).toBe("default") // The shared half of the rollback still ran. expect(provider.contextProxy.getValues().currentApiConfigName).toBe("doomed-profile") const stored = await provider.providerSettingsManager.listConfig() expect(stored.some((config) => config.name === "doomed-profile")).toBe(true) }) it("rolls a sibling back onto the deleted profile when its refresh failed after the re-pin", async () => { await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "default", }) await provider.activateProviderProfile({ name: "doomed-profile" }) // The re-pin write itself lands here; only the refresh on top of it fails. A failed refresh is still a // failed re-pin - the deletion reports it and compensates - but it does not undo the write the sweep // already made, so the sibling needs an undo entry: without one the rollback restored the record and // the shared stores while this live view stayed on the survivor's name and settings. const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // The reviewer's point is the conversation, not only the view buffer: a live task under a // pinned view carries its own sticky profile name and its own api handler built from that // profile, and the re-pin moves both. Only the undo entry can hand them back, so the row // that re-pins a sibling has to carry a task on it. // A real Task, not a recording double: the row reads the settings this conversation is left // holding at three moments, and only the real member assigns them - Task.updateApiConfiguration // writes the configuration and rebuilds the handler from it (Task.ts:2565-2573). A double whose // update method only records the call can show that a hand-back was attempted, not that the // conversation ended up running on the settings it was handed. const { Task: RealTask } = await vi.importActual("../../task/Task") // Deliberately a different model from both profiles stored above: a conversation keeps the // settings its handler was built from, so a rollback that rebuilt from the restored record // would switch this conversation's model while looking like it restored it. const siblingTaskConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o-mini", } const siblingTask = new RealTask({ provider: sibling, apiConfiguration: siblingTaskConfiguration, task: "conversation under the pinned view", // Not started: this row is about what the deletion's undo entry hands back, and a started // task would begin an api request loop nobody is asking about. startTask: false, workspacePath: "/test/workspace", // Checkpoints own a git service and a storage path of their own; nothing here needs them. enableCheckpoints: false, }) const taskNameChanges = vi.spyOn(siblingTask, "setTaskApiConfigName") const taskRebuilds = vi.spyOn(siblingTask, "updateApiConfiguration") vi.spyOn(sibling, "getCurrentTask").mockReturnValue(siblingTask) // The sibling needs a view of its own before its messages can be observed: // postMessageToWebview drops a message when no view is bound. const postedNames: (string | undefined)[] = [] const postedConfigurations: unknown[] = [] const siblingPostMessage = vi.fn( (message: { type?: string; state?: { apiConfiguration?: unknown; currentApiConfigName?: string } }) => { if (message?.type === "state") { const state = message.state postedNames.push(state?.currentApiConfigName) postedConfigurations.push(state?.apiConfiguration) } }, ) const siblingWebviewView = { webview: { postMessage: siblingPostMessage, html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), cspSource: "vscode-webview://test-csp-source", }, visible: true, onDidDispose: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), onDidChangeVisibility: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), } as unknown as vscode.WebviewView await sibling.resolveWebviewView(siblingWebviewView) await sibling.activateProviderProfile({ name: "doomed-profile" }) // The activation put this conversation onto the doomed profile's own settings, which is what an // activation does to the task under the view it activates. The row needs the conversation to run // on a configuration that belongs to neither stored profile - a model change inside the profile // is exactly that state - and going through the real member is what keeps the identity read // below meaningful. siblingTask.updateApiConfiguration(siblingTaskConfiguration) taskNameChanges.mockClear() taskRebuilds.mockClear() // The failure has to come out of the flow, not out of a mock on the method under test: // rejecting postStateToWebview here fails the forward refresh and the rollback refresh // together, and the row would pass even if the rollback never posted the restored state. // This view's modes cache is put back cold - direct private access, the manager only // re-reads and re-writes the merged modes once its cached copy has expired - and the first // durable write that follows, the one inside the re-pin refresh, refuses once. The rollback // refresh runs the same write again and is allowed through. const siblingModesCache = sibling["customModesManager"] siblingModesCache["cachedModes"] = null siblingModesCache["cachedAt"] = 0 let modesWriteRefused = false // First of the three reads, taken from inside the refusal itself: at this instant the sweep has // already rebuilt the conversation on the survivor and re-pointed its sticky name, and the // rollback has not run yet. So this is what the forward re-pin left the conversation running // on - read out of the conversation, not out of a call log. let forwardRebuildConfiguration: ProviderSettings | undefined let forwardRebuildProfileName: string | undefined // The two members that write this conversation, counted at the same instant as the // sample: the counts say how much of the conversation the forward re-pin had already // moved at the moment the failure was observed. let forwardRebuildWrites = 0 let forwardRebuildNameWrites = 0 const realUpdate = mockContext.globalState.update.bind(mockContext.globalState) mockContext.globalState.update = vi.fn((key: string, value: unknown) => { if (key === "customModes" && !modesWriteRefused) { modesWriteRefused = true forwardRebuildConfiguration = siblingTask.apiConfiguration forwardRebuildProfileName = siblingTask.taskApiConfigName forwardRebuildWrites = taskRebuilds.mock.calls.length forwardRebuildNameWrites = taskNameChanges.mock.calls.length return Promise.reject(new Error("custom modes write gone")) } return realUpdate(key, value) }) try { await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("custom modes write gone") expect(sibling.pinnedProfileName).toBe("doomed-profile") expect(sibling["viewLocalState"].currentApiConfigName).toBe("doomed-profile") // Both halves go back: the survivor's configuration was written over an overlay-less pin, so restoring // the name while leaving that configuration in place would pair the restored profile with settings // that belong to another profile. expect(sibling["viewLocalState"].apiConfiguration).toBeUndefined() expect((await sibling.getState()).apiConfiguration?.openRouterModelId).toBe("openai/gpt-4o") // Observation 1 - after the forward rebuild (sampled inside the failure above): the re-pin did // move this conversation, both halves. The survivor's stored model is the one its handler was // rebuilt from, and it is not the configuration this conversation came in on. expect(forwardRebuildProfileName).toBe("default") expect(forwardRebuildConfiguration?.openRouterModelId).toBe("openai/gpt-4.1") expect(forwardRebuildConfiguration).not.toBe(siblingTaskConfiguration) // Sampled at the instant the forward re-pin had written this conversation exactly once // and moved its sticky name exactly once: the one rebuild and the one name move the // sweep performs, with no later write stacked on top of what is read above. expect(forwardRebuildWrites).toBe(1) expect(forwardRebuildNameWrites).toBe(1) // Observation 2 - after the rollback, read out of the same conversation: only the undo entry // knows what this view's task was running, so the sticky name comes back to the profile the // deletion removed and the configuration comes back as the very object the conversation held // before the sweep. A rollback that re-pointed the name while leaving the handler on the // survivor's settings, or that rebuilt from the restored record instead of handing this // conversation's own configuration back, fails here rather than passing a name-only check. expect(siblingTask.taskApiConfigName).toBe("doomed-profile") expect(taskNameChanges).toHaveBeenLastCalledWith("doomed-profile") expect(taskRebuilds).toHaveBeenLastCalledWith(siblingTaskConfiguration) expect(siblingTask.apiConfiguration).toBe(siblingTaskConfiguration) // Observation 3 - the message that finally reaches this view. The restored state has to // actually arrive here and carry the handed-back pair: name and configuration are read // out of one delivered message, so a rollback that rewrote the buffer without posting, or // that posted the survivor payload under the restored name, fails here. The configuration // in the message is the one this conversation runs on - the state the host posts prefers // the running task's own configuration (ClineProvider.ts:5592) and its sticky name (:5644) // - and it is asserted by identity, which is exactly what the undo entry handed back. const lastPost = postedNames.length - 1 expect(postedNames.length).toBeGreaterThan(1) expect(postedNames[lastPost]).toBe("doomed-profile") expect(postedConfigurations[lastPost]).toBe(siblingTaskConfiguration) expect(await provider.providerSettingsManager.hasConfig("doomed-profile")).toBe(true) expect(provider.contextProxy.getValues().currentApiConfigName).toBe("doomed-profile") } finally { await sibling.dispose() } }) // A survivor is not automatically a buildable survivor: a profile left over from a retired // provider still stores, still lists, and can be the survivor the deletion picks, but // rebuilding a conversation on it throws inside buildApiHandler (api/index.ts:218-220). // While that throw ran out of the sweep callback the sibling lost its undo entry even // though its pin and its overlay had already been rewritten, so the rollback restored the // record and the shared stores while this live view stayed on the survivor. // This row runs the conversation and the builder themselves. The acting view is asked to move // its own conversation onto that survivor, so the refusal it has to survive is the rule // buildApiHandler enforces on a retired provider rather than a rejection this row scripts, // and what the rollback owes the conversation is read out of the conversation: the settings it // is left holding and the handler those settings were rebuilt from. The spec mocks the // builder at module level for the rest of the file, so the row installs the real factory on // that same module-level spy for its own duration and puts the double back in its finally - // no later row in the file sees the real factory. it("restores the acting conversation when rebuilding it on the survivor throws before the name moves", async () => { await provider.resolveWebviewView(mockWebviewView) // First survivor in the list, and the profile the shared store names, so this is the // profile the deletion activates. const cliId = await provider.providerSettingsManager.saveConfig("cli-profile", { apiProvider: retiredProviderIdentifiers.geminiCli, }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "cli-profile", id: cliId, apiProvider: retiredProviderIdentifiers.geminiCli }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "cli-profile", }) const actingTaskConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", } // The real conversation: only Task itself assigns the settings a reconfiguration hands it and // then rebuilds its handler from them (Task.ts:2565-2573), so only the real object can show // what this deletion left the acting view running on. Not started - a started task would open // an api request loop nobody is asking about - and without checkpoints, which own a git // service and a storage path of their own. const { Task: RealTask } = await vi.importActual("../../task/Task") // The same swap at the builder's own layer: the real Task rebuilds through the module-level spy // above, so installing the production factory on that spy is what makes the survivor refused // here for the reason it is refused in production (api/index.ts:218-220). const { buildApiHandler: buildRealApiHandler } = await vi.importActual("../../../api") const builderDouble = vi.mocked(buildApiHandler) const builderImplementation = builderDouble.getMockImplementation?.() builderDouble.mockImplementation(buildRealApiHandler) const actingTask = new RealTask({ provider, apiConfiguration: actingTaskConfiguration, task: "conversation in the acting view", startTask: false, workspacePath: "/test/workspace", enableCheckpoints: false, }) // The acting view is running the profile this deletion removes, which is the state a pinned // view is in when a deletion of that profile sweeps it. actingTask.setTaskApiConfigName("doomed-profile") const taskNameChanges = vi.spyOn(actingTask, "setTaskApiConfigName") const taskRebuilds = vi.spyOn(actingTask, "updateApiConfiguration") vi.spyOn(provider, "getCurrentTask").mockReturnValue(actingTask) await provider.activateProviderProfile({ name: "doomed-profile" }) await provider.contextProxy.setValue("currentApiConfigName", "cli-profile") // The configuration and the handler this conversation was actually running when the deletion // captured it - both read out of the conversation rather than written down here. const configurationBefore = actingTask.apiConfiguration const handlerBefore = actingTask.api try { await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("Gemini CLI is no longer supported") // The deletion put the survivor settings into this conversation and then failed on rebuilding // its handler, so it must take them back out: the conversation is left on the exact settings // object it was running and not a look-alike, on the profile name it actually had, and with a // handler rebuilt from those settings - a different handler object than the one that threw, // serving the model the handed-back settings name. The distinctness check rests on the factory // handing out a fresh handler per build: buildApiHandler returns a new provider object on every // call (api/index.ts:211-240, and Task rebuilds through it at Task.ts:801 and :2572), which was // true when this row was measured - if the factory ever caches a handler for identical settings, // this assertion turns red on the cache rather than on a lost hand-back. expect(actingTask.apiConfiguration).toBe(configurationBefore) expect(taskRebuilds).toHaveBeenLastCalledWith(configurationBefore) expect(actingTask.taskApiConfigName).toBe("doomed-profile") expect(taskNameChanges).toHaveBeenLastCalledWith("doomed-profile") expect(actingTask.api).not.toBe(handlerBefore) expect(actingTask.api.getModel().id).toBe(actingTaskConfiguration.openRouterModelId) } finally { if (builderImplementation) { builderDouble.mockImplementation(builderImplementation) } } }) it("keeps the sibling undo entry when rebuilding its conversation on the survivor throws", async () => { await provider.resolveWebviewView(mockWebviewView) // First survivor in the list, so this is the profile the deletion activates. const cliId = await provider.providerSettingsManager.saveConfig("cli-profile", { apiProvider: retiredProviderIdentifiers.geminiCli, }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "cli-profile", id: cliId, apiProvider: retiredProviderIdentifiers.geminiCli }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "cli-profile", }) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await sibling.resolveWebviewView(mockWebviewView) const siblingTaskConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o-mini", } let taskApiConfiguration: { apiProvider?: string } = siblingTaskConfiguration const siblingTask = { taskId: "sibling-conversation", _taskApiConfigName: "doomed-profile", get taskApiConfigName(): string { return this._taskApiConfigName }, get apiConfiguration(): { apiProvider?: string } { return taskApiConfiguration }, setTaskApiConfigName: vi.fn(function (this: { _taskApiConfigName: string }, name: string) { this._taskApiConfigName = name }), // A real conversation assigns the new configuration and only then rebuilds its handler // through buildApiHandler (Task.ts:2565-2572), and a retired provider throws there // (api/index.ts:218-220). The double follows the same order, so the failure the sweep // has to survive is that rule rather than a scripted rejection. updateApiConfiguration: vi.fn(function (this: unknown, settings: { apiProvider?: string }) { taskApiConfiguration = settings if (settings.apiProvider === retiredProviderIdentifiers.geminiCli) { throw new Error( "Gemini CLI is no longer supported. Select a supported provider in your API profile settings.", ) } }), emit: vi.fn(), } vi.spyOn(sibling, "getCurrentTask").mockReturnValue(siblingTask as unknown as Task) await sibling.activateProviderProfile({ name: "doomed-profile" }) // The survivor is the profile the shared store names, so the deletion has no reason to // pick a different one: a sibling activation writes its own profile into that shared // selection on the way here, and the replacement this deletion compensates back is the // selection it read, not whatever the profile list happens to lead with. await provider.contextProxy.setValue("currentApiConfigName", "cli-profile") const siblingOverlayBefore = sibling["viewLocalState"].apiConfiguration // The configuration this conversation was running when the sweep captured it. const siblingTaskConfigurationBefore = siblingTask.apiConfiguration try { await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("Gemini CLI is no longer supported") // The failure is reported and the view still comes back: the pin names the restored // profile again, and the overlay is the exact object this view served before the // deletion, not the survivor settings. expect(sibling.pinnedProfileName).toBe("doomed-profile") expect(sibling["viewLocalState"].apiConfiguration).toBe(siblingOverlayBefore) // The conversation both ways: the rebuild that threw left the sticky name on the // deleted profile and left the handler holding the survivor settings, so the // rollback has to re-point the name and hand back this conversation own // configuration. Asserting the exact object rules out a rollback that rebuilt from // the restored record instead. expect(siblingTask.taskApiConfigName).toBe("doomed-profile") expect(siblingTask.updateApiConfiguration).toHaveBeenLastCalledWith(siblingTaskConfigurationBefore) expect(await provider.providerSettingsManager.hasConfig("doomed-profile")).toBe(true) expect(provider.contextProxy.getValues().currentApiConfigName).toBe("cli-profile") } finally { await sibling.dispose() } }) it("posts the re-pointed sibling only with a name and a configuration from one profile", async () => { // The reviewer point is the pair the webview is shown, not the number of posts. When the rebuild // throws, the conversation already holds the survivor settings while its sticky name still names // the profile being deleted, and the posted state takes both halves from the running conversation // (apiConfiguration at ClineProvider.ts:5638, currentApiConfigName at :5690). A post between the // rebuild and the rollback therefore delivers one profile name on another profile settings, and // the webview has to act on it until the rollback posts again. This row reads the name and the // configuration out of every message this view received. await provider.resolveWebviewView(mockWebviewView) // First survivor in the list, so this is the profile the deletion activates. const cliId = await provider.providerSettingsManager.saveConfig("cli-profile", { apiProvider: retiredProviderIdentifiers.geminiCli, }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "cli-profile", id: cliId, apiProvider: retiredProviderIdentifiers.geminiCli }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "cli-profile", }) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) // Deliberately a different model from either profile stored above: a conversation keeps the // settings its handler was built from, so the restored pair is this object, not the survivor // settings and not the doomed record re-read from disk. const siblingTaskConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o-mini", } let taskApiConfiguration: { apiProvider?: string } = siblingTaskConfiguration const siblingTask = { taskId: "sibling-conversation", _taskApiConfigName: "doomed-profile", get taskApiConfigName(): string { return this._taskApiConfigName }, get apiConfiguration(): { apiProvider?: string } { return taskApiConfiguration }, setTaskApiConfigName: vi.fn(function (this: { _taskApiConfigName: string }, name: string) { this._taskApiConfigName = name }), // Same order as a real conversation: assign the settings, then rebuild the handler, which a // retired provider refuses (Task.ts:2565-2572, api/index.ts:218-220). updateApiConfiguration: vi.fn(function (this: unknown, settings: { apiProvider?: string }) { taskApiConfiguration = settings if (settings.apiProvider === retiredProviderIdentifiers.geminiCli) { throw new Error( "Gemini CLI is no longer supported. Select a supported provider in your API profile settings.", ) } }), emit: vi.fn(), } vi.spyOn(sibling, "getCurrentTask").mockReturnValue(siblingTask as unknown as Task) // The pair is read out of each message this view received, so the assertion is about what the // webview was shown rather than about what the host meant to send. const delivered: { name: string | undefined; configuration: { apiProvider?: string } | undefined }[] = [] const siblingPostMessage = vi.fn( (message: { type?: string state?: { apiConfiguration?: { apiProvider?: string }; currentApiConfigName?: string } }) => { if (message?.type === "state") { delivered.push({ name: message.state?.currentApiConfigName, configuration: message.state?.apiConfiguration, }) } }, ) const siblingWebviewView = { webview: { postMessage: siblingPostMessage, html: "", options: {}, onDidReceiveMessage: vi.fn(), asWebviewUri: vi.fn(), cspSource: "vscode-webview://test-csp-source", }, visible: true, onDidDispose: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), onDidChangeVisibility: vi.fn().mockImplementation(() => { return { dispose: vi.fn() } }), } as unknown as vscode.WebviewView await sibling.resolveWebviewView(siblingWebviewView) await sibling.activateProviderProfile({ name: "doomed-profile" }) // The survivor is the profile the shared store names, so the deletion has no reason to pick a // different one. await provider.contextProxy.setValue("currentApiConfigName", "cli-profile") const configurationBefore = siblingTask.apiConfiguration try { await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("Gemini CLI is no longer supported") // The pair this view ends on: the restored name together with the configuration this // conversation was actually sending, both halves handed back by the undo entry. const last = delivered[delivered.length - 1] expect(delivered.length).toBeGreaterThan(1) expect(last?.name).toBe("doomed-profile") expect(last?.configuration).toBe(configurationBefore) // And no delivery ever crossed the two: the deleted profile name never carried the survivor // provider settings, and the survivor name never carried anything else. The forward post this // row guards against is exactly the first of these two crossings. const crossedProfiles = delivered.filter( (entry) => (entry.name === "doomed-profile" && entry.configuration?.apiProvider === retiredProviderIdentifiers.geminiCli) || (entry.name === "cli-profile" && entry.configuration?.apiProvider !== retiredProviderIdentifiers.geminiCli), ) expect(crossedProfiles).toEqual([]) expect(await provider.providerSettingsManager.hasConfig("doomed-profile")).toBe(true) expect(provider.contextProxy.getValues().currentApiConfigName).toBe("cli-profile") } finally { await sibling.dispose() } }) it("leaves a conversation another view moved onto the survivor holding those settings", async () => { // The gap the review names sits in the rollback guard, not in the sweep. Between the moment this // deletion re-points the acting conversation and the moment its rollback runs there is an awaited // sweep, and a second live view can save the survivor profile in that window: the statement such a // save runs for every view pinned to the profile (ClineProvider.ts:3743, and the same call after an // activation at :4494) rebuilds the handler of a conversation running under it. The guard then // still matches the task instance and the profile name, and neither of those says anything about the // settings the conversation holds, so this deletion has to leave that conversation alone - restoring // what it captured would roll a newer write back. const gate = (() => { let release: () => void = () => {} const promise = new Promise((resolve) => { release = resolve }) return { promise, release } })() await provider.resolveWebviewView(mockWebviewView) const cliId = await provider.providerSettingsManager.saveConfig("cli-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o-mini", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "cli-profile", id: cliId, apiProvider: providerIdentifiers.openrouter }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "cli-profile", }) // The acting conversation runs the profile this row deletes. const actingTaskConfiguration = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o-mini", } let taskApiConfiguration: { apiProvider?: string } = actingTaskConfiguration const actingTask = { taskId: "acting-conversation", _taskApiConfigName: "doomed-profile", get taskApiConfigName(): string { return this._taskApiConfigName }, get apiConfiguration(): { apiProvider?: string } { return taskApiConfiguration }, setTaskApiConfigName: vi.fn(function (this: { _taskApiConfigName: string }, name: string) { this._taskApiConfigName = name }), // A real conversation assigns the new settings here and rebuilds its handler in the same call // (Task.ts:2565-2572), which is the value a later view overwrites. updateApiConfiguration: vi.fn(function (this: unknown, settings: { apiProvider?: string }) { taskApiConfiguration = settings }), emit: vi.fn(), } vi.spyOn(provider, "getCurrentTask").mockReturnValue(actingTask as unknown as Task) await provider.activateProviderProfile({ name: "doomed-profile" }) // A second live view pinned onto the doomed profile: the sweep writes it away from the deleted // profile, and the refresh on top of that write is where this row parks the deletion so the save // below lands inside the rollback window rather than after it. const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await sibling.resolveWebviewView(mockWebviewView) await sibling.activateProviderProfile({ name: "doomed-profile" }) // The sibling activation moved the shared selection onto the doomed profile on its way here; put // it back so the survivor this deletion activates is the profile the store named from the start. await provider.contextProxy.setValue("currentApiConfigName", "cli-profile") const sweepFailure = new Error("sibling refresh refused") const sweepingPost = vi.spyOn(sibling, "postStateToWebview").mockImplementation(async () => { await gate.promise throw sweepFailure }) const configurationBefore = actingTask.apiConfiguration const deleting = provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }) // The deletion can reject before this row reaches its poll, and its outcome is examined // below: a handler attached here keeps that rejection from going unexamined meanwhile. void deleting.catch(() => undefined) // Everything from the poll on can throw - the poll can time out, the sibling refresh can // reject - and the gate, the deletion and the other view have to be settled either way, // so the releasing and the awaits below run in finally. try { await vi.waitFor(() => { if (sweepingPost.mock.calls.length === 0) { throw new Error("the sweep has not reached the sibling refresh yet") } }) // Parked there, this view, its overlay and its conversation all name the survivor with the // survivor settings. The other view now saves that profile, and the refresh a save runs for every // view pinned to it pushes newer settings into this very conversation and rebuilds its handler. const newerSurvivorSettings = { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", } await sibling["refreshViewLocalStateForUpdatedProfile"]("cli-profile", newerSurvivorSettings) gate.release() await expect(deleting).rejects.toThrow("sibling refresh refused") // The conversation this deletion reconfigured is now running another view settings, which are // newer than anything this rollback captured. It stays put: the instance and the profile name // still match what this deletion wrote, so this is exactly the case an instance-and-name guard // alone gets wrong, and putting the captured configuration back would drop the newer write. expect(actingTask.apiConfiguration).toBe(newerSurvivorSettings) // and it is no longer holding what this deletion captured at its own write: the newer view won // the conversation, which is the outcome this guard exists to produce. expect(actingTask.apiConfiguration).not.toBe(configurationBefore) expect(actingTask.updateApiConfiguration).toHaveBeenLastCalledWith(newerSurvivorSettings) expect(actingTask.taskApiConfigName).toBe("cli-profile") // The shared half of the rollback still ran, so the failed deletion is still a failed deletion. expect(await provider.providerSettingsManager.hasConfig("doomed-profile")).toBe(true) expect(provider.contextProxy.getValues().currentApiConfigName).toBe("cli-profile") // The view half is untouched by this change and stays as the rollback leaves it: the pin is back // on the profile this deletion removed. expect(provider.pinnedProfileName).toBe("doomed-profile") } finally { // Releasing a settled gate is a no-op: the release inside the try above and this one // agree, and this one also runs when the row failed before reaching it. gate.release() await deleting.catch(() => undefined) await sibling.dispose() } }) it("keeps the superseded profile settings out of the buffer when the pin is cleared during the load window", async () => { const gate = (() => { let release: () => void = () => {} const promise = new Promise((resolve) => { release = resolve }) return { promise, release } })() const pinnedId = await provider.providerSettingsManager.saveConfig("pinned-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) const sharedId = await provider.providerSettingsManager.saveConfig("shared-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "pinned-profile", id: pinnedId, apiProvider: providerIdentifiers.openrouter }, { name: "shared-profile", id: sharedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "shared-profile", }) // The shared store carries the survivor settings: with no view-local overlay this is what // the view serves, and the row compares it against the settings the lookup resolves. await provider.contextProxy.setProviderSettings({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) // The entry this view hydrates from: a pinned profile and a mode, so the load awaits the // custom modes lookup before it reads the profile record - that await is the window. await provider.contextProxy.setValue("viewStates", { "stable-view": { mode: "code", currentApiConfigName: "pinned-profile" }, }) const getCustomModes = vi .spyOn(provider.customModesManager, "getCustomModes") .mockImplementationOnce(() => gate.promise.then(() => [])) const finishing = provider.setViewStateId("stable-view") await vi.waitFor(() => { expect(getCustomModes).toHaveBeenCalledTimes(1) }) // The pin is cleared through the normal path while the load is paused. Clearing a pin this // buffer never held leaves the name undefined on both sides of the window, so the value // comparison alone reports it as untouched; the mutation count is what says otherwise. await provider.saveViewState("currentApiConfigName", undefined) gate.release() await finishing getCustomModes.mockRestore() expect(provider.pinnedProfileName).toBeUndefined() // The settings the superseded lookup resolved are gone rather than carried under a view // that no longer names that profile: what this view serves is the profile the shared // store selects, which is also the name it reports. expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") const state = await provider.getState() expect((state.apiConfiguration as { openRouterModelId?: string } | undefined)?.openRouterModelId).toBe( "openai/gpt-4.1", ) expect(state.currentApiConfigName).toBe("shared-profile") }) it("hydrates the pin its entry captured before a deletion that lands while hydration is paused", async () => { const gate = (() => { let release: () => void = () => {} const promise = new Promise((resolve) => { release = resolve }) return { promise, release } })() const pinnedId = await provider.providerSettingsManager.saveConfig("pinned-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) const sharedId = await provider.providerSettingsManager.saveConfig("shared-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "pinned-profile", id: pinnedId, apiProvider: providerIdentifiers.openrouter }, { name: "shared-profile", id: sharedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "shared-profile", }) // The shared store carries the survivor settings: with no view-local overlay this is what // the view serves, and the row compares it against the settings the lookup resolves. await provider.contextProxy.setProviderSettings({ apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) // The entry this view hydrates from: a pinned profile and a mode, so the load awaits the // custom modes lookup before it reads the profile record - that await is the window. await provider.contextProxy.setValue("viewStates", { "stable-view": { mode: "code", currentApiConfigName: "pinned-profile" }, }) const getCustomModes = vi .spyOn(provider.customModesManager, "getCustomModes") .mockImplementationOnce(() => gate.promise.then(() => [])) const finishing = provider.setViewStateId("stable-view") await vi.waitFor(() => { expect(getCustomModes).toHaveBeenCalledTimes(1) }) // The order the finding describes, against the real provider and the real ContextProxy: // the pinned profile is deleted through this same provider while the load is paused and // before this view has any pin, so nothing guards the name the load has already // captured, and the durable re-point moves the entry underneath it. expect(provider.pinnedProfileName).toBeUndefined() await provider.deleteProviderProfile({ name: "pinned-profile", id: pinnedId, apiProvider: providerIdentifiers.openrouter, }) const entryDuringWindow = JSON.parse(JSON.stringify(provider["getPersistedViewStates"]())) as { "stable-view"?: { currentApiConfigName?: string } } expect(entryDuringWindow["stable-view"]?.currentApiConfigName).toBe("shared-profile") gate.release() await finishing getCustomModes.mockRestore() // What installs afterwards is the name the captured entry named, with no settings behind // it: the lookup could not resolve the deleted profile. That is the landed contract the // row should keep the persisted profile name and log when the profile lookup fails pins // in ClineProvider.spec.ts - the name stays, the settings do not, and the view serves // the survivor the shared store selects. expect(provider.pinnedProfileName).toBe("pinned-profile") expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") const state = await provider.getState() expect((state.apiConfiguration as { openRouterModelId?: string } | undefined)?.openRouterModelId).toBe( "openai/gpt-4.1", ) // The finding was authored against this order without running it, and registering a // stable view id at launch is separate follow-up work, so this row claims the method- // level order only - not that the current UI can reach it. }) it("keeps the settings an overlay-less restored sibling pin serves on the profile it names", async () => { const sharedStore = (view: ClineProvider) => { const values = view["contextProxy"].getValues() const settings = view["contextProxy"].getProviderSettings() as { openRouterModelId?: string } | undefined return { selection: values.currentApiConfigName, model: settings?.openRouterModelId } } const pairing = async (view: ClineProvider) => { const overlay = view["viewLocalState"].apiConfiguration as { openRouterModelId?: string } | undefined const state = await view["getState"]() return { pin: view.pinnedProfileName, overlayModel: overlay?.openRouterModelId, stateModel: (state as { apiConfiguration?: { openRouterModelId?: string } }).apiConfiguration ?.openRouterModelId, } } await provider.resolveWebviewView(mockWebviewView) const defaultId = await provider.providerSettingsManager.saveConfig("default", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4.1", }) const doomedId = await provider.providerSettingsManager.saveConfig("doomed-profile", { apiProvider: providerIdentifiers.openrouter, openRouterApiKey: "mock-key", openRouterModelId: "openai/gpt-4o", }) await provider.contextProxy.setValues({ listApiConfigMeta: [ { name: "default", id: defaultId, apiProvider: providerIdentifiers.openrouter }, { name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter }, ], currentApiConfigName: "default", }) await provider.activateProviderProfile({ name: "default" }) const sibling = new ClineProvider( mockContext, mockOutputChannel, "editor", new ContextProxy(mockContext), new WebviewFocusTracker(), ) await sibling.resolveWebviewView(mockWebviewView) await sibling.activateProviderProfile({ name: "doomed-profile" }) // A second profile is then activated through the acting view, so the shared store moves // under this view's pin: the deletion this row drives is not deleting the profile the // shared selection names, which is the arrangement the finding is about. await provider.activateProviderProfile({ name: "default" }) // The state the finding describes, written directly: a live view whose pin names a // profile it holds no overlay for - loadViewState leaves a view in this state when the // pinned profile is not resolvable at load, and an activation clears the overlay of the // view that activated it - so what this view serves comes from the fallback in getState // rather than from a settings snapshot of its own. sibling["viewLocalState"].apiConfiguration = undefined const pre = await pairing(sibling) const preShared = sharedStore(provider) // Fail the deletion after the re-pin sweep: the sibling's modes cache is cooled and the // first durable modes write that follows is refused, which is the refresh on top of the // re-pin, so the compensation runs. sibling["customModesManager"]["cachedModes"] = null sibling["customModesManager"]["cachedAt"] = 0 let refused = false const realUpdate = mockContext.globalState.update.bind(mockContext.globalState) mockContext.globalState.update = vi.fn((key: string, value: unknown) => { if (key === "customModes" && !refused) { refused = true return Promise.reject(new Error("sibling modes write gone")) } return realUpdate(key, value) }) await expect( provider.deleteProviderProfile({ name: "doomed-profile", id: doomedId, apiProvider: providerIdentifiers.openrouter, }), ).rejects.toThrow("sibling modes write gone") const post = await pairing(sibling) const postShared = sharedStore(provider) // The compensation put this view's halves back as the sweep captured them: the pin on the // deleted profile, and no overlay - and neither half changed on the way through. expect(post).toEqual(pre) expect(post.pin).toBe("doomed-profile") expect(post.overlayModel).toBeUndefined() // The reviewer's invariant: what this view serves names the profile its pin names. The // acting view's shared store is on the other profile in both snapshots, so the model // below is this view's own pairing and not the shared settings this deletion wrote and // then rolled back. expect(post.stateModel).toBe("openai/gpt-4o") expect(preShared.selection).toBe("default") expect(preShared.model).toBe("openai/gpt-4.1") expect(postShared.selection).toBe("default") expect(postShared.model).toBe("openai/gpt-4.1") await sibling.dispose() }) }) })