diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index f94eb1fbec..ec5a6056ba 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -74,6 +74,7 @@ import { isRetiredProvider, modelIdKeys, providerIdentifiers, + PROVIDER_SETTINGS_KEYS, } from "@roo-code/types" import { RateLimitClock, createRateLimitClock } from "../task/RateLimitClock" import { TaskRegistry } from "../task/TaskRegistry" @@ -164,8 +165,15 @@ import { PendingEditOperationStore, type PendingEditOperationInput } from "./Pen * 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 type PersistedViewState = NonNullable[string] +/** + * 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 @@ -273,6 +281,14 @@ type ViewStateWriteEntry = { readonly generation: number readonly run: (provider: ClineProvider) => Promise } +/** + * Result of registering a stable view id: whether the id was adopted, and what happened to + * the claim this registration minted or re-affirmed. + */ +export type ViewStateRegistrationResult = { adopted: boolean; claim: ViewStateClaimDelivery } + +/** The fields a view owns in its buffer and in its durable record. */ +type ViewLocalStateField = "mode" | "currentApiConfigName" | "apiConfiguration" /** Writes one field of a partial record, or deletes it when the update is nullish. */ function assignOrClearField(target: Partial, key: K, value: T[K] | null | undefined): void { @@ -1129,6 +1145,150 @@ export class ClineProvider } /** Register the stable view id and load its persisted selections; a claim must match. */ + public async setViewStateId( + viewStateId: string | undefined, + presentedClaim?: string, + ): Promise { + // A refused registration reports why and adopts nothing, and its claim field says + // explicitly that no claim came out of it. + const refuseRegistration = (detail: string): ViewStateRegistrationResult => { + this.log(`[setViewStateId] ${detail}`) + + return { adopted: false, claim: "none" } + } + // 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. + return refuseRegistration(`Ignoring a non-string viewStateId for view ${this.viewId}.`) + } + + const normalizedViewStateId = viewStateId.trim().replace(/[^A-Za-z0-9_-]/g, "_") + + // A load that failed leaves the id adopted (the re-key already moved the entry to the + // stable name) with the selections unrestored, so the unchanged-id guard must not + // swallow the retry: while a restoration is pending for this exact id the + // registration continues, and the claim check below still has to pass. + const restorationPending = this.pendingViewStateRestorations.has(normalizedViewStateId) + + if ( + !normalizedViewStateId || + (normalizedViewStateId === this.viewStateId && !restorationPending) || + // 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 { adopted: false, claim: "none" } + } + + // 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) { + return refuseRegistration( + `Ignoring an oversized viewStateId (${normalizedViewStateId.length} chars) for view ${this.viewId}.`, + ) + } + + 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. + return refuseRegistration( + `Refusing ${normalizedViewStateId} for view ${this.viewId}: already claimed by live view ${claimant.viewId}.`, + ) + } + + // 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] + + // What became of the claim this registration mints or re-affirms. A refused registration + // never reaches a claim, and an adopted one whose claim is still queued is not the same + // outcome as one the webview received, so both are reported to the caller. + let claimDelivery: ViewStateClaimDelivery = "none" + + 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. + return refuseRegistration( + `Refusing ${normalizedViewStateId} for view ${this.viewId}: bound concurrently by another registration.`, + ) + } + + claimDelivery = await 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. + return refuseRegistration( + `Refusing ${normalizedViewStateId} for view ${this.viewId}: claim missing or mismatched.`, + ) + } + } + + const previousViewStateId = this.viewStateId + const generation = this.viewStateGeneration + + 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) + + // 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 + + // A registration whose view was disposed mid-flight must not deliver a claim to + // a webview that is no longer there. + if (adoptedClaim && this.isViewStateGenerationLive(generation)) { + claimDelivery = await this.postViewStateClaimToWebview(this.viewStateId, adoptedClaim) + } else if (adoptedClaim) { + // The view was disposed mid-registration: the binding is durable but this provider + // will not post the claim again. + claimDelivery = "dropped" + } + + // Registration is what loads this view's own persisted selections. + await this.loadViewState() + } 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 + } + + return { adopted: true, claim: claimDelivery } + } + /** * Override EventEmitter's on method to match TaskProviderLike interface */ @@ -1435,6 +1595,11 @@ export class ClineProvider private clearWebviewResources() { this.rejectPendingThemeFixtureProbes(new Error("Webview was disposed before the theme fixture probe completed")) this.stopWebviewWatchdog() + // The renderer behind this view is gone or about to be replaced, and its message + // listener dies with it: a post can still resolve true while nobody is there to receive + // it. The flag goes down here so a claim minted before the replacement launches is held + // in the queue and flushed by that replacement's own `webviewDidLaunch`. + this.isViewLaunched = false // Invalidate any recovery reload still awaiting its HTML so it cannot // reassign webview.html on the disposed view. this.webviewRecoveryEpoch++ @@ -1497,6 +1662,8 @@ export class ClineProvider } this.scheduledViewStateWrites = [] + // A claim that never reached a webview dies with this view: nothing may re-post it later. + this.pendingViewStateClaims.clear() this._postStateToWebviewThrottled.cancel() this.stopWebviewWatchdog() this.diagnosticsRecorder.record({ boundary: "provider", phase: "start", type: "dispose" }) @@ -6037,4 +6204,184 @@ export class ClineProvider return vscode.Uri.file(filePath).toString() } } + + /** + * Saves a single view-local state value. The in-memory buffer is always updated; the + * non-secret subset (mode, currentApiConfigName) is persisted durably under the view + * id active when the change was made, re-keyed to the stable id on registration. + */ + public async saveViewState( + key: K, + value: PersistedViewStateValues[K] | undefined, + ): Promise { + const persistence = await this._saveViewLocalStateFromMutation({ [key]: value } as ViewLocalStateValues) + + this.log(`[saveViewState] Saved ${String(key)} for viewId ${this.viewId}`) + + return persistence + } + + /** + * Persists the view-local subset of a ContextProxy mutation, then updates the in-memory + * viewLocalState buffer. Persistence is awaited first so a failed durable write cannot + * leave the local cache ahead of the persisted state. + */ + private async _saveViewLocalStateFromMutation( + values: Partial & Partial, + ): Promise { + const persistence = await this._persistViewLocalStateFromMutation(values) + this._updateViewLocalStateFromMutation(values) + + return persistence + } + + /** + * 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. + */ + private bumpViewLocalStateWriteVersions(values: Partial & Partial): void { + if ("mode" in values) this.viewLocalStateWriteVersions.mode += 1 + if ("currentApiConfigName" in values) this.viewLocalStateWriteVersions.currentApiConfigName += 1 + if ("apiConfiguration" in values) this.viewLocalStateWriteVersions.apiConfiguration += 1 + } + + private _updateViewLocalStateFromMutation(values: Partial & Partial): void { + this.bumpViewLocalStateWriteVersions(values) + if ("mode" in values) assignOrClearField(this.viewLocalState, "mode", values.mode) + + if ("currentApiConfigName" in values) + assignOrClearField(this.viewLocalState, "currentApiConfigName", values.currentApiConfigName) + + if ("apiConfiguration" in values) { + assignOrClearField(this.viewLocalState, "apiConfiguration", values.apiConfiguration) + } else if (PROVIDER_SETTINGS_KEYS.some((key) => key in values)) { + 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, + } + } + } + + /** + * Writes the durably persisted subset of a mutation (mode and currentApiConfigName) + * into the registered viewStates map for this view. + */ + 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) { + return this.savePersistedViewState(persistedValues) + } + + // Nothing in this mutation belongs to the durable record, so there was nothing to write. + return { persisted: false, claim: "none" } + } + + /** Load non-secret persisted selections; in-flight buffer edits are reapplied on top. */ + private async loadViewState(): Promise { + // Capture the id this load is for: a newer id registered while an async + // profile lookup is in flight must not be overwritten by this stale load. + const loadedForViewId = this.viewStateId + + // While the stable id has not been registered yet, the key is this instance's + // session-local name. Temporary names restart from 0 on every host start, so an + // entry under the same name can belong to a different session. Load only entries + // this instance authored. + if (loadedForViewId === this.viewId && !this.wroteUnderTemporaryViewStateId) return + try { + const persisted = this.getPersistedViewStates()[loadedForViewId] + const loadedState: Partial = {} + + // Snapshot the in-memory buffer before the async profile lookup. The + // mutation paths update viewLocalState in place, so a shallow copy is + // what makes fields mutated during the load window observable below. + const preLoadVersions = { ...this.viewLocalStateWriteVersions } + + if (persisted?.mode) { + // A persisted mode may reference a custom mode that was deleted after it was + // pinned: restore it only when the slug still resolves, so a stale slug cannot + // 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 + } + + // Diff each field so in-flight edits win over the loaded values (including + // clears) while untouched fields keep the persisted values authoritative. + const postLoadBuffer = this.viewLocalState + const mergedState: Partial = { ...loadedState } + + const reapplyViewLocalField = (key: K): void => { + if (preLoadVersions[key] !== this.viewLocalStateWriteVersions[key]) { + const buffered = postLoadBuffer[key] + + if (buffered === undefined) { + delete mergedState[key] + } else { + mergedState[key] = buffered + } + } + } + + reapplyViewLocalField("mode") + reapplyViewLocalField("currentApiConfigName") + reapplyViewLocalField("apiConfiguration") + + this.viewLocalState = mergedState + this.pendingViewStateRestorations.delete(loadedForViewId) + this.log(`[loadViewState] Loaded state for viewId ${this.viewId}`) + } catch (error) { + // The load aborted, and `setViewStateId` keeps the id it adopted because the + // entry is already stored under the stable name. Record that this id is unrestored + // so the next registration of the same id is not swallowed by the unchanged-id + // guard; a completed load above clears it. + if (this.viewStateId === loadedForViewId) { + this.pendingViewStateRestorations.add(loadedForViewId) + } + this.log( + `[loadViewState] Error loading state for viewId ${this.viewId}: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } } diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 0be030752c..f042726dfb 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -15,6 +15,7 @@ import { type ClineMessage, type ExtensionMessage, type ExtensionState, + type GlobalState, type RooCodeSettings, type WebviewMessage, ORGANIZATION_ALLOW_ALL, @@ -5818,6 +5819,407 @@ 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 nothing is persisted under it. + expect(provider["viewStateId"]).toBe(provider.viewId) + expect(mockContext.globalState.get("viewStates")).toBeUndefined() + expect(provider["viewLocalState"]).toEqual({}) + + await provider.dispose() + }) + + it("rejects a non-string viewStateId from a crafted message and stays on the temporary id", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The message type declares a string, but a crafted postMessage can carry any JSON + // value, so the double assertion here is the crafted payload, not the call site. + const crafted = JSON.parse('{"viewStateId": 42}') as { viewStateId: string } + const statesBefore = mockContext.globalState.get("viewStates") + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(true) + const loggedBefore = (mockOutputChannel.appendLine as ReturnType).mock.calls.length + + await provider["setViewStateId"](crafted.viewStateId) + + expect(provider["viewStateId"]).toBe(provider.viewId) + // Nothing registered means nothing persisted, nothing loaded, and no claim posted. + expect(mockContext.globalState.get("viewStates")).toBe(statesBefore) + expect(provider["viewLocalState"]).toEqual({}) + expect( + postMessageSpy.mock.calls + .map(([message]) => message) + .filter((message) => message.type === "viewStateClaim"), + ).toHaveLength(0) + const loggedLines = (mockOutputChannel.appendLine as ReturnType).mock.calls + .slice(loggedBefore) + .map((call: unknown[]) => String(call[0])) + expect( + loggedLines.some((line) => line.includes("[setViewStateId] Ignoring a non-string viewStateId")), + ).toBe(true) + + postMessageSpy.mockRestore() + await provider.dispose() + }) + + it("rejects an empty viewStateId and keeps the temporary viewId", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const statesBefore = mockContext.globalState.get("viewStates") + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(true) + + await provider["setViewStateId"]("") + + // The empty id returns without a log line; the absence of every side effect is the + // evidence that registration never happened. + expect(provider["viewStateId"]).toBe(provider.viewId) + // Nothing registered means nothing persisted, nothing loaded, and no claim posted. + expect(mockContext.globalState.get("viewStates")).toBe(statesBefore) + expect(provider["viewLocalState"]).toEqual({}) + expect( + postMessageSpy.mock.calls + .map(([message]) => message) + .filter((message) => message.type === "viewStateClaim"), + ).toHaveLength(0) + postMessageSpy.mockRestore() + await provider.dispose() + }) + + it("rejects a whitespace-only viewStateId that normalizes to empty", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const statesBefore = mockContext.globalState.get("viewStates") + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(true) + + // Whitespace normalizes to the empty string, which is the same rejection. + await provider["setViewStateId"](" ") + + expect(provider["viewStateId"]).toBe(provider.viewId) + // Nothing registered means nothing persisted, nothing loaded, and no claim posted. + expect(mockContext.globalState.get("viewStates")).toBe(statesBefore) + expect(provider["viewLocalState"]).toEqual({}) + expect( + postMessageSpy.mock.calls + .map(([message]) => message) + .filter((message) => message.type === "viewStateClaim"), + ).toHaveLength(0) + postMessageSpy.mockRestore() + await provider.dispose() + }) + + it("rejects a viewStateId longer than the bound and logs the length", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const statesBefore = mockContext.globalState.get("viewStates") + const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(true) + const loggedBefore = (mockOutputChannel.appendLine as ReturnType).mock.calls.length + + // The webview generates a UUID; a 65-character value is not a view id and an + // unbounded key is unbounded growth in the shared viewStates map. + await provider["setViewStateId"]("v".repeat(65)) + + expect(provider["viewStateId"]).toBe(provider.viewId) + // Nothing registered means nothing persisted, nothing loaded, and no claim posted. + expect(mockContext.globalState.get("viewStates")).toBe(statesBefore) + expect(provider["viewLocalState"]).toEqual({}) + expect( + postMessageSpy.mock.calls + .map(([message]) => message) + .filter((message) => message.type === "viewStateClaim"), + ).toHaveLength(0) + const loggedLines = (mockOutputChannel.appendLine as ReturnType).mock.calls + .slice(loggedBefore) + .map((call: unknown[]) => String(call[0])) + expect(loggedLines.some((line) => line.includes("Ignoring an oversized viewStateId (65 chars)"))).toBe(true) + expect(mockContext.globalState.get("viewStates")).toBe(statesBefore) + + postMessageSpy.mockRestore() + await provider.dispose() + }) + + it("loads the persisted selections of the registered view", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.contextProxy.setValue("viewStates", { + "stable-view": { claimToken: "host-token", mode: "architect", currentApiConfigName: "cfg-a" }, + }) + + await provider["setViewStateId"]("stable-view", "host-token") + + // Registration is what loads a view's own selections. + expect(provider["viewLocalState"].mode).toBe("architect") + expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-a") + + await provider.dispose() + }) + it("normalises a registered viewStateId and keys the adopted entry by it", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // The key the host may store, plus a decoy under the raw name a normalizer never + // produces: adopting that entry would load another view's selections. + await provider.contextProxy.setValue("viewStates", { + norm_view: { claimToken: "norm-token", mode: "architect", currentApiConfigName: "cfg-norm" }, + "norm/view": { claimToken: "decoy-token", mode: "code", currentApiConfigName: "cfg-decoy" }, + "norm/view ": { claimToken: "decoy2-token", mode: "ask", currentApiConfigName: "cfg-decoy2" }, + }) + const result = await provider["setViewStateId"](" norm/view ", "norm-token") + expect(result.adopted).toBe(true) + expect(provider["viewStateId"]).toBe("norm_view") + // The selections that came through are the normalized key's, not the decoy's. + expect(provider["viewLocalState"].mode).toBe("architect") + expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-norm") + const states = provider["getPersistedViewStates"]() + // The durable entry the registration read and adopted is the normalized one, and + // nothing was ever stored under the padded name the webview actually sent. + expect(states["norm_view"].claimToken).toBe("norm-token") + expect(Object.keys(states)).not.toContain(" norm/view ") + // The decoys sit under names a normalizer never produces: adopted, they would load + // another view's selections; here they stay exactly as seeded. + expect(states["norm/view"].claimToken).toBe("decoy-token") + expect(states["norm/view"].mode).toBe("code") + expect(states["norm/view "].claimToken).toBe("decoy2-token") + await provider.dispose() + }) + + it("resolves to true when the webview accepts the message", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.resolveWebviewView({ ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } }) + // The spy replaces the resolve-time double so only this post is under test. + const postMessage = vi.spyOn(provider["view"]!.webview, "postMessage").mockResolvedValue(true) + await expect(provider.postMessageToWebview({ type: "action", action: "focusInput" })).resolves.toBe(true) + expect(postMessage).toHaveBeenCalledWith({ type: "action", action: "focusInput" }) + // The delivery result must reach the caller: a caller that rolls back on a failed + // post needs the true case to be true, not merely non-throwing. + await provider.dispose() + }) + + it("resolves to false when the webview refuses the delivery", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + await provider.resolveWebviewView({ ...mockWebviewView, webview: { ...mockWebviewView.webview, html: "" } }) + const postMessage = vi.spyOn(provider["view"]!.webview, "postMessage").mockResolvedValue(false) + await expect(provider.postMessageToWebview({ type: "action", action: "focusInput" })).resolves.toBe(false) + expect(postMessage).toHaveBeenCalledWith({ type: "action", action: "focusInput" }) + 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 through the real write path so the re-key has work to do. + 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. + expect(provider["viewStateId"]).toBe(provider.viewId) + + // A later retry succeeds once the storage write works again. + 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("persisted viewStates record hygiene", () => { + it("drops non-object entries so a corrupt record cannot reject a save", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + // Test data only, hence the assertion: a null or primitive entry is exactly what the + // persisted schema forbids and what a half-written or hand-edited record can still hold. + const corruptStates = { + "corrupt-view": null, + "primitive-view": "not-an-entry", + "healthy-view": { claimToken: "host-token", mode: "code", updatedAt: 5 }, + } as unknown as GlobalState["viewStates"] + await provider.contextProxy.setValue("viewStates", corruptStates) + + // Both read paths filter: the ContextProxy-cached copy (loadViewState reads it) and the + // fresh storage copy every serialized writer reads. + expect(provider["getPersistedViewStates"]()).not.toHaveProperty("corrupt-view") + expect(provider["getPersistedViewStates"]()).not.toHaveProperty("primitive-view") + expect(provider["getPersistedViewStates"]({ fresh: true })["corrupt-view"]).toBeUndefined() + expect(provider["getPersistedViewStates"]({ fresh: true })["healthy-view"]).toMatchObject({ + claimToken: "host-token", + mode: "code", + }) + + // Before the filter this rejects: prunePersistedViewStates sorts every entry by + // `updatedAt`, and reading it from a null entry throws inside the queued write. + await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 10 }) + + const stored = mockContext.globalState.get>("viewStates") ?? {} + expect(stored[provider["viewStateId"]]).toMatchObject({ mode: "architect" }) + expect(stored).not.toHaveProperty("corrupt-view") + expect(stored).not.toHaveProperty("primitive-view") + + await provider.dispose() + }) + + it("deletes the persisted mode when a view-local save clears it", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const stored = () => + mockContext.globalState.get>( + "viewStates", + ) ?? {} + + await provider.saveViewState("mode", "architect") + await provider.saveViewState("currentApiConfigName", "cfg-a") + expect(stored()[provider["viewStateId"]]).toMatchObject({ + mode: "architect", + currentApiConfigName: "cfg-a", + }) + + const cleared = await provider.saveViewState("mode", undefined) + expect(cleared).toEqual({ persisted: true, claim: "none" }) + expect(stored()[provider["viewStateId"]]).not.toHaveProperty("mode") + expect(stored()[provider["viewStateId"]]).toMatchObject({ currentApiConfigName: "cfg-a" }) + expect(provider["viewLocalState"]).not.toHaveProperty("mode") + expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-a") + + await provider.dispose() + }) + + it("removes the record when the last persisted field is cleared", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const stored = () => + mockContext.globalState.get>( + "viewStates", + ) ?? {} + + await provider.saveViewState("mode", "architect") + await provider.saveViewState("currentApiConfigName", "cfg-a") + expect(stored()).toHaveProperty(provider["viewStateId"]) + + await provider.saveViewState("mode", undefined) + const cleared = await provider.saveViewState("currentApiConfigName", undefined) + expect(cleared).toEqual({ persisted: true, claim: "none" }) + // Deleting the last field deletes the entry rather than leaving an empty shell behind. + expect(stored()).not.toHaveProperty(provider["viewStateId"]) + expect(provider["viewLocalState"]).toStrictEqual({}) + + await provider.dispose() + }) + it("evicts exactly the oldest entry when a save crosses the persisted-view cap", async () => { + const provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + const cap = ClineProvider["MAX_PERSISTED_VIEW_STATES"] + expect(cap).toBe(50) + + // One entry over the cap, each with its own timestamp so the eviction order is forced + // rather than left to insertion order. + const seeded: Record = {} + + for (let i = 0; i < cap; i++) { + seeded["seed-" + i] = { claimToken: "token-" + i, mode: "code", updatedAt: i + 1 } + } + + await provider.contextProxy.setValue("viewStates", seeded as GlobalState["viewStates"]) + + const saved = await provider["savePersistedViewState"]({ mode: "architect", updatedAt: cap + 1 }) + expect(saved).toEqual({ persisted: true, claim: "queued" }) + + const stored = + mockContext.globalState.get>("viewStates") ?? {} + expect(Object.keys(stored)).toHaveLength(cap) + expect(stored[provider["viewStateId"]]).toMatchObject({ mode: "architect", updatedAt: cap + 1 }) + // The oldest entry is the one that goes. A cap that evicted an arbitrary survivor + // would satisfy the count above just as easily. + expect(stored).not.toHaveProperty("seed-0") + expect(stored["seed-1"]).toMatchObject({ updatedAt: 2 }) + expect(stored["seed-" + (cap - 1)]).toMatchObject({ updatedAt: cap }) + // And the write that triggered the eviction is never the entry evicted by it. + expect(Object.keys(stored).filter((key) => key.startsWith("seed-"))).toHaveLength(cap - 1) + + await provider.dispose() + }) + }) }) describe("webviewMessageHandler no-floating-promises coverage", () => { diff --git a/src/core/webview/__tests__/ClineProvider.view-state-claim-guard.spec.ts b/src/core/webview/__tests__/ClineProvider.view-state-claim-guard.spec.ts new file mode 100644 index 0000000000..d8b6ef1e59 --- /dev/null +++ b/src/core/webview/__tests__/ClineProvider.view-state-claim-guard.spec.ts @@ -0,0 +1,361 @@ +import { WebviewFocusTracker } from "../WebviewFocusTracker" +// pnpm --dir src exec vitest run core/webview/__tests__/ClineProvider.view-state-claim-guard.spec.ts + +import * as vscode from "vscode" +import { makeCompositeDisposable } from "../../../test-utils/vscode" + +import { TelemetryService } from "@roo-code/telemetry" + +import { ContextProxy } from "../../config/ContextProxy" +import { ClineProvider } from "../ClineProvider" + +// Mock setup +vi.mock("fs/promises", () => ({ + mkdir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), + readFile: vi.fn().mockResolvedValue(""), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("../../../utils/storage", () => ({ + getSettingsDirectoryPath: vi.fn().mockResolvedValue("/test/settings/path"), + getTaskDirectoryPath: vi.fn().mockResolvedValue("/test/task/path"), + getGlobalStoragePath: vi.fn().mockResolvedValue("/test/storage/path"), +})) + +vi.mock("p-wait-for", () => ({ + __esModule: true, + default: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("delay", () => { + const delayFn = (_ms: number) => Promise.resolve() + delayFn.createDelay = delayFn + delayFn.reject = delayFn + delayFn.range = delayFn + return { default: delayFn } +}) + +vi.mock("vscode", () => ({ + ExtensionContext: vi.fn(), + OutputChannel: vi.fn(), + WebviewView: vi.fn(), + Disposable: { from: (...subscriptions: vscode.Disposable[]) => makeCompositeDisposable(...subscriptions) }, + Uri: { + joinPath: vi.fn(), + file: vi.fn(), + }, + commands: { + executeCommand: vi.fn().mockResolvedValue(undefined), + }, + window: { + showInformationMessage: vi.fn(), + showWarningMessage: vi.fn(), + showErrorMessage: vi.fn(), + onDidChangeActiveTextEditor: vi.fn(() => ({ dispose: vi.fn() })), + }, + workspace: { + getConfiguration: vi.fn().mockReturnValue({ + get: vi.fn().mockReturnValue([]), + update: vi.fn(), + }), + onDidChangeConfiguration: vi.fn().mockImplementation(() => { + return { + dispose: vi.fn(), + } + }), + }, + env: { + uriScheme: "vscode", + language: "en", + appName: "Visual Studio Code", + }, + extensions: { + all: [], + }, + ExtensionMode: { + Production: 1, + Development: 2, + Test: 3, + }, + version: "1.85.0", +})) + +vi.mock("../../../utils/tts", () => ({ + setTtsEnabled: vi.fn(), + setTtsSpeed: vi.fn(), +})) + +vi.mock("../../../api", () => ({ + buildApiHandler: vi.fn(), +})) + +vi.mock("../../../integrations/workspace/WorkspaceTracker", () => { + return { + default: vi.fn().mockImplementation(function () { + return { + initializeFilePaths: vi.fn(), + dispose: vi.fn(), + } + }), + } +}) + +vi.mock("../../task/Task", () => ({ + Task: vi.fn().mockImplementation(() => ({ + taskId: "mock-task-id", + instanceId: "mock-instance-id", + abortTask: vi.fn().mockResolvedValue(undefined), + emit: vi.fn(), + })), +})) + +vi.mock("@roo-code/cloud", () => ({ + CloudService: { + hasInstance: vi.fn().mockReturnValue(true), + get instance() { + return { + isAuthenticated: vi.fn().mockReturnValue(false), + off: vi.fn(), + } + }, + }, + getRooCodeApiUrl: vi.fn().mockReturnValue("https://app.roocode.com"), +})) + +vi.mock("../../../integrations/theme/getTheme", () => ({ + getTheme: vi.fn().mockResolvedValue({ kind: "dark" }), +})) + +vi.mock("../webviewMessageHandler", () => ({ + webviewMessageHandler: vi.fn().mockResolvedValue(undefined), +})) + +/** An emitter-backed vscode.Event that also reports how many listeners are installed. */ + +describe("ClineProvider - view-state claim guard", () => { + let provider: ClineProvider + let mockContext: vscode.ExtensionContext + let mockOutputChannel: vscode.OutputChannel + + beforeEach(() => { + vi.clearAllMocks() + + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } + + const globalState: Record = { + mode: "code", + currentApiConfigName: "test-config", + } + + const secrets: Record = {} + + // Structural double providing only the storage members ClineProvider and ContextProxy read. + mockContext = { + extensionPath: "/test/path", + extensionUri: { fsPath: "/test/path" }, + globalState: { + get: vi.fn().mockImplementation((key: string) => globalState[key]), + update: vi.fn().mockImplementation((key: string, value: unknown) => { + globalState[key] = value + return Promise.resolve() + }), + keys: vi.fn().mockImplementation(() => Object.keys(globalState)), + }, + secrets: { + get: vi.fn().mockImplementation((key: string) => secrets[key]), + store: vi.fn().mockImplementation((key: string, value: string | undefined) => { + secrets[key] = value + return Promise.resolve() + }), + delete: vi.fn().mockImplementation((key: string) => { + delete secrets[key] + return Promise.resolve() + }), + }, + workspaceState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + subscriptions: [], + extension: { + packageJSON: { version: "1.0.0" }, + }, + globalStorageUri: { + fsPath: "/test/storage/path", + }, + } as unknown as vscode.ExtensionContext + + // Structural double providing only the logging members ClineProvider calls. + mockOutputChannel = { + appendLine: vi.fn(), + clear: vi.fn(), + dispose: vi.fn(), + } as unknown as vscode.OutputChannel + + provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + }) + + afterEach(async () => { + await provider.dispose() + }) + + // A second live instance, built the same way the harness builds the first, so the claim guard has a claimant to find. + const makeOther = () => + new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockContext), + new WebviewFocusTracker(), + ) + + const ID = "view-state-claim-guard-case-1" + const EXACT = "v".repeat(64) + const TOO_LONG = "v".repeat(65) + + test("a non-string view state id is refused with an explicit empty claim", async () => { + const result = await provider.setViewStateId(undefined) + expect(result).toEqual({ adopted: false, claim: "none" }) + }) + + test("re-registering the id this view already holds adopts nothing and claims nothing", async () => { + const first = await provider.setViewStateId(ID) + expect(first.adopted).toBe(true) + const again = await provider.setViewStateId(ID) + expect(again).toEqual({ adopted: false, claim: "none" }) + }) + + // The claim field reports what a registration delivered to the renderer and reads none for a quiet adoption, so the guard branches are separated by adopted rather than by claim. + test("the length guard cuts off above 64 characters and not at the boundary", async () => { + const boundary = await provider.setViewStateId(EXACT) + const over = await provider.setViewStateId(TOO_LONG) + expect(over).toEqual({ adopted: false, claim: "none" }) + expect(boundary.adopted).toBe(true) + }) + + test("a live second instance holding the id is found as the claimant", async () => { + const other = makeOther() + await other.setViewStateId(ID) + const contested = await provider.setViewStateId(ID) + expect(contested).toEqual({ adopted: false, claim: "none" }) + await other.dispose() + }) + + test("an unheld id takes the adoption path rather than the claimant refusal", async () => { + const uncontested = await provider.setViewStateId("unheld-view-state-id-for-claim-guard") + expect(uncontested.adopted).toBe(true) + }) + + test("the claimant refusal names the id and the live view that holds it", async () => { + const other = makeOther() + const appended: string[] = [] + mockOutputChannel.appendLine = (value?: string) => { + appended.push(String(value)) + } + await other.setViewStateId("shared-claimed-view-state-id") + await provider.setViewStateId("shared-claimed-view-state-id") + expect(appended.some((line: string) => line.includes("already claimed by live view"))).toBe(true) + expect(appended.some((line: string) => line.includes("shared-claimed-view-state-id"))).toBe(true) + await other.dispose() + }) + test("a live second instance holding a different id does not block this registration", async () => { + // Negative control for the claimant search at ClineProvider.ts line 1198. Stryker reports a + // surviving ConditionalExpression there with replacement true, which makes any other live + // provider count as the claimant regardless of which id it holds. The guard must refuse only + // the id that other instance actually holds, so an unrelated live instance must not turn a + // free id into a refusal. + const other = makeOther() + await other.setViewStateId("unrelated-view-state-id") + const mine = await provider.setViewStateId("guard-different-id-case") + expect(mine.adopted).toBe(true) + expect(mine).not.toEqual({ adopted: false, claim: "none" }) + await other.dispose() + }) + + test("an adopting registration reports the delivery value rather than only adopting", async () => { + // ClineProvider.ts line 1218 initialises the delivery value and Stryker reports a surviving + // StringLiteral there with replacement empty string, so an assertion on adopted alone cannot + // tell the sentinel from an empty value. The delivery channel this unit hands to its caller is + // the claim field, and a registration that adopts without handing a claim to a renderer must + // report the sentinel exactly. + const adopted = await provider.setViewStateId("delivery-sentinel-id", "delivery-sentinel-claim") + expect(adopted.adopted).toBe(true) + expect(adopted.claim).toBe("none") + expect(adopted).toEqual({ adopted: true, claim: "none" }) + }) + + test("a persisted entry with no stored claim token gets a fresh binding", async () => { + // Negative control for the sibling mutants at lines 1220 and 1223: replacing the entry test or + // the stored-claim test with false skips the re-bind entirely, which leaves a pre-claim entry + // unbound and lets its unattributable selections survive under a key this view now owns. The + // observable is the entry itself, so the assertion reads the store rather than the result. + mockContext.globalState.update("viewStates", { "unbound-entry-id": {} }) + const result = await provider.setViewStateId("unbound-entry-id") + expect(result.adopted).toBe(true) + const stored = (mockContext.globalState.get("viewStates") as Record)[ + "unbound-entry-id" + ] + expect(typeof stored.claimToken).toBe("string") + expect(stored.claimToken && stored.claimToken.length > 0).toBe(true) + }) + test("a key bound while the re-bind was queued is refused with its reason", async () => { + // ClineProvider.ts line 1230 reports a re-bind that found the key already bound by a concurrent + // registration, and replacing that test with false adopts a key another webview now owns. The + // entry is read once without a claim token, which sends the re-bind off, and then read again + // with a token, which is what a competing registration leaves behind. The scripted double is a + // double assertion because the harness adds positional arguments that the public VS Code type + // of globalState.get omits. + const logged: string[] = [] + const previousAppend = mockOutputChannel.appendLine + mockOutputChannel.appendLine = (value: string) => { + logged.push(String(value)) + previousAppend(value) + } + const entryWithoutToken = { "concurrent-bind-id": { updatedAt: 1 } } + const entryWithToken = { "concurrent-bind-id": { claimToken: "concurrent-winner-token", updatedAt: 2 } } + const originalGet = mockContext.globalState.get as unknown as (key: string, ...rest: unknown[]) => unknown + let viewStatesReads = 0 + const scriptedGet = (key: string, ...rest: unknown[]) => { + if (key === "viewStates") { + viewStatesReads = viewStatesReads + 1 + return viewStatesReads === 1 ? entryWithoutToken : entryWithToken + } + return originalGet(key, ...rest) + } + mockContext.globalState.get = scriptedGet as unknown as typeof mockContext.globalState.get + const result = await provider.setViewStateId("concurrent-bind-id") + expect(result).toEqual({ adopted: false, claim: "none" }) + expect(logged.join("\n")).toContain("bound concurrently by another registration.") + }) + + test("an entry bound by a claim this view did not present is refused with its reason", async () => { + // ClineProvider.ts line 1243 fails closed when the entry carries a stored claim this launch did + // not present and line 1248 states the reason. An earlier case for this path asserted the + // adoption flag alone and was dropped; the reason string is what the surviving StringLiteral + // mutant needs, because replacing it with an empty template keeps the refusal and drops the + // explanation a maintainer would have to reconstruct from the code. + const logged: string[] = [] + const previousAppend = mockOutputChannel.appendLine + mockOutputChannel.appendLine = (value: string) => { + logged.push(String(value)) + previousAppend(value) + } + mockContext.globalState.update("viewStates", { + "foreign-claim-id": { claimToken: "foreign-token", updatedAt: 1 }, + }) + const mine = await provider.setViewStateId("foreign-claim-id", "a-different-token") + expect(mine).toEqual({ adopted: false, claim: "none" }) + expect(logged.join("\n")).toContain("claim missing or mismatched.") + }) +})