Skip to content

Commit ab52cfc

Browse files
author
daewoongoh
committed
fix: address model selector review findings
Persist model changes through a host-side updateProfileModel that merges a patch into the latest stored profile inside the mutation queue, validates the expected provider, patch keys and organization allow-list. Gate router model requests on a real model field, abort them on unmount, show a loading state, make model items keyboard-selectable, and extend test coverage.
1 parent b697032 commit ab52cfc

28 files changed

Lines changed: 599 additions & 127 deletions

‎packages/types/src/vscode-extension-host.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,7 @@ export interface WebviewMessage {
469469
| "currentApiConfigName"
470470
| "saveApiConfiguration"
471471
| "upsertApiConfiguration"
472+
| "updateProfileModel"
472473
| "deleteApiConfiguration"
473474
| "loadApiConfiguration"
474475
| "loadApiConfigurationById"

‎src/core/webview/ClineProvider.ts‎

Lines changed: 115 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import {
5656
DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
5757
getModelId,
5858
isRetiredProvider,
59+
modelIdKeys,
5960
providerIdentifiers,
6061
} from "@roo-code/types"
6162
import { RateLimitClock, createRateLimitClock } from "../task/RateLimitClock"
@@ -191,6 +192,17 @@ function scheduleTask(
191192
})
192193
}
193194

195+
// Keys a model-selector patch may touch: model IDs plus settings reset on model change.
196+
const PROFILE_MODEL_PATCH_KEYS: ReadonlySet<string> = new Set([
197+
...modelIdKeys,
198+
"reasoningEffort",
199+
"modelMaxTokens",
200+
"modelMaxThinkingTokens",
201+
"awsCustomArn",
202+
"awsCustomArnBaseModelId",
203+
"awsModelContextWindow",
204+
])
205+
194206
type GetStateOptions = {
195207
includeTaskHistory?: boolean
196208
}
@@ -1880,49 +1892,9 @@ export class ClineProvider
18801892
activate: boolean = true,
18811893
): Promise<string | undefined> {
18821894
try {
1883-
return await this.enqueueProviderProfileMutation(async (signal) => {
1884-
// TODO: Do we need to be calling `activateProfile`? It's not
1885-
// clear to me what the source of truth should be; in some cases
1886-
// we rely on the `ContextProxy`'s data store and in other cases
1887-
// we rely on the `ProviderSettingsManager`'s data store. It might
1888-
// be simpler to unify these two.
1889-
const id = await this.providerSettingsManager.saveConfig(name, providerSettings)
1890-
1891-
if (signal.aborted) return id
1892-
1893-
if (activate) {
1894-
const { mode } = await this.getState()
1895-
1896-
// These promises do the following:
1897-
// 1. Adds or updates the list of provider profiles.
1898-
// 2. Sets the current provider profile.
1899-
// 3. Sets the current mode's provider profile.
1900-
// 4. Copies the provider settings to the context.
1901-
//
1902-
// Note: 1, 2, and 4 can be done in one `ContextProxy` call:
1903-
// this.contextProxy.setValues({ ...providerSettings, listApiConfigMeta: ..., currentApiConfigName: ... })
1904-
// We should probably switch to that and verify that it works.
1905-
// I left the original implementation in just to be safe.
1906-
await Promise.all([
1907-
this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()),
1908-
this.updateGlobalState("currentApiConfigName", name),
1909-
this.providerSettingsManager.setModeConfig(mode, id),
1910-
this.contextProxy.setProviderSettings(providerSettings),
1911-
])
1912-
1913-
// Change the provider for the current task.
1914-
// TODO: We should rename `buildApiHandler` for clarity (e.g. `getProviderClient`).
1915-
this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
1916-
1917-
// Keep the current task's sticky provider profile in sync with the newly-activated profile.
1918-
await this.persistStickyProviderProfileToCurrentTask(name)
1919-
} else {
1920-
await this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig())
1921-
}
1922-
1923-
await this.postStateToWebview()
1924-
return id
1925-
})
1895+
return await this.enqueueProviderProfileMutation((signal) =>
1896+
this.persistProviderProfile(name, providerSettings, activate, signal),
1897+
)
19261898
} catch (error) {
19271899
this.log(
19281900
`Error create new api configuration: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
@@ -1933,6 +1905,106 @@ export class ClineProvider
19331905
}
19341906
}
19351907

1908+
/**
1909+
* Applies a model change to the latest stored profile inside the mutation queue,
1910+
* so a stale webview snapshot cannot overwrite newer profile settings.
1911+
* A `null` patch value clears the key.
1912+
*/
1913+
async updateProfileModel(name: string, expectedProvider: string, patch: Record<string, unknown>): Promise<void> {
1914+
try {
1915+
await this.enqueueProviderProfileMutation(async (signal) => {
1916+
const { name: _name, ...stored } = await this.providerSettingsManager.getProfile({ name })
1917+
1918+
if (stored.apiProvider !== expectedProvider) {
1919+
throw new Error(
1920+
`Profile "${name}" provider changed from "${expectedProvider}" to "${String(stored.apiProvider)}"`,
1921+
)
1922+
}
1923+
1924+
const merged: Record<string, unknown> = { ...stored }
1925+
1926+
for (const [key, value] of Object.entries(patch)) {
1927+
if (!PROFILE_MODEL_PATCH_KEYS.has(key)) {
1928+
throw new Error(`Key "${key}" is not allowed in a model patch`)
1929+
}
1930+
1931+
if (value === null || value === undefined) {
1932+
delete merged[key]
1933+
} else {
1934+
merged[key] = value
1935+
}
1936+
}
1937+
1938+
const { organizationAllowList } = await this.getState()
1939+
1940+
if (!ProfileValidator.isProfileAllowed(merged as ProviderSettings, organizationAllowList)) {
1941+
throw new OrganizationAllowListViolationError(t("common:errors.violated_organization_allowlist"))
1942+
}
1943+
1944+
if (signal.aborted) return
1945+
1946+
await this.persistProviderProfile(name, merged as ProviderSettings, true, signal)
1947+
})
1948+
} catch (error) {
1949+
this.log(`Error update profile model: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`)
1950+
1951+
vscode.window.showErrorMessage(
1952+
error instanceof OrganizationAllowListViolationError
1953+
? error.message
1954+
: t("common:errors.create_api_config"),
1955+
)
1956+
}
1957+
}
1958+
1959+
private async persistProviderProfile(
1960+
name: string,
1961+
providerSettings: ProviderSettings,
1962+
activate: boolean,
1963+
signal: AbortSignal,
1964+
): Promise<string | undefined> {
1965+
// TODO: Do we need to be calling `activateProfile`? It's not
1966+
// clear to me what the source of truth should be; in some cases
1967+
// we rely on the `ContextProxy`'s data store and in other cases
1968+
// we rely on the `ProviderSettingsManager`'s data store. It might
1969+
// be simpler to unify these two.
1970+
const id = await this.providerSettingsManager.saveConfig(name, providerSettings)
1971+
1972+
if (signal.aborted) return id
1973+
1974+
if (activate) {
1975+
const { mode } = await this.getState()
1976+
1977+
// These promises do the following:
1978+
// 1. Adds or updates the list of provider profiles.
1979+
// 2. Sets the current provider profile.
1980+
// 3. Sets the current mode's provider profile.
1981+
// 4. Copies the provider settings to the context.
1982+
//
1983+
// Note: 1, 2, and 4 can be done in one `ContextProxy` call:
1984+
// this.contextProxy.setValues({ ...providerSettings, listApiConfigMeta: ..., currentApiConfigName: ... })
1985+
// We should probably switch to that and verify that it works.
1986+
// I left the original implementation in just to be safe.
1987+
await Promise.all([
1988+
this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()),
1989+
this.updateGlobalState("currentApiConfigName", name),
1990+
this.providerSettingsManager.setModeConfig(mode, id),
1991+
this.contextProxy.setProviderSettings(providerSettings),
1992+
])
1993+
1994+
// Change the provider for the current task.
1995+
// TODO: We should rename `buildApiHandler` for clarity (e.g. `getProviderClient`).
1996+
this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
1997+
1998+
// Keep the current task's sticky provider profile in sync with the newly-activated profile.
1999+
await this.persistStickyProviderProfileToCurrentTask(name)
2000+
} else {
2001+
await this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig())
2002+
}
2003+
2004+
await this.postStateToWebview()
2005+
return id
2006+
}
2007+
19362008
async deleteProviderProfile(profileToDelete: ProviderSettingsEntry) {
19372009
const globalSettings = this.contextProxy.getValues()
19382010
let profileToActivate: string | undefined = globalSettings.currentApiConfigName

‎src/core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,97 @@ describe("ClineProvider - API Handler Rebuild Guard", () => {
428428
})
429429
})
430430

431+
describe("updateProfileModel", () => {
432+
const storedProfile = {
433+
name: "test-config",
434+
id: "test-id",
435+
apiProvider: providerIdentifiers.openrouter,
436+
openRouterModelId: "openai/gpt-4",
437+
rateLimitSeconds: 5,
438+
reasoningEffort: "high",
439+
}
440+
441+
beforeEach(() => {
442+
provider["providerSettingsManager"].getProfile = vi.fn().mockResolvedValue(storedProfile)
443+
vi.mocked(vscode.window.showErrorMessage).mockClear()
444+
})
445+
446+
test("merges the patch into the latest stored profile, keeping newer settings and clearing null keys", async () => {
447+
await provider.updateProfileModel("test-config", providerIdentifiers.openrouter, {
448+
openRouterModelId: "anthropic/claude",
449+
reasoningEffort: null,
450+
})
451+
452+
const saveConfig = vi.mocked(provider["providerSettingsManager"].saveConfig)
453+
expect(saveConfig).toHaveBeenCalledTimes(1)
454+
const [name, saved] = saveConfig.mock.calls[0]
455+
expect(name).toBe("test-config")
456+
expect(saved).toMatchObject({
457+
id: "test-id",
458+
apiProvider: providerIdentifiers.openrouter,
459+
openRouterModelId: "anthropic/claude",
460+
rateLimitSeconds: 5,
461+
})
462+
expect(saved).not.toHaveProperty("reasoningEffort")
463+
expect(saved).not.toHaveProperty("name")
464+
})
465+
466+
test("rebuilds the current task API handler with the new model", async () => {
467+
const mockTask = new Task({ ...defaultTaskOptions })
468+
mockTask.api = {
469+
getModel: vi.fn().mockReturnValue({ id: "openai/gpt-4", info: { contextWindow: 128000 } }),
470+
} as unknown as typeof mockTask.api
471+
await provider.addClineToStack(mockTask)
472+
473+
await provider.updateProfileModel("test-config", providerIdentifiers.openrouter, {
474+
openRouterModelId: "anthropic/claude",
475+
})
476+
477+
expect(mockTask.updateApiConfiguration).toHaveBeenCalledWith(
478+
expect.objectContaining({ openRouterModelId: "anthropic/claude" }),
479+
)
480+
})
481+
482+
test("rejects the update when the stored provider differs from the expected provider", async () => {
483+
await provider.updateProfileModel("test-config", providerIdentifiers.anthropic, {
484+
apiModelId: "claude-sonnet-4-5",
485+
})
486+
487+
expect(provider["providerSettingsManager"].saveConfig).not.toHaveBeenCalled()
488+
expect(vscode.window.showErrorMessage).toHaveBeenCalled()
489+
})
490+
491+
test("rejects patch keys outside the model and reset allow-list", async () => {
492+
await provider.updateProfileModel("test-config", providerIdentifiers.openrouter, {
493+
openRouterModelId: "anthropic/claude",
494+
openRouterApiKey: "stolen",
495+
})
496+
497+
expect(provider["providerSettingsManager"].saveConfig).not.toHaveBeenCalled()
498+
expect(vscode.window.showErrorMessage).toHaveBeenCalled()
499+
})
500+
501+
test("rejects a model that the organization allow-list forbids", async () => {
502+
const realGetState = provider.getState.bind(provider)
503+
vi.spyOn(provider, "getState").mockImplementation(async () => ({
504+
...(await realGetState()),
505+
organizationAllowList: {
506+
allowAll: false,
507+
providers: {
508+
[providerIdentifiers.openrouter]: { allowAll: false, models: ["openai/gpt-4"] },
509+
},
510+
},
511+
}))
512+
513+
await provider.updateProfileModel("test-config", providerIdentifiers.openrouter, {
514+
openRouterModelId: "anthropic/claude",
515+
})
516+
517+
expect(provider["providerSettingsManager"].saveConfig).not.toHaveBeenCalled()
518+
expect(vscode.window.showErrorMessage).toHaveBeenCalled()
519+
})
520+
})
521+
431522
describe("activateProviderProfile", () => {
432523
test("serializes provider profile mutations without interleaving", async () => {
433524
const events: string[] = []

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

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2368,3 +2368,44 @@ describe("webviewMessageHandler - telemetrySetting", () => {
23682368
expect(TelemetryService.instance.updateTelemetryState).not.toHaveBeenCalled()
23692369
})
23702370
})
2371+
2372+
describe("updateProfileModel", () => {
2373+
let updateProfileModel: Mock<ClineProvider["updateProfileModel"]>
2374+
2375+
beforeEach(() => {
2376+
vi.clearAllMocks()
2377+
updateProfileModel = vi.fn<ClineProvider["updateProfileModel"]>().mockResolvedValue(undefined)
2378+
mockClineProvider.updateProfileModel = updateProfileModel
2379+
})
2380+
2381+
it("delegates a valid message to the provider", async () => {
2382+
await webviewMessageHandler(mockClineProvider, {
2383+
type: "updateProfileModel",
2384+
text: "my-profile",
2385+
values: {
2386+
expectedProvider: providerIdentifiers.openrouter,
2387+
patch: { openRouterModelId: "a/b", reasoningEffort: null },
2388+
},
2389+
})
2390+
2391+
expect(updateProfileModel).toHaveBeenCalledWith("my-profile", providerIdentifiers.openrouter, {
2392+
openRouterModelId: "a/b",
2393+
reasoningEffort: null,
2394+
})
2395+
})
2396+
2397+
it.each([
2398+
["missing profile name", { values: { expectedProvider: providerIdentifiers.openrouter, patch: {} } }],
2399+
["missing expectedProvider", { text: "p", values: { patch: {} } }],
2400+
["non-object patch", { text: "p", values: { expectedProvider: providerIdentifiers.openrouter, patch: "x" } }],
2401+
["array patch", { text: "p", values: { expectedProvider: providerIdentifiers.openrouter, patch: [] } }],
2402+
["missing values", { text: "p" }],
2403+
])("ignores a malformed message: %s", async (_label, partial) => {
2404+
await webviewMessageHandler(mockClineProvider, {
2405+
type: "updateProfileModel",
2406+
...partial,
2407+
} as unknown as Parameters<typeof webviewMessageHandler>[1])
2408+
2409+
expect(updateProfileModel).not.toHaveBeenCalled()
2410+
})
2411+
})

‎src/core/webview/webviewMessageHandler.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2336,6 +2336,20 @@ export const webviewMessageHandler = async (
23362336
await provider.upsertProviderProfile(message.text, message.apiConfiguration)
23372337
}
23382338
break
2339+
case "updateProfileModel": {
2340+
const { expectedProvider, patch } = message.values ?? {}
2341+
2342+
if (
2343+
message.text &&
2344+
typeof expectedProvider === "string" &&
2345+
patch &&
2346+
typeof patch === "object" &&
2347+
!Array.isArray(patch)
2348+
) {
2349+
await provider.updateProfileModel(message.text, expectedProvider, patch)
2350+
}
2351+
break
2352+
}
23392353
case "renameApiConfiguration":
23402354
if (message.values && message.apiConfiguration) {
23412355
try {

0 commit comments

Comments
 (0)