Skip to content

Commit 090d2c8

Browse files
committed
fix(webview): send stable view-state id on launch and re-pin per-view state
WMH webviewDidLaunch persists the webview view-state id via provider.setViewStateId and re-pins the view-local currentApiConfigName through provider.saveViewState when the view-local profile is missing but the shared global selection is still valid. updateSettings is routed through provider.setValue so view-local buffer and pin sync stay consistent with the other mutation paths. The webview VSCodeAPIWrapper gains a stable getViewStateId persisted via setState (with an in-memory fallback) and the launch effect posts the id with the webviewDidLaunch message.
1 parent 43b52aa commit 090d2c8

6 files changed

Lines changed: 528 additions & 17 deletions

File tree

‎src/core/webview/__tests__/webviewMessageHandler.spec.ts‎

Lines changed: 117 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ vi.mock("@roo-code/telemetry", () => ({
6969
},
7070
}))
7171

72-
import type { ModelRecord } from "@roo-code/types"
72+
import type { ModelRecord, RooCodeSettings } from "@roo-code/types"
7373

7474
import { webviewMessageHandler } from "../webviewMessageHandler"
7575
import type { ClineProvider } from "../ClineProvider"
@@ -99,6 +99,7 @@ const mockFetchOpenAiCodexRateLimitInfo = vi.mocked(fetchOpenAiCodexRateLimitInf
9999
const mockClineProvider = {
100100
getState: vi.fn(),
101101
postMessageToWebview: vi.fn(),
102+
saveViewState: vi.fn(),
102103
customModesManager: {
103104
getCustomModes: vi.fn(),
104105
deleteCustomMode: vi.fn(),
@@ -115,6 +116,16 @@ const mockClineProvider = {
115116
setValue: vi.fn(),
116117
getValue: vi.fn(),
117118
},
119+
// Delegates to contextProxy.setValue so existing assertions keep holding while
120+
// the updateSettings flow is exercised through the provider-level mutation path.
121+
setValue: vi
122+
.fn()
123+
.mockImplementation((key: string, value: unknown) =>
124+
mockClineProvider.contextProxy.setValue(
125+
key as keyof RooCodeSettings,
126+
value as RooCodeSettings[keyof RooCodeSettings],
127+
),
128+
),
118129
log: vi.fn(),
119130
postStateToWebview: vi.fn(),
120131
resolveWebviewThemeFixtureProbe: vi.fn(),
@@ -261,6 +272,111 @@ import { Terminal } from "../../../integrations/terminal/Terminal"
261272
import { TerminalRegistry } from "../../../integrations/terminal/TerminalRegistry"
262273
import { providerIdentifiers, retiredProviderIdentifiers } from "@roo-code/types/provider-identifiers"
263274

275+
describe("webviewMessageHandler - webviewDidLaunch", () => {
276+
// Structural view of the provider members this suite reassigns at runtime: the
277+
// double literal does not declare them and some are readonly on the class, so a
278+
// cast of the mock target alone cannot express these reassignments without any.
279+
type LaunchProviderFixture = {
280+
setViewStateId: (viewStateId: string) => Promise<void>
281+
workspaceTracker: { initializeFilePaths: () => Promise<void> }
282+
providerSettingsManager: {
283+
listConfig: () => Promise<unknown[]>
284+
hasConfig: (name: string) => Promise<boolean>
285+
}
286+
activateProviderProfile: (options: { name: string }) => Promise<void>
287+
getMcpHub: () => unknown
288+
getStateToPostToWebview: () => Promise<{ telemetrySetting: string }>
289+
}
290+
const double = mockClineProvider as unknown as LaunchProviderFixture
291+
292+
beforeEach(() => {
293+
vi.clearAllMocks()
294+
vi.mocked(mockClineProvider.getState).mockResolvedValue({
295+
apiConfiguration: { apiProvider: providerIdentifiers.anthropic },
296+
currentApiConfigName: "view-local-profile",
297+
} as unknown as Awaited<ReturnType<typeof mockClineProvider.getState>>)
298+
double.setViewStateId = vi.fn().mockResolvedValue(undefined)
299+
double.workspaceTracker = { initializeFilePaths: vi.fn().mockResolvedValue(undefined) }
300+
double.providerSettingsManager = {
301+
listConfig: vi
302+
.fn()
303+
.mockResolvedValue([{ name: "shared-profile", apiProvider: providerIdentifiers.anthropic }]),
304+
hasConfig: vi.fn().mockResolvedValue(false),
305+
}
306+
double.activateProviderProfile = vi.fn().mockResolvedValue(undefined)
307+
double.getMcpHub = vi.fn().mockReturnValue(undefined)
308+
double.getStateToPostToWebview = vi.fn().mockResolvedValue({ telemetrySetting: "disabled" })
309+
vi.mocked(mockClineProvider.customModesManager.getCustomModes).mockResolvedValue([])
310+
// Key-aware so a mutated global-state key (e.g. "") resolves to nothing instead
311+
// of the canned value, keeping the re-pin branch's global lookup observable.
312+
vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) =>
313+
key === "currentApiConfigName" ? "shared-profile" : undefined,
314+
)
315+
vi.mocked(mockClineProvider.contextProxy.setValue).mockResolvedValue(undefined)
316+
})
317+
318+
it("validates the view-local currentApiConfigName on launch", async () => {
319+
await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" })
320+
await new Promise((resolve) => setImmediate(resolve))
321+
322+
expect(double.setViewStateId).toHaveBeenCalledWith("view-1")
323+
324+
// The merged (view-local) name is validated first; the shared global is only
325+
// consulted when the view-local name is invalid.
326+
expect(double.providerSettingsManager.hasConfig).toHaveBeenCalledWith("view-local-profile")
327+
expect(mockClineProvider.providerSettingsManager.hasConfig).toHaveBeenCalledWith("shared-profile")
328+
// Both names are invalid in this setup, so the shared global is repaired.
329+
expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("currentApiConfigName", "shared-profile")
330+
expect(mockClineProvider.activateProviderProfile).toHaveBeenCalledWith({ name: "shared-profile" })
331+
})
332+
333+
it("re-pins only the view when its profile is missing but the shared global is still valid", async () => {
334+
vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation(
335+
async (name: string) => name === "shared-profile",
336+
)
337+
await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" })
338+
await new Promise((resolve) => setImmediate(resolve))
339+
// The view pin is re-pinned to the first available profile,
340+
// and the shared global selection is left untouched: no global write, no global activation.
341+
expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("currentApiConfigName", "shared-profile")
342+
expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith(
343+
"currentApiConfigName",
344+
"shared-profile",
345+
)
346+
expect(mockClineProvider.activateProviderProfile).not.toHaveBeenCalled()
347+
})
348+
349+
it("re-pins the view to the shared global profile rather than the first listed profile", async () => {
350+
double.providerSettingsManager.listConfig = vi.fn().mockResolvedValue([
351+
{ name: "first-listed", apiProvider: providerIdentifiers.anthropic },
352+
{ name: "shared-profile", apiProvider: providerIdentifiers.anthropic },
353+
])
354+
vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockImplementation(
355+
async (name: string) => name === "shared-profile",
356+
)
357+
await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" })
358+
await new Promise((resolve) => setImmediate(resolve))
359+
// The view pin follows the still-valid shared global selection, not the first
360+
// profile in the list; the global selection is left untouched.
361+
expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("currentApiConfigName", "shared-profile")
362+
expect(mockClineProvider.saveViewState).not.toHaveBeenCalledWith("currentApiConfigName", "first-listed")
363+
expect(mockClineProvider.activateProviderProfile).not.toHaveBeenCalled()
364+
})
365+
366+
it("records the legacy repair without activating a profile when no name is listed", async () => {
367+
double.providerSettingsManager.listConfig = vi
368+
.fn()
369+
.mockResolvedValue([{ apiProvider: providerIdentifiers.anthropic }])
370+
vi.mocked(mockClineProvider.providerSettingsManager.hasConfig).mockResolvedValue(false)
371+
await webviewMessageHandler(mockClineProvider, { type: "webviewDidLaunch", viewStateId: "view-1" })
372+
await new Promise((resolve) => setImmediate(resolve))
373+
// The legacy repair still records the (empty) selection, but does not activate a
374+
// profile that has no name.
375+
expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("currentApiConfigName", undefined)
376+
expect(mockClineProvider.activateProviderProfile).not.toHaveBeenCalled()
377+
})
378+
})
379+
264380
describe("webviewMessageHandler - requestLmStudioModels", () => {
265381
beforeEach(() => {
266382
vi.clearAllMocks()

‎src/core/webview/webviewMessageHandler.ts‎

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -579,7 +579,9 @@ export const webviewMessageHandler = async (
579579
provider.resolveWebviewThemeFixtureProbe(message.requestId, message.themeFixture)
580580
}
581581
break
582-
case "webviewDidLaunch":
582+
case "webviewDidLaunch": {
583+
await provider.setViewStateId(message.viewStateId)
584+
583585
// Load custom modes first
584586
const customModes = await provider.customModesManager.getCustomModes()
585587
await updateGlobalState("customModes", customModes)
@@ -628,17 +630,36 @@ export const webviewMessageHandler = async (
628630
}
629631
}
630632

631-
const currentConfigName = getGlobalState("currentApiConfigName")
633+
const currentState = await provider.getState()
634+
const currentConfigName = currentState.currentApiConfigName
632635

633636
if (currentConfigName) {
634637
if (!(await provider.providerSettingsManager.hasConfig(currentConfigName))) {
635-
// Current config name not valid, get first config in list.
638+
// The merged name (which may be this view's durable pin) no longer
639+
// resolves. When the shared global selection is still valid, re-pin
640+
// only this view so the global selection is left untouched; only
641+
// repair the global when it is invalid as well.
642+
const globalConfigName = getGlobalState("currentApiConfigName")
643+
const globalStillValid =
644+
!!globalConfigName &&
645+
(await provider.providerSettingsManager.hasConfig(globalConfigName))
636646
const name = listApiConfig[0]?.name
637-
await updateGlobalState("currentApiConfigName", name)
638647

639-
if (name) {
640-
await provider.activateProviderProfile({ name })
641-
return
648+
if (globalStillValid && globalConfigName && name) {
649+
// Re-pin this view to the still-valid shared global selection (not the
650+
// first listed profile) so the view adopts the shared choice; the
651+
// global selection itself is left untouched.
652+
await provider.saveViewState("currentApiConfigName", globalConfigName)
653+
// Fall through: refresh listApiConfigMeta and post listApiConfig
654+
// to this webview below.
655+
} else {
656+
// Current config name not valid, get first config in list.
657+
await updateGlobalState("currentApiConfigName", name)
658+
659+
if (name) {
660+
await provider.activateProviderProfile({ name })
661+
return
662+
}
642663
}
643664
}
644665
}
@@ -688,6 +709,7 @@ export const webviewMessageHandler = async (
688709

689710
provider.isViewLaunched = true
690711
break
712+
}
691713
case "newTask":
692714
// Initializing new instance of Cline will make sure that any
693715
// agentically running promises in old instance don't affect our new
@@ -855,7 +877,9 @@ export const webviewMessageHandler = async (
855877
}
856878
}
857879

858-
await provider.contextProxy.setValue(key as keyof RooCodeSettings, newValue)
880+
// Route through provider.setValue so view-local buffer/pin sync stays
881+
// consistent with the other mutation paths.
882+
await provider.setValue(key as keyof RooCodeSettings, newValue)
859883
}
860884

861885
await provider.postStateToWebview()

‎webview-ui/src/context/ExtensionStateContext.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -515,7 +515,10 @@ export const ExtensionStateContextProvider: React.FC<{
515515
}, [handleMessage])
516516

517517
useEffect(() => {
518-
vscode.postMessage({ type: "webviewDidLaunch" })
518+
vscode.postMessage({
519+
type: "webviewDidLaunch",
520+
viewStateId: typeof vscode.getViewStateId === "function" ? vscode.getViewStateId() : undefined,
521+
})
519522
}, [])
520523

521524
// Apply the configurable chat font size as a CSS variable. When unset, the

‎webview-ui/src/context/__tests__/ExtensionStateContext.spec.tsx‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ import {
1515
} from "@roo-code/types"
1616

1717
import { ExtensionStateContextProvider, useExtensionState, mergeExtensionState } from "../ExtensionStateContext"
18+
import { vscode } from "@src/utils/vscode"
19+
20+
vi.mock("@src/utils/vscode", () => ({
21+
vscode: {
22+
postMessage: vi.fn(),
23+
getViewStateId: vi.fn(() => "view-a"),
24+
},
25+
}))
1826

1927
const TestComponent = () => {
2028
const { allowedCommands, setAllowedCommands, soundEnabled, showRooIgnoredFiles, setShowRooIgnoredFiles } =
@@ -105,7 +113,96 @@ const InitialStateTestComponent = () => {
105113
)
106114
}
107115

116+
const ViewLocalStateTestComponent = () => {
117+
const { mode, setMode, currentApiConfigName, setCurrentApiConfigName } = useExtensionState()
118+
119+
return (
120+
<div>
121+
<div data-testid="view-local-mode">{mode}</div>
122+
<div data-testid="view-local-api-config">{currentApiConfigName}</div>
123+
<button data-testid="set-local-mode" onClick={() => setMode("ask")}>
124+
Set Local Mode
125+
</button>
126+
<button data-testid="set-local-api-config" onClick={() => setCurrentApiConfigName("local-profile")}>
127+
Set Local API Config
128+
</button>
129+
</div>
130+
)
131+
}
132+
108133
describe("ExtensionStateContext", () => {
134+
beforeEach(() => {
135+
vi.clearAllMocks()
136+
})
137+
138+
it("posts webviewDidLaunch with the stable viewStateId from vscode API", () => {
139+
render(
140+
<ExtensionStateContextProvider>
141+
<TestComponent />
142+
</ExtensionStateContextProvider>,
143+
)
144+
145+
expect(vscode.getViewStateId).toHaveBeenCalled()
146+
expect(vscode.postMessage).toHaveBeenCalledWith({ type: "webviewDidLaunch", viewStateId: "view-a" })
147+
})
148+
149+
it("posts webviewDidLaunch without a viewStateId when getViewStateId is unavailable", () => {
150+
const savedGetViewStateId = vscode.getViewStateId
151+
Object.defineProperty(vscode, "getViewStateId", { configurable: true, value: undefined })
152+
try {
153+
render(
154+
<ExtensionStateContextProvider>
155+
<TestComponent />
156+
</ExtensionStateContextProvider>,
157+
)
158+
159+
expect(vscode.postMessage).toHaveBeenCalledWith({ type: "webviewDidLaunch", viewStateId: undefined })
160+
} finally {
161+
Object.defineProperty(vscode, "getViewStateId", { configurable: true, value: savedGetViewStateId })
162+
}
163+
})
164+
165+
it("reseeds view-local mode and API profile from a new state payload after local edits", () => {
166+
render(
167+
<ExtensionStateContextProvider>
168+
<ViewLocalStateTestComponent />
169+
</ExtensionStateContextProvider>,
170+
)
171+
172+
act(() => {
173+
window.dispatchEvent(
174+
new MessageEvent("message", {
175+
data: {
176+
type: "state",
177+
state: { mode: "code", currentApiConfigName: "profile-a", apiConfiguration: {} },
178+
},
179+
}),
180+
)
181+
})
182+
expect(screen.getByTestId("view-local-mode")).toHaveTextContent("code")
183+
expect(screen.getByTestId("view-local-api-config")).toHaveTextContent("profile-a")
184+
185+
act(() => {
186+
screen.getByTestId("set-local-mode").click()
187+
screen.getByTestId("set-local-api-config").click()
188+
})
189+
expect(screen.getByTestId("view-local-mode")).toHaveTextContent("ask")
190+
expect(screen.getByTestId("view-local-api-config")).toHaveTextContent("local-profile")
191+
192+
act(() => {
193+
window.dispatchEvent(
194+
new MessageEvent("message", {
195+
data: {
196+
type: "state",
197+
state: { mode: "architect", currentApiConfigName: "profile-b", apiConfiguration: {} },
198+
},
199+
}),
200+
)
201+
})
202+
expect(screen.getByTestId("view-local-mode")).toHaveTextContent("architect")
203+
expect(screen.getByTestId("view-local-api-config")).toHaveTextContent("profile-b")
204+
})
205+
109206
it("initializes with empty allowedCommands array", () => {
110207
render(
111208
<ExtensionStateContextProvider>

0 commit comments

Comments
 (0)