diff --git a/packages/types/src/__tests__/global-settings.test.ts b/packages/types/src/__tests__/global-settings.test.ts index f2b2e7e8e5..b6b01cccf0 100644 --- a/packages/types/src/__tests__/global-settings.test.ts +++ b/packages/types/src/__tests__/global-settings.test.ts @@ -39,6 +39,49 @@ describe("alwaysDenyUnapprovedCommands global setting", () => { }) }) +describe("viewStates global setting", () => { + it("parses a valid per-view record", () => { + const parsed = globalSettingsSchema.parse({ + viewStates: { + "stable-view-1": { mode: "code", currentApiConfigName: "profile-a", updatedAt: 1730000000000 }, + "stable-view-2": {}, + }, + }) + expect(parsed.viewStates?.["stable-view-1"]).toEqual({ + mode: "code", + currentApiConfigName: "profile-a", + updatedAt: 1730000000000, + }) + expect(parsed.viewStates?.["stable-view-2"]).toEqual({}) + expect(GLOBAL_SETTINGS_KEYS).toContain("viewStates") + }) + + it("parses an entry that carries the host-minted claim token", () => { + // The claim binds the entry to the webview that wrote it; a legacy entry without one + // still parses, because refusing it is setViewStateId's job, not the schema's. + const parsed = globalSettingsSchema.parse({ + viewStates: { + "stable-view-1": { mode: "code", updatedAt: 1730000000000, claimToken: "7f9c-host-minted" }, + "stable-view-2": { mode: "code" }, + }, + }) + expect(parsed.viewStates?.["stable-view-1"]?.claimToken).toBe("7f9c-host-minted") + expect(parsed.viewStates?.["stable-view-2"]).toEqual({ mode: "code" }) + }) + + it("rejects invalid field values inside a view entry", () => { + expect(() => globalSettingsSchema.parse({ viewStates: { v: { mode: 42 } } })).toThrow() + expect(() => globalSettingsSchema.parse({ viewStates: { v: { currentApiConfigName: 42 } } })).toThrow() + expect(() => globalSettingsSchema.parse({ viewStates: { v: { updatedAt: "soon" } } })).toThrow() + expect(() => globalSettingsSchema.parse({ viewStates: { v: { claimToken: 42 } } })).toThrow() + }) + + it("rejects non-object viewStates values", () => { + expect(() => globalSettingsSchema.parse({ viewStates: "not-a-record" })).toThrow() + expect(() => globalSettingsSchema.parse({ viewStates: { v: "not-an-entry" } })).toThrow() + }) +}) + describe("collapseCommandOutputByDefault global setting", () => { it.each([true, false, undefined])("round-trips %s through the export/import schema", (value) => { const settings = globalSettingsSchema.parse({ collapseCommandOutputByDefault: value }) diff --git a/packages/types/src/__tests__/index.test.ts b/packages/types/src/__tests__/index.test.ts index 15441d48fd..b4cee22f8c 100644 --- a/packages/types/src/__tests__/index.test.ts +++ b/packages/types/src/__tests__/index.test.ts @@ -3,6 +3,10 @@ import { GLOBAL_STATE_KEYS } from "../index.js" describe("GLOBAL_STATE_KEYS", () => { + it("should contain registered durable per-view state", () => { + expect(GLOBAL_STATE_KEYS).toContain("viewStates") + }) + it("should contain provider settings keys", () => { expect(GLOBAL_STATE_KEYS).toContain("autoApprovalEnabled") }) @@ -13,6 +17,7 @@ describe("GLOBAL_STATE_KEYS", () => { it("should not contain secret state keys", () => { expect(GLOBAL_STATE_KEYS).not.toContain("openRouterApiKey") + expect(GLOBAL_STATE_KEYS).not.toContain("apiKey") }) it("should contain OpenAI Compatible base URL setting", () => { diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index 2bd5573039..9aa2179ae8 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -117,6 +117,17 @@ export const MAX_CHECKPOINT_TIMEOUT_SECONDS = 60 */ export const DEFAULT_CHECKPOINT_TIMEOUT_SECONDS = 15 +/** + * Persisted non-secret selections for a stable webview instance. + */ +export const viewStateSchema = z.object({ + mode: z.string().optional(), + currentApiConfigName: z.string().optional(), + updatedAt: z.number().optional(), + /** Host-minted token binding this entry to the webview that wrote it. */ + claimToken: z.string().optional(), +}) + /** * GlobalSettings */ @@ -125,6 +136,7 @@ export const globalSettingsSchema = z.object({ currentApiConfigName: z.string().optional(), listApiConfigMeta: z.array(providerSettingsEntrySchema).optional(), pinnedApiConfigs: z.record(z.string(), z.boolean()).optional(), + viewStates: z.record(z.string(), viewStateSchema).optional(), lastShownAnnouncementId: z.string().optional(), customInstructions: z.string().optional(), diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 3e23a7934c..4e7e746e5f 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -142,6 +142,7 @@ export interface ExtensionMessage { | "originalContent" | "rooHistoryImportProgress" | "themeFixtureProbeRequest" + | "viewStateClaim" | "diagnosticsRequest" text?: string /** For fileContent: { path, content, error? } */ @@ -201,6 +202,13 @@ export interface ExtensionMessage { // eslint-disable-next-line @typescript-eslint/no-explicit-any values?: Record requestId?: string + /** + * For `viewStateClaim`: the durable `viewStates` key the delivered claim governs. The + * message is only ever sent to the webview that key belongs to. + */ + viewStateId?: string + /** For `viewStateClaim`: the host-minted token the webview stores and echoes on launch. */ + viewStateClaim?: string themeFixture?: WebviewThemeFixture diagnostics?: WebviewDiagnosticsSnapshot promptText?: string @@ -745,6 +753,9 @@ export interface WebviewMessage { | "themeFixtureProbeResponse" | "diagnosticsResponse" text?: string + viewStateId?: string + /** For `webviewDidLaunch`: the claim delivered for `viewStateId`, enforced by setViewStateId. */ + viewStateClaim?: string taskId?: string editedMessageContent?: string tab?: "settings" | "history" | "mcp" | "modes" | "chat" | "marketplace" | "cloud" diff --git a/src/core/config/ContextProxy.ts b/src/core/config/ContextProxy.ts index e53f60fb83..6b84769218 100644 --- a/src/core/config/ContextProxy.ts +++ b/src/core/config/ContextProxy.ts @@ -67,6 +67,9 @@ const globalSettingsExportSchema = globalSettingsSchema.omit({ taskHistory: true, listApiConfigMeta: true, currentApiConfigName: true, + // Per-view selection state is machine-local: it keeps flowing through the + // normal runtime and pruning paths but must not transfer between settings. + viewStates: true, }) export class ContextProxy { @@ -78,6 +81,7 @@ export class ContextProxy { constructor(context: vscode.ExtensionContext) { this.originalContext = context + this.stateCache = {} this.secretCache = {} this._isInitialized = false @@ -397,6 +401,18 @@ export class ContextProxy { */ private readonly stateWriteOwner = new Map() private readonly secretWriteOwner = new Map() + /** + * The secret writes that are still in flight, each paired with the claim it took, + * so a reset can wait for them to settle before it deletes the keys. Without the + * pairing a reset cannot tell a settled-but-orphaned write from a live one. + */ + private readonly pendingSecretWrites = new Map }>>() + // A reset is in progress: the caches are meaningless mid-reset, and a secret write begun + // inside it would commit after the delete pass and survive the erase. + private resetting = false + // The reset pass currently in flight, if any: single-flight so that two callers cannot each run a + // delete pass and have whichever finishes first lower the guard under the other. + private resetInFlight: Promise | null = null /** How many writes of each secret were started. Unlike the owners, it is not cleared when a write is over. */ private readonly secretWriteCount = new Map() @@ -443,6 +459,13 @@ export class ContextProxy { } storeSecret(key: SecretStateKey, value?: string) { + if (this.resetting) { + // Refused rather than deferred: a deferred secret write would re-store exactly the + // value the user asked to erase, and a silently dropped one would lose the save. + return Promise.reject( + new SettingsWriteError([], [key], new Error("secret writes are refused while state is being reset")), + ) + } // Update cache. const owner = {} this.secretWriteOwner.set(key, owner) @@ -454,7 +477,19 @@ export class ContextProxy { // cache (it stays empty until the next write, `refreshSecrets` or a restart) rather than being served. // The entry of the key is removed when the write and its read-back are over (if it is still the latest). A store // that throws at once is turned into a rejection, so it is handled the same. + const pending = this.pendingSecretWrites.get(key) ?? new Set<{ settle: Promise }>() + let settleWrite: () => void = () => {} + const entry: { settle: Promise } = { + settle: new Promise((resolve) => { + settleWrite = resolve + }), + } + pending.add(entry) + this.pendingSecretWrites.set(key, pending) const release = () => { + pending.delete(entry) + if (pending.size === 0) this.pendingSecretWrites.delete(key) + settleWrite() if (this.secretWriteOwner.get(key) === owner) this.secretWriteOwner.delete(key) } const stored = (async () => @@ -715,18 +750,48 @@ export class ContextProxy { * This clears all data from both the in-memory caches and the VSCode storage. * @returns A promise that resolves when all reset operations are complete */ - public async resetAllState() { - // Clear in-memory caches - this.stateCache = {} - this.secretCache = {} - - await Promise.all([ - ...GLOBAL_STATE_KEYS.map((key) => this.originalContext.globalState.update(key, undefined)), - ...SECRET_STATE_KEYS.map((key) => this.originalContext.secrets.delete(key)), - ...GLOBAL_SECRET_KEYS.map((key) => this.originalContext.secrets.delete(key)), - ]) - - await this.initialize() + public resetAllState(): Promise { + if (this.resetInFlight) { + // A caller that arrives mid-reset joins the pass already running rather than starting a + // second delete pass whose end could lower the guard while the first was still writing. + return this.resetInFlight + } + this.resetting = true + const pass = (async () => { + try { + // A secret write that is in flight at this moment has already committed nothing, but it will + // commit as soon as it settles, and the deletes below cannot un-commit a write that lands + // after them. Wait for the pending writes first, then end the claims, then delete, so the + // cleared copy is the last one to land in storage and the cache stays empty afterwards. + const inFlight = [...this.pendingSecretWrites.values()].flatMap((writes) => + [...writes].map((w) => w.settle), + ) + await Promise.allSettled(inFlight) + + // Clear in-memory caches + this.stateCache = {} + this.secretCache = {} + // A reset also ends write ownership: a write that is still in flight reads the Memento back + // into the cache it just lost, so clearing the caches is not enough to keep pre-reset state + // out. Ownership is what the rejection handlers gate on. + this.stateWriteOwner.clear() + this.secretWriteOwner.clear() + + await Promise.all([ + ...GLOBAL_STATE_KEYS.map((key) => this.originalContext.globalState.update(key, undefined)), + ...SECRET_STATE_KEYS.map((key) => this.originalContext.secrets.delete(key)), + ...GLOBAL_SECRET_KEYS.map((key) => this.originalContext.secrets.delete(key)), + ]) + + await this.initialize() + this.resetting = false + } finally { + this.resetting = false + this.resetInFlight = null + } + })() + this.resetInFlight = pass + return pass } private static _instance: ContextProxy | null = null diff --git a/src/core/config/ProviderSettingsManager.ts b/src/core/config/ProviderSettingsManager.ts index 79a9d67c79..fe7ec846cd 100644 --- a/src/core/config/ProviderSettingsManager.ts +++ b/src/core/config/ProviderSettingsManager.ts @@ -55,6 +55,14 @@ export const providerProfilesSchema = z.object({ export type ProviderProfiles = z.infer +/** Already-deleted profile: callers branch on this type instead of matching message text. */ +export class ProviderSettingsNotFoundError extends Error { + constructor(message: string) { + super(message) + this.name = "ProviderSettingsNotFoundError" + } +} + export class ProviderSettingsManager { private static readonly SCOPE_PREFIX = "roo_cline_config_" private readonly defaultConfigId = this.generateId() @@ -514,7 +522,7 @@ export class ProviderSettingsManager { const providerProfiles = await this.load() if (!providerProfiles.apiConfigs[name]) { - throw new Error(`Config '${name}' not found`) + throw new ProviderSettingsNotFoundError(`Config '${name}' not found`) } if (Object.keys(providerProfiles.apiConfigs).length === 1) { @@ -525,6 +533,11 @@ export class ProviderSettingsManager { await this.store(providerProfiles) }) } catch (error) { + // A missing config is a caller-meaningful signal, not a failure: rethrow it + // unwrapped so callers can branch on the type instead of message text. + if (error instanceof ProviderSettingsNotFoundError) { + throw error + } throw new Error(`Failed to delete config: ${error}`) } } diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index 5d78e16351..98785be95e 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -121,6 +121,241 @@ describe("ContextProxy", () => { expect(result).toBe("deepseek") }) + it("should not let an older rejected write clobber a newer cached value", async () => { + let rejectFirst: (error: Error) => void = () => {} + const firstWriteResult = new Promise((_, reject) => { + rejectFirst = reject + }) + + mockGlobalState.update.mockReset() + mockGlobalState.update.mockReturnValueOnce(firstWriteResult) + mockGlobalState.update.mockResolvedValueOnce(undefined) + + const firstWrite = proxy.updateGlobalState("apiProvider", "anthropic") + await proxy.updateGlobalState("apiProvider", "openai") + rejectFirst(new Error("disk full")) + await expect(firstWrite).rejects.toThrow("disk full") + + expect(proxy.getGlobalState("apiProvider")).toBe("openai") + }) + + it("should not restore a pre-reset value when a pending write rejects after reset", async () => { + let rejectPending: (error: Error) => void = () => {} + mockGlobalState.update.mockReset() + mockGlobalState.update.mockReturnValueOnce( + new Promise((_, reject) => { + rejectPending = reject + }), + ) + const pending = proxy.updateGlobalState("apiProvider", "anthropic") + await proxy.resetAllState() + // The Memento answers the read-back with the pre-reset value: only ending write ownership + // during the reset keeps the cache cleared. With the mocked store this is the difference + // between the guarantee holding and the rejected write repopulating the cache. + mockGlobalState.get.mockImplementation((key: string) => (key === "apiProvider" ? "anthropic" : undefined)) + rejectPending(new Error("disk full")) + await expect(pending).rejects.toThrow("disk full") + expect(proxy.getGlobalState("apiProvider")).toBeUndefined() + }) + it("does not restore a pre-reset secret when a pending storeSecret settles after the reset", async () => { + const durable = new Map() + let settle: () => void = () => {} + mockSecrets.get.mockImplementation(async (key: string) => durable.get(key)) + mockSecrets.delete.mockImplementation(async (key: string) => { + durable.delete(key) + }) + mockSecrets.store.mockImplementationOnce( + (key: string, value: string) => + new Promise((resolve) => { + settle = () => { + durable.set(key, value) + resolve(undefined) + } + }), + ) + + const pending = proxy.storeSecret("apiKey", "pre-reset-secret") + setTimeout(settle, 0) + await proxy.resetAllState() + await pending + + // The pending store is held open on a double that only puts the value into storage + // when it settles, so the ordering is observable: the reset must wait for the write to + // settle and then delete the keys, so neither the cache nor the durable copy keeps the + // value that was in flight when the reset started. + expect(await mockSecrets.get("apiKey")).toBeUndefined() + expect(proxy.getSecret("apiKey")).toBeUndefined() + }) + // Two phases, because the guarantee has two halves. A secret write issued while the reset is + // running must be refused rather than deferred - a deferred write would re-store exactly the + // value the user asked to erase - and after a reset that failed the store has to accept writes + // again. The second half is the one that bites: the delete pass is a single Promise.all, so one + // keychain delete rejecting rejects resetAllState itself, and unless the flag that guards + // storeSecret is cleared in a finally the store stays shut for the life of the instance while + // resetState() aborts on the same error. + it("refuses a secret write during a reset and accepts it again after a failed reset", async () => { + const durable = new Map() + mockSecrets.get.mockImplementation(async (key: string) => durable.get(key)) + mockSecrets.store.mockImplementation(async (key: string, value: string) => { + durable.set(key, value) + }) + let rejectDelete: (error: Error) => void = () => {} + mockSecrets.delete.mockImplementation((key: string) => { + if (key === "apiKey") { + return new Promise((_, reject) => { + rejectDelete = reject + }) + } + durable.delete(key) + return Promise.resolve() + }) + + // Holding apiKey's delete open keeps the guard raised across the mid-reset assertion below. + const resetting = proxy.resetAllState() + + await expect(proxy.storeSecret("apiKey", "written-mid-reset")).rejects.toThrow( + "secret writes are refused while state is being reset", + ) + expect(proxy.getSecret("apiKey")).toBeUndefined() + + rejectDelete(new Error("keychain locked")) + await expect(resetting).rejects.toThrow("keychain locked") + + // The store is usable again, measured as a save that resolves and reads back through both the + // cache and storage, not as an absence of errors. + await expect(proxy.storeSecret("apiKey", "written-after-failed-reset")).resolves.toBeUndefined() + expect(await mockSecrets.get("apiKey")).toBe("written-after-failed-reset") + expect(proxy.getSecret("apiKey")).toBe("written-after-failed-reset") + }) + // Overlapping resets are the second half of the same defect: on its own the finally only + // guarantees the flag falls when the pass it belongs to ends. Single-flight is the shape here + // because it makes the invariant structural - a second caller joins the reset already running + // rather than starting a second delete pass whose end could clear the flag while the first was + // still writing. + it("joins an in-flight reset instead of starting a second pass and keeps the guard raised until it ends", async () => { + // Every apiKey erase handed back by the double, with its rejecter kept so the test can settle + // them all at once: a held-open erase is what keeps the guard raised across the join check, + // and the reset issues more than one erase per pass, so they must all be settled or the delete + // pass never finishes. + const erases: { reject: (error: Error) => void }[] = [] + mockSecrets.delete.mockImplementation((key: string) => { + if (key === "apiKey") { + return new Promise((_, reject) => { + erases.push({ reject }) + }) + } + return Promise.resolve() + }) + + const first = proxy.resetAllState() + const second = proxy.resetAllState() + + // One pass, not two racing delete passes: the second caller joins the reset already running. + expect(second).toBe(first) + // The reset yields once before it reaches its delete pass, so give it a macrotask to get there + // rather than counting erases that have not been issued yet. Two passes would by now have issued + // two apiKey erases, which is the defect this half of the row describes. + await new Promise((resolve) => { + setTimeout(resolve, 10) + }) + expect(erases.length).toBe(1) + + erases.forEach((erase) => { + erase.reject(new Error("keychain locked")) + }) + await expect(first).rejects.toThrow("keychain locked") + await expect(second).rejects.toThrow("keychain locked") + + // The guard is down for both joiners, so the store accepts writes again. + await expect(proxy.storeSecret("apiKey", "after-joined-reset")).resolves.toBeUndefined() + expect(proxy.getSecret("apiKey")).toBe("after-joined-reset") + }) + + it("adopts a secret write issued after a reset that waited for a pending write", async () => { + const durable = new Map() + let settle: () => void = () => {} + mockSecrets.get.mockImplementation(async (key: string) => durable.get(key)) + mockSecrets.delete.mockImplementation(async (key: string) => { + durable.delete(key) + }) + mockSecrets.store.mockImplementationOnce( + (key: string, value: string) => + new Promise((resolve) => { + settle = () => { + durable.set(key, value) + resolve(undefined) + } + }), + ) + + const pending = proxy.storeSecret("apiKey", "pre-reset-secret") + const reset = proxy.resetAllState() + setTimeout(settle, 0) + await pending + await reset + + // The reset released only its own claims, so the machinery stays usable afterwards: + // a write issued once the reset has settled is adopted into the cache and reaches storage. + // Back the post-reset write with the durable double as well, so the assertion below reads + // storage rather than only the cache. + mockSecrets.store.mockImplementationOnce(async (key: string, value: string) => { + durable.set(key, value) + }) + await proxy.storeSecret("apiKey", "newer-secret") + expect(proxy.getSecret("apiKey")).toBe("newer-secret") + expect(await mockSecrets.get("apiKey")).toBe("newer-secret") + }) + + it("erases a secret whose write begins after the reset has snapshotted the pending writes", async () => { + const durable = new Map() + let deleteCalls = 0 + let settleFirstDelete: () => void = () => {} + let markDeletePassStarted: () => void = () => {} + const deletePassStarted = new Promise((resolve) => { + markDeletePassStarted = resolve + }) + mockSecrets.get.mockImplementation(async (key: string) => durable.get(key)) + mockSecrets.store.mockImplementation(async (key: string, value: string) => { + durable.set(key, value) + }) + // Park the reset inside its own delete pass so a write can begin in the window the in-flight + // snapshot cannot cover. Only the first delete is held open; the rest settle normally, so + // releasing the park lets the reset finish. + mockSecrets.delete.mockImplementation((key: string) => { + deleteCalls++ + durable.delete(key) + if (deleteCalls === 1) { + return new Promise((resolve) => { + markDeletePassStarted() + settleFirstDelete = () => resolve(undefined) + }) + } + return Promise.resolve(undefined) + }) + + const reset = proxy.resetAllState() + await deletePassStarted + + // The reset has taken its in-flight snapshot, cleared both caches and dropped both write + // claims, and is standing inside the delete pass. This write is invisible to all of it. + const late = proxy.storeSecret("apiKey", "late-secret") + settleFirstDelete() + await reset + await late.catch(() => undefined) + + // All three reads matter. Durable storage is what a reset is supposed to empty, the cache is + // what this provider instance shows the user, and re-initializing is what a restarted + // provider does - which is how a secret that survived the reset reaches the user after the + // fact, so the middle read alone would understate the finding. + expect(await mockSecrets.get("apiKey")).toBeUndefined() + expect(proxy.getSecret("apiKey")).toBeUndefined() + await proxy.initialize() + expect(proxy.getSecret("apiKey")).toBeUndefined() + // The caller is told: a write the reset cannot honour is refused rather than dropped, so + // the save surfaces as a failure instead of vanishing. + await expect(late).rejects.toThrow() + }) + it("should bypass cache for pass-through state keys", async () => { // Setup mock return value mockGlobalState.get.mockReturnValue("pass-through-value") @@ -1170,4 +1405,20 @@ Output only the summary of the conversation so far, without any additional comme expect(customSupportPromptsUpdateCalls.length).toBe(0) }) }) + + describe("export", () => { + it("should exclude viewStates from the exported settings", async () => { + await proxy.setValue("viewStates", { + "stable-sidebar-view": { mode: "architect", currentApiConfigName: "profile-a", updatedAt: 1 }, + }) + await proxy.setValue("customInstructions", "global instructions") + + const exported = await proxy.export() + + // Per-view selection state is machine-local and must never transfer + // between settings, while ordinary global settings keep round-tripping. + expect(exported).not.toHaveProperty("viewStates") + expect(exported?.customInstructions).toBe("global instructions") + }) + }) }) diff --git a/src/core/config/__tests__/ProviderSettingsManager.spec.ts b/src/core/config/__tests__/ProviderSettingsManager.spec.ts index c77464f9f2..393fecbbbd 100644 --- a/src/core/config/__tests__/ProviderSettingsManager.spec.ts +++ b/src/core/config/__tests__/ProviderSettingsManager.spec.ts @@ -12,7 +12,7 @@ import { import { clearAllMocks } from "../../../test-utils/reset" import { makeExtensionContext } from "../../../test-utils/vscode" -import { ProviderSettingsManager, ProviderProfiles } from "../ProviderSettingsManager" +import { ProviderSettingsManager, ProviderSettingsNotFoundError, ProviderProfiles } from "../ProviderSettingsManager" // `export()` builds an API handler per profile to read model capabilities. Mock // buildApiHandler with the real @roo-code/types model definitions so the token-field @@ -973,11 +973,27 @@ describe("ProviderSettingsManager", () => { }), ) + // The typed not-found signal is the contract callers branch on: a profile + // name containing "not found" must not be matchable via message text. + await expect(providerSettingsManager.deleteConfig("nonexistent")).rejects.toBeInstanceOf( + ProviderSettingsNotFoundError, + ) await expect(providerSettingsManager.deleteConfig("nonexistent")).rejects.toThrow( "Config 'nonexistent' not found", ) }) + it('keeps a storage failure whose message mentions "not found" out of the typed not-found signal', async () => { + mockSecrets.get.mockRejectedValue(new Error("vault: secret not found")) + + // A message-based classifier would treat this as a missing profile. The typed + // signal must stay reserved for a missing config entry. + await expect(providerSettingsManager.deleteConfig("default")).rejects.not.toBeInstanceOf( + ProviderSettingsNotFoundError, + ) + await expect(providerSettingsManager.deleteConfig("default")).rejects.toThrow("Failed to delete config") + }) + it("should throw error when trying to delete last remaining config", async () => { mockSecrets.get.mockResolvedValue( JSON.stringify({ diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 6c66655325..fca6cfd3c0 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -331,6 +331,50 @@ describe("importExport", () => { ]) }) + it("should not apply imported viewStates to the context proxy", async () => { + const fileContent = JSON.stringify({ + providerProfiles: { + currentApiConfigName: "test", + apiConfigs: { + test: { apiProvider: providerIdentifiers.openai, apiKey: "test-key", id: "test-id" }, + }, + }, + globalSettings: { + mode: "code", + viewStates: { + "stable-sidebar-view": { + mode: "architect", + currentApiConfigName: "profile-a", + updatedAt: 1, + }, + }, + }, + }) + + ;(fs.readFile as Mock).mockResolvedValue(fileContent) + + mockProviderSettingsManager.export.mockResolvedValue({ + currentApiConfigName: "default", + apiConfigs: { default: { apiProvider: providerIdentifiers.anthropic, id: "default-id" } }, + }) + + mockProviderSettingsManager.listConfig.mockResolvedValue([ + { name: "test", id: "test-id", apiProvider: providerIdentifiers.openai }, + { name: "default", id: "default-id", apiProvider: providerIdentifiers.anthropic }, + ]) + + const result = await importSettingsFromPath("/mock/path/settings.json", { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + expect(result.success).toBe(true) + // Importing must not apply another machine's view pins. + expect(mockContextProxy.setValues).toHaveBeenCalledWith({ mode: "code" }) + expect(result).not.toHaveProperty("globalSettings.viewStates") + }) + it("should return success: false when file content is invalid", async () => { ;(vscode.window.showOpenDialog as Mock).mockResolvedValue([{ fsPath: "/mock/path/settings.json" }]) diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 9882039ad3..530e29cbb9 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -98,6 +98,12 @@ function sanitizeGlobalSettings(rawGlobalSettings: unknown): { for (const [key, rawValue] of Object.entries(rawGlobalSettings)) { const path = `globalSettings.${key}` + + // Per-view selections are machine-local: they must not import across machines. + if (key === "viewStates") { + continue + } + const schema = globalSettingsShape[key as keyof GlobalSettings] if (!schema) { diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 6c9182fcfb..90fb61e844 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -75,6 +75,7 @@ import { isRetiredProvider, modelIdKeys, providerIdentifiers, + PROVIDER_SETTINGS_KEYS, } from "@roo-code/types" import { RateLimitClock, createRateLimitClock } from "../task/RateLimitClock" import { TaskRegistry } from "../task/TaskRegistry" @@ -162,11 +163,29 @@ import { REQUESTY_BASE_URL } from "../../shared/utils/requesty" import { validateAndFixToolResultIds } from "../task/validateToolResultIds" import { PendingEditOperationStore, type PendingEditOperationInput } from "./PendingEditOperationStore" +type PersistedViewState = NonNullable[string] + +/** + * Values that can be held in a view-local state buffer (in-memory) and, for the + * non-secret subset, persisted durably per stable view id. + */ +type ViewLocalStateValues = Partial & Partial + +/** + * The subset of view-local values that has a durable per-view record. `saveViewState` + * and the mutation path handle exactly these keys, so the generic stays narrow enough + * for the compiler to reject e.g. `writeDelayMs`. + */ +type PersistedViewStateValues = Pick + /** * https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts * https://github.com/KumarVariable/vscode-extension-sidebar-html/blob/master/src/customSidebarViewProvider.ts */ +/** Fields of the view-local buffer that a mutation write can touch. */ +type ViewLocalMutationField = keyof PersistedViewStateValues + type DelegatedChildContext = TaskExecutionContext function runDelegationTransition( @@ -250,6 +269,10 @@ export class ClineProvider public static readonly sideBarId = `${Package.name}.SidebarProvider` public static readonly tabPanelId = `${Package.name}.TabPanelProvider` private static activeInstances: Set = new Set() + private static nextViewId = 0 + private static readonly MAX_PERSISTED_VIEW_STATES = 50 + private static readonly MAX_VIEW_STATE_ID_LENGTH = 64 + private static persistedViewStateWriteQueue: Promise = Promise.resolve() private webviewDisposables: vscode.Disposable[] = [] private pendingThemeFixtureProbes = new Map< string, @@ -418,6 +441,45 @@ export class ClineProvider */ private clineMessagesSeq = 0 + /** + * Unique identifier for this provider instance's view. + * Based on renderContext and a monotonically increasing counter to ensure uniqueness across multiple instances. + */ + public readonly viewId: string + + /** Stable id for persisted per-view state keys, bound by the host-minted claim. */ + private viewStateId: string + + /** + * Whether this instance wrote an entry under its own session-local temporary id. + * Temporary ids restart from 0 on every extension host start, so an entry under the + * same name can belong to a different session. Only re-key entries this instance wrote. + */ + private wroteUnderTemporaryViewStateId = false + + /** + * Local state buffer for this specific view instance. + * Used to isolate mode, apiConfiguration, and other fields from the shared ContextProxy singleton + * when running in parallel (multi-tab) mode. + */ + private viewLocalState: Partial = {} + + /** + * Mutation revisions per view-local field. Only mutation writes bump them, so a + * lookup can tell which fields were edited during its awaits even when an edit + * lands back on the value it started from. + */ + private viewLocalFieldRevisions = new Map() + + /** + * This view's pinned profile name from the view-local buffer. Exposed for + * sibling-instance inspection (getAllInstances() filtering): `viewLocalState` + * is private and must not be reached through bracket access. + */ + get pinnedProfileName(): string | undefined { + return this.viewLocalState.currentApiConfigName + } + public isViewLaunched = false public settingsImportedAt?: number public readonly latestAnnouncementId = "nov-2026-v3.98.0-titles-models-reliability" // v3.98.0 task titles, model support, and reliability @@ -447,13 +509,17 @@ export class ClineProvider mdmService?: MdmService, ) { super() + // Initialize viewId based on renderContext and monotonically increasing instance identifier for uniqueness. + // activeInstances is used for visibility/iteration checks, so we keep tracking instances separately. + this.viewId = `${renderContext}-${ClineProvider.nextViewId++}` + this.viewStateId = this.viewId + ClineProvider.activeInstances.add(this) this.currentWorkspacePath = getWorkspacePath() this.pendingEditOperations = new PendingEditOperationStore( ClineProvider.PENDING_OPERATION_TIMEOUT_MS, (message) => this.log(message), ) - ClineProvider.activeInstances.add(this) this.diagnosticsRecorder.record({ boundary: "provider", phase: "success", type: "created" }) this.mdmService = mdmService @@ -513,6 +579,8 @@ export class ClineProvider await this.postStateToWebviewWithoutClineMessages() }) + void this.loadViewState() + // Initialize MCP Hub through the singleton manager McpServerManager.getInstance(this.context, this) .then((hub) => { @@ -658,6 +726,426 @@ export class ClineProvider } } + /** + * Reads the registered viewStates map, returning a defensive copy. + * When fresh is set, the map is read directly from globalState (bypassing the + * ContextProxy cache) so serialized writes never observe a stale in-memory value. + */ + private getPersistedViewStates(options: { fresh?: boolean } = {}): Record { + const viewStates = options.fresh + ? this.context.globalState.get("viewStates") + : this.contextProxy.getValue("viewStates") + + if (!viewStates || typeof viewStates !== "object" || Array.isArray(viewStates)) { + return Object.create(null) + } + + // Copy onto a null prototype. A view id that names an Object.prototype key + // ("constructor", "toString", "valueOf", ...) must not resolve through the + // prototype chain and be mistaken for a persisted entry. + return Object.assign(Object.create(null), viewStates) + } + + /** Persist the non-secret selections through the serialized write queue. */ + private async savePersistedViewState(values: Partial): Promise { + // Capture the id at change time: a write belongs to the view that was active + // when the change was made, even if a newer id is registered while it is queued. + const viewStateId = this.viewStateId + // Set by the queued write when it had to mint a claim, delivered after it lands. + let mintedClaimToken: string | undefined + const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + const states = this.getPersistedViewStates({ fresh: true }) + // The first write to an unowned temporary id claims the slot instead of merging + // into it: temporary names restart from 0 on every host start, so an entry under + // this name can be a leftover from an earlier session, and merging would adopt its + // fields and later re-key them under the stable id. Entries under a stable id, or + // under the temporary id this instance already authored, keep the merge semantics. + const ownsTargetEntry = viewStateId !== this.viewId || this.wroteUnderTemporaryViewStateId + const current = ownsTargetEntry ? (states[viewStateId] ?? {}) : {} + const next: PersistedViewState = { ...current } + + if ("mode" in values) { + if (values.mode === undefined || values.mode === null) { + delete next.mode + } else { + next.mode = values.mode + } + } + + if ("currentApiConfigName" in values) { + if (values.currentApiConfigName === undefined || values.currentApiConfigName === null) { + delete next.currentApiConfigName + } else { + next.currentApiConfigName = values.currentApiConfigName + } + } + + let wroteEntry = false + if (!next.mode && !next.currentApiConfigName) { + delete states[viewStateId] + } else { + next.updatedAt = values.updatedAt ?? Date.now() + // Bind the entry to this webview. An existing entry keeps the token it was + // adopted with (so a reload can still prove ownership); a new entry - or one + // written before claims existed - gets a fresh host-minted token. The token is + // never taken from `values`: it is host-owned, and webview input must not be + // able to choose or supply one. + if (!next.claimToken) { + next.claimToken = crypto.randomUUID() + mintedClaimToken = next.claimToken + } + states[viewStateId] = next + wroteEntry = true + } + + await this.contextProxy.setValue("viewStates", this.prunePersistedViewStates(states)) + // Authorship is recorded only after the durable write lands: a failed persistence + // must not mark the temporary id as owned, or a later load would adopt an entry + // that was never actually stored. + if (wroteEntry && viewStateId === this.viewId) { + this.wroteUnderTemporaryViewStateId = true + } + }) + + ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) + await write + + // Delivered only once the durable write landed: a webview must never hold a claim the + // host did not store, or the next launch would present a token the entry cannot match. + if (mintedClaimToken) { + this.postViewStateClaimToWebview(viewStateId, mintedClaimToken) + } + } + + /** + * Removes the given view's entry from the registered viewStates map. + * Runs through the serialized write queue to avoid racing concurrent view-state writes. + */ + private async clearPersistedViewState(viewStateId = this.viewStateId): Promise { + const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + const states = this.getPersistedViewStates({ fresh: true }) + delete states[viewStateId] + await this.contextProxy.setValue("viewStates", states) + }) + + ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) + await write + } + + /** Re-bind a claim-less entry with a fresh claim; unowned selections are dropped. */ + private async rebindUnboundViewStateEntry(viewStateId: string): Promise { + const claimToken = crypto.randomUUID() + let rebound = false + + const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + const states = this.getPersistedViewStates({ fresh: true }) + const current = states[viewStateId] + // A concurrent registration may have bound this key while this write was queued: + // never overwrite an existing claim, and let the caller refuse the stale adoption. + if (current && typeof current.claimToken === "string" && current.claimToken) { + return + } + states[viewStateId] = { claimToken, updatedAt: Date.now() } + await this.contextProxy.setValue("viewStates", this.prunePersistedViewStates(states)) + rebound = true + }) + + ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) + await write + + return rebound ? claimToken : undefined + } + + /** + * Delivers the host-minted claim that governs a durable viewStates key to this view's + * webview. The webview only stores it and echoes it back on the next launch: it can + * never mint or choose a claim itself. + */ + private postViewStateClaimToWebview(viewStateId: string, claimToken: string): void { + void this.postMessageToWebview({ type: "viewStateClaim", viewStateId, viewStateClaim: claimToken }) + } + + /** + * Keeps only the most recently updated entries of the persisted view states map, + * bounded by MAX_PERSISTED_VIEW_STATES so the global key cannot grow unboundedly. + */ + private prunePersistedViewStates(states: Record): Record { + return Object.fromEntries( + Object.entries(states) + .sort(([, a], [, b]) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0)) + .slice(0, ClineProvider.MAX_PERSISTED_VIEW_STATES), + ) + } + + /** Re-key this instance's authored pre-launch entry to the stable id. */ + private async rekeyPersistedViewStateEntry(nextViewStateId: string): Promise { + const previousViewStateId = this.viewId + + const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { + // An entry under this name can belong to a different session, because temporary + // ids restart from 0 on every extension host start. Only re-key entries this + // instance wrote, otherwise a stale entry from another session is adopted. + if (!this.wroteUnderTemporaryViewStateId) { + return + } + + const states = this.getPersistedViewStates({ fresh: true }) + const previous = states[previousViewStateId] + + if (!previous) { + return + } + + delete states[previousViewStateId] + + const existingStableEntry = states[nextViewStateId] + + if (!existingStableEntry) { + states[nextViewStateId] = previous + } else { + // Registration can bind a claim-less legacy key just before this pre-launch entry + // is re-keyed. Keep the selections the stable entry already carries, but fill in + // anything it lacks so a mode chosen before launch is not silently dropped. + states[nextViewStateId] = { + ...previous, + ...existingStableEntry, + updatedAt: Math.max(previous.updatedAt ?? 0, existingStableEntry.updatedAt ?? 0), + } + } + + await this.contextProxy.setValue("viewStates", this.prunePersistedViewStates(states)) + + // Only a successful write clears authorship: a failed attempt leaves the entry + // under the temporary name, and a retry must still be able to re-key it. + this.wroteUnderTemporaryViewStateId = false + }) + + ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) + await write + } + + /** Register the stable view id and load its persisted selections; a claim must match. */ + public async setViewStateId(viewStateId: string | undefined, presentedClaim?: string): Promise { + // The webview generates this id on purpose - it has to survive a webview reload, + // which recreates the view on both sides - so the host cannot mint it instead. + // What the host owns is which view may hold a given persisted key, so everything + // below validates the supplied value before it becomes one. + if (typeof viewStateId !== "string") { + // A crafted postMessage can carry any JSON value here even though the message + // type declares a string; the persisted key must stay a string. + this.log(`[setViewStateId] Ignoring a non-string viewStateId for view ${this.viewId}.`) + return + } + + const normalizedViewStateId = viewStateId.trim().replace(/[^A-Za-z0-9_-]/g, "_") + + if ( + !normalizedViewStateId || + normalizedViewStateId === this.viewStateId || + // Reject "__proto__" and any other prototype-chain key. The map is copied + // onto a null prototype, so these names can no longer resolve through the + // chain, but they are still rejected as ids so a caller cannot store an + // entry under a name that looks like an inherited member. + normalizedViewStateId === "__proto__" + ) { + return + } + + // Bound the key: the webview generates a UUID, so a much longer value is not a + // view id, and an unbounded key is unbounded growth in the shared viewStates map. + if (normalizedViewStateId.length > ClineProvider.MAX_VIEW_STATE_ID_LENGTH) { + this.log( + `[setViewStateId] Ignoring an oversized viewStateId (${normalizedViewStateId.length} chars) for view ${this.viewId}.`, + ) + return + } + + const claimant = ClineProvider.getAllInstances().find( + (instance) => instance !== this && instance.viewStateId === normalizedViewStateId, + ) + if (claimant) { + // Ownership check: a key another live view holds must not be adopted. Doing so + // would load that view's pinned profile, nested overlay, and mode into this + // provider, and this webview could then overwrite that view's persisted entry. + // Staying on the temporary id keeps this view working against the shared state. + this.log( + `[setViewStateId] Refusing viewStateId ${normalizedViewStateId} for view ${this.viewId}: already claimed by live view ${claimant.viewId}.`, + ) + return + } + + // Claim binding, checked before any re-key or load so a refused registration can + // neither read nor mutate a persisted entry. Read fresh from storage rather than + // through the ContextProxy cache: a security check must not trust a stale copy. + const persistedEntry = this.getPersistedViewStates({ fresh: true })[normalizedViewStateId] + + if (persistedEntry) { + const storedClaim = persistedEntry.claimToken + + if (typeof storedClaim !== "string" || !storedClaim) { + // A pre-claim entry cannot be attributed to any webview, so its selections are + // never loaded. Re-establish the binding with a fresh host-minted claim and hand + // that claim to this webview: the key becomes adoptable again (no upgrade brick) + // and the unbound selections are gone, so the new token cannot resurrect them. + const reboundClaim = await this.rebindUnboundViewStateEntry(normalizedViewStateId) + + if (reboundClaim === undefined) { + // A concurrent registration bound the key while the re-bind was queued: this + // launch adopts a key another webview now owns, so refuse it instead of + // handing out a claim that is not ours. + this.log( + `[setViewStateId] Refusing viewStateId ${normalizedViewStateId} for view ${this.viewId}: bound concurrently by another registration.`, + ) + return + } + + this.postViewStateClaimToWebview(normalizedViewStateId, reboundClaim) + this.log( + `[setViewStateId] Re-bound claim-less viewStates entry ${normalizedViewStateId} for view ${this.viewId}: unbound selections were not loaded.`, + ) + } else if (typeof presentedClaim !== "string" || presentedClaim !== storedClaim) { + // Fail closed: the entry belongs to a webview that never presented this view's + // claim. Rejection is side-effect free, so presenting an id cannot probe, mutate + // or delete another view's entry. + this.log( + `[setViewStateId] Refusing viewStateId ${normalizedViewStateId} for view ${this.viewId}: claim missing or mismatched.`, + ) + return + } + } + + const previousViewStateId = this.viewStateId + + this.viewStateId = normalizedViewStateId + + try { + // Re-key any durable entry written under the temporary pre-launch id before + // loading, so the load sees the view's own pre-registration selections. + await this.rekeyPersistedViewStateEntry(this.viewStateId) + + await this.loadViewState() + + // Re-affirm the binding for the id just adopted: a claim minted while this view was + // still on its temporary id now governs this key (the entry was re-keyed), so the + // webview is told the canonical (viewStateId, claim) pair to echo on its next launch. + const adoptedClaim = this.getPersistedViewStates({ fresh: true })[this.viewStateId]?.claimToken + + if (adoptedClaim) { + this.postViewStateClaimToWebview(this.viewStateId, adoptedClaim) + } + } catch (error) { + // A persistence failure must not leave the provider holding an id that was + // never registered: restore the previous id so a later launch retries the + // registration and the load instead of the guard above early-returning for + // the failed id. + this.viewStateId = previousViewStateId + throw error + } + } + + /** Load non-secret persisted selections; in-flight buffer edits are reapplied on top. */ + private async loadViewState(): Promise { + const loadedForViewId = this.viewStateId + + // Before registration the key is the session-local name, which can be a stale entry + // from another session: load only entries this instance authored. + if (loadedForViewId === this.viewId && !this.wroteUnderTemporaryViewStateId) { + return + } + try { + const persisted = this.getPersistedViewStates()[loadedForViewId] + const loadedState: Partial = {} + + // The mutation paths update viewLocalState in place; the per-field revisions taken + // below make in-flight edits observable, including an edit that lands back on the + // value it started from. + const preLoadRevisions: Record = { + mode: this.viewLocalFieldRevisions.get("mode") ?? 0, + currentApiConfigName: this.viewLocalFieldRevisions.get("currentApiConfigName") ?? 0, + apiConfiguration: this.viewLocalFieldRevisions.get("apiConfiguration") ?? 0, + } + + if (persisted?.mode) { + // A stale custom-mode slug must not shadow the shared mode from getState(). + const customModes = await this.customModesManager.getCustomModes() + if (getModeBySlug(persisted.mode, customModes)) { + loadedState.mode = persisted.mode as Mode + } else { + this.log(`[loadViewState] Ignoring unknown persisted mode "${persisted.mode}"`) + } + } + + if (persisted?.currentApiConfigName) { + loadedState.currentApiConfigName = persisted.currentApiConfigName + + try { + const { name: _name, ...apiConfiguration } = await this.providerSettingsManager.getProfile({ + name: persisted.currentApiConfigName, + }) + loadedState.apiConfiguration = apiConfiguration as ProviderSettings + } catch (error) { + this.log( + `[loadViewState] Unable to resolve API profile '${persisted.currentApiConfigName}' for viewId ${this.viewId}: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } + + if (this.viewStateId !== loadedForViewId) { + this.log(`[loadViewState] Discarding stale state for superseded view id ${loadedForViewId}`) + return + } + + // Apply a persisted field only when no mutation touched that field during the + // awaits above: the revision decides, not the value, so an edit that reverts to // the value it started from still wins over the loaded one (including clears) + // while untouched fields keep the persisted values authoritative. + const postLoadBuffer = this.viewLocalState + const mutatedDuringLookup = (field: ViewLocalMutationField): boolean => + (this.viewLocalFieldRevisions.get(field) ?? 0) !== preLoadRevisions[field] + const mergedState: Partial = { ...loadedState } + + if (mutatedDuringLookup("mode")) { + if (postLoadBuffer.mode === undefined) { + delete mergedState.mode + } else { + mergedState.mode = postLoadBuffer.mode + } + } + + if (mutatedDuringLookup("currentApiConfigName")) { + if (postLoadBuffer.currentApiConfigName === undefined) { + delete mergedState.currentApiConfigName + } else { + mergedState.currentApiConfigName = postLoadBuffer.currentApiConfigName + } + } + + if (mutatedDuringLookup("apiConfiguration")) { + if (postLoadBuffer.apiConfiguration === undefined) { + delete mergedState.apiConfiguration + } else { + mergedState.apiConfiguration = postLoadBuffer.apiConfiguration + } + } + + this.viewLocalState = mergedState + this.log(`[loadViewState] Loaded state for viewId ${this.viewId}`) + } catch (error) { + this.log( + `[loadViewState] Error loading state for viewId ${this.viewId}: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } + + /** Save one view-local value; the durable subset is re-keyed to the stable id. */ + public async saveViewState( + key: K, + value: PersistedViewStateValues[K] | undefined, + ): Promise { + await this._saveViewLocalStateFromMutation({ [key]: value } as ViewLocalStateValues) + + this.log(`[saveViewState] Saved ${String(key)} for viewId ${this.viewId}`) + } + /** * Override EventEmitter's on method to match TaskProviderLike interface */ @@ -1003,7 +1491,6 @@ export class ClineProvider ) } } - async dispose() { if (this._disposed) { return @@ -1512,7 +1999,6 @@ export class ClineProvider ) return run } - private async createTaskWithHistoryItemUnlocked( historyItem: HistoryItem & { rootTask?: Task; parentTask?: Task }, options?: { startTask?: boolean }, @@ -1758,7 +2244,6 @@ export class ClineProvider return task } - public async postMessageToWebview(message: ExtensionMessage) { const startedAt = Date.now() const taskId = this.getCurrentTask()?.taskId @@ -2096,7 +2581,6 @@ export class ClineProvider this.handleModeSwitchUnlocked(newMode, targetTask, signal), ) } - private async handleModeSwitchUnlocked( newMode: Mode, targetTask: Task | null | undefined, @@ -2426,9 +2910,18 @@ export class ClineProvider // `allSettled` so a caller that rolls back after a failure never races a write still in flight. const activationResults = await Promise.allSettled([ this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()), - this.updateGlobalState("currentApiConfigName", name), + // Shared write: adds/updates the profile list entry and the current-profile name. + this.contextProxy.setValue("currentApiConfigName", name), this.setModeConfig(mode, id), this.contextProxy.setProviderSettings(providerSettings), + // setProviderSettings bypasses the buffer path; the mutation below refreshes this view. + // One mutation carries both the name and the settings: pinnedProfileName reads the buffer, + // so a buffer that keeps the previous name while holding the new settings pins a profile + // this view no longer runs under. + this._saveViewLocalStateFromMutation({ + currentApiConfigName: name, + apiConfiguration: providerSettings, + }), ]) const failedActivation = activationResults.find( (result): result is PromiseRejectedResult => result.status === "rejected", @@ -2438,6 +2931,8 @@ export class ClineProvider if (signal.aborted) return id + await this.refreshSiblingsAfterProfileSave(name, providerSettings) + // Change the provider for the current task. // TODO: We should rename `buildApiHandler` for clarity (e.g. `getProviderClient`). this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true }) @@ -2446,6 +2941,20 @@ export class ClineProvider await this.persistStickyProviderProfileToCurrentTask(name) } else { await this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()) + + // A non-activating save still changes the profile's settings: refresh the views + // that buffered a copy, or their getState() keeps the pre-save values. + if (this.pinnedProfileName === name) { + await this._saveViewLocalStateFromMutation({ apiConfiguration: providerSettings }) + // Only rebuild a task that actually runs under the saved profile. + if (this.getCurrentTask()?.taskApiConfigName === name) { + this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true }) + } + } + // A non-activating save changes the profile's settings too: refresh every sibling + // that buffered a copy (pinned siblings included), or their getState() keeps the pre-save + // values. This head had no sibling refresh at all before this change. + await this.refreshSiblingsAfterProfileSave(name, providerSettings) } if (signal.aborted) return id @@ -2453,6 +2962,32 @@ export class ClineProvider await this.postStateToWebview() return id } + /** + * Refresh the buffered overlay of every live sibling pinned to a saved profile and rebuild + * any task that follows it. The handler rebuild is independent of the pin: a task restored + * from history can follow profile A while its view pins profile B. + */ + private async refreshSiblingsAfterProfileSave(name: string, providerSettings: ProviderSettings): Promise { + for (const instance of ClineProvider.getAllInstances()) { + if (instance === this || instance._disposed || instance.pinnedProfileName !== name) { + continue + } + // Direct private access: compile-time safe across sibling instances. + await instance._saveViewLocalStateFromMutation({ apiConfiguration: providerSettings }) + } + + const { + name: _recordName, + id: _recordId, + ...taskSettings + } = providerSettings as ProviderSettings & { name?: string; id?: string } + for (const instance of ClineProvider.getAllInstances()) { + if (instance._disposed || instance.getCurrentTask()?.taskApiConfigName !== name) { + continue + } + instance.updateTaskApiHandlerIfNeeded(taskSettings, { forceRebuild: true }) + } + } async deleteProviderProfile(profileToDelete: ProviderSettingsEntry) { const globalSettings = this.contextProxy.getValues() @@ -2521,7 +3056,6 @@ export class ClineProvider this.activateProviderProfileUnlocked(args, options, signal), ) } - private async activateProviderProfileUnlocked( args: { name: string } | { id: string }, options?: { @@ -2653,9 +3187,6 @@ export class ClineProvider await this.upsertProviderProfile(currentApiConfigName, newConfiguration) } - - // Zoo Code Auth - async handleZooCodeCallback(token: string) { // Auth mutation (token storage, subscription check, success toast) was already // performed by handleAuthCallback() in handleUri.ts before this method was called. @@ -3600,9 +4131,10 @@ export class ClineProvider const taskSyncEnabled: boolean = false + // The view-local buffer wins field by field; a field the buffer does not set falls back to the shared value. // Return the same structure as before. return { - apiConfiguration: providerSettings, + apiConfiguration: this.viewLocalState.apiConfiguration ?? providerSettings, lastShownAnnouncementId: stateValues.lastShownAnnouncementId, customInstructions: stateValues.customInstructions, apiModelId: stateValues.apiModelId, @@ -3651,11 +4183,12 @@ export class ClineProvider terminalZshP10k: stateValues.terminalZshP10k ?? false, terminalZdotdir: stateValues.terminalZdotdir ?? false, terminalProfile: stateValues.terminalProfile, - mode: stateValues.mode ?? defaultModeSlug, + mode: this.viewLocalState.mode ?? stateValues.mode ?? defaultModeSlug, language: stateValues.language ?? formatLanguage(vscode.env.language), mcpEnabled: stateValues.mcpEnabled ?? true, mcpServers: this.mcpHub?.getAllServers() ?? [], - currentApiConfigName: stateValues.currentApiConfigName ?? "default", + currentApiConfigName: + this.viewLocalState.currentApiConfigName ?? stateValues.currentApiConfigName ?? "default", listApiConfigMeta: stateValues.listApiConfigMeta ?? [], pinnedApiConfigs: stateValues.pinnedApiConfigs ?? {}, modeApiConfigs: stateValues.modeApiConfigs ?? ({} as Record), @@ -3794,7 +4327,6 @@ export class ClineProvider private getGlobalState(key: K) { return this.contextProxy.getValue(key) } - public async setValue(key: K, value: RooCodeSettings[K]) { await this.contextProxy.setValue(key, value) } @@ -3802,19 +4334,43 @@ export class ClineProvider public getValue(key: K) { return this.contextProxy.getValue(key) } - public getValues() { return this.contextProxy.getValues() } - public async setValues(values: RooCodeSettings) { await this.contextProxy.setValues( withoutInvalidDisplaySettings(values, (key) => this.log(`[setValues] Ignored an invalid value for ${key}`)), ) } - // dev + /** Persist the durable subset first, then update the in-memory buffer. */ + private async _saveViewLocalStateFromMutation( + values: Partial & Partial, + ): Promise { + await this._persistViewLocalStateFromMutation(values) + this._updateViewLocalStateFromMutation(values) + } + + /** Write the durable subset of a mutation into this view's viewStates entry. */ + private async _persistViewLocalStateFromMutation( + values: Partial & Partial, + ): Promise { + const persistedValues: Partial = {} + + if ("mode" in values) { + persistedValues.mode = values.mode as PersistedViewState["mode"] + } + + if ("currentApiConfigName" in values) { + persistedValues.currentApiConfigName = values.currentApiConfigName + } + + if ("mode" in persistedValues || "currentApiConfigName" in persistedValues) { + await this.savePersistedViewState(persistedValues) + } + } + /** Clear the buffer so getState() falls back to the shared values. */ async resetState() { const answer = await vscode.window.showInformationMessage( t("common:confirmation.reset_state"), @@ -5579,4 +6135,65 @@ export class ClineProvider return vscode.Uri.file(filePath).toString() } } + + /** + * Update or invalidate viewLocalState when ContextProxy is mutated via setValues, setValue, + * profile upsert/activation/deletion, or resetState. This ensures the local cache stays in + * sync with global state changes that would otherwise be invisible behind mergedStateValues. + */ + /** Bump the mutation revision of every field a write touches. */ + private bumpViewLocalFieldRevision(...fields: ViewLocalMutationField[]): void { + for (const field of fields) { + this.viewLocalFieldRevisions.set(field, (this.viewLocalFieldRevisions.get(field) ?? 0) + 1) + } + } + + private _updateViewLocalStateFromMutation(values: Partial & Partial): void { + if ("mode" in values) { + this.bumpViewLocalFieldRevision("mode") + const val = values.mode + if (val === undefined || val === null) { + delete this.viewLocalState.mode + } else { + this.viewLocalState.mode = val + } + } + + if ("currentApiConfigName" in values) { + this.bumpViewLocalFieldRevision("currentApiConfigName") + const val = values.currentApiConfigName + if (val === undefined || val === null) { + delete this.viewLocalState.currentApiConfigName + } else { + this.viewLocalState.currentApiConfigName = val + } + } + + if ("apiConfiguration" in values) { + this.bumpViewLocalFieldRevision("apiConfiguration") + const val = values.apiConfiguration + if (val === undefined || val === null) { + delete this.viewLocalState.apiConfiguration + } else { + this.viewLocalState.apiConfiguration = val + } + } else if (PROVIDER_SETTINGS_KEYS.some((key) => key in values)) { + this.bumpViewLocalFieldRevision("apiConfiguration") + const providerSettingsUpdate = PROVIDER_SETTINGS_KEYS.reduce((acc, key) => { + if (key in values) { + return { ...acc, [key]: values[key as keyof RooCodeSettings] } + } + + return acc + }, {} as ProviderSettings) + + this.viewLocalState.apiConfiguration = + "apiProvider" in providerSettingsUpdate + ? providerSettingsUpdate + : { + ...(this.viewLocalState.apiConfiguration ?? {}), + ...providerSettingsUpdate, + } + } + } } diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 67b1e00853..b950d3423b 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -29,6 +29,7 @@ import { TelemetryService } from "@roo-code/telemetry" import { defaultModeSlug } from "../../../shared/modes" import { experimentDefault } from "../../../shared/experiments" +import { EMBEDDING_MODEL_PROFILES } from "../../../shared/embeddingModels" import { setTtsEnabled } from "../../../utils/tts" import { ContextProxy } from "../../config/ContextProxy" import { ProviderSettingsManager } from "../../config/ProviderSettingsManager" @@ -428,6 +429,23 @@ afterAll(() => { vi.restoreAllMocks() }) +type StalledProfile = Awaited> + +function stallProviderSettingsProfile(provider: ClineProvider) { + let resolveProfile: (value: StalledProfile) => void = () => {} + // The manager is public readonly, so this test spies its getProfile instead of + // reassigning the field; the reassignment is what the ignored error was about. + const getProfileSpy = vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(() => { + if (getProfileSpy.mock.calls.length > 1) { + throw new Error( + "stallProviderSettingsProfile: getProfile called more than once; only one lookup is resolvable", + ) + } + return new Promise((resolve) => (resolveProfile = resolve)) + }) + return { getProfile: getProfileSpy, resolveProfile: (value: StalledProfile) => resolveProfile(value) } +} + describe("ClineProvider", () => { beforeAll(() => { vi.mocked(Task).mockImplementation(function (options: any) { @@ -6058,6 +6076,1466 @@ describe("ClineProvider", () => { ]) }) }) + + describe("setViewStateId", () => { + it('should ignore "__proto__" and keep the temporary viewId', async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider["setViewStateId"]("__proto__") + + // "__proto__" is rejected before assignment so a per-view entry can never be + // keyed through the Object.prototype setter: the temporary id stays active and + // nothing is persisted under the reserved name. + expect(provider["viewStateId"]).toBe(provider.viewId) + expect(mockContext.globalState.get("viewStates")).toBeUndefined() + expect(provider["viewLocalState"]).toEqual({}) + + await provider.dispose() + }) + + it("restores the previous view id when the registration write fails so a later launch retries", async () => { + const contextProxy = new ContextProxy(mockContext) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + contextProxy, + new WebviewFocusTracker(), + ) + // Seed a pre-launch entry under the temporary id through the real write path, + // so the re-key has real work to do and records this instance as its author. + await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) + + const setValueSpy = vi.spyOn(contextProxy, "setValue").mockRejectedValue(new Error("storage down")) + + await expect(provider["setViewStateId"]("stable-sidebar-view")).rejects.toThrow("storage down") + + // The failed id must not stick: the provider keeps its previous (temporary) + // id so a later launch retries registration and the load instead of the + // guard early-returning for an id that was never persisted. + expect(provider["viewStateId"]).toBe(provider.viewId) + + // Pin what the failure left in each store: the durable record still keys the entry under + // the temporary id (the re-key wrote nothing durable), and the payload ContextProxy holds for + // viewStates is the same map the durable store holds, so a rolled-back registration cannot be + // visible through one store and invisible through the other. + const durableAfterFailure = mockContext.globalState.get("viewStates") as Record + expect(durableAfterFailure[provider.viewId]?.mode).toBe("architect") + expect(durableAfterFailure["stable-sidebar-view"]).toBeUndefined() + expect(provider.contextProxy.getValue("viewStates")).toEqual(durableAfterFailure) + + // A later retry succeeds once the storage write works again, and the + // pre-launch entry lands under the registered id. + setValueSpy.mockRestore() + await provider["setViewStateId"]("stable-sidebar-view") + expect(provider["viewStateId"]).toBe("stable-sidebar-view") + expect(mockContext.globalState.get("viewStates")).toEqual({ + "stable-sidebar-view": { mode: "architect", updatedAt: 1, claimToken: expect.any(String) }, + }) + + await provider.dispose() + }) + }) + + describe("view state claim binding", () => { + it("refuses a viewStateId bound by a concurrent registration through setViewStateId", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const beforeViewStateId = provider["viewStateId"] + const postSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) + // A claim-less entry is adoptable at the first read, but a concurrent registration + // binds the key while this launch's queued re-bind is waiting its turn. + await provider.contextProxy.setValue("viewStates", { "legacy-view": { updatedAt: 1 } }) + ClineProvider["persistedViewStateWriteQueue"] = Promise.resolve().then(async () => { + await provider.contextProxy.setValue("viewStates", { + "legacy-view": { claimToken: "winner", updatedAt: 2 }, + }) + }) + + await provider["setViewStateId"]("legacy-view") + + // The launch must not adopt a key another webview now owns: no claim is delivered, + // the provider stays on its temporary id, and the winner's claim is untouched. + expect(postSpy).not.toHaveBeenCalledWith(expect.objectContaining({ type: "viewStateClaim" })) + expect(provider["viewStateId"]).toBe(beforeViewStateId) + const states = provider.contextProxy.getValue("viewStates") as Record + expect(states["legacy-view"].claimToken).toBe("winner") + ClineProvider["persistedViewStateWriteQueue"] = Promise.resolve() + postSpy.mockRestore() + await provider.dispose() + }) + + it("does not overwrite a claim bound by a concurrent registration", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("viewStates", { "legacy-view": { updatedAt: 1 } }) + // A concurrent registration binds this key while the re-bind write is queued. + ClineProvider["persistedViewStateWriteQueue"] = Promise.resolve().then(async () => { + await provider.contextProxy.setValue("viewStates", { + "legacy-view": { claimToken: "winner", updatedAt: 2 }, + }) + }) + + const claim = await provider["rebindUnboundViewStateEntry"]("legacy-view") + + // The queued re-bind must not replace the claim the other registration wrote; it + // reports that nothing was rebound so the caller can refuse the stale adoption. + expect(claim).toBeUndefined() + const states = provider.contextProxy.getValue("viewStates") as Record + expect(states["legacy-view"].claimToken).toBe("winner") + ClineProvider["persistedViewStateWriteQueue"] = Promise.resolve() + await provider.dispose() + }) + + const createProvider = () => + new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + const storedEntries = () => + mockContext.globalState.get>("viewStates") ?? {} + + test("refuses a disposed view's id when no claim is presented, and loads nothing", async () => { + // The vulnerable path: a view registers a durable entry, is disposed, and a second + // webview presents the same id. dispose() removes the instance but leaves the entry, + // so only the claim can stop the second webview from loading the first one's pinned + // profile (and the profile's secrets) through the state post. + const owner = createProvider() + await owner["setViewStateId"]("closed-view") + await owner.saveViewState("mode", "architect") + await owner.saveViewState("currentApiConfigName", "profile-with-secrets") + + const storedClaim = storedEntries()["closed-view"]?.claimToken + expect(storedClaim).toEqual(expect.any(String)) + + await owner.dispose() + + const intruder = createProvider() + const postMessageSpy = vi.spyOn(intruder, "postMessageToWebview").mockResolvedValue(undefined) + + await intruder["setViewStateId"]("closed-view") + + // Fail closed: the id is not adopted, no selections reach this view and no state is + // posted back to the webview that asked for it. + expect(intruder["viewStateId"]).toBe(intruder.viewId) + expect(intruder["viewLocalState"]).toStrictEqual({}) + expect((await intruder.getState()).currentApiConfigName).not.toBe("profile-with-secrets") + expect(postMessageSpy).not.toHaveBeenCalled() + + // A refused adoption is side-effect free: presenting an id must not probe or rewrite + // the entry that a different webview owns. + expect(storedEntries()["closed-view"]).toMatchObject({ + mode: "architect", + currentApiConfigName: "profile-with-secrets", + claimToken: storedClaim, + }) + + await intruder.dispose() + }) + + test("refuses a mismatched claim", async () => { + const owner = createProvider() + await owner["setViewStateId"]("closed-view") + await owner.saveViewState("currentApiConfigName", "profile-with-secrets") + await owner.dispose() + + const intruder = createProvider() + const postMessageSpy = vi.spyOn(intruder, "postMessageToWebview").mockResolvedValue(undefined) + + // A webview-generated value is not a claim: only the token the host minted matches. + await intruder["setViewStateId"]("closed-view", "webview-chosen-claim") + + expect(intruder["viewStateId"]).toBe(intruder.viewId) + expect(intruder["viewLocalState"]).toStrictEqual({}) + expect(postMessageSpy).not.toHaveBeenCalled() + + await intruder.dispose() + }) + + test("does not churn the claim on later writes to the same entry", async () => { + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) + await provider["setViewStateId"]("minted-view") + await provider.saveViewState("mode", "architect") + + const mintedClaim = storedEntries()["minted-view"]?.claimToken + expect(mintedClaim).toEqual(expect.any(String)) + + await provider.saveViewState("currentApiConfigName", "profile-b") + + // A merge into an entry this view already owns keeps its token, so the claim the + // webview holds keeps working and is not re-sent. + expect(storedEntries()["minted-view"]?.claimToken).toBe(mintedClaim) + expect( + postMessageSpy.mock.calls.map(([message]) => message).filter((m) => m.type === "viewStateClaim"), + ).toHaveLength(1) + }) + + test("re-binds a claim-less legacy entry instead of loading its selections", async () => { + // An entry written before claims existed cannot be attributed to any webview: its + // selections are refused, and the key is re-bound with a fresh host-minted claim so + // the upgrade does not brick per-view persistence. + await provider.contextProxy.setValue("viewStates", { + "legacy-view": { mode: "architect", currentApiConfigName: "profile-a", updatedAt: 1 }, + }) + + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined) + + await provider["setViewStateId"]("legacy-view") + + // No stored selection is adopted... + expect(provider["viewStateId"]).toBe("legacy-view") + expect(provider["viewLocalState"]).toStrictEqual({}) + + // ...the old entry is replaced by a claim-bearing one with the unbound selections gone... + const rebound = storedEntries()["legacy-view"] + expect(rebound).toEqual({ claimToken: expect.any(String), updatedAt: expect.any(Number) }) + expect(rebound).not.toHaveProperty("mode") + expect(rebound).not.toHaveProperty("currentApiConfigName") + + // ...and the fresh claim is handed to this webview so the next launch can prove ownership. + expect(postMessageSpy).toHaveBeenCalledWith({ + type: "viewStateClaim", + viewStateId: "legacy-view", + viewStateClaim: rebound?.claimToken, + }) + + await provider.dispose() + + const reopened = createProvider() + await reopened["setViewStateId"]("legacy-view", rebound?.claimToken) + + expect(reopened["viewStateId"]).toBe("legacy-view") + expect(reopened["viewLocalState"]).toStrictEqual({}) + + await reopened.dispose() + }) + + test("still refuses an id a live view holds, even when the claim matches", async () => { + const owner = createProvider() + await owner["setViewStateId"]("shared-live-view") + await owner.saveViewState("mode", "architect") + const claim = storedEntries()["shared-live-view"]?.claimToken + + const sibling = createProvider() + + try { + await sibling["setViewStateId"]("shared-live-view", claim) + + // The live-instance guard runs first and keeps working: a second live view never + // shares a key with the view that holds it. + expect(sibling["viewStateId"]).toBe(sibling.viewId) + expect(sibling["viewLocalState"]).toStrictEqual({}) + expect(owner["viewStateId"]).toBe("shared-live-view") + } finally { + await sibling.dispose() + await owner.dispose() + } + }) + }) + + describe("view state persistence edge cases", () => { + it("should read viewStates from the ContextProxy cache when not fresh", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("viewStates", { "stable-sidebar-view": { mode: "architect" } }) + expect(provider["getPersistedViewStates"]()).toEqual({ "stable-sidebar-view": { mode: "architect" } }) + await provider.dispose() + }) + + it("should treat a corrupted non-object viewStates value as an empty map", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await mockContext.globalState.update("viewStates", "corrupted-storage-value") + expect(provider["getPersistedViewStates"]({ fresh: true })).toEqual({}) + await provider.dispose() + }) + + it("should merge saved fields, drop cleared fields and delete emptied entries", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + const save = provider.saveViewState.bind(provider) as (key: string, value: unknown) => Promise + const states = () => mockContext.globalState.get>("viewStates") ?? {} + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("mode", "architect") + await provider.saveViewState("currentApiConfigName", "profile-a") + const merged = states()["stable-sidebar-view"] + expect(merged).toMatchObject({ mode: "architect", currentApiConfigName: "profile-a" }) + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Saved mode for viewId")) + await save("mode", undefined) + expect(states()["stable-sidebar-view"]).toStrictEqual({ + currentApiConfigName: "profile-a", + updatedAt: expect.any(Number), + claimToken: expect.any(String), + }) + await save("mode", null) + expect(states()["stable-sidebar-view"]).not.toHaveProperty("mode") + await provider.saveViewState("mode", "architect") + await save("currentApiConfigName", undefined) + expect(states()["stable-sidebar-view"]).toStrictEqual({ + mode: "architect", + updatedAt: expect.any(Number), + claimToken: expect.any(String), + }) + await provider.saveViewState("currentApiConfigName", "profile-c") + await provider.saveViewState("mode", "architect") + expect(states()["stable-sidebar-view"]).toMatchObject({ + mode: "architect", + currentApiConfigName: "profile-c", + }) + await save("currentApiConfigName", null) + expect(states()["stable-sidebar-view"]).not.toHaveProperty("currentApiConfigName") + await save("mode", null) + expect(states()["stable-sidebar-view"]).toBeUndefined() + expect(provider["viewLocalState"]).toStrictEqual({}) // buffer ends fully cleared + await provider.dispose() + }) + + it("should rekey a pre-launch entry under the temporary id to the registered stable id", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Seed through the write path so this instance authors the entry under its temporary id; an entry authored by another session must not be adopted. + await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 1 }) + await provider["setViewStateId"]("stable-sidebar-view") + expect(mockContext.globalState.get("viewStates")).toEqual({ + // The minted claim travels with the re-keyed entry, so the webview's token keeps working. + "stable-sidebar-view": { mode: "architect", updatedAt: 1, claimToken: expect.any(String) }, + }) + await provider.dispose() + }) + + it("leaves an unowned entry under the temporary id alone and mints a fresh claim", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + type DurableEntry = { + mode?: string + currentApiConfigName?: string + updatedAt?: number + claimToken?: string + } + const temporaryId = provider.viewId + // An earlier session left this entry behind under the same temporary name, with its + // own profile and claim. This instance never authored it, so it is not this + // instance's to re-key and not this instance's to adopt. + await provider.contextProxy.setValue("viewStates", { + [temporaryId]: { + mode: "code", + currentApiConfigName: "earlier-profile", + updatedAt: 1, + claimToken: "legacy-claim", + }, + }) + await provider["setViewStateId"]("stable-sidebar-view") + const afterRegistration = mockContext.globalState.get>("viewStates") ?? {} + // Registration authors nothing this view never wrote: the earlier session keeps + // its entry, its profile and its claim, and none of them are loaded here. + expect(afterRegistration[temporaryId]).toMatchObject({ + currentApiConfigName: "earlier-profile", + claimToken: "legacy-claim", + }) + expect(afterRegistration["stable-sidebar-view"]).toBeUndefined() + expect(provider["viewLocalState"]).not.toHaveProperty("currentApiConfigName") + // The first durable write lands under the stable id and carries a claim this + // host minted - never the token the earlier session left behind. + await provider.saveViewState("mode", "architect") + const states = mockContext.globalState.get>("viewStates") ?? {} + expect(states["stable-sidebar-view"]).toMatchObject({ + mode: "architect", + updatedAt: expect.any(Number), + claimToken: expect.any(String), + }) + expect(states["stable-sidebar-view"]?.claimToken).not.toBe("legacy-claim") + expect(states[temporaryId]).toMatchObject({ + currentApiConfigName: "earlier-profile", + claimToken: "legacy-claim", + }) + await provider.dispose() + }) + + it("keeps a reverting buffer edit ahead of the profile resolved during the lookup", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) + // No custom modes exist, so the persisted builtin slug resolves without a lookup. + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + // The selections this view pins are already durable under the stable id, bound by + // this webview's claim; the profile behind them resolves to a different provider + // configuration. + await provider.contextProxy.setValue("viewStates", { + "stable-sidebar-view": { + mode: "code", + currentApiConfigName: "cfg-a", + updatedAt: 1, + claimToken: "seeded-claim", + }, + }) + const pinnedApiConfiguration = { apiProvider: providerIdentifiers.openrouter } + await provider.saveViewState("apiConfiguration", pinnedApiConfiguration) + const load = provider["setViewStateId"]("stable-sidebar-view", "seeded-claim") + // Let the stalled lookup begin so the edits below land inside it. + await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) + // The user switches provider and switches it back while the lookup is in flight: + // the buffer ends on the value it started from, but the edit happened. + await provider.saveViewState("apiConfiguration", { + apiProvider: providerIdentifiers.anthropic, + apiKey: "typed-then-erased", + }) + await provider.saveViewState("apiConfiguration", pinnedApiConfiguration) + resolveProfile({ + name: "cfg-a", + id: "cfg-a-id", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + await load + // The reverting edit is still the user's own, so the resolved profile must not + // overwrite it; the fields nobody touched keep the persisted selections. + expect(provider["viewLocalState"].apiConfiguration).toBe(pinnedApiConfiguration) + expect(provider["viewLocalState"]).toMatchObject({ + mode: "code", + currentApiConfigName: "cfg-a", + }) + await provider.dispose() + }) + + it("applies the resolved profile only to the fields no edit touched during the lookup", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + // Durable selections from an earlier session, bound by this webview's claim, naming a + // profile whose settings differ from the ones this view has pinned. + await provider.contextProxy.setValue("viewStates", { + "stable-sidebar-view": { + mode: "code", + currentApiConfigName: "cfg-a", + updatedAt: 1, + claimToken: "seeded-claim", + }, + }) + const pinnedApiConfiguration = { apiProvider: providerIdentifiers.openrouter } + // A write of its own raises the field's revision before the lookup begins, so the + // readings the lookup compares against are real numbers rather than map misses. + await provider.saveViewState("apiConfiguration", pinnedApiConfiguration) + const load = provider["setViewStateId"]("stable-sidebar-view", "seeded-claim") + await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) + // Two fields edited while the profile is still resolving: the buffer keeps them. + await provider.saveViewState("mode", "plan") + await provider.saveViewState("currentApiConfigName", "buffer-selection") + resolveProfile({ + name: "cfg-a", + id: "cfg-a-id", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + await load + // The profile the durable selection names fills the field nobody edited, and the + // fields the user moved during the lookup keep the buffer's values. + expect(provider["viewLocalState"].apiConfiguration).toMatchObject({ + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + expect(provider["viewLocalState"].apiConfiguration).not.toBe(pinnedApiConfiguration) + expect(provider["viewLocalState"]).toMatchObject({ + mode: "plan", + currentApiConfigName: "buffer-selection", + }) + await provider.dispose() + }) + + it("gives each instance its own session-local view id and tracks it as active", async () => { + const first = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const second = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Temporary ids restart from 0 on every host start, but two live instances in one + // host must not share one, or they would claim each other's persisted entries. + expect(first.viewId).not.toBe(second.viewId) + expect(first["viewStateId"]).toBe(first.viewId) + expect(second["viewStateId"]).toBe(second.viewId) + expect(ClineProvider.getAllInstances()).toEqual(expect.arrayContaining([first, second])) + // Ids increase within one host, so a later instance never lands on an earlier one's number. + expect(Number(second.viewId.split("-")[1])).toBeGreaterThan(Number(first.viewId.split("-")[1])) + await first.dispose() + await second.dispose() + }) + + it("should keep the stable entry and drop the temporary entry when both exist", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Author the temporary entry through the write path so this instance owns it, + // then add a stable entry that already exists in storage. + await provider["savePersistedViewState"]({ mode: "temp-mode", updatedAt: 1 }) + await provider.contextProxy.setValue("viewStates", { + [provider.viewId]: { mode: "temp-mode", updatedAt: 1 }, + "stable-sidebar-view": { mode: "stable-mode", updatedAt: 5, claimToken: "stable-claim" }, + }) + await provider["setViewStateId"]("stable-sidebar-view", "stable-claim") + expect(mockContext.globalState.get("viewStates")).toEqual({ + "stable-sidebar-view": { mode: "stable-mode", updatedAt: 5, claimToken: "stable-claim" }, + }) + await provider.dispose() + }) + + it("should prune by updatedAt regardless of insertion order", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const states = Object.fromEntries( + Array.from({ length: 55 }, (_, index) => [ + `view-${index}`, + { mode: `mode-${index}`, updatedAt: (index * 7) % 55 }, + ]), + ) + const pruned = provider["prunePersistedViewStates"](states) + expect(Object.keys(pruned)).toHaveLength(50) + // view-1/view-54 survive the true newest-50 selection; view-8 (updatedAt 1) does not. + expect(pruned["view-1"]).toEqual({ mode: "mode-1", updatedAt: 7 }) + expect(pruned["view-54"]).toEqual({ mode: "mode-54", updatedAt: 48 }) + expect(pruned["view-8"]).toBeUndefined() + await provider.dispose() + }) + + it("should log a successful empty load when no persisted entry exists", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + await provider["setViewStateId"]("stable-sidebar-view") + expect(provider["viewLocalState"]).toEqual({}) + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Loaded state for viewId")) + await provider.dispose() + }) + + it("should keep the persisted profile name and log when the profile lookup fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + vi.spyOn(provider.providerSettingsManager, "getProfile").mockRejectedValue(new Error("profile missing")) + await provider.saveViewState("currentApiConfigName", "my-profile") + await provider["setViewStateId"]("stable-sidebar-view") + expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") + expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Unable to resolve API profile 'my-profile'")) + await provider.dispose() + }) + + it("should discard a stale load when the viewStateId changes during the profile lookup", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + // Only getProfile is rewritten, so the lookup itself swaps the id out from under the load. + vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(() => { + provider["viewStateId"] = "superseded-view" + return Promise.resolve({ + name: "my-profile", + id: "my-profile-id", + apiProvider: providerIdentifiers.openrouter, + }) + }) + await provider.saveViewState("currentApiConfigName", "my-profile") + await provider["setViewStateId"]("stable-sidebar-view") + expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration") + const staleMsg = expect.stringContaining("Discarding stale state for superseded view id") + expect(logSpy).toHaveBeenCalledWith(staleMsg) + await provider.dispose() + }) + + it("should not restore a persisted mode whose custom mode no longer exists", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + // No custom modes exist, so nothing can resolve the persisted slug. + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + // The file-level modes mock resolves every slug to a mode; drop the pinned slug. + const modesModule = vi.mocked(await import("../../../shared/modes")) + const originalMode = modesModule.getModeBySlug("code") + modesModule.getModeBySlug.mockImplementation(((slug: string) => + slug === "deleted-custom-mode" ? undefined : originalMode) as typeof modesModule.getModeBySlug) + try { + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("mode", "deleted-custom-mode") + // Reload the persisted entry: the custom mode was deleted in the meantime. + await provider["loadViewState"]() + // The stale slug must not be restored into the buffer. + expect(provider["viewLocalState"]).not.toHaveProperty("mode") + expect(logSpy).toHaveBeenCalledWith( + expect.stringContaining('Ignoring unknown persisted mode "deleted-custom-mode"'), + ) + } finally { + modesModule.getModeBySlug.mockReturnValue(originalMode) + } + await provider.dispose() + }) + + it("should keep every persisted field authoritative when the load is untouched", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const { getProfile: getProfileSpy, resolveProfile } = stallProviderSettingsProfile(provider) + // No custom modes exist, so nothing can resolve the persisted slug. + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + await provider.saveViewState("mode", "code") + await provider.saveViewState("currentApiConfigName", "cfg-a") + const load = provider["setViewStateId"]("stable-sidebar-view") + + // Let the stalled lookup begin so the in-flight mutation and the resolver + // target the pending promise rather than the initial no-op. + await vi.waitFor(() => expect(getProfileSpy).toHaveBeenCalledTimes(1)) + // No mutation while the lookup is in flight: the persisted values must win. + resolveProfile({ + name: "cfg-a", + id: "cfg-a-id", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + await load + + expect(provider["viewLocalState"]).toEqual({ + mode: "code", + currentApiConfigName: "cfg-a", + apiConfiguration: { + id: "cfg-a-id", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }, + }) + await provider.dispose() + }) + // The activation path writes the profile settings straight into this view's buffer, so the + // buffered profile name has to move with them: pinnedProfileName reads the buffer, and a later + // non-activating save of the same profile is gated on that name. + it("keeps the buffered profile name in step with the profile it activates", async () => { + const saver = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await saver["saveViewState"]("currentApiConfigName", "profile-a") + expect(saver["pinnedProfileName"]).toBe("profile-a") + // Spy the profile-store calls the save path makes; the manager itself stays real. + vi.spyOn(saver.providerSettingsManager, "saveConfig").mockResolvedValue("profile-b-id") + vi.spyOn(saver.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "profile-b", id: "profile-b-id" }, + ]) + vi.spyOn(saver.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + const providerSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "activated-key" } + + await saver.upsertProviderProfile("profile-b", providerSettings, true) + + // One mutation: the name and the settings land in the buffer together, or the view pins a + // profile whose settings it is no longer holding. + expect(saver["viewLocalState"]).toMatchObject({ + currentApiConfigName: "profile-b", + apiConfiguration: providerSettings, + }) + expect(saver["pinnedProfileName"]).toBe("profile-b") + await saver.dispose() + }) + + it("should refresh the buffered overlay of another view pinned to the saved profile on a non-activating save", async () => { + const saver = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const pinned = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // saveViewState is the buffer write on this head: setValue is a ContextProxy pass-through, + // so going through setValue here would leave pinnedProfileName undefined. + await pinned["saveViewState"]("currentApiConfigName", "shared-profile") + // Spy the profile-store calls the save path makes; the manager itself stays real. + vi.spyOn(saver.providerSettingsManager, "saveConfig").mockResolvedValue("shared-id") + vi.spyOn(saver.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "shared-profile", id: "shared-id" }, + ]) + vi.spyOn(saver.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + const providerSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "fresh-key" } + + await saver.upsertProviderProfile("shared-profile", providerSettings, false) + + // The pinned view buffered a copy of the profile's settings; a non-activating save must + // refresh it, or its getState() keeps serving the pre-save configuration. + expect(pinned["viewLocalState"].apiConfiguration).toEqual(providerSettings) + await saver.dispose() + await pinned.dispose() + }) + + it("should refresh the buffered overlay of another view pinned to the activated profile", async () => { + const saver = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const pinned = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // saveViewState is the buffer write on this head: setValue is a ContextProxy pass-through, + // so going through setValue here would leave pinnedProfileName undefined. + await pinned["saveViewState"]("currentApiConfigName", "shared-profile") + // Spy the profile-store calls the save path makes; the manager itself stays real. + vi.spyOn(saver.providerSettingsManager, "saveConfig").mockResolvedValue("shared-id") + vi.spyOn(saver.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "shared-profile", id: "shared-id" }, + ]) + vi.spyOn(saver.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + const providerSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "fresh-key" } + + await saver.upsertProviderProfile("shared-profile", providerSettings, true) + + // The pinned view buffered a copy of the profile's settings; an activating save refreshes + // it through the sibling loop, so this row covers the activate=true branch that the case + // above no longer reaches. + expect(pinned["viewLocalState"].apiConfiguration).toEqual(providerSettings) + await saver.dispose() + await pinned.dispose() + }) + + // The task-handler rebuild is keyed on the task's own profile name rather than on the view's + // pin: a task restored from history can follow profile A while its view pins profile B, and only + // the matching side gets its handler rebuilt with forceRebuild (ClineProvider.ts:2897-2902). + // These two cases are the matching and non-matching halves of that branch, which is the coverage + // the review row on this file asked for. + it("rebuilds a sibling task's API handler with a forced rebuild when that task follows the saved profile", async () => { + const saver = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const runner = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The rebuild itself is stubbed so the case asserts the call and its options rather than the + // internals of a handler build. The assertion-free cast is needed because + // updateTaskApiHandlerIfNeeded is private on ClineProvider and vi.spyOn needs the object and + // the key together; the private-field alternative of instance["name"] cannot be spied. + const task = new Task(defaultTaskOptions) + Object.defineProperty(task, "taskApiConfigName", { value: "shared-profile" }) + vi.spyOn(runner, "getCurrentTask").mockReturnValue(task) + vi.spyOn(saver, "getCurrentTask").mockReturnValue(undefined) + const rebuildTarget = runner as unknown as { + updateTaskApiHandlerIfNeeded: ( + settings: Record, + options?: { forceRebuild?: boolean }, + ) => void + } + const rebuild = vi.spyOn(rebuildTarget, "updateTaskApiHandlerIfNeeded").mockImplementation(() => {}) + vi.spyOn(saver.providerSettingsManager, "saveConfig").mockResolvedValue("shared-id") + vi.spyOn(saver.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "shared-profile", id: "shared-id" }, + ]) + vi.spyOn(saver.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + + await saver.upsertProviderProfile( + "shared-profile", + { apiProvider: providerIdentifiers.anthropic, apiKey: "fresh-key" }, + false, + ) + + // Forced, because the saved settings can change with the provider and model both the same, + // and a rebuild that skipped on equality would leave the running task on the old client. + expect(rebuild).toHaveBeenCalledWith( + expect.objectContaining({ apiProvider: providerIdentifiers.anthropic, apiKey: "fresh-key" }), + { forceRebuild: true }, + ) + expect(rebuild).toHaveBeenCalledTimes(1) + + await saver.dispose() + await runner.dispose() + vi.restoreAllMocks() + }) + + it("leaves a sibling task alone when that task follows a different profile than the one saved", async () => { + const saver = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const runner = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Same shape as the case above with one value changed: the sibling's task follows another + // profile, so its handler must keep the settings it was built with rather than inherit this + // save's settings. Its overlay refresh is a separate question and is covered by the two cases + // above this one; this case is only about the rebuild's own selector. + const task = new Task(defaultTaskOptions) + Object.defineProperty(task, "taskApiConfigName", { value: "other-profile" }) + vi.spyOn(runner, "getCurrentTask").mockReturnValue(task) + vi.spyOn(saver, "getCurrentTask").mockReturnValue(undefined) + const rebuildTarget = runner as unknown as { + updateTaskApiHandlerIfNeeded: ( + settings: Record, + options?: { forceRebuild?: boolean }, + ) => void + } + const rebuild = vi.spyOn(rebuildTarget, "updateTaskApiHandlerIfNeeded").mockImplementation(() => {}) + vi.spyOn(saver.providerSettingsManager, "saveConfig").mockResolvedValue("shared-id") + vi.spyOn(saver.providerSettingsManager, "listConfig").mockResolvedValue([ + { name: "shared-profile", id: "shared-id" }, + ]) + vi.spyOn(saver.providerSettingsManager, "setModeConfig").mockResolvedValue(undefined) + + await saver.upsertProviderProfile( + "shared-profile", + { apiProvider: providerIdentifiers.anthropic, apiKey: "fresh-key" }, + false, + ) + + expect(rebuild).not.toHaveBeenCalled() + + await saver.dispose() + await runner.dispose() + vi.restoreAllMocks() + }) + }) + + describe("saveViewState", () => { + it("should update viewLocalState and persist mode through registered viewStates", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + const contextProxySpy = vi.spyOn(provider.contextProxy, "setValue") + await provider["setViewStateId"]("stable-sidebar-view") + + await provider.saveViewState("mode", "architect") + + expect(provider["viewLocalState"].mode).toBe("architect") + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + "stable-sidebar-view": { mode: "architect" }, + }) + expect(contextProxySpy).toHaveBeenCalledWith( + "viewStates", + expect.objectContaining({ + "stable-sidebar-view": expect.objectContaining({ + mode: "architect", + updatedAt: expect.any(Number), + }), + }), + ) + expect(contextProxySpy).not.toHaveBeenCalledWith("__view_state_stable-sidebar-view_mode", expect.anything()) + + await provider.dispose() + }) + + it("should update viewLocalState and persist currentApiConfigName through registered viewStates", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("currentApiConfigName", "my-profile") + + expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") + expect(provider.contextProxy.getValue("viewStates")).toMatchObject({ + "stable-sidebar-view": { currentApiConfigName: "my-profile" }, + }) + + await provider.dispose() + }) + + it("should update viewLocalState for apiConfiguration without persisting provider settings or secrets", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + const testApiConfig = { + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "claude-3.5-sonnet", + openRouterApiKey: "secret-key", + } + + await provider["setViewStateId"]("stable-sidebar-view") + await provider.saveViewState("apiConfiguration", testApiConfig) + + expect(provider["viewLocalState"].apiConfiguration).toEqual(testApiConfig) + expect(provider.contextProxy.getValue("viewStates")).toBeUndefined() + + await provider.dispose() + }) + + it("should clear local override when saveViewState receives undefined", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider.saveViewState("mode", "architect") + expect(provider["viewLocalState"].mode).toBe("architect") + + await provider.saveViewState("mode", undefined) + + expect(Object.prototype.hasOwnProperty.call(provider["viewLocalState"], "mode")).toBe(false) + + await provider.dispose() + }) + + it("should clear the currentApiConfigName override when saveViewState receives undefined", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider.saveViewState("currentApiConfigName", "my-profile") + expect(provider["viewLocalState"].currentApiConfigName).toBe("my-profile") + + await provider.saveViewState("currentApiConfigName", undefined) + + expect(Object.prototype.hasOwnProperty.call(provider["viewLocalState"], "currentApiConfigName")).toBe(false) + + await provider.dispose() + }) + + it("should not update viewLocalState when durable view-state persistence fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + vi.spyOn(provider.contextProxy, "setValue").mockRejectedValueOnce(new Error("persist failed")) + + await provider["setViewStateId"]("stable-sidebar-view") + + await expect(provider.saveViewState("mode", "architect")).rejects.toThrow("persist failed") + expect(provider["viewLocalState"]).not.toHaveProperty("mode") + expect(provider.contextProxy.getValue("viewStates")).toBeUndefined() + + await provider.dispose() + }) + + it("should merge concurrent persisted updates from separate provider instances without lost viewStates", async () => { + const provider1 = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + + new WebviewFocusTracker(), + ) + const provider2 = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider1["setViewStateId"]("stable-sidebar-view") + await provider2["setViewStateId"]("stable-editor-view") + + await Promise.all([ + provider1.saveViewState("mode", "architect"), + provider2.saveViewState("currentApiConfigName", "editor-profile"), + ]) + + expect(mockContext.globalState.get("viewStates")).toMatchObject({ + "stable-sidebar-view": { mode: "architect" }, + "stable-editor-view": { currentApiConfigName: "editor-profile" }, + }) + + await provider1.dispose() + await provider2.dispose() + }) + }) + + it("reapplies the durable profile selection when its revision was raised before the lookup", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Shared storage is snapshotted so this fixture leaves nothing behind for the tests + // that run after it. + const priorViewStates = provider["getPersistedViewStates"]({ fresh: true }) + const { getProfile, resolveProfile } = stallProviderSettingsProfile(provider) + // No custom modes exist, so the persisted builtin slug resolves without a lookup. + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + await provider.contextProxy.setValue("viewStates", { + "u7-167-reapply-view": { + mode: "code", + currentApiConfigName: "cfg-a", + updatedAt: 1, + claimToken: "seeded-claim", + }, + }) + // A buffer write earlier in this session already raised this field's revision, so the load + // must compare the field against the revision it started from rather than against zero: + // otherwise that earlier write reads as an edit made during the lookup and the durable + // profile name is dropped although nobody touched the field. + provider["_updateViewLocalStateFromMutation"]({ currentApiConfigName: "prior-buffer-profile" }) + const load = provider["setViewStateId"]("u7-167-reapply-view", "seeded-claim") + await vi.waitFor(() => { + expect(getProfile).toHaveBeenCalledTimes(1) + }) + // Only another field moves while the profile is still resolving. + await provider.saveViewState("mode", "plan") + resolveProfile({ + name: "cfg-a", + id: "cfg-a-id", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + await load + expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-a") + expect(provider["viewLocalState"].mode).toBe("plan") + expect(provider["viewLocalState"].apiConfiguration).toMatchObject({ + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + await provider.dispose() + await provider.contextProxy.setValue("viewStates", priorViewStates) + }) + + it("keeps a provider-settings edit made during the lookup out of the resolved profile", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Shared storage is snapshotted so this fixture leaves nothing behind for the tests + // that run after it. + const priorViewStates = provider["getPersistedViewStates"]({ fresh: true }) + const { getProfile, resolveProfile } = stallProviderSettingsProfile(provider) + // No custom modes exist, so the persisted builtin slug resolves without a lookup. + vi.spyOn(provider.customModesManager, "getCustomModes").mockResolvedValue([]) + await provider.contextProxy.setValue("viewStates", { + "u7-167-provider-key-view": { + mode: "code", + currentApiConfigName: "cfg-a", + updatedAt: 1, + claimToken: "seeded-claim", + }, + }) + const load = provider["setViewStateId"]("u7-167-provider-key-view", "seeded-claim") + await vi.waitFor(() => { + expect(getProfile).toHaveBeenCalledTimes(1) + }) + // A bare provider-settings key arrives while the profile lookup is in flight. It names no + // apiConfiguration field, so only the provider-settings branch can notice it; if that branch + // fails to raise the apiConfiguration revision the late profile overwrites the key. + provider["_updateViewLocalStateFromMutation"]({ apiKey: "written-during-lookup" }) + resolveProfile({ + name: "cfg-a", + id: "cfg-a-id", + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-x", + }) + await load + expect(provider["viewLocalState"].apiConfiguration).toMatchObject({ apiKey: "written-during-lookup" }) + expect(provider["viewLocalState"].apiConfiguration).not.toHaveProperty("openRouterModelId") + await provider.dispose() + await provider.contextProxy.setValue("viewStates", priorViewStates) + }) + + it("raises one field's mutation revision by exactly one per write", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The guard detects a mutation by inequality, so the counter has to move by exactly one: + // a write that decrements or that lands on another field leaves the guard blind. + expect(provider["viewLocalFieldRevisions"].get("mode")).toBeUndefined() + provider["_updateViewLocalStateFromMutation"]({ mode: "plan" }) + expect(provider["viewLocalFieldRevisions"].get("mode")).toBe(1) + provider["_updateViewLocalStateFromMutation"]({ mode: "code" }) + expect(provider["viewLocalFieldRevisions"].get("mode")).toBe(2) + expect(provider["viewLocalFieldRevisions"].has("currentApiConfigName")).toBe(false) + await provider.dispose() + }) + + it("claims a leftover temporary entry instead of adopting its fields", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Shared storage is snapshotted so this fixture leaves nothing behind for the tests + // that run after it. + const priorViewStates = provider["getPersistedViewStates"]({ fresh: true }) + // An earlier session left this entry under the name this instance just minted; this + // instance never authored it, so its first write claims the slot instead of merging into + // fields it never wrote. + await provider.contextProxy.setValue("viewStates", { + [provider.viewId]: { mode: "leftover-mode", currentApiConfigName: "leftover-profile", updatedAt: 1 }, + }) + await provider.saveViewState("mode", "fresh-mode") + const entry = provider["getPersistedViewStates"]({ fresh: true })[provider.viewId] + expect(entry).toMatchObject({ mode: "fresh-mode" }) + expect(entry).not.toHaveProperty("currentApiConfigName") + await provider.dispose() + await provider.contextProxy.setValue("viewStates", priorViewStates) + }) + + it("records the created provider boundary event with its payload fields", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The created row is the one event that says this provider came up, so its three payload + // fields are asserted here instead of leaving them to the recorder, which accepts any + // object shape it is handed. + const created = provider["diagnosticsRecorder"] + .snapshot(200) + .events.filter( + (event) => event.boundary === "provider" && event.phase === "success" && event.type === "created", + ) + expect(created).toHaveLength(1) + await provider.dispose() + }) + + it("seeds the embedding model profiles under their own global-state key at construction", async () => { + // The seed is not awaited by the constructor, so the key is what a consumer sees first: + // an empty key parks the profiles where no reader looks. Clearing the key first makes + // this read the write this instance makes and not one an earlier instance left behind. + await mockContext.globalState.update("codebaseIndexModels", undefined) + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await vi.waitFor(() => { + expect(mockContext.globalState.get("codebaseIndexModels")).toEqual(EMBEDDING_MODEL_PROFILES) + }) + expect(mockContext.globalState.get("")).toBeUndefined() + await provider.dispose() + }) + + it("forwards pending-edit store logging to the extension log", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The store owns its wording and this instance supplies the sink, so the row has to reach + // the output channel the user reads. + provider.setPendingEditOperation("u7-168-pending-edit-log", { + messageTs: 1, + editedContent: "draft", + messageIndex: 0, + apiConversationHistoryIndex: 0, + }) + expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( + expect.stringContaining("[PendingEditOperationStore.set] Set pending operation: u7-168-pending-edit-log"), + ) + await provider.dispose() + }) + + describe("getState view-local overlay", () => { + it("returns this view buffered mode, profile name and configuration from getState", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const bufferedConfig = { + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "model-under-review", + } + await provider["setViewStateId"]("overlay-sidebar-view") + await provider.saveViewState("mode", "architect") + await provider.saveViewState("currentApiConfigName", "my-profile") + await provider.saveViewState("apiConfiguration", bufferedConfig) + const state = await provider.getState() + // The buffer is written by every mutation path, so the read path has to serve it. + expect(state.mode).toBe("architect") + expect(state.currentApiConfigName).toBe("my-profile") + expect(state.apiConfiguration).toMatchObject(bufferedConfig) + await provider.dispose() + }) + it("falls back per field to the shared values for fields the buffer does not set", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // A raw ContextProxy write does not touch the buffer, so this is the shared side of the pair. + await provider.contextProxy.setValue("currentApiConfigName", "shared-profile") + await provider["setViewStateId"]("fallback-sidebar-view") + await provider.saveViewState("mode", "architect") + await provider.contextProxy.setValue("openRouterModelId", "shared-model") + const state = await provider.getState() + expect(state.mode).toBe("architect") + expect(state.currentApiConfigName).toBe("shared-profile") + expect(state.apiConfiguration.openRouterModelId).toBe("shared-model") + await provider.dispose() + await provider.dispose() + }) + }) + + describe("loadViewState", () => { + it("should keep viewLocalState empty when no stable per-view values exist", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await vi.waitFor(() => { + expect(provider["viewLocalState"]).toEqual({}) + }) + + const state = await provider.getState() + // No per-view entry: getState() falls back to the shared defaults. + expect(state.mode).toBe("code") + expect(state.currentApiConfigName).toBe("default") + + await provider.dispose() + }) + + it("should log and keep existing viewLocalState when loadViewState fails", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const logSpy = vi.spyOn(provider, "log") + + // Register a stable id so the load is not skipped by the ownership guard: + // only entries this instance authored are loaded under a temporary name. + await provider["setViewStateId"]("stable-sidebar-view") + + provider["viewLocalState"] = { mode: "architect" } + vi.spyOn(provider.contextProxy, "getValue").mockImplementation(() => { + throw new Error("load failed") + }) + + await provider["loadViewState"]() + + expect(provider["viewLocalState"].mode).toBe("architect") + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Error loading state")) + + await provider.dispose() + }) + }) + + describe("persisted view state pruning", () => { + it("should keep the newest 50 persisted view states", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const states = Object.fromEntries( + Array.from({ length: 55 }, (_, index) => [ + `view-${index}`, + { mode: `mode-${index}`, updatedAt: index }, + ]), + ) + + const pruned = provider["prunePersistedViewStates"](states) + + expect(Object.keys(pruned)).toHaveLength(50) + expect(pruned["view-54"]).toEqual({ mode: "mode-54", updatedAt: 54 }) + expect(pruned["view-5"]).toEqual({ mode: "mode-5", updatedAt: 5 }) + expect(pruned["view-4"]).toBeUndefined() + + await provider.dispose() + }) + }) + + it("should merge concurrent persisted updates from separate provider instances without lost viewStates", async () => { + const provider1 = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + + new WebviewFocusTracker(), + ) + const provider2 = new ClineProvider( + mockContext, + mockOutputChannel, + "editor", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + await provider1["setViewStateId"]("stable-sidebar-view") + await provider2["setViewStateId"]("stable-editor-view") + + await Promise.all([ + provider1.saveViewState("mode", "architect"), + provider2.saveViewState("currentApiConfigName", "editor-profile"), + ]) + + expect(mockContext.globalState.get("viewStates")).toMatchObject({ + "stable-sidebar-view": { mode: "architect" }, + "stable-editor-view": { currentApiConfigName: "editor-profile" }, + }) + + await provider1.dispose() + await provider2.dispose() + }) }) describe("webviewMessageHandler no-floating-promises coverage", () => {