Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): compose a backend's model list from its providers (#1839)
Call White77c1fd8a4d02
diff --git a/ui/e2e/README.md b/ui/e2e/README.mdindex 02a58f015..48887d2df 100644--- a/ui/e2e/README.md+++ b/ui/e2e/README.md@@ -16,6 +16,12 @@ counterpart; if the pytest lane lands an orchestration that runs this suite andrecords its result, that runner — not the spec files — is what belongs in thecatalog.+A spec whose surface has no §3 family carries no id at all and states the+property in its title instead — `model-list.spec.ts` is one: §3 covers routing,+sources, guards and usage, but not the model list a backend routes. Inventing a+letter here would put a label in the spec titles that the plan cannot resolve,+so the id waits for the plan.+## What it talks to| Variable | Default | What it is |@@ -297,3 +303,17 @@ Recorded here so the gaps are visible rather than merely absent:run: the copy is reached by intercepting that one PATCH, and Chinese is aconfig-GET rewrite for that page only — the instance's language is neversaved.+- **A saved model list, and the routes an addition seeds.** `model-list.spec.ts`+ adds and then cancels, because the list it opens is the instance's own and a+ committed row changes what that backend offers its users — the suite owns its+ sources outright, but not a backend's model menu. So "the addition persists"+ and "the supplier chips a candidate was shown with are the hops its route is+ seeded with" are asserted where a disposable list can be saved and its chains+ read back, not here.+- **The models a backend can be given.** The picker's built-in and provider+ groups are one server read+ (`GET /api/models/agents/<backend>/models/candidates`). An instance that does+ not serve it skips that spec — an environmental fact, like a stopped runtime.+ Note that the status cannot establish it: the UI server's static catch-all+ answers an unmatched extension-less GET with `index.html` at 200, so+ `HubApi.servesModelCandidates` judges the payload instead.diff --git a/ui/e2e/model-list.spec.ts b/ui/e2e/model-list.spec.tsnew file mode 100644index 000000000..ffbb55410--- /dev/null+++ b/ui/e2e/model-list.spec.ts@@ -0,0 +1,154 @@+// A backend's model list: the one action that adds to it, the picker that+// action opens, and the editor the picker hands off to.+//+// No scenario ID. docs/plans/model-hub-e2e-test-plan.md §3 has no family for a+// backend's model list, and its Playwright scope for this round does not name+// one, so allocating an ID belongs to whoever owns that plan; until then these+// tests are named by the property they assert.+//+// Edited and then CANCELLED, for suite D's reason: the list here belongs to the+// instance, not to this suite, and a committed row changes what that backend+// actually offers its users. Two claims therefore sit with the integration pass+// that has the compose-from-providers server rather than in this file — that a+// saved addition persists, and that the supplier chips a candidate is shown+// with are exactly the hops its route is seeded with.+import { hub as copy, hubOrNull } from './support/copy';+import { E2E_SOURCE_PREFIX } from './support/env';+import {+ expectVisibleWithout,+ requireMockUpstream,+ requireModelHub,+ requireRuntimeRunning,+} from './support/fixtures';+import { expect, test } from './support/gateway';+import { labelledButton, pickerRowId } from './support/hub';++/** The product falls back to the raw backend id for a backend it has no label+ * for, so this does too rather than throwing on an id the bundle never named. */+const backendLabel = (backend: string): string => hubOrNull(`backends.${backend}`) ?? backend;++test.describe('Model list · what a backend can be given', () => {+ test.beforeEach(async ({ api, mock }) => {+ await requireModelHub(api);+ await requireRuntimeRunning(api);+ await requireMockUpstream(mock);+ });++ test('one way in, ending at an id the backend accepts, and a cancel that leaves nothing', async ({ hub, gateway }) => {+ await hub.goto();+ await hub.manageModelsButton(gateway.backend).click();++ const catalog = hub.catalogDialog;+ await expect(catalog).toBeVisible();+ // Enabled is this dialog's own "ready": it reads the saved list first, and+ // a backend whose list cannot be read offers nothing to add to it. Counting+ // rows before that would count a list still arriving.+ const addModels = labelledButton(catalog, copy('gateway.catalog.add'));+ await expect(addModels).toBeEnabled();+ const before = await hub.catalogRows.count();++ // One decision with a fallback, not two entry points to choose between: the+ // list's add action opens the picker, and the editor is reached from inside+ // it — never instead of it.+ await addModels.click();+ const picker = hub.pickerDialog;+ await expect(picker).toBeVisible();+ await expect(picker).toContainText(copy('gateway.picker.title', { backend: backendLabel(gateway.backend) }));+ await expect(hub.modelEditorDialog).toHaveCount(0);++ // The footer's own action, which is offered whatever the candidates read+ // did: a model nobody can list is exactly the one a user needs to type.+ await picker.getByRole('button', { name: copy('gateway.picker.custom'), exact: true }).click();+ const editor = hub.modelEditorDialog;+ await expect(editor).toBeVisible();++ // An id models.dev has never heard of, which is the case the typeahead's+ // last row exists for. That row is what this asserts, rather than the+ // matches above it: whether models.dev answers at all is a fact about this+ // instance's network, not about the product.+ const typed = `${E2E_SOURCE_PREFIX}model-${Date.now()}`;+ const field = hub.modelIdField;+ await field.fill(typed);+ const escape = hub.literalIdOption;+ await expect(escape).toBeVisible();+ const offered = (await escape.innerText()).trim();+ await escape.click();++ // What the row offered is what the field now holds, and it still carries+ // what was typed. A backend with an identifier scheme of its own resolves+ // the query into an id it will accept instead of refusing it later, so the+ // two are asserted as the same string rather than assumed to be the query.+ const created = await field.inputValue();+ expect(offered).toBe(copy('gateway.modelEditor.useAsId', { query: created }));+ expect(created).toContain(typed);++ await labelledButton(editor, copy('gateway.modelEditor.add')).click();+ await expect(editor).toHaveCount(0);+ await expect(hub.catalogRow(created)).toBeVisible();+ await expect(hub.catalogRows).toHaveCount(before + 1);++ // Cancelled, and what the cancel owes is nothing left behind: not on the+ // card the dialog was opened from, and not in the list the next read of it+ // builds — which is the instance's own answer, not this dialog's memory.+ await labelledButton(catalog, copy('gateway.catalog.cancel')).click();+ await expect(catalog).toHaveCount(0);+ await expectVisibleWithout(hub.agentCard(gateway.backend), created);++ await hub.manageModelsButton(gateway.backend).click();+ await expect(addModels).toBeEnabled();+ await expect(hub.catalogRow(created)).toHaveCount(0);+ await expect(hub.catalogRows).toHaveCount(before);+ await labelledButton(catalog, copy('gateway.catalog.cancel')).click();+ });++ test('every model the picker offers can be added, and the confirm says how many', async ({ api, hub, gateway }) => {+ test.skip(+ !(await api.servesModelCandidates(gateway.backend)),+ 'This instance does not serve the models a backend can be given '+ + '(GET /api/models/agents/<backend>/models/candidates), so the picker has no built-in group and no '+ + 'provider group to offer. That read arrives with the compose-from-providers server, and the '+ + 'integration pass on a server that has it is the layer that can execute this scenario.',+ );++ await hub.goto();+ await hub.manageModelsButton(gateway.backend).click();++ const catalog = hub.catalogDialog;+ const addModels = labelledButton(catalog, copy('gateway.catalog.add'));+ await expect(addModels).toBeEnabled();+ const before = await hub.catalogRows.count();++ await addModels.click();+ const picker = hub.pickerDialog;+ await expect(picker).toBeVisible();+ // Settled is either an offer or the answer that there is nothing to offer;+ // waiting on a row alone would spend the whole timeout on the second one.+ const offers = hub.pickerOffers;+ await expect(offers.first().or(picker.getByText(copy('gateway.picker.noMatch')))).toBeVisible();++ const available = await offers.count();+ test.skip(+ available === 0,+ 'Every model this instance can offer this backend is already in its list, so the picker has nothing '+ + 'left to add.',+ );++ // Two if the instance has two, because the confirm counts what was picked+ // and a count of one cannot tell a count from a constant.+ const take = Math.min(2, available);+ const picked: string[] = [];+ for (let index = 0; index < take; index += 1) {+ const row = offers.nth(index);+ picked.push(await pickerRowId(row));+ await row.click();+ }++ await labelledButton(picker, copy('gateway.picker.confirm', { count: take })).click();+ await expect(picker).toHaveCount(0);+ for (const id of picked) await expect(hub.catalogRow(id)).toBeVisible();+ await expect(hub.catalogRows).toHaveCount(before + take);++ await labelledButton(catalog, copy('gateway.catalog.cancel')).click();+ await expect(catalog).toHaveCount(0);+ });+});diff --git a/ui/e2e/support/api.ts b/ui/e2e/support/api.tsindex 630d324e2..32a0f17c4 100644--- a/ui/e2e/support/api.ts+++ b/ui/e2e/support/api.ts@@ -12,7 +12,7 @@// failures as routing failures.//// The line is: whatever the scenario is about goes through the browser.-import type { APIRequestContext } from '@playwright/test';+import type { APIRequestContext, APIResponse } from '@playwright/test';import { BASE_URL, E2E_SOURCE_PREFIX } from './env';@@ -244,19 +244,24 @@ export class HubApi {*/async read<T>(path: string): Promise<T> {const response = await this.request.get(path);- if (!response.ok()) {- const text = await response.text();- const refusal = remoteAuthRefusal(response.status(), text);- if (refusal) throw new Error(refusal);- throw new Error(- `GET ${path} → ${response.status()} ${response.statusText()}. `- + `This is the instance at ${BASE_URL} failing a read, not a missing capability: `- + `${text.slice(0, 300)}`,- );- }+ if (!response.ok()) throw await this.readFailure(path, response);return (await response.json()) as T;}+ /** The sentence a failed read owes the operator, kept in one place so a probe+ * that must not throw for one particular answer still throws it for every+ * other one. */+ private async readFailure(path: string, response: APIResponse): Promise<Error> {+ const text = await response.text();+ const refusal = remoteAuthRefusal(response.status(), text);+ if (refusal) return new Error(refusal);+ return new Error(+ `GET ${path} → ${response.status()} ${response.statusText()}. `+ + `This is the instance at ${BASE_URL} failing a read, not a missing capability: `+ + `${text.slice(0, 300)}`,+ );+ }+private async mutate(method: 'post' | 'patch' | 'delete' | 'put',path: string,@@ -306,6 +311,33 @@ export class HubApi {return (await this.read<{ agents: Agent[] }>('/api/models/agents')).agents ?? [];}+ /**+ * Whether this instance answers the read the picker's built-in and provider+ * groups are made of.+ *+ * Judged on the PAYLOAD, because the status cannot say. `vibe/ui_server.py`+ * registers its static catch-all last, and that route's SPA fallback answers+ * any unmatched extension-less GET with `index.html` at 200 — so an instance+ * that has never heard of this path reports the same status as one serving+ * it, and the browser's own failure there is a non-JSON body rather than a+ * named 404. Any other refusal is a read failing and throws: whether the Hub+ * is on at all is `requireModelHub`'s question, already answered.+ */+ async servesModelCandidates(backend: string): Promise<boolean> {+ const path = `/api/models/agents/${backend}/models/candidates`;+ const response = await this.request.get(path);+ if (response.status() === 404) return false;+ if (!response.ok()) throw await this.readFailure(path, response);+ let payload: unknown;+ try {+ payload = (await response.json()) as unknown;+ } catch {+ return false;+ }+ const candidates = (payload as { candidates?: unknown }).candidates;+ return typeof candidates === 'object' && candidates !== null;+ }+/** `null` here means the payload carried no `runtime` — an answered read with* nothing installed to describe, not a read that failed. */async runtime(): Promise<Runtime | null> {diff --git a/ui/e2e/support/hub.ts b/ui/e2e/support/hub.tsindex 478063e68..22c509e7f 100644--- a/ui/e2e/support/hub.ts+++ b/ui/e2e/support/hub.ts@@ -143,6 +143,15 @@ export class ModelHubPage {return this.agentCard(backend).getByRole('button', { name: hub('gateway.sourceOrder') });}+ /** The card's own "Manage models", scoped to the card head: a gateway backend+ * whose list is empty offers the same action a second time from the body,+ * and either one alone is the wrong thing for a name to match twice. */+ manageModelsButton(backend: string): Locator {+ return this.agentCard(backend)+ .locator('.model-hub-agent-head-action')+ .filter({ hasText: hub('gateway.manageModels') });+ }+// --- Dialogs --------------------------------------------------------------/** Add / replace API key. Both modes render the same surface. */@@ -278,8 +287,70 @@ export class ModelHubPage {get installDialog(): Locator {return this.page.locator('.model-hub-adopt-dialog').filter({ hasText: hub('install.title') });}++ // --- The backend's model list ---------------------------------------------++ /**+ * "Manage models" itself. The picker is built on the same surface — same+ * chrome, same search, same footer — and both can be mounted at once, which+ * is the whole point of the flow, so the class alone names two dialogs and+ * the list is the one that is not the picker.+ */+ get catalogDialog(): Locator {+ return this.page.locator('.model-hub-catalog-dialog:not(.model-hub-picker)');+ }++ get pickerDialog(): Locator {+ return this.page.locator('.model-hub-picker');+ }++ get modelEditorDialog(): Locator {+ return this.page.locator('.model-hub-model-editor');+ }++ get catalogRows(): Locator {+ return this.catalogDialog.locator('.model-hub-catalog-row');+ }++ /** One row of the list, named by the id the row shows. Exact, because the+ * list is where `claude-3-5` and `claude-3-5-haiku` sit next to each other,+ * and a row with no display name shows its id as the name instead — so the+ * text is asked of the row rather than of either span. */+ catalogRow(modelId: string): Locator {+ return this.catalogRows.filter({ has: this.page.getByText(modelId, { exact: true }) });+ }++ /** The candidates the picker is offering right now: a row for an id already+ * in the list is rendered checked and disabled, and adding it is not+ * something a user can do or a spec can ask for. */+ get pickerOffers(): Locator {+ return this.pickerDialog.locator('.model-hub-picker-row:not(:disabled)');+ }++ /** The editor's first field, which is also its models.dev search box. */+ get modelIdField(): Locator {+ return this.modelEditorDialog.getByLabel(hub('gateway.modelEditor.id.label'), { exact: true });+ }++ /** The last row of the editor's typeahead: take the query as the id. It is+ * present in every open state, including "searching" and "unavailable", and+ * it names the id it will actually create — which on a backend with an+ * identifier scheme of its own is not the query as typed. */+ get literalIdOption(): Locator {+ return this.modelEditorDialog.locator('.model-hub-model-match--literal');+ }}+/** The model id a picker row names, wherever that row put it: a candidate with+ * a display name shows the id beside the name, and one without shows the id AS+ * the name. */+export const pickerRowId = async (row: Locator): Promise<string> => {+ const beside = row.locator('.model-hub-picker-id');+ const asName = row.locator('.model-hub-picker-name--id');+ const text = (await beside.count()) > 0 ? await beside.innerText() : await asName.innerText();+ return text.trim();+};+/*** The button a user would READ as `name`, inside a surface that also has an* icon-only close carrying the same accessible name.diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsxindex 0fc377548..9dcbebe74 100644--- a/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx@@ -1,14 +1,14 @@// @vitest-environment jsdom-import { cleanup, render, screen, waitFor } from '@testing-library/react';+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { I18nextProvider } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';import i18n from '@/i18n';import { BackendModelCatalogDialog } from './BackendModelCatalogDialog';-import { blankBackendModel } from './backendCatalog';+import { blankBackendModel, candidateBackendModel } from './backendCatalog';import { ApiCallError, modelsApi } from './modelsApi';-import type { AgentSupply, BackendModel } from './types';+import type { AgentSupply, BackendModel, ModelCandidate, RouteHop } from './types';const model = (id: string, overrides: Partial<BackendModel> = {}): BackendModel => ({...blankBackendModel(),@@ -18,6 +18,42 @@ const model = (id: string, overrides: Partial<BackendModel> = {}): BackendModelconst locked = model('claude-default', { locked: true, routeable: false });+const candidate = (id: string, overrides: Partial<ModelCandidate> = {}): ModelCandidate => ({+ id,+ display_name: null,+ reasoning_efforts: [],+ suppliers: [],+ origin: 'provider',+ ...overrides,+});++/** What the one read behind the picker answers. Stubbed per test rather than by+ * default: a test that never opens the picker must not be able to pass on a+ * group it silently supplied. */+const offered = (groups: Partial<Record<'builtin' | 'providers' | 'in_list', ModelCandidate[]>> = {}) => ({+ builtin: groups.builtin ?? [],+ providers: groups.providers ?? [],+ in_list: groups.in_list ?? [],+});++/** The stale-candidate refusal: nothing was committed, and the `changed` map is+ * the whole answer — hence its own shape rather than a guard refusal. */+const staleCandidates = (changed: Record<string, RouteHop[]>) => new ApiCallError(+ 'candidate_suppliers_changed',+ 'modelHub.errors.candidate_suppliers_changed',+ true,+ [],+ [],+ [],+ 409,+ undefined,+ changed,+);++/** The confirmation lives inside the row it is about, and its Cancel is one of+ * three on screen. */+const confirmation = () => within(screen.getByRole('alert').parentElement as HTMLElement);+const agent = (catalog: BackendModel[] | undefined, overrides: Partial<AgentSupply> = {}): AgentSupply => ({backend: 'claude',cli_present: true,@@ -40,6 +76,11 @@ const renderDialog = (overrides: Partial<React.ComponentProps<typeof BackendMode<BackendModelCatalogDialogopenbackend="claude"+ canReadSources+ // Nothing named by default: what a hop reads as without the page's+ // Sources is the case every other test here is about, so a test that+ // wants a name says so.+ sourceNames={{}}onClose={onClose}onSaved={onSaved}onObserved={onObserved}@@ -99,17 +140,23 @@ describe('BackendModelCatalogDialog', () => {expect(screen.queryByText('src_a')).toBeNull();});- it('adds a model through the editor and settles the whole list in one write', async () => {+ it('adds what the providers offer, and promises the suppliers it displayed', async () => {const user = userEvent.setup();const catalog = [locked, model('alpha')];- const echoed = agent([...catalog, model('added')]);+ const glm = candidate('glm-5.2', {+ display_name: 'GLM 5.2',+ reasoning_efforts: ['low'],+ suppliers: [{ source_id: 'src_a', source_name: 'Primary relay', model_id: 'glm-5.2-air' }],+ });+ const echoed = agent([...catalog, model('glm-5.2')]);vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog));+ vi.spyOn(modelsApi, 'getAgentModelCandidates').mockResolvedValue(offered({ providers: [glm] }));const putAgentModels = vi.spyOn(modelsApi, 'putAgentModels').mockResolvedValue(echoed);const { onSaved, onClose } = renderDialog();- await user.click(await screen.findByRole('button', { name: 'Add model' }));- await user.type(screen.getByLabelText('Backend model ID'), 'added');- await user.click(screen.getByRole('button', { name: 'Add model' }));+ await user.click(await screen.findByRole('button', { name: 'Add models' }));+ await user.click(await screen.findByRole('checkbox', { name: /GLM 5\.2/ }));+ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));// Nothing is written until the list itself is saved.expect(putAgentModels).not.toHaveBeenCalled();@@ -119,12 +166,91 @@ describe('BackendModelCatalogDialog', () => {await waitFor(() => expect(putAgentModels).toHaveBeenCalledWith('claude', {baseline: catalog,- models: [...catalog, model('added')],+ models: [...catalog, candidateBackendModel(glm)],+ // Per addition, the projection the picker displayed for it. The server+ // matches the addition itself, so this is what makes the seeded route the+ // one the user agreed to rather than whatever supply exists at commit+ // time. The rows the baseline already holds are matched by nobody, so+ // promising anything about them would describe nothing this write does.+ expected_suppliers: { 'glm-5.2': [{ source_id: 'src_a', model_id: 'glm-5.2-air' }] },}));expect(onSaved).toHaveBeenCalledWith(echoed);expect(onClose).toHaveBeenCalled();});+ it('hands a model nobody offers to the editor, and promises nothing about it', async () => {+ const user = userEvent.setup();+ const catalog = [locked, model('alpha')];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog));+ vi.spyOn(modelsApi, 'getAgentModelCandidates').mockResolvedValue(offered());+ vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([]);+ const putAgentModels = vi.spyOn(modelsApi, 'putAgentModels').mockResolvedValue(agent([...catalog, model('added')]));+ renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Add models' }));+ await user.click(await screen.findByRole('button', { name: 'Add custom model…' }));+ await user.type(screen.getByLabelText('Model'), 'added');+ await user.click(screen.getByRole('button', { name: 'Add model' }));++ expect(await screen.findByText('3 models')).toBeTruthy();+ await user.click(screen.getByRole('button', { name: 'Save' }));++ // A row written by hand was never shown a supplier, so the write states no+ // expectation for it: there is nothing for the server to disagree with.+ await waitFor(() => expect(putAgentModels).toHaveBeenCalledWith('claude', {+ baseline: catalog,+ models: [...catalog, model('added')],+ }));+ });++ it('asks which row a typed ID names as the ID it would be saved as', async () => {+ const user = userEvent.setup();+ // The id the user types is not yet the id the row is saved under: on OpenCode+ // an unrecognized provider resolves to `custom/`, and the editor applies that+ // rule when it commits. So the lookup behind this door has to be asked about+ // the resolved id. Asked about the raw one it misses the row the user already+ // has and opens a blank one, which then commits over that same saved id and+ // drops everything they had described about it.+ const FOO = model('custom/foo', {+ display_name: 'Foo Air',+ context_window: 180000,+ origin: 'manual',+ });+ const catalog = [model('zai/glm-4.7'), FOO];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog, {+ backend: 'opencode',+ standard_vendors: ['zai'],+ }));+ // Nothing offered under this query, which is the only state that offers the+ // typed id as a custom model at all.+ vi.spyOn(modelsApi, 'getAgentModelCandidates').mockResolvedValue(offered());+ vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([]);+ const write = vi.spyOn(modelsApi, 'putAgentModels').mockResolvedValue(agent(catalog));+ renderDialog({ backend: 'opencode' });++ await user.click(await screen.findByRole('button', { name: 'Remove Foo Air' }));+ await user.click(screen.getByRole('button', { name: 'Add models' }));+ await user.type(await screen.findByLabelText('Search models or providers'), 'foo');+ await user.click(await screen.findByRole('button', { name: 'Add "foo" as a custom model…' }));++ // Their own row, opened as itself: the id fixed, and the description they+ // wrote still in it. The button is the tell — this is an edit, not an add.+ expect((await screen.findByLabelText('Model') as HTMLInputElement).value).toBe('custom/foo');+ expect((screen.getByLabelText('Display name') as HTMLInputElement).value).toBe('Foo Air');+ expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('180,000');+ await user.type(screen.getByLabelText('Maximum output'), '8000');+ await user.click(screen.getByRole('button', { name: 'Save model' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ // And the row goes back whole, changed only where they changed it. A blank+ // row carrying the same id would have saved this list with the name and the+ // window gone — the write is what the user would have to undo by hand.+ await waitFor(() => expect(write).toHaveBeenCalledWith('opencode', {+ baseline: catalog,+ models: [model('zai/glm-4.7'), { ...FOO, max_output_tokens: 8000 }],+ }));+ });+it('edits an existing row without renaming it', async () => {const user = userEvent.setup();const catalog = [model('alpha', { context_window: 1000 })];@@ -133,7 +259,7 @@ describe('BackendModelCatalogDialog', () => {renderDialog();await user.click(await screen.findByRole('button', { name: 'Edit alpha' }));- expect((screen.getByLabelText('Backend model ID') as HTMLInputElement).readOnly).toBe(true);+ expect((screen.getByLabelText('Model') as HTMLInputElement).readOnly).toBe(true);await user.clear(screen.getByLabelText('Context window'));await user.type(screen.getByLabelText('Context window'), '2000');await user.click(screen.getByRole('button', { name: 'Save model' }));@@ -145,21 +271,169 @@ describe('BackendModelCatalogDialog', () => {}));});- it('refuses to remove a model that still has a route', async () => {+ it('shows what a removal takes with it, then echoes the guard byte for byte whatever order it was clicked in', async () => {const user = userEvent.setup();- vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')], {- routes: { alpha: { hops: [{ source_id: 'src_a', model_id: 'alpha' }] } },+ const catalog = [model('alpha'), model('beta'), model('gamma')];+ /**+ * The server's plan, in the server's order: it walks the baseline it was+ * sent, so `beta` comes before `gamma` no matter which the user clicked+ * first. Written once, because it is the fixture for every half of the+ * property below — what each question shows, and what the forced save+ * carries, are these same bytes.+ */+ const hops = [+ { backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 },+ { backend: 'claude' as const, menu_model: 'beta', source_id: 'src_gone', model_id: 'beta-backup', position: 2 },+ { backend: 'claude' as const, menu_model: 'gamma', source_id: 'src_a', model_id: 'gamma-air', position: 1 },+ ];+ const routed = (menuModel: string) => hops.filter((hop) => hop.menu_model === menuModel);+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog, {+ routes: Object.fromEntries(['beta', 'gamma'].map((menuModel) => [+ menuModel,+ { hops: routed(menuModel).map(({ source_id, model_id }) => ({ source_id, model_id })) },+ ])),}));+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(new ApiCallError(+ 'backend_model_in_route',+ 'modelHub.errors.backend_model_in_route',+ true,+ [],+ [],+ hops,+ 409,+ ))+ .mockResolvedValue(agent([model('alpha')]));renderDialog();+ // A route is the only thing a removal takes with it that the user did not+ // name, so it is the only removal that asks — and it asks on the click,+ // from the routes the dialog already holds, not after a round-trip.await user.click(await screen.findByRole('button', { name: 'Remove alpha' }));- expect(screen.getByRole('alert').textContent).toBe('This model still has a route. Clear its route first, then remove it.');+ expect(screen.queryByRole('alert')).toBeNull();expect(screen.getByText('2 models')).toBeTruthy();- expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);await user.click(screen.getByRole('button', { name: 'Remove beta' }));+ const asked = screen.getByRole('alert');+ // The shared guard body, as the Route dialog shows it: every hop the plan+ // names, at the order it sits at, and however many there are.+ expect(asked.textContent).toContain('2 hops');+ for (const hop of routed('beta')) {+ expect(within(asked).getByText(`${hop.model_id} · Order #${hop.position}`)).toBeTruthy();+ }+ // Whether anything is stranded is the guard's answer, not this dialog's, so+ // the preview says what it knows and stays silent about the rest. Both+ // readings are withheld, not just the alarming one: 「still has another+ // source available」 is the dangerous half here, because it is a promise+ // about supply this dialog cannot see, made in the confirmation the user+ // decides on.+ expect(within(asked).queryByText('Models that will be left with no source')).toBeNull();+ expect(asked.textContent).not.toContain('These models still have another source available.');+ expect(asked.textContent).not.toContain('Some models will be left with no usable source.');+ expect(screen.getByText('2 models')).toBeTruthy();++ // Asking is not doing.+ await user.click(confirmation().getByRole('button', { name: 'Cancel' }));expect(screen.queryByRole('alert')).toBeNull();- expect(screen.getByText('1 model')).toBeTruthy();+ expect(screen.getByText('2 models')).toBeTruthy();++ // Answered in the order the user chose, which is the reverse of the order+ // the server will report them in.+ const clicked = ['gamma', 'beta'];+ for (const menuModel of clicked) {+ await user.click(screen.getByRole('button', { name: `Remove ${menuModel}` }));+ await user.click(confirmation().getByRole('button', { name: 'Remove' }));+ }+ expect(screen.getByText('0 models')).toBeTruthy();+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(write).toHaveBeenCalledTimes(2));+ // Nothing was asked twice: the guard named the consequences the user had+ // already accepted, so the retry is the dialog's own business rather than a+ // second confirmation of the same removal.+ expect(screen.queryByRole('alert')).toBeNull();+ const [first, second] = write.mock.calls.map(([, body]) => body as Record<string, unknown>);+ // The first attempt claims no agreement at all. Only the server states what+ // a write would take with it, so until it has, there is nothing to echo.+ expect(Object.keys(first)).toEqual(['baseline', 'models']);+ // The second is the refusal itself, byte for byte and in the server's own+ // order — byte-equal because that is how the server reads it, element by+ // element against what it sent, so the same consequences in another order+ // is a different answer and not the one it asked for.+ expect(second.force).toBe(true);+ expect(JSON.stringify(second.would_remove_hops)).toBe(JSON.stringify(hops));+ expect(JSON.stringify(second.would_interrupt)).toBe(JSON.stringify([]));+ // And the fixture earns that: the order the rows were clicked in is not the+ // order the echo carries, so nothing reassembled from the questions could+ // have passed the line above.+ expect(clicked).not.toEqual([...new Set(hops.map((hop) => hop.menu_model))]);+ });++ it('re-asks with the current suppliers when the ones it displayed went stale', async () => {+ const user = userEvent.setup();+ const catalog = [model('alpha')];+ const shown = candidate('glm-5.2', {+ display_name: 'GLM 5.2',+ suppliers: [{ source_id: 'src_a', source_name: 'Primary relay', model_id: 'glm-5.2-air' }],+ });+ const current = candidate('glm-5.2', {+ display_name: 'GLM 5.2',+ suppliers: [{ source_id: 'src_b', source_name: 'Backup relay', model_id: 'glm-5.2' }],+ });+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog));+ const read = vi.spyOn(modelsApi, 'getAgentModelCandidates')+ .mockResolvedValueOnce(offered({ providers: [shown] }))+ .mockResolvedValue(offered({ providers: [current] }));+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(staleCandidates({ 'glm-5.2': [{ source_id: 'src_b', model_id: 'glm-5.2' }] }))+ .mockResolvedValue(agent([...catalog, model('glm-5.2')]));+ const { onSaved, onObserved } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Add models' }));+ await user.click(await screen.findByRole('checkbox', { name: /Primary relay/ }));+ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ // Nothing was committed, so there is nothing to report and no list to+ // re-read: the answer to this refusal is the same question again, asked+ // against the suppliers the server matched this time.+ //+ // The candidates are read twice for that, and both reads have a job. The+ // refusal is reconciled against one — whether the id is still offered is+ // the only thing that withdraws it, and an answer that withdrew every pick+ // would open no picker to read it. The question then takes its own, because+ // the chips it shows are the promise its confirmation sends, and a picker+ // rendering a read it did not take would display one and send the other.+ expect(await screen.findByRole('checkbox', { name: /Backup relay/ })).toBeTruthy();+ expect(read).toHaveBeenCalledTimes(3);+ expect(onObserved).not.toHaveBeenCalled();+ expect(screen.queryByRole('status')).toBeNull();++ // Still picked, because it is still what the user asked for — only the+ // supply behind it changed.+ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ await waitFor(() => expect(write).toHaveBeenLastCalledWith('claude', expect.objectContaining({+ expected_suppliers: { 'glm-5.2': [{ source_id: 'src_b', model_id: 'glm-5.2' }] },+ })));+ expect(onSaved).toHaveBeenCalled();+ });++ it('offers no way in to a role that may not read Sources', async () => {+ // The candidates read names Sources, and the editor is reached through the+ // picker, so the whole add path goes where the page's other Source-reading+ // surfaces go. What is left is still a complete surface: the list, its+ // order, its edits and its removals.+ const read = vi.spyOn(modelsApi, 'getAgentModelCandidates');+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha')]));+ renderDialog({ canReadSources: false });++ expect(await screen.findByRole('button', { name: 'Reorder alpha' })).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Add models' })).toBeNull();+ expect(screen.getByRole('button', { name: 'Edit alpha' })).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Remove alpha' })).toBeTruthy();+ expect(read).not.toHaveBeenCalled();});it('reorders with the keyboard, announces the move, and leaves the locked row where it is', async () => {@@ -227,7 +501,7 @@ describe('BackendModelCatalogDialog', () => {expect(screen.getByText('legacy-b')).toBeTruthy();expect(screen.getByText('This model engine build does not offer an editable model list yet. These are the models it currently exposes.')).toBeTruthy();expect(screen.getByText('2 models')).toBeTruthy();- expect(screen.getByRole('button', { name: 'Add model' }).hasAttribute('disabled')).toBe(true);+ expect(screen.getByRole('button', { name: 'Add models' }).hasAttribute('disabled')).toBe(true);expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);expect(screen.queryByRole('button', { name: /^Reorder / })).toBeNull();expect(putAgentModels).not.toHaveBeenCalled();@@ -288,6 +562,686 @@ describe('BackendModelCatalogDialog', () => {expect(await screen.findByText('A model you removed still has a route. The list was re-read from the server; clear the route first, then remove it.')).toBeTruthy();});+ /**+ * The refusals that commit nothing, and the one property they share.+ *+ * Both are the server saying 「not on this plan」: the write did not land, so+ * the draft is still the user's and exactly one agreement inside it is out of+ * date. The failure mode both shipped with was answering that with an edit —+ * dropping the row the picker had asked about, rebasing the removal in as+ * though it had been agreed — which spends the user's work to settle a+ * question about the server's, and leaves the same refusal waiting on the next+ * save. So the members are the fixture: a refusal that commits nothing is+ * added to this list and inherits the whole property, or it is not added and+ * this file is where that shows.+ */+ describe('a refusal that committed nothing', () => {+ const ALPHA = model('alpha', { context_window: 1000 });+ /** A hand edit no refusal is about, so it has to survive every one of them. */+ const EDITED = model('alpha', { context_window: 2000 });+ const CATALOG = [ALPHA, model('beta')];++ const shown = candidate('glm-5.2', {+ display_name: 'GLM 5.2',+ suppliers: [{ source_id: 'src_a', source_name: 'Primary relay', model_id: 'glm-5.2-air' }],+ });+ const current = candidate('glm-5.2', {+ display_name: 'GLM 5.2',+ suppliers: [{ source_id: 'src_b', source_name: 'Backup relay', model_id: 'glm-5.2' }],+ });++ /** Widen one row's context window by hand, from the row's own editor. */+ const widen = async (user: ReturnType<typeof userEvent.setup>, row: string) => {+ await user.click(await screen.findByRole('button', { name: `Edit ${row}` }));+ await user.clear(screen.getByLabelText('Context window'));+ await user.type(screen.getByLabelText('Context window'), '2000');+ await user.click(screen.getByRole('button', { name: 'Save model' }));+ };++ type Member = {+ what: string;+ /** What the server serves. One answer, not a sequence: a refusal that+ * commits nothing has nothing to re-read, and the runner holds every+ * member to that — so a member needing a second answer here is a member+ * that has left this property. */+ read: AgentSupply;+ /** The draft the user builds, hand edit included — placed where this+ * refusal could spend it, which is the whole question. */+ arrange: (user: ReturnType<typeof userEvent.setup>) => Promise<void>;+ refusal: ApiCallError;+ /** The same question, asked again with what the server actually holds. */+ reasked: () => Promise<unknown>;+ answer: (user: ReturnType<typeof userEvent.setup>) => Promise<void>;+ /** Exactly the list the answered save sends. Exact, not 「contains」: a row+ * rebuilt from its candidate keeps the id and loses the edit. */+ models: BackendModel[];+ /** The fields that save adds, beyond the list itself. */+ agreement: Record<string, unknown>;+ };++ /**+ * The plan the server holds and the client could not see.+ *+ * Written once, because it is the fixture for both halves of the property:+ * what the confirmation shows and what the answered save echoes are the same+ * two arrays. It strands a model on purpose — a refusal that interrupts+ * something is still a question the user may answer, so the ask must carry+ * the interruption rather than be withheld because of it.+ */+ const GUARDED = {+ hops: [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 }],+ gaps: [{ backend: 'claude' as const, model_id: 'beta', agents: ['main'] }],+ };++ const MEMBERS: readonly Member[] = [+ {+ what: 'the suppliers the picker displayed went stale',+ read: agent(CATALOG),+ arrange: async (user) => {+ vi.spyOn(modelsApi, 'getAgentModelCandidates')+ .mockResolvedValueOnce(offered({ providers: [shown] }))+ .mockResolvedValue(offered({ providers: [current] }));+ await user.click(await screen.findByRole('button', { name: 'Add models' }));+ await user.click(await screen.findByRole('checkbox', { name: /Primary relay/ }));+ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ // On the added row itself: the refusal is about its suppliers, and+ // this is the work a rebuild from its candidate would cost.+ await widen(user, 'GLM 5.2');+ },+ refusal: staleCandidates({ 'glm-5.2': [{ source_id: 'src_b', model_id: 'glm-5.2' }] }),+ reasked: async () => {+ const row = await screen.findByRole('checkbox', { name: /Backup relay/ });+ // Offered back as pickable, not filed under 「Already in the list」:+ // the row is in the draft now, so the group that would claim it is+ // search-only and the user would be asked a question with nothing on+ // screen to answer it with.+ expect((row as HTMLInputElement).disabled).toBe(false);+ return row;+ },+ answer: async (user) => {+ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ },+ models: [ALPHA, model('beta'), { ...candidateBackendModel(shown), context_window: 2000 }],+ agreement: { expected_suppliers: { 'glm-5.2': [{ source_id: 'src_b', model_id: 'glm-5.2' }] } },+ },+ {+ what: 'a route the client could not see guarded the removal',+ // No route in the read at all: it was created after the baseline, which+ // is why the client removed the row without asking and only the server+ // could refuse it. And why the list is not read again — the refusal+ // answers the exact write that was sent, so the draft is rebased onto+ // the same baseline it was built from.+ read: agent(CATALOG),+ arrange: async (user) => {+ // A removal cannot carry an edit, so the work at stake is the rest of+ // the draft: this refusal hands the removal back, and rebasing it in+ // is where an edit goes missing.+ await widen(user, 'alpha');+ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ expect(screen.queryByRole('alert')).toBeNull();+ },+ refusal: new ApiCallError(+ 'backend_model_in_route',+ 'modelHub.errors.backend_model_in_route',+ true,+ GUARDED.gaps,+ [],+ GUARDED.hops,+ 409,+ ),+ // Asked through the same confirmation that records what a save may+ // force, and showing the whole plan the server named rather than the+ // empty one the client had — the same evidence body the Route dialog+ // shows, so a removal here and a route change there answer the same+ // question with the same words.+ reasked: async () => {+ const asked = await screen.findByRole('alert');+ for (const hop of GUARDED.hops) {+ expect(within(asked).getByText(`${hop.model_id} · Order #${hop.position}`)).toBeTruthy();+ }+ expect(within(asked).getByText('Models that will be left with no source')).toBeTruthy();+ for (const gap of GUARDED.gaps) {+ expect(within(asked).getByText(`Agents pinned to it: ${gap.agents.join(', ')}`)).toBeTruthy();+ }+ expect(asked.textContent).toContain('Some models will be left with no usable source.');+ return asked;+ },+ answer: async (user) => {+ await user.click(confirmation().getByRole('button', { name: 'Remove' }));+ },+ models: [EDITED],+ // Both arrays, because both were shown: an echo of one would claim a+ // confirmation for half of what the user answered.+ agreement: { force: true, would_remove_hops: GUARDED.hops, would_interrupt: GUARDED.gaps },+ },+ ];++ for (const member of MEMBERS) {+ it(`asks again and keeps the draft when ${member.what}`, async () => {+ const user = userEvent.setup();+ const read = vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(member.read);+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(member.refusal)+ .mockResolvedValue(agent([EDITED]));+ const { onSaved, onClose } = renderDialog();++ await member.arrange(user);+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ // The question again — never a sentence about a save that never+ // happened, and never a closed dialog.+ expect(await member.reasked()).toBeTruthy();+ expect(screen.queryByRole('status')).toBeNull();+ expect(onSaved).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ // And the list is never read a second time: a refusal commits nothing,+ // so the draft still stands on the baseline it was built from, and the+ // agreement below still answers the write that was actually sent.+ expect(read).toHaveBeenCalledTimes(1);++ await member.answer(user);+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ // One save per answer, carrying the draft the user built and the+ // agreement the server itself stated. Asserted on the last call because+ // the first is the refused one: an agreement granted without being+ // asked for would have gone out there.+ await waitFor(() => expect(write).toHaveBeenLastCalledWith('claude', expect.objectContaining({+ models: member.models,+ ...member.agreement,+ })));+ expect(write).toHaveBeenCalledTimes(2);+ });+ }++ it('withdraws a candidate the refreshed offer no longer holds, and re-sends the save it was already owed', async () => {+ const user = userEvent.setup();+ // Withdrawal has one source of evidence, and this is it: the refusal still+ // names suppliers for the picked id, and the refreshed offer does not hold+ // the id at all. So the answer is not another question — a row left in the+ // draft with no agreement behind it would go out on the next save as+ // though it had been typed by hand, which is the silent re-send the re-ask+ // exists to prevent.+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(CATALOG));+ const read = vi.spyOn(modelsApi, 'getAgentModelCandidates')+ .mockResolvedValueOnce(offered({ providers: [shown] }))+ .mockResolvedValue(offered());+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(staleCandidates({ 'glm-5.2': [{ source_id: 'src_b', model_id: 'glm-5.2' }] }))+ .mockResolvedValue(agent([EDITED, model('beta')]));+ const { onSaved, onClose } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Add models' }));+ await user.click(await screen.findByRole('checkbox', { name: /Primary relay/ }));+ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ await widen(user, 'alpha');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ // The row leaves, and it leaves without a question: nothing reopens for a+ // candidate the server has stopped offering. One read settled it — the+ // reconciliation takes its own, because a withdrawal that opens no picker+ // would otherwise never be read at all.+ await waitFor(() => expect(screen.queryByText('GLM 5.2')).toBeNull());+ expect(screen.queryByRole('heading', { name: 'Add Claude Code models' })).toBeNull();+ expect(read).toHaveBeenCalledTimes(2);+ // Nor a sentence about it: the row that disappeared and the count that fell+ // are the report, and a failure line here would be the dialog telling the+ // user about its own edit.+ expect(screen.queryByRole('status')).toBeNull();++ // And the save the user pressed is still owed — nothing was committed — so+ // it goes again on the reduced list rather than charging them a second+ // press for a withdrawal they did not make.+ await waitFor(() => expect(write).toHaveBeenCalledTimes(2));+ // The rest of the draft is still the user's, and the write claims nothing+ // beyond the list itself — an `expected_suppliers` entry would be an+ // agreement about a candidate that no longer exists, and there is no other+ // field this save was granted.+ const body = write.mock.lastCall?.[1] as Record<string, unknown>;+ expect(body.models).toEqual([EDITED, model('beta')]);+ expect(Object.keys(body)).toEqual(['baseline', 'models']);+ expect(onSaved).toHaveBeenCalled();+ expect(onClose).toHaveBeenCalled();+ });++ it('keeps a candidate the offer holds with no suppliers, and promises exactly that', async () => {+ const user = userEvent.setup();+ // The other side of the same definition: empty is not withdrawn. A+ // built-in the server still offers with nothing behind it is a candidate+ // whose route starts empty, and a refusal naming it with no suppliers is a+ // statement about supply, not about the offer. So the row stays, the+ // re-ask shows it claiming no supplier, and the save promises the empty+ // list the user agreed to — which is what lets the server seed an empty+ // route instead of matching a supplier nobody offered.+ const bare = candidate('glm-5.2', { display_name: 'GLM 5.2', origin: 'builtin' });+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(CATALOG));+ vi.spyOn(modelsApi, 'getAgentModelCandidates').mockResolvedValue(offered({ builtin: [bare] }));+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(staleCandidates({ 'glm-5.2': [] }))+ .mockResolvedValue(agent([...CATALOG, model('glm-5.2')]));+ const { onSaved } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Add models' }));+ await user.click(await screen.findByRole('checkbox', { name: /GLM 5\.2/ }));+ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ // Asked again rather than withdrawn, still picked, and showing the model+ // and nothing else: there is no supplier to name, and a chip here would be+ // the dialog claiming one on the server's behalf.+ const reasked = await screen.findByRole('checkbox', { name: /GLM 5\.2/ });+ expect(reasked.getAttribute('aria-checked')).toBe('true');+ expect((reasked as HTMLButtonElement).disabled).toBe(false);+ expect(reasked.textContent).toBe('GLM 5.2glm-5.2');+ expect(onSaved).not.toHaveBeenCalled();++ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ await waitFor(() => expect(write).toHaveBeenCalledTimes(2));+ const body = write.mock.lastCall?.[1] as Record<string, unknown>;+ expect(body.models).toEqual([...CATALOG, candidateBackendModel(bare)]);+ // Promised, not omitted: an addition with no entry is one the server+ // matches by its own reading, and 「nothing supplies this yet」 is a claim+ // only the user's agreement can carry.+ expect(body.expected_suppliers).toEqual({ 'glm-5.2': [] });+ });++ it('restores a refused removal to its own place, so cancelling it leaves nothing edited', async () => {+ const user = userEvent.setup();+ // A removal the server refuses was never a decision, so undoing it may not+ // cost the row its place: the requested list is the one it is already gone+ // from, and appending it back would answer 「are you sure?」 with a+ // reordered catalog the user never asked for. Cancelling then has to leave+ // the draft equal to the baseline, rows and order — the only state that+ // can honestly report itself as unedited.+ const rowOrder = () => screen.getAllByRole('button', { name: /^Reorder / })+ .map((row) => row.getAttribute('aria-label')?.replace('Reorder ', ''));+ vi.spyOn(modelsApi, 'getAgentSources')+ .mockResolvedValue(agent([model('alpha'), model('beta'), model('gamma')]));+ const write = vi.spyOn(modelsApi, 'putAgentModels').mockRejectedValue(new ApiCallError(+ 'backend_model_in_route',+ 'modelHub.errors.backend_model_in_route',+ true,+ [],+ [],+ GUARDED.hops,+ 409,+ ));+ const { onSaved, onClose } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ expect(rowOrder()).toEqual(['alpha', 'gamma']);+ await user.click(screen.getByRole('button', { name: 'Save' }));++ // Handed back into its own row, between the two it sat between — not after+ // the rows that outlived it.+ expect(await screen.findByRole('alert')).toBeTruthy();+ expect(rowOrder()).toEqual(['alpha', 'beta', 'gamma']);++ await user.click(confirmation().getByRole('button', { name: 'Cancel' }));+ expect(rowOrder()).toEqual(['alpha', 'beta', 'gamma']);+ // And nothing left to send, because nothing is different: a draft still+ // reporting itself as edited would offer a write that repeats the+ // baseline back to the server.+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);+ expect(write).toHaveBeenCalledTimes(1);+ expect(onSaved).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ });++ it('promises what the refreshed offer holds, whichever picks the refusal disputes', async () => {+ const user = userEvent.setup();+ // One refusal carrying both answers at once: a pick the offer has dropped+ // and a pick whose suppliers moved. The property is that the next write+ // promises exactly what the server just said is there — so the withdrawn+ // id may appear in neither the list nor the agreement, and the re-asked+ // one may appear in both only with today's suppliers.+ const kimi = candidate('kimi-3', {+ display_name: 'Kimi 3',+ suppliers: [{ source_id: 'src_a', source_name: 'Primary relay', model_id: 'kimi-3-turbo' }],+ });+ const kimiNow = candidate('kimi-3', {+ display_name: 'Kimi 3',+ suppliers: [{ source_id: 'src_b', source_name: 'Backup relay', model_id: 'kimi-3' }],+ });+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(CATALOG));+ vi.spyOn(modelsApi, 'getAgentModelCandidates')+ .mockResolvedValueOnce(offered({ providers: [shown, kimi] }))+ // The refreshed offer no longer holds `glm-5.2` at all. That, and not the+ // empty supplier list the refusal names it with, is what withdraws it.+ .mockResolvedValue(offered({ providers: [kimiNow] }));+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(staleCandidates({+ 'glm-5.2': [],+ 'kimi-3': [{ source_id: 'src_b', model_id: 'kimi-3' }],+ }))+ .mockResolvedValue(agent([...CATALOG, model('kimi-3')]));+ renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Add models' }));+ await user.click(await screen.findByRole('checkbox', { name: /GLM 5\.2/ }));+ await user.click(screen.getByRole('checkbox', { name: /Kimi 3/ }));+ await user.click(screen.getByRole('button', { name: 'Add 2 models' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ // Reconciled before anything reopens: the picker comes back seeded with the+ // one id that is still a question, and the other is already gone from the+ // draft — so this re-ask cannot be answered with an agreement the dialog+ // would have no way to discharge.+ expect(await screen.findByRole('checkbox', { name: /Backup relay/ })).toBeTruthy();+ expect(screen.queryByText('GLM 5.2')).toBeNull();+ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ await waitFor(() => expect(write).toHaveBeenCalledTimes(2));+ const body = write.mock.lastCall?.[1] as Record<string, unknown>;+ expect(body.models).toEqual([...CATALOG, candidateBackendModel(kimi)]);+ expect(body.expected_suppliers).toEqual({ 'kimi-3': [{ source_id: 'src_b', model_id: 'kimi-3' }] });+ });++ it('takes a dismissed re-ask as 「add none of these」, so a refused promise cannot be re-sent', async () => {+ const user = userEvent.setup();+ // The dead end this closes: one seeded id, unchecked, leaves the primary+ // with nothing to confirm — so walking away has to be an answer the dialog+ // acts on, or the refused projection is the only thing the next save can+ // send and the server refuses it again forever.+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(CATALOG));+ vi.spyOn(modelsApi, 'getAgentModelCandidates')+ .mockResolvedValueOnce(offered({ providers: [shown] }))+ .mockResolvedValue(offered({ providers: [current] }));+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(staleCandidates({ 'glm-5.2': [{ source_id: 'src_b', model_id: 'glm-5.2' }] }))+ .mockResolvedValue(agent(CATALOG));+ renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Add models' }));+ await user.click(await screen.findByRole('checkbox', { name: /Primary relay/ }));+ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ await screen.findByRole('checkbox', { name: /Backup relay/ });+ // Either control the picker offers to leave is the same answer, and the+ // dialog treats it as one: 「add none of these」.+ const [dismiss] = within(screen.getByRole('dialog', { name: 'Add Claude Code models' }))+ .getAllByRole('button', { name: 'Cancel' });+ await user.click(dismiss);++ // The row and its promise go together. What is left is the list the server+ // already holds, so there is nothing to save — the surest statement that+ // the refused projection cannot go out again.+ await waitFor(() => expect(screen.queryByText('GLM 5.2')).toBeNull());+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);+ expect(write).toHaveBeenCalledTimes(1);+ });++ it('takes the custom-model door out of a re-ask as the same 「add none of these」', async () => {+ const user = userEvent.setup();+ // The third way out of a seeded re-ask, and the one that does not answer+ // it: leaving by the editor confirms none of the seeded ids just as+ // walking away does, so their refused projections have to be discharged+ // on the way out. Kept, they are what the next Save would send — an+ // agreement the server has already refused, granted by a door.+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(CATALOG));+ vi.spyOn(modelsApi, 'getAgentModelCandidates')+ .mockResolvedValueOnce(offered({ providers: [shown] }))+ .mockResolvedValue(offered({ providers: [current] }));+ vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([]);+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(staleCandidates({ 'glm-5.2': [{ source_id: 'src_b', model_id: 'glm-5.2' }] }))+ .mockResolvedValue(agent(CATALOG));+ renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Add models' }));+ await user.click(await screen.findByRole('checkbox', { name: /Primary relay/ }));+ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ await screen.findByRole('checkbox', { name: /Backup relay/ });+ await user.click(screen.getByRole('button', { name: 'Add custom model…' }));++ // The editor is open on a blank row, and the seeded one left with its+ // promise: what remains is the list the server already holds, so there is+ // nothing to save — the surest statement that the refused projection+ // cannot go out again. Asked back at the catalog, since the door closed+ // the picker on its way out; the editor's own control is named for it,+ // because the catalog behind it carries that word too.+ expect((await screen.findByLabelText('Model') as HTMLInputElement).value).toBe('');+ const [leave] = within(screen.getByRole('dialog', { name: 'Add model' }))+ .getAllByRole('button', { name: 'Cancel' });+ await user.click(leave);+ await waitFor(() => expect(screen.queryByText('GLM 5.2')).toBeNull());+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);+ expect(write).toHaveBeenCalledTimes(1);+ });++ it('asks about every removal the guard held back, not just the first', async () => {+ const user = userEvent.setup();+ const catalog = [model('alpha'), model('beta'), model('gamma')];+ const routed = agent(catalog, {+ routes: {+ beta: { hops: [{ source_id: 'src_a', model_id: 'beta-air' }] },+ gamma: { hops: [{ source_id: 'src_a', model_id: 'gamma-air' }] },+ },+ });+ vi.spyOn(modelsApi, 'getAgentSources')+ .mockResolvedValueOnce(agent(catalog))+ .mockResolvedValue(routed);+ /** One hop per held-back removal. The fixture for the whole property:+ * each question shows its own hop, and the answered save echoes all of+ * them — so neither half may state the plan a second time. */+ const hops = [+ { backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 },+ { backend: 'claude' as const, menu_model: 'gamma', source_id: 'src_a', model_id: 'gamma-air', position: 1 },+ ];+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(new ApiCallError(+ 'backend_model_in_route',+ 'modelHub.errors.backend_model_in_route',+ true,+ [],+ [],+ hops,+ 409,+ ))+ .mockResolvedValue(agent([model('alpha')]));+ renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Remove gamma' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));++ // One question at a time, because the confirmation lives in the row it is+ // about — but every held-back removal gets one, carrying its own hop and+ // no one else's. A row handed back with no question is a removal the user+ // asked for that nobody answered; a question carrying the whole refusal+ // would ask each row to confirm the others.+ for (const hop of hops) {+ const asked = await screen.findByRole('alert');+ expect(within(asked).getByText(`${hop.model_id} · Order #${hop.position}`)).toBeTruthy();+ expect(asked.textContent).toContain('1 hop');+ await user.click(confirmation().getByRole('button', { name: 'Remove' }));+ }+ expect(screen.queryByRole('alert')).toBeNull();++ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(write).toHaveBeenLastCalledWith('claude', expect.objectContaining({+ models: [model('alpha')],+ force: true,+ would_remove_hops: hops,+ would_interrupt: [],+ })));+ });++ it('shows the row of whichever question is pending, whatever the search says', async () => {+ const user = userEvent.setup();+ // A question pending and a filter that matches none of the rows it is+ // about. The confirmation renders inside its row, so a filter that hid+ // that row would leave the draft holding a model the user removed, Save+ // disabled behind an unanswered question, and nothing on screen to+ // explain either — a dead end reachable by typing.+ const catalog = [model('alpha'), model('beta'), model('gamma')];+ const routed = agent(catalog, {+ routes: {+ beta: { hops: [{ source_id: 'src_a', model_id: 'beta-air' }] },+ gamma: { hops: [{ source_id: 'src_a', model_id: 'gamma-air' }] },+ },+ });+ vi.spyOn(modelsApi, 'getAgentSources')+ .mockResolvedValueOnce(agent(catalog))+ .mockResolvedValue(routed);+ const hops = [+ { backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 },+ { backend: 'claude' as const, menu_model: 'gamma', source_id: 'src_a', model_id: 'gamma-air', position: 1 },+ ];+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(new ApiCallError(+ 'backend_model_in_route',+ 'modelHub.errors.backend_model_in_route',+ true,+ [],+ [],+ hops,+ 409,+ ))+ .mockResolvedValue(agent([model('alpha')]));+ renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Remove gamma' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));+ await screen.findByRole('alert');+ await user.type(screen.getByLabelText('Search name or model ID'), 'alpha');++ for (const hop of hops) {+ // Whichever question is pending, its row is on screen with its own hop+ // and its own controls — and it is the only held-back row the search+ // lets through, so what put it there was the queue, not the query.+ const asked = await screen.findByRole('alert');+ expect(within(asked).getByText(`${hop.model_id} · Order #${hop.position}`)).toBeTruthy();+ expect(screen.getByText(hop.menu_model)).toBeTruthy();+ for (const other of hops.filter((entry) => entry !== hop)) {+ expect(screen.queryByText(other.menu_model)).toBeNull();+ }+ await user.click(confirmation().getByRole('button', { name: 'Remove' }));+ }++ // Queue empty, so the search is back in charge of the whole list.+ expect(screen.queryByRole('alert')).toBeNull();+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(write).toHaveBeenLastCalledWith('claude', expect.objectContaining({+ models: [model('alpha')],+ force: true,+ would_remove_hops: hops,+ would_interrupt: [],+ })));+ });++ it('discards a queued question whose row has already left the draft, and forces nothing on its behalf', async () => {+ const user = userEvent.setup();+ // The queue outlives the question on screen, and the rows behind the head+ // keep their own controls — so the user can remove one before its turn+ // comes. There is then nothing left to remove and nowhere to ask, because+ // the confirmation renders inside the row, so the question goes with the+ // row. Left pending it would be worse than invisible: it is the head, and+ // the row that could advance the queue is the one that is gone, so every+ // question behind it goes unasked and the removals the user did ask for+ // can never be confirmed — the guard would refuse the list forever.+ //+ // Discarding it keeps the queue live but settles nothing: the consequence+ // the server named for that row was never displayed. So the save that+ // follows goes out unforced, and the two properties hold together — the+ // dialog never stalls, and it never vouches for what it did not show.+ const catalog = [model('alpha'), model('beta'), model('gamma'), model('delta')];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog, {+ // The one route this dialog can see. The others were created after the+ // read, which is why only the server could refuse them.+ routes: { delta: { hops: [{ source_id: 'src_a', model_id: 'delta-air' }] } },+ }));+ const hops = [+ { backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 },+ { backend: 'claude' as const, menu_model: 'gamma', source_id: 'src_a', model_id: 'gamma-air', position: 1 },+ ];+ const refusal = () => new ApiCallError(+ 'backend_model_in_route',+ 'modelHub.errors.backend_model_in_route',+ true,+ [],+ [],+ hops,+ 409,+ );+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(refusal())+ // The same refusal, because nothing was accepted and so nothing about+ // the routes changed: an unforced save asks the guard the same question+ // and gets the same answer.+ .mockRejectedValueOnce(refusal())+ .mockResolvedValue(agent([model('alpha'), model('delta')]));+ renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Remove gamma' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));++ // Both removals come back with a question each, the first of them on+ // screen with the server's own hop.+ const asked = await screen.findByRole('alert');+ expect(within(asked).getByText('beta-air · Order #1')).toBeTruthy();++ // The user answers the second one their own way instead: gamma has no+ // route this dialog knows of, so it simply leaves — and takes both the+ // pending question and its own queued one with it.+ await user.click(screen.getByRole('button', { name: 'Remove gamma' }));+ expect(screen.queryByRole('alert')).toBeNull();++ // A question about a row that is still here, so the queue gets another+ // chance to reach the one about the row that is not.+ await user.click(screen.getByRole('button', { name: 'Remove delta' }));+ expect(within(screen.getByRole('alert')).getByText('delta-air · Order #1')).toBeTruthy();+ await user.click(confirmation().getByRole('button', { name: 'Cancel' }));++ // Nothing is asked in gamma's name. The dialog is answering the user+ // again — not holding a question with no row to hold it, behind which+ // beta's removal could never be confirmed.+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByText('delta')).toBeTruthy();++ await user.click(screen.getByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));++ // The list is byte-for-byte the one the guard refused — and that is not+ // enough. Both questions left without ever being answered, so the two+ // hops the server named were never put to the user, and a `force` here+ // would be the client vouching for a consequence nobody was shown.+ await waitFor(() => expect(write).toHaveBeenCalledTimes(2));+ expect(write.mock.calls[1]?.[1]).toEqual({ baseline: catalog, models: [model('alpha'), model('delta')] });++ // So the guard refuses it again, with the same two hops, and the+ // questions come back — the round-trip the swallow cost, in exchange for+ // the user seeing what they are agreeing to.+ const reasked = await screen.findByRole('alert');+ expect(within(reasked).getByText('beta-air · Order #1')).toBeTruthy();+ await user.click(confirmation().getByRole('button', { name: 'Remove' }));+ expect(within(screen.getByRole('alert')).getByText('gamma-air · Order #1')).toBeTruthy();+ await user.click(confirmation().getByRole('button', { name: 'Remove' }));++ // Answered now, both of them, against the server's own account. This is+ // the only way the echo is reached, so it carries the refusal whole and+ // in the server's order rather than a transcript of the asking.+ await user.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(write).toHaveBeenLastCalledWith('claude', expect.objectContaining({+ models: [model('alpha'), model('delta')],+ force: true,+ would_remove_hops: hops,+ would_interrupt: [],+ })));+ expect(write).toHaveBeenCalledTimes(3);+ });+ });+it('treats a lost answer as saved once the re-read shows the intent already applied', async () => {const user = userEvent.setup();const settled = agent([model('alpha')]);diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.tsxindex abc47c946..10d3a89ca 100644--- a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.tsx@@ -23,16 +23,36 @@ import {applyBackendCatalogIntent,backendCatalogIntent,backendCatalogIntentApplied,+ backendModelId,catalogModelIds,+ chosenCandidate,+ draftRowFor,+ echoableRefusal,+ heldRowFor,+ offeredCandidates,+ orderWithRestored,readBackendCatalogBaseline,sameCatalog,+ samePlanContents,type BackendCatalogBaseline,+ type BackendCatalogIntent,+ type ChosenCandidate,} from './backendCatalog';import { BackendModelEditorDialog } from './BackendModelEditorDialog';+import { BackendModelPickerDialog } from './BackendModelPickerDialog';+import { GuardImpact, type GuardPicture, type GuardPlan } from './GuardImpact';import { apiFailure, modelsApi } from './modelsApi';import { movedOrder, sameIds } from './reorder';import { catalogSaveFailureKey, catalogSaveLeftUnloaded } from './serverCopy';-import type { AgentBackend, AgentSupply, BackendModel } from './types';+import type {+ AgentBackend,+ AgentSupply,+ BackendModel,+ BackendModelsPut,+ ModelCandidate,+ RouteHopRef,+ SupplyGap,+} from './types';type ReadState = 'loading' | 'ready' | 'error';@@ -54,14 +74,132 @@ const matchesQuery = (model: BackendModel, query: string, renderedLabel: string)|| renderedLabel.toLowerCase().includes(needle);};+/**+ * One removal, waiting on an answer, carrying the account of its consequence+ * the user is being shown.+ *+ * The plan travels with the question because a re-ask after the guard refused+ * is about the server's plan and a first ask is about the baseline's — the+ * question is not answerable without the plan it was raised from. `account`+ * names whose plan it is, and that is the whole reason the field exists:+ * agreeing to what the dialog projected from the routes it holds is not+ * agreeing to what the server refused. Only a `guard` answer can settle a+ * refusal, so only a `guard` answer is allowed to discharge what one owes.+ */+type RemovalQuestion = { modelId: string; plan: GuardPicture; account: 'draft' | 'guard' };++/** A guard refusal, as received, together with the write it refused. Both+ * halves are needed to use it: the arrays are what a retry echoes, and the+ * write is what makes them true — the same refusal says nothing about a+ * different list. */+type StoredRefusal = {+ hops: readonly RouteHopRef[];+ gaps: readonly SupplyGap[];+ baseline: readonly BackendModel[];+ models: readonly BackendModel[];+ /**+ * The held-back removals still owed an answer against the server's own plan.+ *+ * This is the acceptance bit: empty means accepted, and only an accepted+ * refusal may be echoed with `force`. It is separate from the write above+ * because the two answer different questions — the write says 「is this the+ * same save the server refused?」 and this says 「did the user accept that+ * refusal?」 — and the reachable path that made one stand in for the other is+ * why it exists. A queued question can be taken off the screen by removing+ * its row through the ordinary trash action, which recomputes from the+ * baseline and shows the dialog's own projection instead; answer the rest and+ * the draft is byte-for-byte the refused list again, so equality alone would+ * have forced a plan whose interruptions were never displayed.+ *+ * Discharged one id at a time, and only by a `guard` answer. A swallowed+ * question therefore leaves the save unforced, the server refuses it again+ * with the same arrays, and the question comes back — one extra round-trip,+ * and no loop, because acceptance is the only route to `force`.+ */+ owed: ReadonlySet<string>;+};++/**+ * The guard's refusal, split into the questions it forces.+ *+ * The server reports one plan for the whole write and the confirmation lives+ * inside a row, so each held-back removal is asked with the part of that plan+ * that names it: hops by the menu model they serve, gaps by the model they+ * would strand. Splitting decides what to SHOW and nothing else — what the next+ * save echoes is the refusal exactly as it arrived, never these pieces+ * reassembled (C3) — so a split that cannot cover every element still asks+ * everything it can rather than editing the plan down to what it understood.+ *+ * Anything the refusal names that this write does not remove belongs to no+ * question this dialog can ask, so it produces none; with nothing to ask at+ * all, the caller falls through to the failure sentence instead of retrying+ * forever.+ */+const refusalPlans = (+ hops: readonly RouteHopRef[],+ gaps: readonly SupplyGap[],+ removed: ReadonlySet<string>,+ backend: AgentBackend,+): RemovalQuestion[] => {+ const plans = new Map<string, GuardPlan>();+ const planFor = (modelId: string): GuardPlan | null => {+ if (!removed.has(modelId)) return null;+ const existing = plans.get(modelId);+ if (existing) return existing;+ const created: GuardPlan = { hops: [], gaps: [] };+ plans.set(modelId, created);+ return created;+ };+ for (const hop of hops) planFor(hop.menu_model)?.hops.push(hop);+ for (const gap of gaps) {+ if (gap.backend === backend) planFor(gap.model_id)?.gaps.push(gap);+ }+ return [...plans].map(([modelId, plan]) => ({ modelId, plan, account: 'guard' as const }));+};++/** The stale-candidate refusal (C1), named by the route's own `error` rather+ * than by status: nothing was committed and nothing was interrupted, so it is+ * answered by asking again with today's suppliers, not by a failure sentence. */+const CANDIDATES_CHANGED = 'candidate_suppliers_changed';++/** The route guard (C3). Like the refusal above it commits nothing, so it is+ * answered by asking again with the plan the server actually has — not by a+ * sentence about a save that never happened. */+const MODEL_IN_ROUTE = 'backend_model_in_route';++/** The ids a picker may not offer: everything the draft holds, less the ones it+ * was reopened to ask about. A re-ask is about a row the draft still holds (the+ * addition was refused, not applied), so counting it as 「already in the list」+ * would show the user their own pending addition as an unpickable row and leave+ * the question it was reopened to ask unanswerable. */+const offerable = (taken: ReadonlySet<string>, seed: ReadonlySet<string>): ReadonlySet<string> => {+ if (seed.size === 0) return taken;+ const listed = new Set(taken);+ for (const id of seed) listed.delete(id);+ return listed;+};++/** Nothing pre-picked, held once so opening the picker is not a new object each+ * render — the picker applies its seed when it opens. */+const NO_SEED: ReadonlySet<string> = new Set();+export const BackendModelCatalogDialog: React.FC<{open: boolean;backend: AgentBackend;+ /** Whether this role may read Sources. The candidates read names them, so the+ * action that opens it is offered exactly where the page's other+ * Source-reading surfaces are (C4). */+ canReadSources: boolean;+ /** Source id → name, for the removal confirmation's hops. The catalog names no+ * Source of its own (that stays with the Route), but a removal that takes a+ * Route with it has to say whose hop goes away — so the page's own Sources+ * answer it, and an id they do not cover simply goes unnamed. */+ sourceNames: Readonly<Record<string, string>>;onClose: () => void;onSaved: (echoed: AgentSupply) => void | Promise<void>;onObserved: (observed: AgentSupply) => void | Promise<void>;catalogWrite: PendingWrite;-}> = ({ open, backend, onClose, onSaved, onObserved, catalogWrite }) => {+}> = ({ open, backend, canReadSources, sourceNames, onClose, onSaved, onObserved, catalogWrite }) => {const { t } = useTranslation();const [baseline, setBaseline] = React.useState<BackendCatalogBaseline | null>(null);const baselineRef = React.useRef<BackendCatalogBaseline | null>(null);@@ -70,13 +208,76 @@ export const BackendModelCatalogDialog: React.FC<{const draftRef = React.useRef<BackendModel[]>([]);const [query, setQuery] = React.useState('');const [saveFailedKey, setSaveFailedKey] = React.useState<string | null>(null);- const [editing, setEditing] = React.useState<{ model: BackendModel | null } | null>(null);- const [removeBlocked, setRemoveBlocked] = React.useState<string | null>(null);+ const [editing, setEditing] = React.useState<{ model: BackendModel | null; seedId?: string } | null>(null);+ const [picking, setPicking] = React.useState<{ seed: ReadonlySet<string> } | null>(null);+ const [removing, setRemoving] = React.useState<RemovalQuestion | null>(null);const [grabbedId, setGrabbedId] = React.useState<string | null>(null);const [announcement, setAnnouncement] = React.useState<Announcement>(null);const readAttempt = React.useRef(0);const grips = React.useRef(new Map<string, HTMLButtonElement>());const grabbedFrom = React.useRef<string[] | null>(null);+ /**+ * The picks this draft holds an agreement for (C1), each still paired with the+ * suppliers its row displayed.+ *+ * One object per pick, and this is its only home: a set of added ids beside a+ * map of expectations is two records of one agreement, and the id can leave+ * the set while its promise stays behind — which is how a save comes to send+ * a projection nobody agreed to. Kept in a ref because it is not rendered;+ * the list on screen is the decision, and this is what it was made against.+ */+ const chosenRef = React.useRef(new Map<string, ChosenCandidate>());+ /**+ * Per removed id, the consequence the user was shown and accepted (C3).+ *+ * A record of what was asked, never a source of what is sent: the arrays a+ * forced write carries come from `refusalRef` and from nowhere else. This one+ * answers a different question — 「does the server's refusal say what the user+ * already agreed to?」 — and its only effect is whether the same consequence is+ * put to them a second time.+ */+ const previewRef = React.useRef(new Map<string, GuardPicture>());+ /**+ * The last guard refusal, stored exactly as it arrived and bound to the write+ * it refused.+ *+ * The single source of a forced body (C3). The two arrays are the server's+ * own, kept verbatim and in the server's order, because that is what the+ * server compares the echo against — a client that rebuilt them from what it+ * showed would be answering with its own sentence and be refused for the+ * wording, not the meaning.+ *+ * The write is stored with them so the echo cannot outlive its subject. A+ * refusal answers one exact `baseline` + `models` pair; the moment the draft+ * moves, the plan describes consequences of a write nobody is making any+ * more, and `putBody` finds it no longer matching rather than having to be+ * told to forget it.+ */+ const refusalRef = React.useRef<StoredRefusal | null>(null);+ /** Removals the guard held back, still owed an answer, each with the plan the+ * server refused them for. The confirmation lives inside the row it is about,+ * so they are asked one at a time — and all of them, because a row that came+ * back unasked is a removal the user requested and nobody ever answered. */+ const guardedRef = React.useRef<RemovalQuestion[]>([]);++ /**+ * Ask the next held-back removal, or stop asking. Also how an ordinary+ * confirmation closes: with nothing held back, this is `setRemoving(null)`.+ *+ * A queued question whose row has since left the draft is discarded rather+ * than asked. The confirmation renders inside the row it is about, so a+ * question about a row that no longer exists — a fresh baseline the server no+ * longer holds it in, an addition withdrawn on the way here — has nothing to+ * remove and nowhere to appear: asking it would leave the dialog waiting on an+ * answer the user has no controls to give. Discarding it is not losing the+ * user's intent either; the row it named is already gone.+ */+ const askNextGuarded = () => {+ const held = new Set(draftRef.current.map((model) => model.id));+ let next = guardedRef.current.shift();+ while (next && !held.has(next.modelId)) next = guardedRef.current.shift();+ setRemoving(next ?? null);+ };const applyBaseline = React.useCallback((observed: BackendCatalogBaseline, models: BackendModel[]) => {baselineRef.current = observed;@@ -106,14 +307,23 @@ export const BackendModelCatalogDialog: React.FC<{}, [applyBaseline, backend]);React.useEffect(() => {- if (open) loadBaseline(false);+ if (!open) return;+ // All of these describe decisions taken against one baseline, so a dialog+ // that is reading a new one starts with none of them.+ chosenRef.current = new Map();+ previewRef.current = new Map();+ refusalRef.current = null;+ guardedRef.current = [];+ setPicking(null);+ setRemoving(null);+ loadBaseline(false);return () => { readAttempt.current += 1; };}, [loadBaseline, open]);const mutate = (next: BackendModel[]) => {draftRef.current = next;setDraft(next);- setRemoveBlocked(null);+ setRemoving(null);setSaveFailedKey(null);};@@ -137,11 +347,30 @@ export const BackendModelCatalogDialog: React.FC<{? t('settings.models.gateway.catalog.systemDefault') as string: model.display_name ?? model.id);- const visible = draft.filter((model) => matchesQuery(model, query.trim(), displayLabel(model)));+ /**+ * The rows on screen.+ *+ * A pending removal question is always one of them, whatever the query says.+ * Its confirmation renders inside its own row (the shape every guarded Model+ * Hub mutation asks in), so a filter that hides that row hides the only+ * controls that can answer it — and the draft has already restored the row, so+ * Save stays disabled with nothing on screen to explain why. Deriving+ * visibility from the queue rather than keeping the two beside each other is+ * what makes 「a question that is pending is on screen」 a property of this one+ * line instead of a rule every path that advances the queue has to remember.+ */+ const visible = draft.filter((model) => (+ model.id === removing?.modelId || matchesQuery(model, query.trim(), displayLabel(model))+ ));const movableIds = draft.filter((model) => !model.locked).map((model) => model.id);const takenIds = new Set(draft.map((model) => model.id));const effortSuggestions = [...new Set(draft.flatMap((model) => model.reasoning_efforts))];- const routeLength = (modelId: string): number => baseline?.agent.routes?.[modelId]?.hops.length ?? 0;+ /** Threaded from the server's own projection rather than mirrored here: the+ * editor's id rule has to agree with the backend that will accept the id. */+ const standardVendors = React.useMemo(+ () => new Set(baseline?.agent.standard_vendors ?? []),+ [baseline?.agent.standard_vendors],+ );/** Reordering permutes which movable row sits in which movable slot; a locked* row keeps its absolute index, so the order sent never moves one. */@@ -218,22 +447,198 @@ export const BackendModelCatalogDialog: React.FC<{if (neighbour) focusGrip(neighbour);};+ /**+ * A preview of what a removal would take with it, from the routes this dialog+ * already holds.+ *+ * It exists so the question can be asked when the user clicks the trash,+ * rather than after a round-trip — but it is a picture, not a plan, and+ * nothing it produces is ever sent. Only the server states the consequences+ * of a write (C3); this reads the baseline's own hops in their one-based+ * positions so that the picture matches the statement, and when it does the+ * save goes through without asking the same question twice.+ *+ * The gaps are `null`, not empty: whether a removal strands an Agent is the+ * guard's answer, and this dialog holds no supply to answer it from. Empty+ * would have made `GuardImpact` read 「these models still have another source+ * available」 — a promise about the rest of the Hub, made by the one surface+ * that cannot see it, in the confirmation the user decides on. So the picture+ * shows its hops and says nothing about interruption; the guard refuses with+ * the real gaps before anything commits, and those are what the user is then+ * shown.+ */+ const removalPreview = (modelId: string): GuardPicture => ({+ hops: (baseline?.agent.routes?.[modelId]?.hops ?? []).map((hop, index) => ({+ ...hop,+ backend,+ menu_model: modelId,+ position: index + 1,+ })),+ gaps: null,+ });++ /** The row leaves the draft; its route leaves with it when the list saves. */+ const dropModel = (modelId: string, plan: GuardPicture) => {+ chosenRef.current.delete(modelId);+ if (plan.hops.length > 0 || (plan.gaps?.length ?? 0) > 0) previewRef.current.set(modelId, plan);+ else previewRef.current.delete(modelId);+ mutate(draftRef.current.filter((entry) => entry.id !== modelId));+ };++ /**+ * The user answers one removal question: the row leaves, and if the question+ * was the guard's own, the refusal is one answer closer to being echoable.+ *+ * Only a `guard` answer discharges anything. The same confirmation renders for+ * a removal the dialog itself asked about, and what that one shows is the+ * dialog's projection from the routes it holds — accepting it says nothing+ * about the plan the server refused, which may name interruptions the+ * projection had no way to know about.+ */+ const acceptRemoval = (question: RemovalQuestion) => {+ dropModel(question.modelId, question.plan);+ const refusal = refusalRef.current;+ if (question.account !== 'guard' || !refusal || !refusal.owed.has(question.modelId)) return;+ const owed = new Set(refusal.owed);+ owed.delete(question.modelId);+ refusalRef.current = { ...refusal, owed };+ };+const removeModel = (model: BackendModel) => {- if (routeLength(model.id) > 0) {- setRemoveBlocked(model.id);+ const plan = removalPreview(model.id);+ // A route is the only thing a removal takes with it that the user did not+ // name, so it is the only removal that asks first.+ if (plan.hops.length > 0) {+ setRemoving({ modelId: model.id, plan, account: 'draft' });return;}- mutate(draft.filter((entry) => entry.id !== model.id));+ dropModel(model.id, plan);};const commitEdit = (model: BackendModel) => {const existing = draft.findIndex((entry) => entry.id === model.id);+ // A row written by hand promises nothing about its suppliers, so an id+ // created here carries no displayed projection into the save. Editing an+ // existing row keeps whatever it already carried: the editor holds its id+ // fixed, so the projection is still about the same addition.+ if (existing < 0) chosenRef.current.delete(model.id);mutate(existing >= 0? draft.map((entry, index) => (index === existing ? { ...model, locked: entry.locked, routeable: entry.routeable } : entry)): [...draft, model]);setEditing(null);};+ /**+ * Picks, poured into the draft.+ *+ * Each arrives as the agreement itself — the candidate and the suppliers its+ * row displayed — and is stored whole. The server matches the addition at+ * commit time, so this states which projection the user agreed to, and a+ * changed one is re-asked instead of silently seeding a route the picker never+ * displayed (C1). A pick the draft already holds is exactly that re-ask: the+ * refused save left the row alone and left only the agreement undone, so+ * confirming supplies it without rebuilding a row the user may have edited.+ *+ * A seeded id that comes back unpicked has no agreement any more, and this+ * dialog has no way to add a row without one — the picker is where a supplier+ * promise is made, and a pending addition that survived with none would be+ * sent as if it had been written by hand, which is precisely the silent+ * re-send the re-ask exists to prevent. So it leaves the draft with its+ * promise. Never a saved row: a disagreement about suppliers may not delete+ * something the server already holds, and it cannot — a seed only ever names+ * pending additions.+ *+ * 「Confirm none of them」 is therefore the same operation as 「dismiss the+ * re-ask」, and the picker's Cancel is wired to exactly this call with no picks:+ * a re-ask the user walks away from has answered every seeded id with 「not+ * this」, and leaving those rows behind is what let a refused projection be+ * re-sent by the next Save with no way to stop it. An ordinary add has an empty+ * seed, so the same call still means 「nothing happened」.+ *+ * Which ROW an id lands as is not decided here — `draftRowFor` owns that, so a+ * re-added row comes back as the one the user already has rather than as a+ * fresh synthesis of the proposal.+ */+ const addCandidates = (picked: ChosenCandidate[]) => {+ const seed = picking?.seed ?? NO_SEED;+ setPicking(null);+ const confirmed = new Set(picked.map((pick) => pick.candidate.id));+ const saved = new Set((baselineRef.current?.models ?? []).map((model) => model.id));+ const withdrawn = new Set([...seed].filter((id) => !confirmed.has(id) && !saved.has(id)));+ if (picked.length === 0 && withdrawn.size === 0) return;+ for (const id of withdrawn) chosenRef.current.delete(id);+ for (const pick of picked) {+ chosenRef.current.set(pick.candidate.id, pick);+ // Re-adding a row voids the removal that was confirmed for it.+ previewRef.current.delete(pick.candidate.id);+ }+ const held = new Set(draftRef.current.map((model) => model.id));+ const additions = picked+ .filter((pick) => !held.has(pick.candidate.id))+ .map((pick) => draftRowFor(pick.candidate, draftRef.current, baselineRef.current?.models ?? []));+ mutate([...draftRef.current.filter((model) => !withdrawn.has(model.id)), ...additions]);+ };++ /**+ * What the server offers right now, or `null` when that could not be read.+ *+ * A 409 answers a pick, a pick came from the picker, and the picker is only+ * offered where Sources are readable (C4) — so a read that does not arrive+ * here is a failed read, not a role forbidden to take one, and `null` is the+ * whole of what this dialog learned about the offer. The caller decides what+ * to do with not knowing; it may not guess.+ */+ const offeredNow = async (): Promise<Map<string, ModelCandidate> | null> => {+ try {+ return offeredCandidates(await modelsApi.getAgentModelCandidates(backend));+ } catch {+ return null;+ }+ };++ /**+ * The one write this dialog makes.+ *+ * `baseline` + `models` is the whole list settling through a single optimistic+ * merge (C1). The other three fields exist only because two of that merge's+ * consequences are not derivable from the list: `force` answers the route+ * guard, and `expected_suppliers` states, per addition, the projection the+ * picker displayed for it. Only per addition: a row the baseline already holds+ * is not matched again, so a promise about it would describe nothing this+ * write does.+ *+ * The forced arrays are produced HERE and only here, from the stored refusal+ * and only from it, verbatim and in the server's own order (C3). That is what+ * makes the echo an echo: the server compares it against what it sent, and+ * it compares element by element, so a plan reassembled from per-row pieces+ * would carry the order they were clicked in and be refused for saying the+ * same thing differently. Nothing this dialog composes can reach these two+ * fields — there is no path to them that does not pass through a refusal the+ * server wrote.+ *+ * Whether a stored refusal has earned that echo is `echoableRefusal`'s+ * question, asked against this write rather than against a flag someone has+ * to remember to clear.+ */+ const putBody = (baselineModels: BackendModel[], requested: BackendModel[]): BackendModelsPut => {+ const body: BackendModelsPut = { baseline: baselineModels, models: requested };+ const refusal = refusalRef.current;+ if (refusal && echoableRefusal(refusal, baselineModels, requested)) {+ body.force = true;+ body.would_remove_hops = [...refusal.hops];+ body.would_interrupt = [...refusal.gaps];+ }+ const baselineIds = new Set(baselineModels.map((model) => model.id));+ const expected = Object.fromEntries(+ requested.flatMap((model) => {+ const pick = baselineIds.has(model.id) ? undefined : chosenRef.current.get(model.id);+ return pick ? [[model.id, pick.expected_suppliers] as const] : [];+ }),+ );+ if (Object.keys(expected).length > 0) body.expected_suppliers = expected;+ return body;+ };+const save = () => {const base = baselineRef.current;// A pre-catalog server has no baseline to send, so there is nothing this@@ -243,12 +648,175 @@ export const BackendModelCatalogDialog: React.FC<{const requested = draftRef.current;const intent = backendCatalogIntent(baselineModels, requested);setSaveFailedKey(null);+ const body = putBody(baselineModels, requested);void catalogWrite.track(async () => {let echoed: AgentSupply;try {- echoed = await modelsApi.putAgentModels(backend, { baseline: baselineModels, models: requested });+ echoed = await modelsApi.putAgentModels(backend, body);} catch (error) {const failure = apiFailure(error);+ if (failure?.code === CANDIDATES_CHANGED) {+ // Nothing was committed, so there is no list to re-read and nothing to+ // report: the answer is the same question again, and the draft is+ // still the user's. The rows stay exactly as they built them — a+ // context window they widened or a name they wrote is theirs, and+ // rebuilding the row from its candidate would spend those edits to+ // answer a question about suppliers. Only the projection is in doubt,+ // so only the projection waits: it stays as displayed until the re-ask+ // replaces it, which leaves the guard armed rather than granting an+ // agreement the user never gave if they dismiss the picker instead of+ // answering it.+ //+ // The refusal is reconciled HERE, where the evidence arrives, and+ // before anything reopens — so no later path has to remember to undo a+ // projection the server has already refused.+ //+ // What `changed` reports is suppliers, and suppliers are not the+ // question of whether an id is still on offer: a built-in the server+ // still serves with none of them is a legitimate candidate whose route+ // starts empty (C1), so reading an empty list as a withdrawal deletes+ // a row the user may still add. Only one thing withdraws an id — the+ // server no longer offering it — and only a candidates read says that+ // (C4), so the refusal is reconciled against one, taken HERE, because+ // an answer where every pick is withdrawn opens no picker and a read+ // that only the picker performs would never happen.+ //+ // Withdrawn takes the row and the agreement together: the row that+ // disappears and the count that falls are the whole report, and the+ // entry goes with it so nothing is left describing a row this dialog+ // no longer has. An offered id keeps its row and takes the read's own+ // candidate as its agreement — both halves from one read, including an+ // empty supplier list, which re-asks as a row with no chips and saves+ // as an empty promise the server seeds an empty route for. Only picks:+ // a supplier disagreement may not delete a row the server already+ // holds, and one this write promised nothing for is no part of it.+ const saved = new Set(baselineModels.map((model) => model.id));+ const disputed = Object.entries(failure.changedSuppliers)+ .filter(([modelId]) => chosenRef.current.has(modelId) && !saved.has(modelId));+ // A read that failed knows nothing about what is offered, so it+ // withdraws nothing and every disputed pick is asked again, promising+ // the suppliers the refusal itself named — the freshest word there is+ // when the read that would supersede it never arrived. The picker+ // reads on its way in, so a withdrawal invisible here is still caught+ // there; a row deleted on a failed read would be this dialog spending+ // the user's list on its own missing evidence.+ const offered = disputed.length > 0 ? await offeredNow() : null;+ const withdrawn = new Set(+ offered ? disputed.filter(([modelId]) => !offered.has(modelId)).map(([modelId]) => modelId) : [],+ );+ const reask: string[] = [];+ for (const [modelId, suppliers] of disputed) {+ if (withdrawn.has(modelId)) {+ chosenRef.current.delete(modelId);+ continue;+ }+ const fresh = offered?.get(modelId);+ const pick = chosenRef.current.get(modelId);+ if (fresh) chosenRef.current.set(modelId, chosenCandidate(fresh));+ else if (pick) chosenRef.current.set(modelId, { ...pick, expected_suppliers: [...suppliers] });+ reask.push(modelId);+ }+ if (withdrawn.size > 0) mutate(draftRef.current.filter((model) => !withdrawn.has(model.id)));+ if (reask.length > 0) {+ setPicking({ seed: new Set(reask) });+ return;+ }+ // Nothing left to ask, and the list already shows what changed: a drop+ // is its own answer, and a sentence about it would be this dialog+ // reporting its own edit back to the user. But the save they pressed is+ // still owed — nothing was committed — so it goes again on the reduced+ // list rather than costing them a second press for a withdrawal they+ // did not make. It terminates: every pass either drops at least one+ // pick from the map that `disputed` is drawn from, or asks instead.+ if (withdrawn.size > 0) {+ void save();+ return;+ }+ // Nothing to ask and nothing to drop: a refusal about ids this write+ // promised nothing for is not one this dialog can answer, so it keeps+ // the failure sentence below rather than resolving into silence.+ }+ // The route guard. Nothing was committed, so this is not a failed save+ // but an unanswered question: the server has now stated what this exact+ // write would take with it, and the only thing missing is the user's+ // agreement to it.+ //+ // The statement is kept whole and unedited, bound to the write it+ // answers, because that is what the retry will echo. What follows+ // decides only whether the user has to be asked.+ const refusal = failure?.code === MODEL_IN_ROUTE ? failure : null;+ const guardedPlans = refusal+ ? refusalPlans(refusal.wouldRemoveHops, refusal.wouldInterrupt, intent.removed, backend)+ : [];+ if (refusal && guardedPlans.length > 0) {+ // Does the server's plan say what the user already accepted? Compared+ // as contents, not as sequence: the previews were recorded row by row+ // as the trash was clicked, the server walks its own baseline, and two+ // orders of the same consequences are not a disagreement about them.+ const shown = [...previewRef.current]+ .filter(([modelId]) => intent.removed.has(modelId))+ .map(([, plan]) => plan);+ // A picture contributes no gaps, because it never claimed any: so a+ // server plan that names an interruption is by construction not+ // covered by what the user has already accepted, and the question is+ // re-asked with the server's own words.+ const agreed = samePlanContents(refusal.wouldRemoveHops, shown.flatMap((plan) => plan.hops))+ && samePlanContents(refusal.wouldInterrupt, shown.flatMap((plan) => plan.gaps ?? []));+ refusalRef.current = {+ hops: refusal.wouldRemoveHops,+ gaps: refusal.wouldInterrupt,+ baseline: baselineModels,+ models: requested,+ // An agreement that already covers this plan owes nothing: the user+ // has seen these consequences, and `agreed` is that statement.+ // Otherwise every removal being handed back owes an answer, and the+ // echo waits for the last of them.+ //+ // What the split could not attribute to any removed row is owed by+ // nobody, because there is no row for it to be asked in. It still+ // travels in the echo once every question that COULD be asked has+ // been answered — the alternative is a save the user can never make+ // — and that residue is a recorded decision, not an oversight.+ owed: agreed ? new Set() : new Set(guardedPlans.map((question) => question.modelId)),+ };+ // Already agreed, and this attempt did not carry the agreement: the+ // user answered this question before they pressed Save, and asking it+ // again would only be the dialog telling them what they just told it.+ // The same list goes again, this time echoing the server's own plan.+ // It terminates — that retry is forced, so it cannot take this branch+ // a second time.+ if (agreed && body.force !== true) {+ void save();+ return;+ }+ // Not what was shown — a route created since the baseline was read, or+ // an Agent stranded by a removal that looked free — so every held-back+ // removal comes back into the draft and is asked again, through the+ // same confirmation, now carrying the server's own plan. The baseline+ // is deliberately NOT re-read: the refusal above answers this+ // `baseline` + `models` pair, and reading a newer list would leave the+ // dialog holding a plan about a write it can no longer make.+ //+ // It comes back to its own place, not to the end. The requested order+ // is the list with the row already gone, so the baseline is what says+ // where it belongs — and a removal the user then cancels leaves the+ // draft equal to the baseline, rows and order, which is the only state+ // that can honestly report itself as unedited.+ const heldBack = new Set(guardedPlans.map((question) => question.modelId));+ const held: BackendCatalogIntent = {+ ...intent,+ removed: new Set([...intent.removed].filter((id) => !heldBack.has(id))),+ order: orderWithRestored(intent.order, baselineModels.map((model) => model.id), heldBack),+ };+ mutate(applyBackendCatalogIntent(baselineModels, held));+ // What the user accepted for these rows was the preview, and it is not+ // what the server says. Confirming a question below records the+ // server's own account in its place.+ for (const modelId of heldBack) previewRef.current.delete(modelId);+ guardedRef.current = [...guardedPlans];+ askNextGuarded();+ return;+ }// A route that named its failure has decided what it did, and for this// endpoint 「decided」 can still mean 「wrote」: the server commits the// catalog and only then asks the backend to load it, so `engine_down`@@ -324,11 +892,55 @@ export const BackendModelCatalogDialog: React.FC<{);};- const blockedNote = (model: BackendModel) => (- removeBlocked === model.id- ? <p className="model-hub-catalog-blocked" role="alert">{t('settings.models.gateway.catalog.removeBlocked')}</p>- : null- );+ /**+ * The question a routed removal asks, inside the row it is about.+ *+ * A route is a consequence the user did not choose when they chose the model,+ * so it is shown before it is taken — through the same evidence body every+ * other guarded Model Hub mutation shows, because the question is the same+ * question and an answer to it means the same thing. It renders the plan the+ * question was raised from: the baseline's route on a first ask, the server's+ * own refusal on a re-ask. Answering it removes the row and its route+ * together, in one transaction, when the list saves (C3).+ *+ * The page's Sources travel with it so each hop names its supplier. This+ * dialog still holds no Source concept — it does not resolve one, order one or+ * write one — but 「no hidden mappings」 is a rule about what the user is shown+ * before they agree, and 「a hop at position 2 disappears」 without whose hop it+ * was is exactly the hidden half.+ */+ const removeConfirmation = (model: BackendModel) => {+ if (removing?.modelId !== model.id) return null;+ const { plan } = removing;+ const asked = removing;+ return (+ <div className="model-hub-catalog-confirm">+ <div className="model-hub-catalog-consequence" role="alert">+ <GuardImpact hops={plan.hops} gaps={plan.gaps} sourceNames={sourceNames} />+ </div>+ <div className="flex items-center gap-2">+ <Button+ type="button"+ variant="outline"+ className="model-hub-catalog-confirm-action rounded-md text-[12.5px] font-semibold"+ disabled={busy}+ onClick={askNextGuarded}+ >+ {t('settings.models.gateway.catalog.cancel')}+ </Button>+ <Button+ type="button"+ variant="destructive"+ className="model-hub-catalog-confirm-action rounded-md text-[12.5px] font-bold"+ disabled={busy}+ onClick={() => { acceptRemoval(asked); askNextGuarded(); }}+ >+ {t('settings.models.gateway.catalog.removeConfirm')}+ </Button>+ </div>+ </div>+ );+ };return (<>@@ -364,16 +976,24 @@ export const BackendModelCatalogDialog: React.FC<{disabled={!editable || busy}/></div>- <Button- type="button"- variant="brand"- className="model-hub-catalog-control shrink-0 rounded-md px-4 text-[12.5px] font-semibold"- disabled={!editable || busy}- onClick={() => setEditing({ model: null })}- >- <Plus aria-hidden="true" />- {t('settings.models.gateway.catalog.add')}- </Button>+ {/* One action for both paths. The picker offers what this backend+ and the user's providers already have, and hands off to the+ editor for anything they do not — so 「add a model」 is one+ decision with a fallback, not two entry points the user has to+ choose between up front. It reads Sources, so it is offered+ only where the page's other Source-reading surfaces are. */}+ {canReadSources && (+ <Button+ type="button"+ variant="brand"+ className="model-hub-catalog-control shrink-0 rounded-md px-4 text-[12.5px]"+ disabled={!editable || busy}+ onClick={() => setPicking({ seed: NO_SEED })}+ >+ <Plus aria-hidden="true" />+ {t('settings.models.gateway.catalog.add')}+ </Button>+ )}</div>{ready && (draft.length > 0 || legacyIds.length > 0) && (@@ -436,6 +1056,7 @@ export const BackendModelCatalogDialog: React.FC<{key={model.id}model={model}grabbed={grabbedId === model.id}+ confirming={removing?.modelId === model.id}draggable={!filtering && !busy}registerGrip={(node) => {if (node) grips.current.set(model.id, node);@@ -444,7 +1065,7 @@ export const BackendModelCatalogDialog: React.FC<{onGripKeyDown={(event) => handleGripKey(model.id, event)}body={rowBody(model)}actions={rowActions(model)}- note={blockedNote(model)}+ note={removeConfirmation(model)}/>)))}@@ -490,13 +1111,54 @@ export const BackendModelCatalogDialog: React.FC<{</DialogContent></Dialog>+ {picking && (+ <BackendModelPickerDialog+ open+ backend={backend}+ listedIds={offerable(takenIds, picking.seed)}+ seedPicked={picking.seed}+ // 「Add none of these」 — the same answer as confirming with nothing+ // picked, and the same call, because a re-ask the user dismisses has+ // declined every id it seeded. An ordinary add seeds nothing, so this+ // still just closes.+ onCancel={() => addCandidates([])}+ onAdd={addCandidates}+ // The editor is the other door an id becomes a row through, so leaving+ // by it answers this picker's two standing questions in the same order+ // every other exit answers them, through the same call.+ //+ // `addCandidates([])` first, for the same reason Cancel makes that+ // call: walking out through the editor confirms none of a re-ask's+ // seeded ids, and a seeded projection this dialog keeps is one the+ // next Save would send as if it had been agreed.+ //+ // Then the id, resolved BEFORE the row lookup and through the rule the+ // editor itself commits under (`backendModelId`, which `draftWithId`+ // applies there). The lookup is a total function of the id, so the id+ // it is asked about has to be the one the row would be saved as: asked+ // about a typed `foo` it does not find the user's saved `custom/foo`,+ // and the editor — resolving the id only on commit — would then write+ // a blank row onto it, dropping the limits, modalities, capabilities+ // and name they had described. The resolver is idempotent, so the+ // editor re-applying it to this seed changes nothing.+ onCustom={(typed) => {+ addCandidates([]);+ const seedId = backendModelId(typed, backend, standardVendors);+ const existing = heldRowFor(seedId, draftRef.current, baselineRef.current?.models ?? []);+ setEditing(existing ? { model: existing } : { model: null, seedId });+ }}+ />+ )}+{editing && (<BackendModelEditorDialogopenbackend={backend}model={editing.model}+ seedId={editing.seedId}takenIds={takenIds}effortSuggestions={effortSuggestions}+ standardVendors={standardVendors}onCancel={() => setEditing(null)}onCommit={commitEdit}/>@@ -508,13 +1170,14 @@ export const BackendModelCatalogDialog: React.FC<{const CatalogRow: React.FC<{model: BackendModel;grabbed: boolean;+ confirming: boolean;draggable: boolean;registerGrip: (node: HTMLButtonElement | null) => void;onGripKeyDown: (event: React.KeyboardEvent<HTMLButtonElement>) => void;body: React.ReactNode;actions: React.ReactNode;note: React.ReactNode;-}> = ({ model, grabbed, draggable, registerGrip, onGripKeyDown, body, actions, note }) => {+}> = ({ model, grabbed, confirming, draggable, registerGrip, onGripKeyDown, body, actions, note }) => {const { t } = useTranslation();const controls = useDragControls();return (@@ -522,7 +1185,10 @@ const CatalogRow: React.FC<{value={model.id}dragListener={false}dragControls={controls}- className="model-hub-catalog-row flex min-w-0 list-none flex-col justify-center"+ className={cn(+ 'model-hub-catalog-row flex min-w-0 list-none flex-col justify-center',+ confirming && 'is-confirming',+ )}><div className="flex min-w-0 items-center gap-3"><buttondiff --git a/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.test.tsxindex ba41b326f..ab59f5e1a 100644--- a/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx+++ b/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx@@ -2,7 +2,7 @@import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { I18nextProvider } from 'react-i18next';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import i18n from '@/i18n';import { BackendModelEditorDialog } from './BackendModelEditorDialog';@@ -37,6 +37,7 @@ const renderEditor = (overrides: Partial<React.ComponentProps<typeof BackendModemodel={null}takenIds={new Set()}effortSuggestions={[]}+ standardVendors={new Set()}onCancel={onCancel}onCommit={onCommit}{...overrides}@@ -60,6 +61,18 @@ const answered = (name: 'Tool calling' | 'Reasoning'): string | null =>capability(name).getAllByRole('radio').find((radio) => radio.getAttribute('aria-checked') === 'true')?.textContent?? null;+const modelField = () => screen.getByLabelText('Model') as HTMLInputElement;++const spy = () => vi.spyOn(modelsApi, 'searchModelsDev');+let search: ReturnType<typeof spy>;++beforeEach(() => {+ // The first field is a search now, so every keystroke in it asks models.dev.+ // Stubbed by default so a test that is about something else neither reaches+ // the network nor has to say so.+ search = spy().mockResolvedValue([]);+});+afterEach(() => {cleanup();vi.restoreAllMocks();@@ -74,12 +87,11 @@ describe('BackendModelEditorDialog', () => {expect(screen.getByText('Enter a backend model ID.')).toBeTruthy();expect(onCommit).not.toHaveBeenCalled();- const id = screen.getByLabelText('Backend model ID');- await user.type(id, 'taken');+ await user.type(modelField(), 'taken');expect(screen.getByText('This list already has a model with this ID.')).toBeTruthy();- await user.clear(id);- await user.type(id, 'kept');+ await user.clear(modelField());+ await user.type(modelField(), 'kept');await user.click(screen.getByRole('button', { name: 'Add model' }));expect(onCommit).toHaveBeenCalledTimes(1);expect(onCommit.mock.calls[0][0]).toMatchObject({@@ -94,11 +106,10 @@ describe('BackendModelEditorDialog', () => {const user = userEvent.setup();const { onCommit } = renderEditor();- const id = screen.getByLabelText('Backend model ID');- expect(id.getAttribute('maxlength')).toBe('256');+ expect(modelField().getAttribute('maxlength')).toBe('256');// The browser stops at the cap, so reaching the error needs a value the// field never lets a keystroke produce.- fireEvent.change(id, { target: { value: 'x'.repeat(257) } });+ fireEvent.change(modelField(), { target: { value: 'x'.repeat(257) } });await user.click(screen.getByRole('button', { name: 'Add model' }));expect(onCommit).not.toHaveBeenCalled();@@ -118,10 +129,9 @@ describe('BackendModelEditorDialog', () => {};const { onCommit } = renderEditor({ model: legacy, takenIds: new Set([legacy.id]) });- const id = screen.getByLabelText('Backend model ID') as HTMLInputElement;// Shown in full, not clipped: the cap belongs to what can be typed.- expect(id.value).toBe(legacy.id);- expect(id.getAttribute('maxlength')).toBeNull();+ expect(modelField().value).toBe(legacy.id);+ expect(modelField().getAttribute('maxlength')).toBeNull();expect(screen.queryByText('A model ID may be at most 256 characters.')).toBeNull();await user.type(screen.getByLabelText('Display name'), 'Legacy house model');@@ -151,10 +161,13 @@ describe('BackendModelEditorDialog', () => {const { onCommit } = renderEditor({ model: existing, takenIds: new Set([existing.id]) });expect(screen.getByRole('heading', { name: 'Edit model' })).toBeTruthy();- const id = screen.getByLabelText('Backend model ID') as HTMLInputElement;- expect(id.readOnly).toBe(true);- await user.type(id, 'suffix');- expect(id.value).toBe('anthropic/claude-opus-4');+ expect(modelField().readOnly).toBe(true);+ await user.type(modelField(), 'suffix');+ expect(modelField().value).toBe('anthropic/claude-opus-4');+ // A saved row's id is not a search: the one metadata source this dialog has+ // belongs to the field the user can still answer.+ expect(screen.queryByRole('listbox')).toBeNull();+ expect(search).not.toHaveBeenCalled();// The grouped form is what the field shows, so the grouped form is what it// must accept back.@@ -175,7 +188,7 @@ describe('BackendModelEditorDialog', () => {const user = userEvent.setup();const { onCommit } = renderEditor();- await user.type(screen.getByLabelText('Backend model ID'), 'm');+ await user.type(modelField(), 'm');await user.type(screen.getByLabelText('Context window'), '20k');await user.click(screen.getByRole('button', { name: 'Add model' }));@@ -183,22 +196,27 @@ describe('BackendModelEditorDialog', () => {expect(onCommit).not.toHaveBeenCalled();});- it('fills every field from a single models.dev match and leaves them editable', async () => {+ it('fills every field a suggestion knows, the ID included, and leaves each editable', async () => {const user = userEvent.setup();- const search = vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([match()]);+ search.mockResolvedValue([match()]);const { onCommit } = renderEditor();- await user.type(screen.getByLabelText('Backend model ID'), 'anthropic/claude-sonnet-4-5-20250929');- await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));+ await user.type(modelField(), 'sonnet');+ await user.click(await screen.findByRole('option', { name: /Claude Sonnet 4\.5/ }));- await screen.findByText('models.dev · anthropic/claude-sonnet-4-5');- expect(search).toHaveBeenCalledWith('anthropic/claude-sonnet-4-5-20250929');+ // Choosing a suggestion is choosing a model: the row becomes the model that+ // was picked, under the id its provider publishes — not the catalog key, and+ // not the half-typed query that found it.+ expect(modelField().value).toBe(match().model_id);+ expect(screen.queryByRole('listbox')).toBeNull();expect((screen.getByLabelText('Display name') as HTMLInputElement).value).toBe('Claude Sonnet 4.5');expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('200,000');+ expect((screen.getByLabelText('Maximum output') as HTMLInputElement).value).toBe('64,000');expect(modalities('Input').getByRole('checkbox', { name: 'Image' }).getAttribute('aria-checked')).toBe('true');expect(answered('Reasoning')).toBe('Yes');- // Every filled field stays the user's: the fill is a starting point.+ // Every filled field stays the user's: what they wanted may be the model+ // next to the one they found.await user.click(modalities('Input').getByRole('checkbox', { name: 'Image' }));await user.clear(screen.getByLabelText('Maximum output'));await user.type(screen.getByLabelText('Maximum output'), '8000');@@ -206,9 +224,8 @@ describe('BackendModelEditorDialog', () => {await user.click(screen.getByRole('button', { name: 'Add model' }));expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({- // A fill never renames the row the user typed.- id: 'anthropic/claude-sonnet-4-5-20250929',- models_dev_id: 'anthropic/claude-sonnet-4-5',+ id: match().model_id,+ models_dev_id: match().models_dev_id,display_name: 'Claude Sonnet 4.5',origin: 'models_dev',input_modalities: ['text'],@@ -217,117 +234,163 @@ describe('BackendModelEditorDialog', () => {}));});- it('offers a selectable list when models.dev returns several matches', async () => {+ it('offers each match once and keeps the keyboard on the same rows as the pointer', async () => {const user = userEvent.setup();- vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([+ search.mockResolvedValue([match(),- match({ provider_id: 'bedrock', provider_name: 'Amazon Bedrock', models_dev_id: 'bedrock/claude-sonnet-4-5', display_name: 'Sonnet 4.5 (Bedrock)', context_window: 180000 }),+ match({+ provider_id: 'bedrock',+ provider_name: 'Amazon Bedrock',+ model_id: 'anthropic.claude-sonnet-4-5-v1',+ models_dev_id: 'bedrock/claude-sonnet-4-5',+ display_name: 'Sonnet 4.5 (Bedrock)',+ context_window: 180000,+ }),]);renderEditor();- await user.type(screen.getByLabelText('Backend model ID'), 'claude-sonnet-4-5');- await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));-- const options = await screen.findAllByRole('option');- expect(options).toHaveLength(2);+ await user.type(modelField(), 'sonnet');+ await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(3));+ // Every match, plus the escape — one row per answer and one row for the+ // query itself, so the list can never dead-end.+ const rows = screen.getAllByRole('option');+ expect(rows[2].textContent).toContain('Use "sonnet" as the model ID');+ // Nothing is filled by merely being offered.expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('');- await user.click(options[1]);+ // The field keeps the caret and the list keeps the focus ring: the active+ // row is what Enter takes, whichever way it was reached.+ await user.keyboard('{ArrowDown}{Enter}');- expect(screen.queryByRole('option')).toBeNull();+ expect(modelField().value).toBe('anthropic.claude-sonnet-4-5-v1');expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('180,000');- expect(screen.getByText('models.dev · bedrock/claude-sonnet-4-5')).toBeTruthy();+ expect(screen.queryByRole('listbox')).toBeNull();});- it('reports an empty or unreachable models.dev without touching the draft', async () => {+ it('takes the query as the ID and, on OpenCode, as one OpenCode accepts', async () => {const user = userEvent.setup();- const search = vi.spyOn(modelsApi, 'searchModelsDev')- .mockResolvedValueOnce([])- .mockRejectedValueOnce(new Error('offline'));- renderEditor();+ // The one id rule this dialog owns: OpenCode addresses `provider/model`, so+ // the escape supplies the provider a query does not name and offers the id+ // the backend will accept rather than the one it would reject after saving.+ const { onCommit } = renderEditor({ backend: 'opencode', standardVendors: new Set(['zai']) });++ await user.type(modelField(), 'glm-4.7');+ expect(await screen.findByRole('option', { name: 'Use "custom/glm-4.7" as the model ID' })).toBeTruthy();++ await user.clear(modelField());+ await user.type(modelField(), 'zai/glm-4.7');+ // A query that already names a provider is taken as typed.+ expect(await screen.findByRole('option', { name: 'Use "zai/glm-4.7" as the model ID' })).toBeTruthy();++ await user.clear(modelField());+ await user.type(modelField(), 'acme/glm-4.7');+ // Including a provider the standard vendor list does not know. The server+ // admits any provider segment its grammar accepts, so offering+ // `custom/acme/glm-4.7` would save a different public model id than the one+ // that was typed — and save it silently, because the server accepts that too.+ await user.click(await screen.findByRole('option', { name: 'Use "acme/glm-4.7" as the model ID' }));++ expect(modelField().value).toBe('acme/glm-4.7');+ await user.click(screen.getByRole('button', { name: 'Add model' }));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ id: 'acme/glm-4.7', origin: 'manual' }));+ });- await user.type(screen.getByLabelText('Backend model ID'), 'private/model');- await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));- expect(await screen.findByText('models.dev has no model matching this ID.')).toBeTruthy();+ it('takes the query verbatim on a backend whose IDs have no provider segment', async () => {+ const user = userEvent.setup();+ const { onCommit } = renderEditor({ backend: 'claude' });++ await user.type(modelField(), 'claude-house-1');+ await user.click(await screen.findByRole('option', { name: 'Use "claude-house-1" as the model ID' }));- await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));- expect(await screen.findByText('models.dev could not be reached.')).toBeTruthy();- expect(search).toHaveBeenCalledTimes(2);- expect((screen.getByLabelText('Backend model ID') as HTMLInputElement).value).toBe('private/model');+ expect(modelField().value).toBe('claude-house-1');+ await user.click(screen.getByRole('button', { name: 'Add model' }));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ id: 'claude-house-1' }));});- it('names an upstream models.dev outage as a cause of its own', async () => {- // The server separates 「the catalog is down」 from every other fill failure,- // and it is the one where retrying is the wrong advice: the fields it would- // have filled are all typeable by hand.- const user = userEvent.setup();- vi.spyOn(modelsApi, 'searchModelsDev').mockRejectedValue(- new ApiCallError('upstream_unavailable', 'modelHub.errors.models_dev_unavailable', true),- );- renderEditor();+ it('opens on the query the picker carried over', async () => {+ // The user already typed it once, in the picker's own search. Asking again+ // would be the surface forgetting.+ search.mockResolvedValue([match()]);+ renderEditor({ seedId: 'sonnet' });- await user.type(screen.getByLabelText('Backend model ID'), 'openai/gpt-5');- await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));- expect(- await screen.findByText('The models.dev catalog is unavailable right now. You can fill these fields in by hand.'),- ).toBeTruthy();- expect(screen.queryByText('models.dev could not be reached.')).toBeNull();- expect(screen.queryByText('modelHub.errors.models_dev_unavailable')).toBeNull();+ expect(modelField().value).toBe('sonnet');+ expect(await screen.findByRole('option', { name: /Claude Sonnet 4\.5/ })).toBeTruthy();+ expect(search).toHaveBeenCalledWith('sonnet', expect.anything());});- it('drops a models.dev answer once the ID that asked for it is gone', async () => {- // The answer describes the id that was typed when 填充 was pressed. Landing- // it on the id that replaced it would file one model's context window,- // modalities and efforts under another model's name.+ it('answers the query the user is on, never the one they left', async () => {+ // The answer describes the query that asked for it. Landing a late one would+ // file one model's context window, modalities and efforts under another+ // model's name.const user = userEvent.setup();- let settle: (matches: ModelsDevMatch[]) => void = () => {};- vi.spyOn(modelsApi, 'searchModelsDev').mockImplementation(- () => new Promise<ModelsDevMatch[]>((resolve) => { settle = resolve; }),- );- const { onCommit } = renderEditor();+ const pending = new Map<string, (matches: ModelsDevMatch[]) => void>();+ search.mockImplementation((query) => new Promise((resolve) => { pending.set(query, resolve); }));+ renderEditor();- const id = screen.getByLabelText('Backend model ID');- await user.type(id, 'anthropic/claude-sonnet-4-5');- await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));- await user.clear(id);- await user.type(id, 'openai/gpt-5');+ await user.type(modelField(), 'sonnet');+ await waitFor(() => expect(pending.has('sonnet')).toBe(true));+ await user.type(modelField(), '-4-5');+ await waitFor(() => expect(pending.has('sonnet-4-5')).toBe(true));- await act(async () => { settle([match()]); });+ await act(async () => { pending.get('sonnet')?.([match()]); });+ expect(screen.queryByRole('option', { name: /Claude Sonnet 4\.5/ })).toBeNull();- expect(screen.queryByText('models.dev · anthropic/claude-sonnet-4-5')).toBeNull();- expect(screen.queryByRole('option')).toBeNull();- expect((screen.getByLabelText('Display name') as HTMLInputElement).value).toBe('');- expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('');- // The retired request also releases the button, so the new id can be filled.- expect((screen.getByRole('button', { name: 'Fill from models.dev' }) as HTMLButtonElement).disabled).toBe(false);+ await act(async () => { pending.get('sonnet-4-5')?.([match({ display_name: 'Sonnet, current' })]); });+ expect(await screen.findByRole('option', { name: /Sonnet, current/ })).toBeTruthy();+ });++ it('lets the user name their own model while models.dev is slow', async () => {+ const user = userEvent.setup();+ search.mockImplementation(() => new Promise<ModelsDevMatch[]>(() => {}));+ const { onCommit } = renderEditor();+ await user.type(modelField(), 'private/model');+ expect(await screen.findByText('Searching models.dev…')).toBeTruthy();+ // The escape is a row in every open state: a catalog that is slow to answer+ // is not a reason the user may not name their own model.+ await user.click(screen.getByRole('option', { name: 'Use "private/model" as the model ID' }));await user.click(screen.getByRole('button', { name: 'Add model' }));+expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({- id: 'openai/gpt-5',+ id: 'private/model',origin: 'manual',models_dev_id: null,- display_name: null,- context_window: null,- reasoning_efforts: [],}));});+ it('names an unreachable models.dev in its own words and still offers the query', async () => {+ const user = userEvent.setup();+ search+ .mockRejectedValueOnce(new Error('offline'))+ .mockRejectedValueOnce(new ApiCallError('upstream_unavailable', 'modelHub.errors.models_dev_unavailable', true));+ renderEditor();++ await user.type(modelField(), 'private/model');+ expect(await screen.findByText('models.dev could not be reached')).toBeTruthy();+ expect(screen.getByRole('option', { name: 'Use "private/model" as the model ID' })).toBeTruthy();++ // The server separates 「the catalog itself is down」 from every other+ // failure, and its key is never what the user reads.+ await user.type(modelField(), '-2');+ expect(await screen.findByText('models.dev unavailable')).toBeTruthy();+ expect(screen.queryByText('modelHub.errors.models_dev_unavailable')).toBeNull();+ expect(modelField().value).toBe('private/model-2');+ });+it('retires filled metadata once the ID it describes is replaced', async () => {- // The settled answer is the same hazard as the one in flight: a fill fetched- // for one id must not end up saved under another.+ // A fill describes the model it was chosen for. Keeping its facts under a+ // different id would save one model's metadata under another model's name.const user = userEvent.setup();- vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([match()]);+ search.mockResolvedValue([match()]);const { onCommit } = renderEditor();- const id = screen.getByLabelText('Backend model ID');- await user.type(id, 'anthropic/claude-sonnet-4-5');- await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));- await screen.findByText('models.dev · anthropic/claude-sonnet-4-5');+ await user.type(modelField(), 'sonnet');+ await user.click(await screen.findByRole('option', { name: /Claude Sonnet 4\.5/ }));+ expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('200,000');- await user.clear(id);- await user.type(id, 'openai/gpt-5');+ await user.clear(modelField());+ await user.type(modelField(), 'openai/gpt-5');- expect(screen.queryByText('models.dev · anthropic/claude-sonnet-4-5')).toBeNull();expect((screen.getByLabelText('Display name') as HTMLInputElement).value).toBe('');expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('');expect((screen.getByLabelText('Maximum output') as HTMLInputElement).value).toBe('');@@ -345,13 +408,13 @@ describe('BackendModelEditorDialog', () => {const user = userEvent.setup();const { onCommit } = renderEditor();- await user.type(screen.getByLabelText('Backend model ID'), 'internal/hous');+ await user.type(modelField(), 'internal/hous');await user.type(screen.getByLabelText('Display name'), 'House model');await user.type(screen.getByLabelText('Context window'), '32000');await user.click(modalities('Input').getByRole('checkbox', { name: 'Image' }));// A row that owes models.dev nothing has nothing to retire: fixing a typo in// the id is not a decision to retype everything under it.- await user.type(screen.getByLabelText('Backend model ID'), 'e');+ await user.type(modelField(), 'e');await user.click(screen.getByRole('button', { name: 'Add model' }));expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({@@ -363,6 +426,63 @@ describe('BackendModelEditorDialog', () => {}));});+ it('keeps what the user typed over a fill while retiring the rest of it', async () => {+ // The half the two cases above do not reach: a row that is part fill and+ // part the user's own typing. Which half a field belongs to is decided+ // against the fill itself — `retireModelsDevMatch` owns that rule and states+ // it over every field — so this asserts the wiring the helper cannot see,+ // the three boxes the editor holds as text until it commits.+ const user = userEvent.setup();+ search.mockResolvedValue([match()]);+ const { onCommit } = renderEditor();++ await user.type(modelField(), 'sonnet');+ await user.click(await screen.findByRole('option', { name: /Claude Sonnet 4\.5/ }));+ await user.clear(screen.getByLabelText('Display name'));+ await user.type(screen.getByLabelText('Display name'), 'House relay');+ await user.clear(screen.getByLabelText('Maximum output'));+ await user.type(screen.getByLabelText('Maximum output'), '8000');++ await user.clear(modelField());+ await user.type(modelField(), 'openai/gpt-5');++ // Theirs stands. Correcting an id is not a decision to retype the form.+ expect((screen.getByLabelText('Display name') as HTMLInputElement).value).toBe('House relay');+ // Grouped, because leaving the box is what formats it — their 8000, shown+ // the way every token count is.+ expect((screen.getByLabelText('Maximum output') as HTMLInputElement).value).toBe('8,000');+ // The fill's own answers go, because they describe a model this row no+ // longer names.+ expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('');+ expect(answered('Reasoning')).toBe('No');++ await user.click(screen.getByRole('button', { name: 'Add model' }));+ expect(onCommit).toHaveBeenCalledWith({+ ...blankBackendModel(),+ id: 'openai/gpt-5',+ display_name: 'House relay',+ max_output_tokens: 8000,+ });+ });++ it('closes the suggestion list once the user is working somewhere else', async () => {+ // It is an overlay over the fields below it, so an open list the user has+ // left is covering the controls they moved on to.+ const user = userEvent.setup();+ search.mockResolvedValue([match()]);+ renderEditor();++ await user.type(modelField(), 'sonnet');+ expect(await screen.findByRole('option', { name: /Claude Sonnet 4\.5/ })).toBeTruthy();++ await user.click(screen.getByLabelText('Display name'));++ expect(screen.queryByRole('listbox')).toBeNull();+ // The id the user typed is theirs either way: leaving the list is not+ // abandoning the field.+ expect(modelField().value).toBe('sonnet');+ });+it('keeps a display name optional, trimmed, and null when the box is empty', async () => {const user = userEvent.setup();const unnamed: BackendModel = { ...blankBackendModel(), id: 'gpt-5-codex', context_window: 400000 };@@ -391,7 +511,7 @@ describe('BackendModelEditorDialog', () => {const user = userEvent.setup();const { onCommit } = renderEditor({ effortSuggestions: ['low'] });- await user.type(screen.getByLabelText('Backend model ID'), 'm');+ await user.type(modelField(), 'm');await user.click(capability('Reasoning').getByRole('radio', { name: 'Yes' }));await user.click(screen.getByRole('checkbox', { name: 'low' }));await user.click(screen.getByRole('button', { name: 'Custom effort' }));@@ -477,13 +597,11 @@ describe('BackendModelEditorDialog', () => {it('carries a capability models.dev does not state through the fill', async () => {const user = userEvent.setup();- vi.spyOn(modelsApi, 'searchModelsDev')- .mockResolvedValue([match({ supports_tools: null, supports_reasoning: null, reasoning_efforts: [] })]);+ search.mockResolvedValue([match({ supports_tools: null, supports_reasoning: null, reasoning_efforts: [] })]);const { onCommit } = renderEditor();- await user.type(screen.getByLabelText('Backend model ID'), 'anthropic/claude-sonnet-4-5');- await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));- await screen.findByText('models.dev · anthropic/claude-sonnet-4-5');+ await user.type(modelField(), 'sonnet');+ await user.click(await screen.findByRole('option', { name: /Claude Sonnet 4\.5/ }));expect(answered('Tool calling')).toBe('Not set');expect(answered('Reasoning')).toBe('Not set');@@ -530,7 +648,7 @@ describe('BackendModelEditorDialog', () => {const user = userEvent.setup();const { onCancel, onCommit } = renderEditor();- await user.type(screen.getByLabelText('Backend model ID'), 'abandoned');+ await user.type(modelField(), 'abandoned');// The header close and the footer button are the same decision, so both// discard the draft rather than one of them saving it.const cancels = screen.getAllByRole('button', { name: 'Cancel' });diff --git a/ui/src/components/settings/models/BackendModelEditorDialog.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.tsxindex 0d4ba72b9..2a9b13bfe 100644--- a/ui/src/components/settings/models/BackendModelEditorDialog.tsx+++ b/ui/src/components/settings/models/BackendModelEditorDialog.tsx@@ -5,20 +5,24 @@// baseline — an editor that saved on its own would make every row its own// mutation and leave no way to cancel a list still being arranged.//-// models.dev is a metadata source here, not an authority: it fills fields the-// user can then change, and it never touches the backend model id, which is the-// routing identity the user typed.+// models.dev is a metadata source here, not an authority: the first field is a+// search, and choosing a suggestion fills the model id along with every fact the+// catalog knows about it — all of them still editable, because what the user+// wanted may be the model next to the one they found.import * as React from 'react';-import { Check, Database, DownloadCloud, LoaderCircle, Plus } from 'lucide-react';+import { Check, Plus } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { Input } from '@/components/ui/input';import { SegmentedRadio } from '@/components/ui/segmented';+import { isComposingKey } from '@/lib/imeComposition';import { cn } from '@/lib/utils';-import { applyModelsDevMatch, blankBackendModel } from './backendCatalog';+import { applyModelsDevMatch, backendModelId, blankBackendModel, draftWithId, opencodeMenuIdentity, retireModelsDevMatch } from './backendCatalog';import { Field } from './dialogFields';+import { formatTokensCompact } from './format';+import type { StandardVendors } from './menus/identifiers';import { apiFailure, modelsApi } from './modelsApi';import { modelsDevFillFailureKey } from './serverCopy';import {@@ -33,7 +37,11 @@ import {type ModelsDevMatch,} from './types';-type FillState = 'idle' | 'loading' | 'empty' | 'error';+type FillState = 'idle' | 'loading' | 'error';++/** Long enough that a typed word is one read rather than one per keystroke,+ * short enough that the list is there when the typing stops. */+const LOOKUP_DEBOUNCE_MS = 250;/** Digits only. A pasted 「163,840」 is the same number as 「163840」, and the* field renders the grouped form itself, so refusing the separator would refuse@@ -111,14 +119,22 @@ export const BackendModelEditorDialog: React.FC<{backend: AgentBackend;/** null opens the editor in add mode. */model: BackendModel | null;+ /** What the picker's 「add as a custom model」 action carried over, so the+ * editor opens on that query instead of asking for it a second time. */+ seedId?: string;/** Ids the draft catalog already holds; a second row may not claim one. */takenIds: ReadonlySet<string>;/** Effort values this backend's other rows already use. Suggestions, never a* vocabulary — every effort is sent verbatim and any string is equally valid. */effortSuggestions: readonly string[];+ /** OpenCode's standard vendor ids, as the server projects them — the input to+ * the shared id rule both typeahead rows resolve through (`backendModelId`).+ * Empty for every other backend, and for a server too old to project them:+ * `custom/` is then the answer for every query, which OpenCode still accepts. */+ standardVendors: StandardVendors;onCancel: () => void;onCommit: (model: BackendModel) => void;-}> = ({ open, backend, model, takenIds, effortSuggestions, onCancel, onCommit }) => {+}> = ({ open, backend, model, seedId, takenIds, effortSuggestions, standardVendors, onCancel, onCommit }) => {const { t } = useTranslation();const creating = model === null;const [draft, setDraft] = React.useState<BackendModel>(() => model ?? blankBackendModel());@@ -132,11 +148,22 @@ export const BackendModelEditorDialog: React.FC<{* own answer is still in hand. */const [fillFailedKey, setFillFailedKey] = React.useState('settings.models.gateway.modelEditor.fillFailed');const [matches, setMatches] = React.useState<ModelsDevMatch[]>([]);- const [matchesOpen, setMatchesOpen] = React.useState(false);+ /** The query the typeahead is answering; empty closes it. Held apart from+ * `draft.id` because choosing a suggestion writes the id, and a list keyed on+ * the id would reopen on the answer it just gave. */+ const [lookup, setLookup] = React.useState('');+ const [active, setActive] = React.useState(0);const [customOpen, setCustomOpen] = React.useState(false);const [customEffort, setCustomEffort] = React.useState('');const [submitted, setSubmitted] = React.useState(false);const fillAttempt = React.useRef(0);+ /** The whole editable surface exactly as the last models.dev fill left it —+ * the draft and the three fields held as text. A value that still matches it+ * is models.dev's answer; a value that differs is the user's own typing. Null+ * once no answer is outstanding, which is the only state `changeId` needs to+ * tell apart. A ref, not state: nothing renders from it. */+ const filled = React.useRef<{ draft: BackendModel; name: string; context: string; output: string } | null>(null);+ const listId = React.useId();const seed = React.useCallback((next: BackendModel) => {setDraft(next);@@ -145,20 +172,90 @@ export const BackendModelEditorDialog: React.FC<{setOutputText(groupTokens(next.max_output_tokens));setFillState('idle');setMatches([]);- setMatchesOpen(false);+ setActive(0);setCustomOpen(false);setCustomEffort('');setSubmitted(false);+ filled.current = null;}, []);React.useEffect(() => {- if (open) seed(model ?? blankBackendModel());- else fillAttempt.current += 1;- }, [model, open, seed]);+ if (!open) {+ fillAttempt.current += 1;+ return;+ }+ // A seeded add opens with the query already running: the user typed it in+ // the picker, and asking for it again would be the surface forgetting. The+ // id it lands as goes through the one chokepoint like every other produced+ // id — a seed that skipped it would be an id the backend refuses, arriving+ // by the one route nobody watches. The query stays what was typed: it is a+ // models.dev search, and searching for the resolved id would search for the+ // vendor prefix the resolver just added.+ const next = model ?? draftWithId(blankBackendModel(), seedId?.trim() ?? '', backend, standardVendors);+ seed(next);+ setLookup(model === null ? seedId?.trim() ?? '' : '');+ }, [backend, model, open, seed, seedId, standardVendors]);++ /**+ * The typeahead: what has been typed so far, answered by models.dev.+ *+ * Debounced, because the query is a keystroke and the answer is a network+ * hop. Aborted on the way out, so a reply to a query the user has already+ * replaced never lands — and the attempt counter is bumped on every exit,+ * because aborting raises inside the request, and a stale attempt that still+ * matched would report 「models.dev could not be reached」 about a search+ * nobody is waiting for.+ */+ React.useEffect(() => {+ if (!creating || lookup === '') {+ fillAttempt.current += 1;+ setFillState('idle');+ setMatches([]);+ return;+ }+ const attempt = ++fillAttempt.current;+ setFillState('loading');+ setMatches([]);+ const controller = new AbortController();+ const timer = window.setTimeout(() => {+ void (async () => {+ try {+ const found = await modelsApi.searchModelsDev(lookup, controller.signal);+ if (attempt !== fillAttempt.current) return;+ setMatches(found);+ setActive(0);+ setFillState('idle');+ } catch (error) {+ if (attempt !== fillAttempt.current) return;+ setFillFailedKey(modelsDevFillFailureKey(apiFailure(error)?.detail));+ setFillState('error');+ }+ })();+ }, LOOKUP_DEBOUNCE_MS);+ return () => {+ window.clearTimeout(timer);+ controller.abort();+ fillAttempt.current += 1;+ };+ }, [creating, lookup]);const context = parseTokens(contextText);const output = parseTokens(outputText);const trimmedId = draft.id.trim();+ /**+ * The row as it would be stored.+ *+ * Add mode resolves the id through the one chokepoint here, so the rules below+ * and the row `commit` sends judge and write the same value — the one the+ * backend receives. Checking the raw box instead would measure a length and a+ * collision against an id that does not exist yet: `custom/` is part of what+ * gets stored, and a row already holding `custom/foo` collides with a freshly+ * typed `foo`.+ *+ * An edit mints nothing. The id came from the server and is held read-only, so+ * resolving it again would rename a saved row whose id predates the rule.+ */+ const resolved = creating ? draftWithId(draft, trimmedId, backend, standardVendors) : draft;// Every id rule is a rule about what the user may type, and only add mode lets// them type it — an edit shows the id read-only. Judging a value the dialog// itself locks is what made a persisted row whose id predates the length@@ -168,11 +265,18 @@ export const BackendModelEditorDialog: React.FC<{? null: trimmedId === ''? 'required'- : trimmedId.length > BACKEND_MODEL_ID_MAX_LENGTH+ : resolved.id.length > BACKEND_MODEL_ID_MAX_LENGTH? 'tooLong'- : takenIds.has(trimmedId)- ? 'duplicate'- : null;+ // Asked of the resolved id for the same reason the length and the+ // collision are: `custom/` is part of what gets stored, so the shape+ // rule has to judge the value the backend will actually parse. It is+ // the last rule that can be answered without the list, and the+ // collision check below is the one that needs it.+ : !opencodeMenuIdentity(resolved.id, backend)+ ? 'invalid'+ : takenIds.has(resolved.id)+ ? 'duplicate'+ : null;const valid = idError === null && context.ok && output.ok;const patch = (next: Partial<BackendModel>) => setDraft((current) => ({ ...current, ...next }));@@ -194,14 +298,29 @@ export const BackendModelEditorDialog: React.FC<{});const applyMatch = (match: ModelsDevMatch) => {- // `applyModelsDevMatch` leaves `id` alone: a fill never renames the row, even- // when the chosen match is published under a different id.- setDraft((current) => applyModelsDevMatch(current, match, creating ? 'models_dev' : current.origin));- setNameText(match.display_name ?? '');- setContextText(groupTokens(match.context_window));- setOutputText(groupTokens(match.max_output_tokens));- setMatchesOpen(false);- setFillState('idle');+ // The id comes with it — the row is the model that was chosen, under the id+ // its provider publishes it as. `origin` is `models_dev` unconditionally+ // because the typeahead is add mode's field: a saved row's own creation path+ // is never re-decided here.+ const next = applyModelsDevMatch(draft, match, 'models_dev', backend, standardVendors);+ const name = match.display_name ?? '';+ const context = groupTokens(match.context_window);+ const output = groupTokens(match.max_output_tokens);+ setDraft(next);+ setNameText(name);+ setContextText(context);+ setOutputText(output);+ filled.current = { draft: next, name, context, output };+ setLookup('');+ };++ /** Take the query as the id itself, resolved to one this backend accepts. The+ * draft's other fields are the user's own by construction: whatever an+ * earlier fill still owned was retired by `changeId` the moment they typed+ * again, and what survived that is what they typed themselves. */+ const takeLookupAsId = () => {+ setDraft((current) => draftWithId(current, lookup.trim(), backend, standardVendors));+ setLookup('');};/**@@ -209,52 +328,61 @@ export const BackendModelEditorDialog: React.FC<{* request still in flight, the match list it would open, and the metadata an* earlier fill already poured in.*- * `models_dev_id` decides how far that goes, because it is the schema's own- * record of where a row's metadata came from. A filled draft describes the id- * that fetched it — keeping its context window, modalities or efforts would- * save one model's facts under another model's name — so it goes back to- * blank. A hand-typed draft owes models.dev nothing and keeps every field,- * since correcting a typo in the id is not a decision to retype the rest.+ * How far that reaches is decided field by field against the fill itself, not+ * by one flag over the whole row — see `retireModelsDevMatch`. A draft that+ * owes models.dev nothing keeps every field, since correcting a typo in the id+ * is not a decision to retype the rest, and after one retirement there is+ * nothing left to retire.*/const changeId = (nextId: string) => {- fillAttempt.current += 1;- setFillState('idle');- setMatches([]);- setMatchesOpen(false);- if (draft.models_dev_id === null) {+ setActive(0);+ setLookup(nextId.trim());+ const fill = filled.current;+ if (fill === null) {patch({ id: nextId });return;}- setDraft({ ...blankBackendModel(), id: nextId });- setNameText('');- setContextText('');- setOutputText('');+ setDraft((current) => retireModelsDevMatch(current, fill.draft, nextId));+ if (nameText === fill.name) setNameText('');+ if (contextText === fill.context) setContextText('');+ if (outputText === fill.output) setOutputText('');+ filled.current = null;};- const fill = () => {- const query = trimmedId;- if (query === '') return;- const attempt = ++fillAttempt.current;- setFillState('loading');- setMatchesOpen(false);- void (async () => {- try {- const found = await modelsApi.searchModelsDev(query);- if (attempt !== fillAttempt.current) return;- setMatches(found);- if (found.length === 0) {- setFillState('empty');- return;- }- setFillState('idle');- if (found.length === 1) applyMatch(found[0]);- else setMatchesOpen(true);- } catch (error) {- if (attempt !== fillAttempt.current) return;- setFillFailedKey(modelsDevFillFailureKey(apiFailure(error)?.detail));- setFillState('error');- }- })();+ // The escape is the last row in every open state, including 「searching」 and+ // 「unavailable」: models.dev being slow or down is not a reason the user may+ // not name their own model.+ const lookupOpen = creating && lookup !== '';+ const rowCount = matches.length + 1;+ const activeRow = Math.min(active, rowCount - 1);+ const chooseRow = (index: number) => {+ if (index < matches.length) applyMatch(matches[index]);+ else takeLookupAsId();+ };++ const onIdKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {+ // Every key below is one an IME candidate window uses too — Enter accepts+ // the characters being composed, the arrows move through the candidates —+ // so while one is open none of them are aimed at this list.+ if (isComposingKey(event)) return;+ if (!lookupOpen) return;+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {+ event.preventDefault();+ const step = event.key === 'ArrowDown' ? 1 : rowCount - 1;+ setActive((current) => (Math.min(current, rowCount - 1) + step) % rowCount);+ } else if (event.key === 'Home' || event.key === 'End') {+ event.preventDefault();+ setActive(event.key === 'Home' ? 0 : rowCount - 1);+ } else if (event.key === 'Enter') {+ event.preventDefault();+ chooseRow(activeRow);+ } else if (event.key === 'Escape') {+ // Only the list closes. Without this the dialog would take the same key+ // and discard a row the user is still filling in.+ event.preventDefault();+ event.stopPropagation();+ setLookup('');+ }};const addCustomEffort = () => {@@ -269,8 +397,7 @@ export const BackendModelEditorDialog: React.FC<{setSubmitted(true);if (!valid) return;onCommit({- ...draft,- id: trimmedId,+ ...resolved,// An empty box is 「no name」, not an empty name: the schema takes null and// the list falls back to the id.display_name: nameText.trim() || null,@@ -306,17 +433,31 @@ export const BackendModelEditorDialog: React.FC<{<div className="model-hub-model-editor-body min-h-0 flex-1 overflow-y-auto"><section className="model-hub-model-section"><SectionLabel>{t('settings.models.gateway.modelEditor.section.basic')}</SectionLabel>- <div className="flex flex-col gap-2 sm:flex-row sm:items-end">- <Field- label={t('settings.models.gateway.modelEditor.id.label')}- className="min-w-0 flex-1 gap-1.5"- labelClassName="model-hub-model-field-label"- >- {(id) => (+ <Field+ label={t('settings.models.gateway.modelEditor.id.label')}+ className="min-w-0 gap-1.5"+ labelClassName="model-hub-model-field-label"+ >+ {(id) => (+ <div+ className="relative min-w-0"+ // The list is an overlay over the fields below it, so it lives+ // exactly as long as the user is in it: focus moving anywhere+ // outside closes it, the same containment check+ // `SourceDetailPanel` uses. Its own rows never trigger this —+ // they refuse focus on mousedown to keep the caret in the+ // field — so choosing one still runs.+ onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) setLookup(''); }}+ ><Inputid={id}value={draft.id}readOnly={!creating}+ role="combobox"+ aria-expanded={lookupOpen}+ aria-controls={listId}+ aria-autocomplete="list"+ aria-activedescendant={lookupOpen ? `${listId}-${activeRow}` : undefined}aria-invalid={Boolean(idHint)}// The ceiling belongs to the field that can still be typed// into; a read-only legacy id is shown in full, not clipped.@@ -324,69 +465,87 @@ export const BackendModelEditorDialog: React.FC<{spellCheck={false}autoComplete="off"onChange={(event) => changeId(event.target.value)}+ onKeyDown={onIdKeyDown}placeholder={t('settings.models.gateway.modelEditor.id.placeholder') as string}className="model-hub-model-control w-full font-mono text-[12.5px] read-only:text-muted"/>- )}- </Field>- <Button- type="button"- variant="outline"- className="model-hub-model-control shrink-0 rounded-md px-3.5 text-[12.5px] font-semibold"- disabled={trimmedId === '' || fillState === 'loading'}- onClick={fill}- >- {fillState === 'loading'- ? <LoaderCircle className="animate-spin" aria-hidden="true" />- : <DownloadCloud aria-hidden="true" />}- {t('settings.models.gateway.modelEditor.fill')}- </Button>- </div>+ {lookupOpen && (+ // Over the form, not in it: the fields below keep their+ // places while the list opens and closes on every keystroke.+ <div className="model-hub-model-match-list absolute inset-x-0 top-full z-30 mt-1.5 flex flex-col">+ {fillState !== 'idle' && (+ <p className="model-hub-model-match-state" role="status">+ {t(fillState === 'loading' ? 'settings.models.gateway.modelEditor.lookupLoading' : fillFailedKey)}+ </p>+ )}+ <div+ id={listId}+ role="listbox"+ aria-label={t('settings.models.gateway.modelEditor.matches') as string}+ className="flex min-w-0 flex-col"+ >+ {matches.map((match, index) => {+ const context = formatTokensCompact(match.context_window);+ return (+ <button+ key={match.models_dev_id}+ type="button"+ role="option"+ id={`${listId}-${index}`}+ aria-selected={activeRow === index}+ // The field keeps the caret: a click that moved+ // focus would close the list before it fired.+ onMouseDown={(event) => event.preventDefault()}+ onMouseEnter={() => setActive(index)}+ onClick={() => applyMatch(match)}+ className={cn('model-hub-model-match flex min-w-0 items-center gap-2.5 text-left', activeRow === index && 'is-selected')}+ >+ <span className="flex min-w-0 flex-1 items-center gap-2">+ {/* No `shrink-0`: pinning the name at its full+ * width is what its own `truncate` is there+ * to prevent, and a name long enough to need+ * cutting would instead squeeze the id and+ * the provider out of the row before running+ * past its edge. Left to shrink, the three+ * yield in proportion to what they show, so+ * the longest gives up the most. */}+ <span className="model-hub-model-match-name truncate">{match.display_name ?? match.model_id}</span>+ <span className="model-hub-model-match-id truncate font-mono">{match.model_id}</span>+ <span className="model-hub-model-match-meta truncate">{match.provider_name}</span>+ </span>+ {context && <span className="model-hub-model-match-meta shrink-0">{context}</span>}+ </button>+ );+ })}+ <button+ type="button"+ role="option"+ id={`${listId}-${matches.length}`}+ aria-selected={activeRow === matches.length}+ onMouseDown={(event) => event.preventDefault()}+ onMouseEnter={() => setActive(matches.length)}+ onClick={takeLookupAsId}+ className={cn(+ 'model-hub-model-match model-hub-model-match--literal flex min-w-0 items-center text-left',+ activeRow === matches.length && 'is-selected',+ )}+ >+ {/* The id it will create, not the raw query: on+ OpenCode those differ, and the row that names the+ other one would be describing a different model. */}+ <span className="model-hub-model-match-literal min-w-0 truncate">+ {t('settings.models.gateway.modelEditor.useAsId', {+ query: backendModelId(lookup.trim(), backend, standardVendors),+ })}+ </span>+ </button>+ </div>+ </div>+ )}+ </div>+ )}+ </Field>{idHint && <p className="model-hub-model-error" role="alert">{idHint}</p>}- {fillState === 'empty' && <p className="model-hub-model-error" role="status">{t('settings.models.gateway.modelEditor.fillEmpty')}</p>}- {fillState === 'error' && <p className="model-hub-model-error" role="status">{t(fillFailedKey)}</p>}-- {draft.models_dev_id && (- <div className="model-hub-model-source-strip flex min-w-0 items-center gap-2.5">- <Database className="size-[14px] shrink-0 text-muted" aria-hidden="true" />- <span className="model-hub-model-source-id shrink-0 font-mono">{`models.dev · ${draft.models_dev_id}`}</span>- <span className="model-hub-model-source-note min-w-0 flex-1 truncate">{t('settings.models.gateway.modelEditor.filled')}</span>- <button- type="button"- className="model-hub-model-source-view shrink-0"- aria-expanded={matchesOpen}- disabled={matches.length === 0}- onClick={() => setMatchesOpen((value) => !value)}- >- {t('settings.models.gateway.modelEditor.viewMatches')}- </button>- </div>- )}-- {matchesOpen && matches.length > 0 && (- <div className="model-hub-model-match-list flex flex-col" role="listbox" aria-label={t('settings.models.gateway.modelEditor.matches') as string}>- {matches.map((match) => {- const selected = draft.models_dev_id === match.models_dev_id;- return (- <button- key={match.models_dev_id}- type="button"- role="option"- aria-selected={selected}- onClick={() => applyMatch(match)}- className={cn('model-hub-model-match flex min-w-0 items-center gap-2.5 text-left', selected && 'is-selected')}- >- <span className="min-w-0 flex-1">- <span className="model-hub-model-match-name block truncate">{match.display_name ?? match.model_id}</span>- <span className="model-hub-model-match-id block truncate font-mono">{match.models_dev_id}</span>- </span>- <span className="model-hub-pill model-hub-fill-0a shrink-0 border border-border text-muted">{match.provider_name}</span>- {selected && <Check className="model-hub-ink-mint size-4 shrink-0" aria-hidden="true" />}- </button>- );- })}- </div>- )}<Fieldlabel={t('settings.models.gateway.modelEditor.displayName.label')}@@ -501,6 +660,9 @@ export const BackendModelEditorDialog: React.FC<{placeholder={t('settings.models.gateway.modelEditor.customEffortPlaceholder') as string}onChange={(event) => setCustomEffort(event.target.value)}onKeyDown={(event) => {+ // The Enter that accepts an IME candidate is not the+ // Enter that names an effort.+ if (isComposingKey(event)) return;if (event.key === 'Enter') {event.preventDefault();addCustomEffort();diff --git a/ui/src/components/settings/models/BackendModelPickerDialog.test.tsx b/ui/src/components/settings/models/BackendModelPickerDialog.test.tsxnew file mode 100644index 000000000..1cd2e23fd--- /dev/null+++ b/ui/src/components/settings/models/BackendModelPickerDialog.test.tsx@@ -0,0 +1,266 @@+// @vitest-environment jsdom+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import type { ChosenCandidate } from './backendCatalog';+import { BackendModelPickerDialog } from './BackendModelPickerDialog';+import { modelsApi } from './modelsApi';+import type { BackendModelCandidates, ModelCandidate } from './types';++const candidate = (id: string, overrides: Partial<ModelCandidate> = {}): ModelCandidate => ({+ id,+ display_name: null,+ reasoning_efforts: [],+ suppliers: [],+ origin: 'provider',+ ...overrides,+});++const read = (groups: Partial<BackendModelCandidates> = {}): BackendModelCandidates => ({+ builtin: groups.builtin ?? [],+ providers: groups.providers ?? [],+ in_list: groups.in_list ?? [],+});++const answers = (groups: Partial<BackendModelCandidates> = {}) =>+ vi.spyOn(modelsApi, 'getAgentModelCandidates').mockResolvedValue(read(groups));++const renderPicker = (overrides: Partial<React.ComponentProps<typeof BackendModelPickerDialog>> = {}) => {+ const onCancel = vi.fn();+ const onAdd = vi.fn();+ const onCustom = vi.fn();+ render(+ <I18nextProvider i18n={i18n}>+ <BackendModelPickerDialog+ open+ backend="claude"+ listedIds={new Set()}+ onCancel={onCancel}+ onAdd={onAdd}+ onCustom={onCustom}+ {...overrides}+ />+ </I18nextProvider>,+ );+ return { onCancel, onAdd, onCustom };+};++const group = (name: string) => within(screen.getByRole('group', { name }));+const BUILT_IN = 'Claude Code built-in';+const PROVIDERS = 'From your providers';+const LISTED = 'Already in the list';+const search = () => screen.getByLabelText('Search models or providers');+// The confirmation, whether it is counting picks or naming the action it would+// perform. `Add custom model…` is a different offer and must not answer to this.+const confirm = () => screen.getByRole('button', { name: /^Add (models|\d+ models?)$/ }) as HTMLButtonElement;++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe('BackendModelPickerDialog', () => {+ it('shows each group as the server served it, and every row as what it can say', async () => {+ answers({+ builtin: [candidate('gpt-6', { origin: 'builtin' }), candidate('gpt-6-mini', { origin: 'builtin' })],+ providers: [candidate('glm-5.2', {+ display_name: 'GLM 5.2',+ suppliers: [+ { source_id: 'src_a', source_name: 'Primary relay', model_id: 'glm-5.2-air' },+ { source_id: 'src_b', source_name: 'Backup relay', model_id: 'glm-5.2' },+ ],+ })],+ });+ renderPicker();++ expect(await screen.findByRole('heading', { name: 'Add Claude Code models' })).toBeTruthy();+ // A built-in row has nothing but an id, so the id is its label rather than a+ // sub-line under an empty one.+ expect(group(BUILT_IN).getAllByRole('checkbox').map((row) => row.textContent))+ .toEqual(['gpt-6', 'gpt-6-mini']);+ expect(group(BUILT_IN).getByText('2')).toBeTruthy();+ // A provider row names the model, its id, and — in the order the server gave+ // them — who can serve it. That order is the route's own preference, so it is+ // not the client's to sort.+ expect(group(PROVIDERS).getByRole('checkbox').textContent).toBe('GLM 5.2glm-5.2Primary relayBackup relay');+ expect(screen.queryByRole('group', { name: LISTED })).toBeNull();+ });++ it('keeps a pick through the query that hid it, and adds in the order offered', async () => {+ const user = userEvent.setup();+ answers({+ builtin: [candidate('gpt-6', { origin: 'builtin' })],+ providers: [candidate('glm-5.2', { display_name: 'GLM 5.2' })],+ });+ const { onAdd } = renderPicker();++ // Picked in the reverse of the offered order, and through a search that+ // leaves only one of them on screen.+ await user.click(await screen.findByRole('checkbox', { name: /GLM 5\.2/ }));+ await user.type(search(), 'gpt');+ expect(screen.queryByRole('checkbox', { name: /GLM 5\.2/ })).toBeNull();+ await user.click(screen.getByRole('checkbox', { name: 'gpt-6' }));+ await user.clear(search());++ // A query narrows what is shown, never what is chosen: the pick the search+ // hid is still a pick, and the confirmation still counts it.+ expect(screen.getByRole('checkbox', { name: /GLM 5\.2/ }).getAttribute('aria-checked')).toBe('true');+ await user.click(screen.getByRole('button', { name: 'Add 2 models' }));++ expect(onAdd).toHaveBeenCalledTimes(1);+ // Group order, not click order: additions land where the picker offered+ // them, so the list the user gets back reads the way the one they picked from+ // did.+ const chosen: ChosenCandidate[] = onAdd.mock.calls[0][0];+ expect(chosen.map((entry) => entry.candidate.id)).toEqual(['gpt-6', 'glm-5.2']);+ // The property behind every one of them, whatever was picked and in whatever+ // order: what a pick promises is the projection of the suppliers its own row+ // displayed. Not a fixture of expected pairs — derived from the candidate the+ // object carries, so the two can never describe different models.+ for (const entry of chosen) {+ expect(entry.expected_suppliers).toEqual(+ entry.candidate.suppliers.map(({ source_id, model_id }) => ({ source_id, model_id })),+ );+ }+ });++ it('refuses to confirm nothing, and names what it would do instead', async () => {+ const user = userEvent.setup();+ answers({ builtin: [candidate('gpt-6', { origin: 'builtin' })] });+ const { onAdd } = renderPicker();++ await waitFor(() => expect(confirm().textContent).toBe('Add models'));+ expect(confirm().disabled).toBe(true);++ await user.click(screen.getByRole('checkbox', { name: 'gpt-6' }));+ expect(confirm().textContent).toBe('Add 1 model');+ expect(confirm().disabled).toBe(false);++ // A pick is a toggle, so the way back out is the way in.+ await user.click(screen.getByRole('checkbox', { name: 'gpt-6' }));+ expect(confirm().textContent).toBe('Add models');+ expect(confirm().disabled).toBe(true);+ expect(onAdd).not.toHaveBeenCalled();+ });++ it('finds an already-added model by its supplier and shows it as already added', async () => {+ const user = userEvent.setup();+ // Searching is how a long list is used, so a search that finds nothing has to+ // distinguish 「no such model」 from 「you already have it」 — otherwise the+ // answer is 「add a custom model」 for a model that is already in the list.+ answers({+ builtin: [candidate('gpt-6', { origin: 'builtin' })],+ in_list: [candidate('glm-5.2', {+ display_name: 'GLM 5.2',+ suppliers: [{ source_id: 'src_a', source_name: 'Primary relay', model_id: 'glm-5.2-air' }],+ })],+ });+ const { onAdd } = renderPicker({ listedIds: new Set(['glm-5.2']) });++ // With no query the list shows only what can be added.+ expect(await screen.findByRole('checkbox', { name: 'gpt-6' })).toBeTruthy();+ expect(screen.queryByRole('group', { name: LISTED })).toBeNull();++ await user.type(search(), 'primary');+ const row = group(LISTED).getByRole('checkbox') as HTMLButtonElement;+ // Its chips are what the query matched, so they stay on screen.+ expect(row.textContent).toBe('GLM 5.2glm-5.2Primary relay');+ // Checked because it is in the list, disabled because that is not an offer.+ expect(row.getAttribute('aria-checked')).toBe('true');+ expect(row.disabled).toBe(true);+ await user.click(row);+ expect(screen.getByRole('button', { name: 'Add models' }).hasAttribute('disabled')).toBe(true);++ // And the search did not dead-end: there is no 「no model matches」 to answer+ // with a duplicate.+ expect(screen.queryByText('No model matches.')).toBeNull();+ expect(onAdd).not.toHaveBeenCalled();+ });++ it('hands an unmatched query to the editor, and hands over nothing when there is none', async () => {+ const user = userEvent.setup();+ answers({ builtin: [candidate('gpt-6', { origin: 'builtin' })] });+ const { onCustom } = renderPicker();++ await user.type(await screen.findByLabelText('Search models or providers'), ' gemini-4 ');+ expect(screen.getByText('No model matches.')).toBeTruthy();+ // The query is the id the user has already typed once. Asking for it again+ // in the next dialog would be this one forgetting.+ await user.click(screen.getByRole('button', { name: 'Add "gemini-4" as a custom model…' }));+ expect(onCustom).toHaveBeenLastCalledWith('gemini-4');++ await user.clear(search());+ // With no query there is nothing to quote, and the footer already offers the+ // same editor.+ expect(screen.queryByRole('button', { name: /as a custom model/ })).toBeNull();+ await user.click(screen.getByRole('button', { name: 'Add custom model…' }));+ expect(onCustom).toHaveBeenLastCalledWith('');+ });++ it('offers a retry when the models it can add cannot be read', async () => {+ const user = userEvent.setup();+ const candidates = vi.spyOn(modelsApi, 'getAgentModelCandidates')+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValueOnce(read({ builtin: [candidate('gpt-6', { origin: 'builtin' })] }));+ renderPicker();++ expect(await screen.findByText('The models you can add could not be read.')).toBeTruthy();+ // Nothing to search while there is nothing read.+ expect((search() as HTMLInputElement).disabled).toBe(true);++ await user.click(screen.getByRole('button', { name: 'Retry' }));++ expect(await screen.findByRole('checkbox', { name: 'gpt-6' })).toBeTruthy();+ expect(candidates).toHaveBeenCalledTimes(2);+ });++ it('re-asks with a seeded pick, and counts only what the current read still offers', async () => {+ const user = userEvent.setup();+ // The re-ask after a stale-supplier refusal (C1): the same models come back+ // picked, with the suppliers the server matched this time. One of them is no+ // longer offered at all — and a label that counted it would add fewer models+ // than it named.+ answers({+ providers: [candidate('glm-5.2', {+ display_name: 'GLM 5.2',+ suppliers: [{ source_id: 'src_b', source_name: 'Backup relay', model_id: 'glm-5.2' }],+ })],+ });+ const { onAdd } = renderPicker({ seedPicked: new Set(['glm-5.2', 'withdrawn']) });++ const row = await screen.findByRole('checkbox', { name: /GLM 5\.2/ });+ expect(row.getAttribute('aria-checked')).toBe('true');+ expect(row.textContent).toContain('Backup relay');+ expect(screen.getByRole('button', { name: 'Add 1 model' })).toBeTruthy();++ await user.click(screen.getByRole('button', { name: 'Add 1 model' }));+ // One object per pick, carrying exactly the suppliers its row displayed —+ // the agreement and the id it is about cannot come apart. And the seeded id+ // this read no longer offers is not in it at all: a withdrawn candidate is+ // dropped from the selection, never re-sent under an expectation nobody+ // could see (C1).+ expect(onAdd.mock.calls[0][0]).toEqual([{+ candidate: expect.objectContaining({ id: 'glm-5.2' }),+ expected_suppliers: [{ source_id: 'src_b', model_id: 'glm-5.2' }],+ }]);+ });++ it('cancels without choosing anything', async () => {+ const user = userEvent.setup();+ answers({ builtin: [candidate('gpt-6', { origin: 'builtin' })] });+ const { onCancel, onAdd } = renderPicker();++ await user.click(await screen.findByRole('checkbox', { name: 'gpt-6' }));+ const exits = screen.getAllByRole('button', { name: 'Cancel' });+ for (const exit of exits) await user.click(exit);++ // Every way out is the same way out: the corner control borrows the+ // footer's label rather than inventing a second word for it, and neither+ // one takes the picks with it.+ expect(onCancel).toHaveBeenCalledTimes(exits.length);+ expect(onAdd).not.toHaveBeenCalled();+ });+});diff --git a/ui/src/components/settings/models/BackendModelPickerDialog.tsx b/ui/src/components/settings/models/BackendModelPickerDialog.tsxnew file mode 100644index 000000000..f263ab1fa--- /dev/null+++ b/ui/src/components/settings/models/BackendModelPickerDialog.tsx@@ -0,0 +1,345 @@+// Picking models to add to a backend's catalog.+//+// The whole dialog renders one server read. What a candidate is, which group it+// belongs to, which suppliers it has, and what its label and efforts should be+// are all answered by `GET .../models/candidates` (C4) — this file adds no rule+// of its own, because every rule it could add is one the server already applies+// to the write that follows. A client that re-derived them would disagree with+// the server the moment either changed.+//+// It writes nothing either. Picks go back into the catalog dialog's draft, so+// the list still settles through one `PUT .../models` with one baseline.+import * as React from 'react';+import { LoaderCircle, Plus, Search } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Input } from '@/components/ui/input';+import { cn } from '@/lib/utils';+import { chosenCandidate, EMPTY_PICKER_GROUPS, pickerGroups } from './backendCatalog';+import type { ChosenCandidate, PickerGroups } from './backendCatalog';+import { modelsApi } from './modelsApi';+import type { AgentBackend, BackendModelCandidates, ModelCandidate } from './types';++type ReadState = 'loading' | 'ready' | 'error';++const NO_SEED: ReadonlySet<string> = new Set();+const NO_PICKS: ReadonlyMap<string, ChosenCandidate> = new Map();++/**+ * The seed, re-agreed against the read that just arrived.+ *+ * A re-ask is a question about suppliers, so only today's answer can settle it:+ * a seeded id the server still offers comes back picked with its current chips,+ * and one it no longer offers is simply not picked. That withdrawal needs no+ * sentence of its own — the row is absent and the confirmation counts one fewer,+ * which is the same signal the user gets from unpicking it themselves, and+ * nothing carries the old projection forward.+ */+const seededPicks = (+ read: BackendModelCandidates,+ seed: ReadonlySet<string>,+): ReadonlyMap<string, ChosenCandidate> => {+ const picks = new Map<string, ChosenCandidate>();+ if (seed.size === 0) return picks;+ for (const candidate of [...read.builtin, ...read.providers]) {+ if (seed.has(candidate.id) && !picks.has(candidate.id)) picks.set(candidate.id, chosenCandidate(candidate));+ }+ return picks;+};++/** Id, display name, and supplier name — the three things a row shows are the+ * three things a query searches, so nothing on screen is unsearchable and+ * nothing off it is matched. */+const matchesQuery = (candidate: ModelCandidate, needle: string): boolean =>+ needle === ''+ || candidate.id.toLowerCase().includes(needle)+ || (candidate.display_name ?? '').toLowerCase().includes(needle)+ || candidate.suppliers.some((supplier) => supplier.source_name.toLowerCase().includes(needle));++export const BackendModelPickerDialog: React.FC<{+ open: boolean;+ backend: AgentBackend;+ /** Ids the catalog draft already holds — saved rows and unsaved additions alike. */+ listedIds: ReadonlySet<string>;+ /** Ids to open with already picked, for a re-ask: the server refused an+ * addition because its suppliers had moved (C1), so the same models come back+ * selected with the chips they have now and one confirmation answers again.+ * Applied against the read, not before it — see `seededPicks`. Keep the value+ * stable while the dialog is open. */+ seedPicked?: ReadonlySet<string>;+ onCancel: () => void;+ /** The picks, each carrying the projection its row displayed. */+ onAdd: (chosen: ChosenCandidate[]) => void;+ /** Hand off to the custom-model editor, seeding the id with the query when the+ * action the user pressed named it. */+ onCustom: (seedId: string) => void;+}> = ({ open, backend, listedIds, seedPicked, onCancel, onAdd, onCustom }) => {+ const { t } = useTranslation();+ const [readState, setReadState] = React.useState<ReadState>('loading');+ const [candidates, setCandidates] = React.useState<BackendModelCandidates | null>(null);+ const [query, setQuery] = React.useState('');+ /** What the confirmation will send, held as the agreement itself rather than as+ * ids beside a projection kept somewhere else. */+ const [chosen, setChosen] = React.useState<ReadonlyMap<string, ChosenCandidate>>(NO_PICKS);+ const readAttempt = React.useRef(0);++ const load = React.useCallback((seed: ReadonlySet<string>) => {+ const attempt = ++readAttempt.current;+ setReadState('loading');+ setChosen(NO_PICKS);+ void (async () => {+ try {+ const read = await modelsApi.getAgentModelCandidates(backend);+ if (attempt !== readAttempt.current) return;+ setCandidates(read);+ setChosen(seededPicks(read, seed));+ setReadState('ready');+ } catch {+ if (attempt === readAttempt.current) setReadState('error');+ }+ })();+ }, [backend]);++ const seed = seedPicked ?? NO_SEED;+ React.useEffect(() => {+ if (!open) return;+ setQuery('');+ load(seed);+ return () => { readAttempt.current += 1; };+ }, [load, open, seed]);++ const groups = candidates ? pickerGroups(candidates, listedIds) : EMPTY_PICKER_GROUPS;+ const needle = query.trim().toLowerCase();+ const filtering = needle !== '';+ const shown: PickerGroups = {+ builtin: groups.builtin.filter((candidate) => matchesQuery(candidate, needle)),+ providers: groups.providers.filter((candidate) => matchesQuery(candidate, needle)),+ // With no query the list shows only what can be added, so the already-added+ // group exists exactly when a search could otherwise dead-end on it.+ listed: filtering ? groups.listed.filter((candidate) => matchesQuery(candidate, needle)) : [],+ };+ const nothingShown = shown.builtin.length === 0 && shown.providers.length === 0 && shown.listed.length === 0;++ /** Picking a row records the row: the id and the suppliers it is showing.+ * Unpicking deletes that one object, so there is no expectation left over to+ * promise something about a model the user just took off the list. */+ const toggle = (candidate: ModelCandidate) => {+ setChosen((current) => {+ const next = new Map(current);+ if (!next.delete(candidate.id)) next.set(candidate.id, chosenCandidate(candidate));+ return next;+ });+ };++ /** Resolved against the unfiltered groups, in group order: a pick survives+ * clearing or retyping the query, and additions land in the order they were+ * offered rather than the order they were clicked. The count comes from the+ * same list the confirmation sends, so a seeded id the current read no longer+ * offers cannot be counted in a label that would then add fewer. */+ const picks = [...groups.builtin, ...groups.providers].flatMap((candidate) => {+ const pick = chosen.get(candidate.id);+ return pick ? [pick] : [];+ });++ const group = (key: 'builtin' | 'providers' | 'listed', label: string, rows: ModelCandidate[]) => (+ rows.length === 0 ? null : (+ <div key={key} role="group" aria-label={label} className="model-hub-picker-group">+ <div className="model-hub-picker-group-head">+ <span>{label}</span>+ <span>{rows.length}</span>+ </div>+ {rows.map((candidate) => (+ <PickerRow+ key={candidate.id}+ candidate={candidate}+ picked={chosen.has(candidate.id)}+ listed={key === 'listed'}+ onToggle={() => toggle(candidate)}+ />+ ))}+ </div>+ )+ );++ return (+ <Dialog open={open} onOpenChange={(next) => { if (!next) onCancel(); }}>+ <DialogContent+ mobileSheetHeight="tall"+ closeLabel={t('settings.models.gateway.catalog.cancel') as string}+ className="model-hub-catalog-dialog model-hub-picker flex h-[min(642px,calc(100dvh-32px))] w-[min(680px,calc(100vw-32px))] max-w-[680px] flex-col gap-0 overflow-hidden rounded-[14px] border-border-strong bg-surface p-0 shadow-[var(--model-hub-dialog-shadow)] max-md:w-full max-md:max-w-none max-md:rounded-t-2xl max-md:p-0 max-md:pt-2"+ >+ <DialogHeader className="model-hub-catalog-head shrink-0 justify-center border-b border-border">+ <DialogTitle className="model-hub-catalog-title">+ {t('settings.models.gateway.picker.title', { backend: t(`settings.models.backends.${backend}`) })}+ </DialogTitle>+ <DialogDescription className="sr-only">{t('settings.models.gateway.picker.description')}</DialogDescription>+ </DialogHeader>++ <div className="model-hub-catalog-body flex min-h-0 flex-1 flex-col">+ <div className="model-hub-catalog-control model-hub-catalog-search flex min-w-0 shrink-0 items-center gap-2">+ <Search className="size-4 shrink-0 text-muted" aria-hidden="true" />+ <Input+ variant="bare"+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t('settings.models.gateway.picker.search') as string}+ aria-label={t('settings.models.gateway.picker.search') as string}+ className="min-w-0 flex-1 text-[12.5px]"+ disabled={readState !== 'ready'}+ />+ </div>++ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">+ {readState === 'loading' ? (+ <div className="model-hub-picker-empty">+ <LoaderCircle className="size-5 animate-spin" aria-hidden="true" />+ </div>+ ) : readState === 'error' ? (+ <div className="model-hub-picker-empty">+ <p>{t('settings.models.gateway.picker.unavailable')}</p>+ <Button type="button" variant="outline" size="sm" onClick={() => load(seed)}>+ {t('settings.models.gateway.retry')}+ </Button>+ </div>+ ) : nothingShown ? (+ <div className="model-hub-picker-empty">+ <p>{t('settings.models.gateway.picker.noMatch')}</p>+ {/* Only when the query is the thing the action would name. With an+ empty one the footer already offers the same editor, and the+ label would quote nothing. */}+ {filtering && (+ <Button+ type="button"+ variant="ghost"+ className="model-hub-catalog-control rounded-md px-2.5 text-[12.5px] font-semibold text-muted-foreground"+ onClick={() => onCustom(query.trim())}+ >+ <Plus aria-hidden="true" />+ {t('settings.models.gateway.picker.customFromQuery', { query: query.trim() })}+ </Button>+ )}+ </div>+ ) : (+ <div className="model-hub-picker-list">+ {group('builtin', t('settings.models.gateway.picker.groupBuiltin', { backend: t(`settings.models.backends.${backend}`) }) as string, shown.builtin)}+ {group('providers', t('settings.models.gateway.picker.groupProviders') as string, shown.providers)}+ {group('listed', t('settings.models.gateway.picker.groupListed') as string, shown.listed)}+ </div>+ )}+ </div>+ </div>++ <DialogFooter className="model-hub-catalog-foot shrink-0 items-center border-t border-border sm:justify-between">+ <Button+ type="button"+ variant="ghost"+ className="model-hub-catalog-control shrink-0 rounded-md px-2.5 text-[12.5px] font-semibold text-muted-foreground max-sm:w-full"+ onClick={() => onCustom('')}+ >+ <Plus aria-hidden="true" />+ {t('settings.models.gateway.picker.custom')}+ </Button>+ <div className="flex w-full gap-2 sm:w-auto">+ <Button+ type="button"+ variant="outline"+ className="model-hub-catalog-control flex-1 rounded-md px-5 text-[12.5px] font-semibold sm:flex-none"+ onClick={onCancel}+ >+ {t('settings.models.gateway.catalog.cancel')}+ </Button>+ <Button+ type="button"+ variant="brand"+ className="model-hub-catalog-control flex-1 rounded-md px-5 text-[12.5px] font-semibold sm:flex-none"+ disabled={picks.length === 0}+ onClick={() => onAdd(picks)}+ >+ {/* The empty state borrows the catalog's own action label rather+ than a count of zero, so the footer keeps its width and the+ button keeps naming what it does. */}+ {picks.length === 0+ ? t('settings.models.gateway.catalog.add')+ : t('settings.models.gateway.picker.confirm', { count: picks.length })}+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};++/**+ * One candidate.+ *+ * The row owns the `checkbox` role and the box inside it is presentational —+ * one target, one toggle, and the whole line is clickable. An already-listed row+ * renders checked and disabled: it answers 「this exists」 without offering a+ * duplicate.+ */+const PickerRow: React.FC<{+ candidate: ModelCandidate;+ picked: boolean;+ listed: boolean;+ onToggle: () => void;+}> = ({ candidate, picked, listed, onToggle }) => {+ const checked = picked || listed;+ const supplied = candidate.suppliers.length > 0;+ return (+ <button+ type="button"+ role="checkbox"+ aria-checked={checked}+ disabled={listed}+ onClick={onToggle}+ className={cn(+ 'model-hub-picker-row min-w-0',+ picked && 'is-picked',+ listed && 'model-hub-picker-row--listed cursor-not-allowed',+ supplied && 'model-hub-picker-row--suppliers',+ )}+ >+ <Checkbox presentational checked={checked} disabled={listed} />+ {/* The label and the strip share a box so the checkbox stays centred on+ * the pair however the pair is arranged, and so the narrow layout can+ * stack them without the row itself having to wrap. */}+ <span className="model-hub-picker-entry">+ {/* `flex-auto`, not `flex-1`: both grow into the space the strip+ * leaves, but `flex-1` bases the label at 0, and a flex base of 0 is+ * also a shrink weight of 0 — the strip would claim its full width+ * first and the label would be left with whatever remained, down to+ * nothing. From `auto` the two yield in proportion to what they are+ * actually showing, so a wide strip costs the label some of its name+ * rather than all of it, and neither is what overflows. */}+ <span className="model-hub-picker-line flex-auto">+ {candidate.display_name ? (+ <>+ <span className="model-hub-picker-name truncate">{candidate.display_name}</span>+ <span className="model-hub-picker-id truncate font-mono">{candidate.id}</span>+ </>+ ) : (+ // No display name, so the id IS the label and sits where one would.+ <span className="model-hub-picker-name model-hub-picker-name--id truncate font-mono">{candidate.id}</span>+ )}+ </span>+ {supplied && (+ <span className="model-hub-picker-chips">+ {candidate.suppliers.map((supplier) => (+ <span+ key={`${supplier.source_id}\0${supplier.model_id}`}+ className="model-hub-pill model-hub-fill-0a border border-border text-muted"+ >+ {supplier.source_name}+ </span>+ ))}+ </span>+ )}+ </span>+ </button>+ );+};++export default BackendModelPickerDialog;diff --git a/ui/src/components/settings/models/GuardImpact.test.tsx b/ui/src/components/settings/models/GuardImpact.test.tsxnew file mode 100644index 000000000..f29537295--- /dev/null+++ b/ui/src/components/settings/models/GuardImpact.test.tsx@@ -0,0 +1,114 @@+// @vitest-environment jsdom+import { cleanup, render, screen, within } from '@testing-library/react';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it } from 'vitest';++import i18n from '@/i18n';+import { GuardImpact } from './GuardImpact';+import type { RouteHopRef } from './types';++const hop = (overrides: Partial<RouteHopRef> = {}): RouteHopRef => ({+ backend: 'claude',+ menu_model: 'alpha',+ source_id: 'src_a',+ model_id: 'alpha-air',+ position: 1,+ ...overrides,+});++const renderImpact = (props: React.ComponentProps<typeof GuardImpact>) => render(+ <I18nextProvider i18n={i18n}>+ <GuardImpact {...props} />+ </I18nextProvider>,+);++/** What one hop row reads as, derived from the same map the caller passed — so+ * the expectation is the rule rather than a copy of the output. */+const hopText = (target: RouteHopRef, names: Readonly<Record<string, string>>) => {+ const source = names[target.source_id];+ return `${source ? `${source} → ${target.model_id}` : target.model_id} · Order #${target.position}`;+};++afterEach(async () => {+ cleanup();+ await i18n.changeLanguage('en');+});++describe('GuardImpact', () => {+ it('names the supplier of every hop the caller can resolve, and leaves the rest unnamed', () => {+ // One hop of each shape the map can produce, so an id the page does not+ // cover is exercised by construction rather than by being remembered.+ const hops = [+ hop(),+ hop({ menu_model: 'beta', source_id: 'src_missing', model_id: 'beta-air', position: 2 }),+ ];+ const sourceNames = { src_a: 'Primary relay' };+ const { container } = renderImpact({ hops, gaps: [], sourceNames });++ expect(container.querySelectorAll('.model-hub-guard-hop')).toHaveLength(hops.length);+ for (const target of hops) {+ expect(within(container).getByText(hopText(target, sourceNames))).toBeTruthy();+ }+ // An id no Source answers for stays out of the copy entirely: a raw `src_…`+ // in front of a model would name nothing while looking like it did.+ expect(within(container).queryByText(/src_/)).toBeNull();+ });++ it('says nothing about a supplier when the caller names none', () => {+ const hops = [+ hop(),+ hop({ menu_model: 'beta', source_id: 'src_b', model_id: 'beta-air', position: 2 }),+ ];+ const omitted = renderImpact({ hops, gaps: [] });++ expect(omitted.container.querySelectorAll('.model-hub-guard-hop')).toHaveLength(hops.length);+ for (const target of hops) {+ expect(within(omitted.container).getByText(hopText(target, {}))).toBeTruthy();+ }++ // A map that resolves none of these hops renders identically to no map at+ // all, so the callers that pass nothing keep exactly the body they had and+ // a caller whose Sources simply do not cover a hop cannot look different.+ const empty = renderImpact({ hops, gaps: [], sourceNames: {} });+ expect(empty.container.innerHTML).toBe(omitted.container.innerHTML);+ });++ it('distinguishes a stated absence of gaps from nobody having stated one', () => {+ // Every claim this body can make about interruption, read off the keys+ // rather than copied, so a reworded claim is caught by the same assertion.+ const claims = [+ 'settings.models.guard.hint.safe',+ 'settings.models.guard.hint.interrupt',+ 'settings.models.guard.result.hint.safe',+ 'settings.models.guard.result.hint.interrupt',+ 'settings.models.guard.gap.label',+ 'settings.models.guard.result.gapLabel',+ ].map((key) => i18n.t(key));++ // `[]` is the guard saying so, and it is entitled to: it can see the supply.+ const stated = renderImpact({ hops: [hop()], gaps: [] });+ expect(stated.container.textContent).toContain(i18n.t('settings.models.guard.hint.safe'));++ // `null` is a caller that cannot see the supply and does not pretend to.+ const unstated = renderImpact({ hops: [hop()], gaps: null });++ // The hops survive — they are what such a caller does know — and every+ // statement about what removing them costs elsewhere is withheld.+ expect(within(unstated.container).getByText(hopText(hop(), {}))).toBeTruthy();+ for (const claim of claims) {+ expect(unstated.container.textContent).not.toContain(claim);+ }+ });++ it('keeps the mapping copy the rest of the Model Hub uses, in either language', async () => {+ await i18n.changeLanguage('zh');+ const sourceNames = { src_a: '主中继' };+ const { container } = renderImpact({ hops: [hop()], gaps: [], sourceNames });++ // The same key the Agent card renders a supply mapping with, so one mapping+ // reads one way wherever the Model Hub shows it — including where zh and en+ // deliberately share the arrow.+ expect(within(container).getByText(new RegExp(`${sourceNames.src_a} → alpha-air`))).toBeTruthy();+ expect(screen.getByText(i18n.t('settings.models.guard.label'))).toBeTruthy();+ });+});diff --git a/ui/src/components/settings/models/GuardImpact.tsx b/ui/src/components/settings/models/GuardImpact.tsxindex 7c7f111c5..e3377227b 100644--- a/ui/src/components/settings/models/GuardImpact.tsx+++ b/ui/src/components/settings/models/GuardImpact.tsx@@ -6,12 +6,45 @@ import { cn } from '@/lib/utils';import { GuardGapList } from './GuardGapList';import type { RouteHopRef, SupplyGap } from './types';+/**+ * What a guarded mutation would take with it.+ *+ * The two arrays travel together because the guard reports them together, the+ * confirmation shows both, and the forced retry echoes both: a caller holding+ * them apart can echo one without the other, which claims a confirmation the+ * user was never shown. Named here, beside the body that renders them, so a+ * surface that has to CARRY a plan before showing it uses the same shape.+ */+export type GuardPlan = { hops: RouteHopRef[]; gaps: SupplyGap[] };++/**+ * What a caller can show BEFORE the guard has spoken.+ *+ * `gaps: null` is 「nobody has said」, and it is not `[]`. Whether a removal+ * strands an Agent is the guard's answer — it depends on supply this client+ * cannot see — so a client that answers `[]` on its own has told the user+ * 「another source is available」 during the one confirmation that matters, on no+ * authority at all. A picture says which hops it can see and stays silent about+ * the rest; only a `GuardPlan`, whose halves both come from the server, may+ * carry a statement about interruption.+ */+export type GuardPicture = Omit<GuardPlan, 'gaps'> & { gaps: SupplyGap[] | null };+/** The shared evidence body for every guarded Model Hub mutation and its result. */-export const GuardImpact: React.FC<{- hops: RouteHopRef[];- gaps: SupplyGap[];+export const GuardImpact: React.FC<GuardPicture & {committed?: boolean;-}> = ({ hops, gaps, committed = false }) => {+ /**+ * Source id → that Source's own name, for the callers that can resolve one.+ *+ * A hop goes THROUGH a supplier, and 「no hidden mappings」 means the+ * confirmation says which — otherwise a user forcing a removal reads which+ * position disappears without reading whose it was. Only a caller holding the+ * page's Sources can answer that, so it is asked for rather than looked up+ * here, and an id it cannot name leaves the row exactly as it was: a raw+ * `src_…` in front of the model would name nothing while looking like it did.+ */+ sourceNames?: Readonly<Record<string, string>>;+}> = ({ hops, gaps, committed = false, sourceNames }) => {const { t } = useTranslation();return (<>@@ -22,30 +55,47 @@ export const GuardImpact: React.FC<{<span>{t('settings.models.guard.count', { count: hops.length })}</span></div><div className="model-hub-guard-list">- {hops.map((hop) => (- <div- key={`${hop.backend}:${hop.menu_model}:${hop.position}:${hop.source_id}:${hop.model_id}`}- className="model-hub-guard-hop"- >- <span className="min-w-0 flex-1">- <strong>- {t(`settings.models.backends.${hop.backend}`, { defaultValue: hop.backend })} · {hop.menu_model}- </strong>- <span>{hop.model_id} · {t('settings.models.guard.hop.position', { n: hop.position })}</span>- </span>- </div>- ))}+ {hops.map((hop) => {+ const source = sourceNames?.[hop.source_id];+ return (+ <div+ key={`${hop.backend}:${hop.menu_model}:${hop.position}:${hop.source_id}:${hop.model_id}`}+ className="model-hub-guard-hop"+ >+ <span className="min-w-0 flex-1">+ <strong>+ {t(`settings.models.backends.${hop.backend}`, { defaultValue: hop.backend })} · {hop.menu_model}+ </strong>+ {/* The supplier and the model it serves, in the Agent card's+ own mapping copy rather than a second string that would+ say the same thing: one mapping reads one way wherever+ the Model Hub shows it. */}+ <span>{source ? t('settings.models.gateway.row.current', { source, model: hop.model_id }) : hop.model_id} · {t('settings.models.guard.hop.position', { n: hop.position })}</span>+ </span>+ </div>+ );+ })}</div></>)}- <GuardGapList- gaps={gaps}- labelKey={committed ? 'settings.models.guard.result.gapLabel' : undefined}- />- <p className={cn('model-hub-guard-hint', gaps.length > 0 && 'text-destructive-ink')}>- <Info aria-hidden />- {t(`settings.models.guard.${committed ? 'result.' : ''}hint.${gaps.length > 0 ? 'interrupt' : 'safe'}`)}- </p>+ {/* Both of these are statements ABOUT the gaps — the list names them, and+ the hint below says whether there are any — so an unstated gap list+ renders neither. Silence is the only honest reading: 「safe」 would be+ this client vouching for supply it cannot see, and 「interrupt」 would+ invent a consequence. The hops above are unaffected; they are what the+ caller does know. */}+ {gaps !== null && (+ <>+ <GuardGapList+ gaps={gaps}+ labelKey={committed ? 'settings.models.guard.result.gapLabel' : undefined}+ />+ <p className={cn('model-hub-guard-hint', gaps.length > 0 && 'text-destructive-ink')}>+ <Info aria-hidden />+ {t(`settings.models.guard.${committed ? 'result.' : ''}hint.${gaps.length > 0 ? 'interrupt' : 'safe'}`)}+ </p>+ </>+ )}</>);};diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex a2c285c5b..dea2ac545 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -6,8 +6,10 @@ import userEvent from '@testing-library/user-event';import { I18nextProvider } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { InstanceAuthorizationContext } from '@/context/InstanceAuthorizationContext';import { ToastProvider } from '@/context/ToastProvider';import i18n from '@/i18n';+import { OWNER_INSTANCE_CAPABILITIES } from '@/lib/sessionInfo';import { MANAGE_COMMIT_ACTIONS } from './manage';import type { ModelsSurfaceKind } from './modelHubSurfaceState';import { modelsApi } from './modelsApi';@@ -178,18 +180,27 @@ describe('SettingsModelsPage surface branches', () => {vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(initial);vi.spyOn(modelsApi, 'putAgentModels').mockResolvedValue(saved);+ // Nobody offers this id, so it arrives through the picker's own way out to+ // the editor — the only path left for a model the server cannot propose.+ vi.spyOn(modelsApi, 'getAgentModelCandidates').mockResolvedValue({ builtin: [], providers: [], in_list: [] });+ vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([]);render(- <ToastProvider>- <I18nextProvider i18n={i18n}>- <SettingsModelsPage />- </I18nextProvider>- </ToastProvider>,+ <InstanceAuthorizationContext.Provider+ value={{ remote: false, instanceKind: null, instanceRole: 'owner', capabilities: OWNER_INSTANCE_CAPABILITIES }}+ >+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>+ </InstanceAuthorizationContext.Provider>,);await userEvent.click(await screen.findByRole('button', { name: /^Manage models$|^管理模型$/i }));- await userEvent.click(await screen.findByRole('button', { name: /^Add model$|^添加模型$/i }));- await userEvent.type(screen.getByLabelText(/^Backend model ID$|^后端模型 ID$/i), addedId);+ await userEvent.click(await screen.findByRole('button', { name: /^Add models$|^添加模型$/i }));+ await userEvent.click(await screen.findByRole('button', { name: /^Add custom model…$|^添加自定义模型…$/i }));+ await userEvent.type(await screen.findByLabelText(/^Model$|^模型$/i), addedId);await userEvent.click(screen.getByRole('button', { name: /^Add model$|^添加模型$/i }));await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex f5bb0067a..ee92c7913 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -6,6 +6,7 @@ import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';+import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';import { useToast } from '@/context/ToastContext';import { cn } from '@/lib/utils';import { ToggleSwitch } from '../SettingsPrimitives';@@ -340,6 +341,11 @@ const TakeoverPill: React.FC<{ count: number }> = ({ count }) => {export const SettingsModelsPage: React.FC = () => {const { t } = useTranslation();const { showToast } = useToast();+ /** The catalog's 「Add models」 action reads the candidates endpoint, which+ * names Sources — so it is offered on the same capability that lets a role+ * administer this instance's Agents, and read here rather than in the dialog+ * because the page is where this surface's authorization already lands. */+ const { capabilities } = useInstanceAuthorization();const [sourcesRead, setSourcesRead] = React.useState<RegionRead<Source[]>>(loadingRegion);const [supplyRead, setSupplyRead] = React.useState<RegionRead<AgentSupply[]>>(loadingRegion);const [chainsRead, setChainsRead] = React.useState<RegionRead<ModelChainIndex>>(loadingRegion);@@ -1084,6 +1090,13 @@ export const SettingsModelsPage: React.FC = () => {}}, [chainsRead, routeCommitted, suspendedRouteAttempts]);const supplyRelations = React.useMemo(() => buildSupplyRelations(installedAgents, sources, chains, runtime), [chains, installedAgents, runtime, sources]);+ /** The Sources this page has read, by id — for the surfaces that show a hop and+ * have to name whose it is. Only what was read: an id no Source answers for is+ * left unnamed rather than rendered raw. */+ const sourceNames = React.useMemo(+ () => Object.fromEntries(sources.map((source) => [source.id, source.display_name])),+ [sources],+ );const takeoverCount = React.useMemo(() => new Set(supplyRelations.filter(({ kind }) => kind === 'takeover').map(({ backend }) => backend),).size, [supplyRelations]);@@ -1387,7 +1400,7 @@ export const SettingsModelsPage: React.FC = () => {/>)}{orderAgent && <SourceOrderDrawer open agent={orderAgent} sources={sources} sourceReads={sourceCollectionReads} onClose={() => setOrderBackend(null)} onSaved={agentSaved} orderWrite={{ pending: agentWrites.has(orderAgent.backend), track: (work) => agentWriteRegistry.track(orderAgent.backend, work) }} />}- {menuAgent && <BackendModelCatalogDialog open backend={menuAgent.backend} onClose={() => setMenuBackend(null)} onSaved={catalogSaved} onObserved={applyAgentEcho} catalogWrite={{ pending: agentWrites.has(menuAgent.backend), track: (work) => agentWriteRegistry.track(menuAgent.backend, work) }} />}+ {menuAgent && <BackendModelCatalogDialog open backend={menuAgent.backend} canReadSources={capabilities.can_manage_agents} sourceNames={sourceNames} onClose={() => setMenuBackend(null)} onSaved={catalogSaved} onObserved={applyAgentEcho} catalogWrite={{ pending: agentWrites.has(menuAgent.backend), track: (work) => agentWriteRegistry.track(menuAgent.backend, work) }} />}<RouteChainDialogselection={routeSelection}sources={sources}diff --git a/ui/src/components/settings/models/backendCatalog.test.ts b/ui/src/components/settings/models/backendCatalog.test.tsindex 0352540e0..0a45259d1 100644--- a/ui/src/components/settings/models/backendCatalog.test.ts+++ b/ui/src/components/settings/models/backendCatalog.test.ts@@ -1,3 +1,6 @@+import { readdirSync, readFileSync } from 'node:fs';+import { join, relative } from 'node:path';+import { describe, expect, it, vi } from 'vitest';import {@@ -6,12 +9,33 @@ import {backendCatalogIntent,backendCatalogIntentApplied,blankBackendModel,+ candidateBackendModel,catalogModelIds,catalogModels,+ backendModelId,+ draftRowFor,+ draftWithId,+ echoableRefusal,+ heldRowFor,+ offeredCandidates,+ opencodeMenuIdentity,+ orderWithRestored,+ MODELS_DEV_FIELDS,+ pickerGroups,readBackendCatalogBaseline,+ retireModelsDevMatch,sameBackendModel,+ samePlanContents,} from './backendCatalog';-import type { AgentSupply, BackendModel, ModelsDevMatch } from './types';+import { inferProvider, type StandardVendors } from './menus/identifiers';+import type {+ AgentSupply,+ BackendModel,+ BackendModelCandidates,+ ModelCandidate,+ ModelCandidateSupplier,+ ModelsDevMatch,+} from './types';const model = (id: string, overrides: Partial<BackendModel> = {}): BackendModel => ({...blankBackendModel(),@@ -78,31 +102,515 @@ describe('catalogModelIds', () => {});describe('applyModelsDevMatch', () => {- it('fills metadata without ever renaming the row', () => {- const filled = applyModelsDevMatch(model('anthropic/claude-sonnet-4-5-20250929'), match, 'models_dev');+ /** These cases are about the fields a match fills, so they use a backend+ * whose ids carry no provider segment; the id rule has its own describe. */+ const NO_VENDORS: ReadonlySet<string> = new Set();++ it('names the row after the model that was picked and fills the rest from it', () => {+ const draft = model('half-typed-anthro', { locked: true, routeable: false });++ const filled = applyModelsDevMatch(draft, match, 'models_dev', 'codex', NO_VENDORS);- expect(filled.id).toBe('anthropic/claude-sonnet-4-5-20250929');- expect(filled.models_dev_id).toBe('anthropic/claude-sonnet-4-5');- expect(filled.display_name).toBe('Claude Sonnet 4.5');- expect(filled.context_window).toBe(200000);- expect(filled.max_output_tokens).toBe(64000);- expect(filled.input_modalities).toEqual(['text', 'image', 'pdf']);- expect(filled.reasoning_efforts).toEqual(['low', 'high']);+ // Choosing a suggestion is choosing a model, not decorating one, so the row+ // carries that model's own id — the one a backend accepts, not the+ // models.dev catalog key.+ expect(filled.id).toBe(match.model_id);+ expect(filled.id).not.toBe(match.models_dev_id);+ // Asserted as the whole row rather than field by field: every field is+ // either answered by the match or left as the draft had it, so a field the+ // mirror gains fails here instead of quietly arriving unfilled.+ expect(filled).toEqual({+ ...draft,+ id: match.model_id,+ origin: 'models_dev',+ models_dev_id: match.models_dev_id,+ display_name: match.display_name,+ context_window: match.context_window,+ max_output_tokens: match.max_output_tokens,+ input_modalities: match.input_modalities,+ output_modalities: match.output_modalities,+ supports_tools: match.supports_tools,+ supports_reasoning: match.supports_reasoning,+ reasoning_efforts: match.reasoning_efforts,+ });+ // The server's own projections are not the match's to state.+ expect(filled.locked).toBe(true);+ expect(filled.routeable).toBe(false);});it('takes the origin from the caller so a re-fill never rewrites how the row was created', () => {- expect(applyModelsDevMatch(model('m', { origin: 'manual' }), match, 'manual').origin).toBe('manual');- expect(applyModelsDevMatch(blankBackendModel(), match, 'models_dev').origin).toBe('models_dev');+ expect(applyModelsDevMatch(model('m', { origin: 'manual' }), match, 'manual', 'codex', NO_VENDORS).origin).toBe('manual');+ expect(applyModelsDevMatch(blankBackendModel(), match, 'models_dev', 'codex', NO_VENDORS).origin).toBe('models_dev');});it('copies the match lists instead of aliasing them', () => {- const filled = applyModelsDevMatch(model('m'), match, 'models_dev');+ const filled = applyModelsDevMatch(model('m'), match, 'models_dev', 'codex', NO_VENDORS);filled.reasoning_efforts.push('mutated');expect(match.reasoning_efforts).toEqual(['low', 'high']);});});+/**+ * Retiring a fill, asserted over every field the fill owns.+ *+ * The rule has two halves and they are decided per field, so a test that named+ * fields would be a list of the ones somebody thought of. `MODELS_DEV_FIELDS` is+ * the fixture instead: every field is walked, and the values the two halves are+ * told apart by are derived from each field's shape rather than written down —+ * so a field the mirror gains is covered here without this file being edited,+ * and a field added to `applyModelsDevMatch` alone fails the first case.+ */+describe('retireModelsDevMatch', () => {+ const NO_VENDORS: ReadonlySet<string> = new Set();+ /** A match differing from the blank row in every field it fills, so 「the fill+ * set this」 is never indistinguishable from 「it was already blank」. */+ const sentinel: ModelsDevMatch = {+ ...match,+ model_id: 'sentinel',+ display_name: 'Sentinel',+ context_window: 1,+ max_output_tokens: 2,+ input_modalities: ['image'],+ output_modalities: ['audio'],+ supports_tools: null,+ supports_reasoning: true,+ reasoning_efforts: ['sentinel'],+ };+ const fill = () => applyModelsDevMatch(blankBackendModel(), sentinel, 'models_dev', 'codex', NO_VENDORS);++ const same = (left: unknown, right: unknown): boolean =>+ Array.isArray(left) && Array.isArray(right)+ ? left.length === right.length && left.every((value, index) => value === right[index])+ : left === right;++ const changedFrom = (before: BackendModel, after: BackendModel): Set<string> =>+ new Set(Object.keys(after).filter((key) => !same(+ before[key as keyof BackendModel],+ after[key as keyof BackendModel],+ )));++ /** A value distinct from both the fill's and the blank row's, whatever shape+ * the field has — otherwise 「the user typed this」 could read as 「this was+ * retired」. Chosen by shape, never by field name. */+ const typedByUser = (filled: unknown, blank: unknown): unknown => {+ if (Array.isArray(filled)) return [...filled, 'text'];+ const choices: unknown[] = typeof filled === 'number' || typeof blank === 'number'+ ? [7, 8]+ : typeof filled === 'string' || typeof blank === 'string'+ ? ['mine', 'yours']+ : [true, false, null];+ return choices.find((choice) => choice !== filled && choice !== blank);+ };++ it('owns exactly the fields the fill writes', () => {+ // Both directions at once: the constant matches the applier, and the+ // sentinel really does move every one of them off the blank floor.+ expect(changedFrom(blankBackendModel(), fill())).toEqual(new Set([...MODELS_DEV_FIELDS, 'id']));+ });++ it('takes back every field the fill still owns, and only those', () => {+ const filled = fill();++ const retired = retireModelsDevMatch(filled, filled, 'typed-instead');++ expect(retired).toEqual({ ...blankBackendModel(), id: 'typed-instead' });+ });++ for (const field of MODELS_DEV_FIELDS) {+ it(`keeps ${field} when the user typed it themselves`, () => {+ const blank = blankBackendModel();+ const filled = fill();+ const mine = typedByUser(filled[field], blank[field]);+ const edited: BackendModel = { ...filled, ...{ [field]: mine } };++ const retired = retireModelsDevMatch(edited, filled, 'typed-instead');++ // Theirs survives; the rest of the fill goes, so the row is never left+ // describing a model whose id it no longer carries.+ expect(retired[field]).toEqual(mine);+ expect(retired).toEqual({ ...blank, id: 'typed-instead', ...{ [field]: mine } });+ });+ }+});++/**+ * The id rule, asserted where ids are written instead of at each writer.+ *+ * This started as a table of producers, and the table is what kept failing. The+ * rule was written for the 「use what I typed」 escape; choosing a models.dev+ * suggestion then shipped with a bare id OpenCode rejects; the picker's seed did+ * it again. A list of producers cannot state this property, because the producer+ * that is missing from the list is exactly the one nobody checked — and the list+ * reads complete either way.+ *+ * So the property belongs to `draftWithId`, the one write that gives a draft row+ * its id, and it is stated over arbitrary input rather than over known callers:+ * whatever this function is handed, what it writes is admissible. A producer+ * added later inherits it by calling the only function that can write the field,+ * and the boundary test below is what keeps 「the only」 true.+ */+describe('the id chokepoint', () => {+ const VENDORS: StandardVendors = new Set(['anthropic', 'zhipuai']);+ /** Not a list of cases that must pass — a spread of shapes the field can hold:+ * no vendor, a standard one, an unknown one, the escape hatch, extra+ * separators, and separators in the positions that parse to nothing. */+ const HANDED = [+ 'glm-5.2',+ 'zhipuai/glm-5.2',+ 'anthropic/claude',+ 'nosuchvendor/glm-5.2',+ 'custom/glm-5.2',+ 'a/b/c',+ '/leading',+ 'trailing/',+ ];+ /** Who offered the model, when anyone did: the picker and the escape name no+ * vendor, a models.dev match names its provider, standard or not. */+ const OFFERED_BY = ['', 'zhipuai', 'nosuchvendor'];++ /** Admissible as the backend decides it, not as this test decides it. This+ * used to ask the vendor list — whether OpenCode's own normalization agreed+ * the segment was that segment — and that was the defect, stated as the+ * property: `canonical_opencode_menu_identity` admits any segment matching+ * its grammar and never consults `standard_vendors`, so the test called+ * `nosuchvendor/glm-5.2` inadmissible and locked in a rewrite the server had+ * no objection to. The one mirror of that rule is the authority here too. */+ const admissible = (id: string): boolean => opencodeMenuIdentity(id, 'opencode');+ /** Each bucket asserted below, and asserted to be inhabited: a filter that+ * matches nothing states its property vacuously forever. */+ const bucket = (of: (id: string) => boolean): string[] => {+ const ids = HANDED.filter(of);+ expect(ids.length).toBeGreaterThan(0);+ return ids;+ };++ it('round-trips an identity that already names a provider, standard or not', () => {+ for (const handed of bucket(admissible)) {+ for (const vendor of OFFERED_BY) {+ // Byte-identical, `nosuchvendor/…` included. An id the user gave is the+ // public model they asked for, and the server splits on the first+ // separator, so `custom/nosuchvendor/glm-5.2` would be accepted as a+ // different model with nothing downstream to notice the substitution.+ expect(draftWithId(blankBackendModel(), handed, 'opencode', VENDORS, vendor).id).toBe(handed);+ }+ }+ });++ it('gives an id that names no provider exactly one, from whoever offered it', () => {+ for (const handed of bucket((id) => !id.includes('/'))) {+ for (const vendor of OFFERED_BY) {+ const written = draftWithId(blankBackendModel(), handed, 'opencode', VENDORS, vendor).id;+ // The vendor list's one job: which segment a SOURCE's vendor maps to,+ // byte-matching `opencode_model_id(source.vendor, model.id)`.+ expect(written).toBe(`${inferProvider(vendor, VENDORS)}/${handed}`);+ expect(admissible(written), `${handed} from ${vendor || 'nobody'} was written as ${written}`).toBe(true);+ }+ }+ });++ it('leaves a malformed identity malformed instead of completing it into another one', () => {+ for (const handed of bucket((id) => id.includes('/') && !admissible(id))) {+ for (const vendor of OFFERED_BY) {+ const written = draftWithId(blankBackendModel(), handed, 'opencode', VENDORS, vendor).id;+ // The prefix is for an id that names no provider, and these name a+ // broken one. `custom//leading` and `custom/trailing/` are both+ // admissible to the server and neither is what was typed, so a typo+ // would be saved as a row instead of refused at the field — which is+ // where admissibility is asked, of this write's own output.+ expect(written).toBe(handed);+ expect(admissible(written)).toBe(false);+ }+ }+ });++ it('is settled by one pass, so resolving an already-resolved id changes nothing', () => {+ for (const handed of HANDED) {+ for (const vendor of OFFERED_BY) {+ const once = draftWithId(blankBackendModel(), handed, 'opencode', VENDORS, vendor);+ // Why a producer may route a value through here twice — an editor that+ // resolves at commit what the escape already resolved — without the+ // prefix accumulating.+ expect(draftWithId(once, once.id, 'opencode', VENDORS, vendor).id).toBe(once.id);+ }+ }+ });++ it('has nothing to prefix the blank floor with', () => {+ // The one id that is not admissible and must still pass: a draft opens with+ // no id at all, and 「required」 is the editor's answer to that, not a vendor.+ expect(draftWithId(blankBackendModel(), '', 'opencode', VENDORS).id).toBe('');+ });++ it('leaves a backend without provider segments alone', () => {+ for (const handed of HANDED) {+ expect(draftWithId(blankBackendModel(), handed, 'codex', VENDORS).id).toBe(handed);+ }+ });++ it('writes the id and nothing else', () => {+ const row = model('kept', { display_name: 'Kept', context_window: 200_000, origin: 'models_dev' });+ expect(draftWithId(row, 'glm-5.2', 'opencode', VENDORS)).toEqual({ ...row, id: 'custom/glm-5.2' });+ });++ it('takes the offering provider when it is standard and falls back to custom when it is not', () => {+ const from = (providerId: string, vendors: StandardVendors) => applyModelsDevMatch(+ blankBackendModel(),+ { ...match, model_id: 'glm-5.2', provider_id: providerId },+ 'models_dev',+ 'opencode',+ vendors,+ ).id;++ expect(from('zhipuai', VENDORS)).toBe('zhipuai/glm-5.2');+ // Not `zhipuai/…`: an unrecognized vendor is one provider called `custom`+ // there, so naming it would produce an id the menu rejects.+ expect(from('zhipuai', new Set())).toBe('custom/glm-5.2');+ });++ it('gives an id that names no vendor a custom provider', () => {+ expect(backendModelId('glm-5.2', 'opencode', VENDORS)).toBe('custom/glm-5.2');+ });+});++describe('the OpenCode identity rule', () => {+ // One clause of `canonical_opencode_menu_identity` (config/v2_config.py) each,+ // named by what the server checks, so a rule that moves there is findable+ // here. The server is still the authority; this only decides early enough for+ // the id field to say what is wrong before the `PUT` rejects the whole list.+ it.each([+ // `not separator`: nothing splits the halves.+ ['glm-5.2', false],+ // `not model_id`: the hole this closes. Any provider prefix is taken as+ // given by the chokepoint, which hands `openai/` straight back — and+ // `custom/` is the same hole behind the fallback prefix it adds itself.+ ['openai/', false],+ ['custom/', false],+ // `not provider`: a leading separator names no provider.+ ['/glm-5.2', false],+ // The provider segment's own shape: lowercase alphanumeric runs, joined by+ // single `.`, `_` or `-`.+ ['OpenAI/glm-5.2', false],+ ['-openai/glm-5.2', false],+ ['open_ai/glm-5.2', true],+ ['relay.example/glm-5.2', true],+ // `identifier != identifier.strip()`, then `model_id != model_id.strip()`.+ [' openai/glm-5.2', false],+ ['openai/glm-5.2 ', false],+ ['openai/ glm-5.2', false],+ // Split on the FIRST separator, so a reseller keeps its own: this is+ // provider `openrouter` serving the model `anthropic/claude-x`.+ ['openrouter/anthropic/claude-x', true],+ ['custom/glm-5.2-air', true],+ ])('mirrors the server rule for %s', (id, admissible) => {+ expect(opencodeMenuIdentity(id, 'opencode')).toBe(admissible);+ });++ it('judges nothing for a backend whose ids have no segments to satisfy', () => {+ // claude and codex ids are flat, and their admission rules stay the+ // server's alone: a copy here would be a second authority over admission+ // that drifts silently (Known-by-design 22).+ for (const backend of ['claude', 'codex'] as const) {+ for (const id of ['openai/', 'claude-sonnet-4-5', 'anything at all']) {+ expect(opencodeMenuIdentity(id, backend)).toBe(true);+ }+ }+ });+});++/**+ * What makes 「the only write」 true.+ *+ * The property above is about `draftWithId`; it says nothing about a producer+ * that sets `id` itself. That is the defect that shipped twice, so it is checked+ * mechanically rather than by review: outside the module that owns the rule,+ * `backendModelId` may be read for display but never assigned to an `id`. A+ * producer that reaches for the resolver directly is one that is about to write+ * a draft field without the write that carries the rule.+ */+const MODELS_DIR = join(process.cwd(), 'src/components/settings/models');+const OWNER = 'backendCatalog.ts';++/**+ * Every Model Hub module that ships, by path relative to the tree's root.+ *+ * Recursive, and tests excluded. Recursive because a producer one folder down is+ * exactly the one a flat read would miss, and a boundary test that can be+ * escaped by moving a file is a boundary in name only.+ */+const shippedModules = (): { name: string; source: string }[] => {+ const walk = (dir: string): string[] => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => (+ entry.isDirectory() ? walk(join(dir, entry.name)) : [join(dir, entry.name)]+ ));+ return walk(MODELS_DIR)+ .filter((path) => /\.tsx?$/.test(path) && !/\.test\.tsx?$/.test(path))+ .map((path) => ({ name: relative(MODELS_DIR, path), source: readFileSync(path, 'utf8') }));+};++/** Whoever calls this, outside the module that owns the rule, is who breaks it. */+const callersOutsideOwner = (call: RegExp) => shippedModules()+ .filter((module) => module.name !== OWNER && call.test(module.source))+ .map((module) => module.name);++describe('the id chokepoint boundary', () => {+ /** `id:` or `id =` fed from the resolver, however the call is spelled or+ * wrapped — the assignment is the part that matters, not the formatting. */+ const ASSIGNS_FROM_RESOLVER = /\bid\s*[:=]\s*[^;,\n]*\bbackendModelId\s*\(/;++ it('lets no module outside the resolver’s own write the id from it', () => {+ expect(callersOutsideOwner(ASSIGNS_FROM_RESOLVER)).toEqual([]);+ });+});++describe('candidateBackendModel', () => {+ const candidate: ModelCandidate = {+ id: 'glm-5.2',+ display_name: 'GLM 5.2',+ reasoning_efforts: ['low', 'high'],+ suppliers: [{ source_id: 'src_relay0001', source_name: 'relay.example', model_id: 'glm-5.2-air' }],+ origin: 'provider',+ };++ it('copies what the server proposed and states nothing else at all', () => {+ const drafted = candidateBackendModel(candidate);++ // `PUT` stores the request literally, so a context window nobody stated+ // would persist as if the user had. Whole-row equality is what says so: a+ // value the proposal grows is either answered here or still unstated.+ //+ // Written out rather than spread from `blankBackendModel()`, because THAT+ // is the row under test. Spreading the editor's floor here would assert+ // that a picked row inherits the editor's defaults, which is the defect: a+ // new manual default would flow into every picked row and this test would+ // approve it. A literal makes the row's own claims the subject, so a field+ // added to `BackendModel` has to be decided here before it can ship.+ expect(drafted).toEqual({+ id: candidate.id,+ display_name: candidate.display_name,+ origin: candidate.origin,+ reasoning_efforts: candidate.reasoning_efforts,+ models_dev_id: null,+ context_window: null,+ max_output_tokens: null,+ // No editor opened, so there was nobody to show a default to: the row+ // asserts no capability and no modality. `null` is not `false` — the+ // projection omits the capability and the backend's own default stands.+ input_modalities: [],+ output_modalities: [],+ supports_tools: null,+ supports_reasoning: null,+ locked: false,+ routeable: true,+ });+ // The editor's floor is a different row and stays that way: these four are+ // exactly what it adds, and none of them may reach a pick.+ expect(blankBackendModel()).toMatchObject({+ input_modalities: ['text'],+ output_modalities: ['text'],+ supports_tools: true,+ supports_reasoning: false,+ });+ // The suppliers the picker displayed travel as the write's+ // `expected_suppliers`; a catalog row names no Source at all.+ expect(Object.keys(drafted)).not.toContain('suppliers');+ });++ it('copies the proposed efforts instead of aliasing them', () => {+ candidateBackendModel(candidate).reasoning_efforts.push('mutated');++ expect(candidate.reasoning_efforts).toEqual(['low', 'high']);+ });+});++/**+ * Which row an id names, stated over where a row can be, not over who asks.+ *+ * The defect this closes reached the user through two different doors — the+ * picker re-adding a removed model and the editor being seeded with its id — so+ * the property is about the stores, and every door inherits it by asking. The+ * proposal is held constant throughout: what decides the answer is where a row+ * already exists, never what the server said about it.+ */+describe('the row chokepoint', () => {+ const proposal: ModelCandidate = {+ id: 'glm-5.2',+ display_name: 'GLM 5.2',+ reasoning_efforts: ['low'],+ suppliers: [{ source_id: 'src_relay0001', source_name: 'relay.example', model_id: 'glm-5.2-air' }],+ origin: 'provider',+ };++ /** A row carrying what a proposal cannot restate: the fields the user stated+ * themselves, which are exactly the ones the defect cleared. */+ const stated = (id: string) => model(id, {+ display_name: 'GLM 5.2 (mine)',+ context_window: 200_000,+ max_output_tokens: 64_000,+ input_modalities: ['text', 'image'],+ output_modalities: ['text'],+ supports_tools: true,+ models_dev_id: 'zhipuai/glm-5.2',+ origin: 'models_dev',+ });++ /** Every arrangement of the two stores, so 「wherever it exists」 is covered by+ * construction rather than by the cases anyone thought to name. A store that+ * holds an unrelated row is what says the answer comes from a match and not+ * from a store being non-empty. */+ const HOLDING = [+ { where: 'the draft', held: [stated('glm-5.2')], saved: [] as BackendModel[] },+ { where: 'the baseline', held: [], saved: [stated('glm-5.2')] },+ { where: 'both', held: [stated('glm-5.2')], saved: [stated('glm-5.2')] },+ { where: 'the draft, beside other rows', held: [model('alpha'), stated('glm-5.2')], saved: [model('beta')] },+ { where: 'the baseline, beside other rows', held: [model('alpha')], saved: [model('beta'), stated('glm-5.2')] },+ ];++ it('answers with the row that already exists, wherever it exists', () => {+ for (const { where, held, saved } of HOLDING) {+ expect(heldRowFor(proposal.id, held, saved), where).toEqual(stated('glm-5.2'));+ expect(draftRowFor(proposal, held, saved), where).toEqual(stated('glm-5.2'));+ }+ });++ it('yields the baseline row when a removed saved model is re-added', () => {+ const saved = stated('glm-5.2');+ // 「Remove it, change my mind, re-add it」: the draft no longer holds the row,+ // the baseline still does, and `PUT`'s three-way merge reads any difference+ // as an edit — so anything short of deep equality persists as a clearing the+ // user never asked for.+ expect(draftRowFor(proposal, [], [saved])).toEqual(saved);+ });++ it('builds from the proposal only when neither store holds the id', () => {+ expect(heldRowFor(proposal.id, [model('alpha')], [model('beta')])).toBeNull();+ expect(draftRowFor(proposal, [model('alpha')], [model('beta')])).toEqual(candidateBackendModel(proposal));+ });++ it('has nothing to hand back for the id a blank draft opens with', () => {+ // The editor's seed is the query the user typed, and it is empty when they+ // asked for a custom row without typing one. Nothing may match it, or that+ // door would open on whatever row the list happens to hold.+ expect(heldRowFor('', [stated('glm-5.2')], [stated('alpha')])).toBeNull();+ });+});++/**+ * What makes 「every door asks」 true.+ *+ * The property above is about the stores; it says nothing about a producer that+ * builds a row from a candidate itself, which is the defect that shipped three+ * times. So it is checked mechanically: outside the module that owns the rule,+ * nothing calls the builder at all — reaching for it is reaching past the only+ * function that can find the row the user already has.+ */+describe('the row chokepoint boundary', () => {+ const BUILDS_FROM_A_CANDIDATE = /\bcandidateBackendModel\s*\(/;++ it('lets no module outside the chokepoint’s own build a row from a candidate', () => {+ expect(callersOutsideOwner(BUILDS_FROM_A_CANDIDATE)).toEqual([]);+ });+});+describe('sameBackendModel', () => {it('ignores the server-derived projections', () => {expect(sameBackendModel(model('m'), model('m', { locked: true, routeable: false }))).toBe(true);@@ -143,6 +651,45 @@ describe('backendCatalogIntent', () => {});});+describe('orderWithRestored', () => {+ const BASELINE = ['a', 'b', 'c', 'd'];++ const without = (...ids: string[]) => BASELINE.filter((id) => !ids.includes(id));++ it('puts a cancelled removal back where the baseline had it, wherever that was', () => {+ // The property, stated for every position rather than for the one that+ // happens to be interesting: undoing a removal restores the baseline+ // exactly. A row that came back at the end would answer 「are you sure?」+ // with a reordered catalog the user never asked for — and one that reports+ // itself as edited afterwards can never be saved back to what it was.+ for (const id of BASELINE) {+ expect(orderWithRestored(without(id), BASELINE, new Set([id])), id).toEqual(BASELINE);+ }+ // Including all of them at once, in any combination: the restored rows keep+ // their baseline sequence among themselves, so neighbours cannot swap.+ expect(orderWithRestored(without('b', 'c'), BASELINE, new Set(['b', 'c']))).toEqual(BASELINE);+ expect(orderWithRestored([], BASELINE, new Set(BASELINE))).toEqual(BASELINE);+ });++ it('leaves every other edit alone', () => {+ // A refusal answers one removal; it says nothing about a reorder or an+ // addition the user also made, and those are still theirs afterwards. So+ // the baseline decides positions and is never replayed as the order.+ expect(orderWithRestored(['d', 'a', 'c'], BASELINE, new Set(['b'])))+ .toEqual(['d', 'a', 'b', 'c']);+ expect(orderWithRestored(['a', 'c', 'd', 'new'], BASELINE, new Set(['b'])))+ .toEqual(['a', 'b', 'c', 'd', 'new']);+ expect(orderWithRestored(['a', 'b', 'c', 'd'], BASELINE, new Set())).toEqual(BASELINE);+ });++ it('restores an id whose baseline neighbours are all gone', () => {+ // Nothing to anchor to is still an answer: the front, because a row with no+ // surviving predecessor had none in the baseline either.+ expect(orderWithRestored(['d'], BASELINE, new Set(['b']))).toEqual(['b', 'd']);+ expect(orderWithRestored(['new'], BASELINE, new Set(['c']))).toEqual(['c', 'new']);+ });+});+describe('applyBackendCatalogIntent', () => {it('replays edits onto a newer catalog and keeps a concurrent addition visible', () => {const intent = backendCatalogIntent([model('a'), model('b')], [model('b'), model('a', { display_name: 'A' })]);@@ -226,3 +773,282 @@ describe('readBackendCatalogBaseline', () => {.rejects.toThrow('Backend model catalog is unavailable');});});++describe('pickerGroups', () => {+ const offered = (id: string, overrides: Partial<ModelCandidate> = {}): ModelCandidate => ({+ id,+ display_name: null,+ reasoning_efforts: [],+ suppliers: [],+ origin: 'provider',+ ...overrides,+ });++ const read = (groups: Partial<BackendModelCandidates> = {}): BackendModelCandidates => ({+ builtin: groups.builtin ?? [],+ providers: groups.providers ?? [],+ in_list: groups.in_list ?? [],+ });++ it('files every id exactly once, whatever the response repeats', () => {+ // The property the picker's own copy depends on: a count beside a group+ // header, and an id under one of them. Neither survives a response whose+ // groups overlap, and only the client can hold the line — the read is three+ // lists, not a map.+ const groups = pickerGroups(read({+ builtin: [offered('shared'), offered('shared'), offered('gpt-6')],+ providers: [offered('shared'), offered('glm-5.2')],+ in_list: [+ offered('shared', { group_if_removed: 'providers' }),+ offered('kimi-k3'),+ offered('gpt-6', { group_if_removed: 'builtin' }),+ ],+ }), new Set(['kimi-k3']));++ const filed = [...groups.builtin, ...groups.providers, ...groups.listed].map((entry) => entry.id);+ expect(filed).toHaveLength(new Set(filed).size);+ expect(new Set(filed)).toEqual(new Set(['shared', 'gpt-6', 'glm-5.2', 'kimi-k3']));+ });++ it('takes membership from the draft rather than from the saved list', () => {+ // The read projects the SAVED menu; the list behind the dialog is a draft.+ // Reading `in_list` literally would call a row the user just removed+ // 「already in the list」 and offer a row they just added as if it were new.+ const response = read({+ builtin: [offered('gpt-6')],+ providers: [offered('glm-5.2')],+ in_list: [offered('kimi-k3', { group_if_removed: 'builtin' })],+ });++ const groups = pickerGroups(response, new Set(['glm-5.2']));++ // Added in the draft, so it is listed even though the server has not seen it.+ expect(groups.listed.map((entry) => entry.id)).toEqual(['glm-5.2']);+ // Removed in the draft, so it returns to the group that will serve it once+ // that removal saves.+ expect(groups.builtin.map((entry) => entry.id)).toEqual(['kimi-k3', 'gpt-6']);+ expect(groups.providers).toEqual([]);+ });++ it('files a draft-removed row by what supplies it now, never by the path that created it', () => {+ // Why `group_if_removed` exists at all (C4): `origin` records the creation+ // path and nothing else (C2), so a row added through a provider whose Source+ // was deleted months ago still reads `provider`. Filing by that would offer+ // it under 「From your providers」 and name a supplier that no longer exists.+ // So the group is a function of the server's own answer alone — and a row+ // that answer places nowhere is absent from the picker, with `Add custom+ // model…` as its way back, which costs the user far less than a row filed+ // under a supplier nothing can serve.+ const ORIGINS: ModelCandidate['origin'][] = ['builtin', 'models_dev', 'manual', 'provider'];+ const SUPPLIED: ModelCandidateSupplier[] = [{ source_id: 'src', source_name: 'Src', model_id: 'upstream' }];++ /** One row per shape the read can answer `group_if_removed` in, absence+ * included, each paired with the group it must reach. Seeded over the+ * field's closed domain rather than listed as cases: a value the server+ * gains is one row here, and every origin below then covers it. Every row+ * pairs the answer with a `suppliers` that would disagree with it, so a+ * result can only have come from the answer itself — and the last two say+ * an absent answer reads exactly as `null`, whatever else the row carries,+ * because there is nothing else the client is entitled to read it from. */+ const FACTS: {+ what: string;+ supply: Partial<ModelCandidate>;+ group: 'builtin' | 'providers' | null;+ }[] = [+ { what: 'the server names the built-in snapshot', supply: { group_if_removed: 'builtin', suppliers: SUPPLIED }, group: 'builtin' },+ { what: 'the server names the providers', supply: { group_if_removed: 'providers', suppliers: [] }, group: 'providers' },+ { what: 'the server names nowhere', supply: { group_if_removed: null, suppliers: SUPPLIED }, group: null },+ { what: 'no answer, and a provider supplies it', supply: { suppliers: SUPPLIED }, group: null },+ { what: 'no answer, and nothing supplies it', supply: { suppliers: [] }, group: null },+ ];++ /** The one group a candidate reaches, and proof there is only one. */+ const groupOf = (candidate: ModelCandidate): 'builtin' | 'providers' | 'listed' | null => {+ const groups = pickerGroups(read({ in_list: [candidate] }), new Set());+ const reached = (['builtin', 'providers', 'listed'] as const).filter((name) => groups[name].length > 0);+ expect(reached.length).toBeLessThan(2);+ return reached[0] ?? null;+ };++ for (const fact of FACTS) {+ const reached = ORIGINS.map((origin) => groupOf(offered('kimi-k3', { ...fact.supply, origin })));+ // One group for one answer, whatever origin arrived with it…+ expect(new Set(reached).size, fact.what).toBe(1);+ // …and it is the group that answer names.+ expect(reached[0], fact.what).toBe(fact.group);+ }+ });+});++describe('offeredCandidates', () => {+ const candidate = (id: string, overrides: Partial<ModelCandidate> = {}): ModelCandidate => ({+ id,+ display_name: null,+ reasoning_efforts: [],+ suppliers: [],+ origin: 'provider',+ ...overrides,+ });++ const read = (groups: Partial<BackendModelCandidates> = {}): BackendModelCandidates => ({+ builtin: groups.builtin ?? [],+ providers: groups.providers ?? [],+ in_list: groups.in_list ?? [],+ });++ const supplier: ModelCandidateSupplier = { source_id: 'src_a', source_name: 'Primary relay', model_id: 'up' };++ it('offers every pickable id, whatever its suppliers say', () => {+ // The property: being offered and having suppliers are two different facts,+ // and only the first one this answers. A candidate the server serves with+ // nothing behind it yet is a row the user may add — its route starts empty —+ // so a supplier list can never be the reason an id is missing from here.+ const rows = [+ candidate('supplied', { suppliers: [supplier] }),+ candidate('unsupplied'),+ candidate('many', { suppliers: [supplier, { ...supplier, source_id: 'src_b' }] }),+ ];++ for (const group of ['builtin', 'providers'] as const) {+ const offered = offeredCandidates(read({ [group]: rows }));+ expect([...offered.keys()], group).toEqual(rows.map((row) => row.id));+ expect([...offered.values()], group).toEqual(rows);+ }+ });++ it('answers for the ids the picker would offer, and files each of them once', () => {+ // One answer, not two: the withdrawal decision here and the rows the picker+ // puts in front of the user are the same question, so 「offered」 is the+ // pickable groups in group order with the same first-wins dedupe — a+ // response that repeats an id across them cannot make it two offers.+ const arrival = read({+ builtin: [candidate('shared'), candidate('shared', { display_name: 'again' }), candidate('gpt-6')],+ providers: [candidate('shared'), candidate('glm-5.2')],+ });+ const groups = pickerGroups(arrival, new Set());++ expect([...offeredCandidates(arrival).keys()])+ .toEqual([...groups.builtin, ...groups.providers].map((entry) => entry.id));+ });++ it('never offers an id the saved menu already holds', () => {+ // `in_list` is not an offer, whatever it carries: it reports what the saved+ // menu holds, and a row already in the list is not one this dialog can offer+ // to add. `group_if_removed` says where such a row would RE-enter if it were+ // removed, which is a question about a removal nobody has made.+ const arrival = read({+ in_list: [candidate('kimi-k3', { group_if_removed: 'providers' }), candidate('gpt-6')],+ providers: [candidate('glm-5.2')],+ });++ expect([...offeredCandidates(arrival).keys()]).toEqual(['glm-5.2']);+ });++ it('drops an id the response left blank', () => {+ expect([...offeredCandidates(read({ providers: [candidate(''), candidate('glm-5.2')] })).keys()])+ .toEqual(['glm-5.2']);+ });+});++describe('samePlanContents', () => {+ const hop = (position: number) => ({+ source_id: 'src', model_id: 'kimi-k3', backend: 'claude', menu_model: 'kimi-k3', position,+ });+ const gap = (agents: string[]) => ({ backend: 'claude', model_id: 'kimi-k3', agents });++ /** Every ordering of a list. */+ const orderings = <T>(list: readonly T[]): T[][] => (+ list.length <= 1+ ? [[...list]]+ : list.flatMap((head, index) => orderings([...list.slice(0, index), ...list.slice(index + 1)])+ .map((rest) => [head, ...rest]))+ );++ it('reads any two orderings of the same consequences as one plan', () => {+ // The decision it serves: 「is the server's refusal the one the user already+ // confirmed?」. The preview follows the order the user clicked and the+ // refusal follows the server's own walk of the baseline, so an order that+ // differs between them is not a disagreement about what would happen — and+ // asking the same question twice for it is the bug.+ const plan = [hop(1), hop(2), gap(['reviewer'])];+ const every = orderings(plan);+ expect(every).toHaveLength(6);+ expect(every.filter((ordering) => !samePlanContents(plan, ordering))).toEqual([]);+ });++ it('reads consequences that are not the same as a different plan', () => {+ // What makes the automatic retry safe: a server whose answer moved between+ // the question and the retry has to ask it again.+ const plan = [hop(1), hop(2)];+ const moved = [+ [], // nothing left+ [hop(1)], // one fewer+ [hop(1), hop(2), hop(3)], // one more+ [hop(1), hop(1)], // one replaced by a copy of the other+ [hop(1), hop(9)], // one altered+ ];+ expect(moved.filter((other) => samePlanContents(plan, other))).toEqual([]);+ // Including inside an element, where no story explains a reordering: one+ // side produced that list, so a different order there is a real change.+ expect(samePlanContents([gap(['a', 'b'])], [gap(['b', 'a'])])).toBe(false);+ });++ it('reads no difference into how the same element happens to be written', () => {+ // Both halves are JSON off a wire, and neither side controls the other's+ // key order or how it spells a field it has nothing to say about.+ expect(samePlanContents(+ [{ source_id: 'src', model_id: 'kimi-k3', position: 1 }],+ [{ position: 1, model_id: 'kimi-k3', source_id: 'src', menu_model: undefined }],+ )).toBe(true);+ });+});++describe('echoableRefusal', () => {+ const BASELINE = [model('alpha'), model('beta'), model('gamma')];+ const REQUESTED = [model('alpha')];+ const stored = (owed: readonly string[]) => ({+ baseline: BASELINE,+ models: REQUESTED,+ owed: new Set(owed),+ });++ it('permits an echo only where the refusal was accepted AND still describes this write', () => {+ // Two independent facts decide it, so what is stated here is their product+ // rather than a list of cases: whether every held-back removal has been+ // answered against the server's own plan, and whether the write is still+ // the one the server refused. `force` asserts both at once — 「the user saw+ // this consequence, and it is the consequence of what I am sending」 — so+ // the answer is their conjunction, and each dimension is free to grow+ // without the expectations being rewritten.+ const ACCEPTANCE = [+ { what: 'every question answered', owed: [], accepted: true },+ { what: 'one still owed', owed: ['beta'], accepted: false },+ { what: 'every one still owed', owed: ['beta', 'gamma'], accepted: false },+ ];+ const SUBJECT = [+ { what: 'the write it refused', baseline: BASELINE, requested: REQUESTED, same: true },+ { what: 'a draft that removed more since', baseline: BASELINE, requested: [], same: false },+ { what: 'a draft that put a row back', baseline: BASELINE, requested: BASELINE, same: false },+ { what: 'a draft that added a row', baseline: BASELINE, requested: [...REQUESTED, model('delta')], same: false },+ { what: 'the same ids, one row edited', baseline: BASELINE, requested: [model('alpha', { display_name: 'Alpha' })], same: false },+ { what: 'a newer server catalog', baseline: [...BASELINE, model('delta')], requested: REQUESTED, same: false },+ ];+ const cells = ACCEPTANCE.flatMap((acceptance) => SUBJECT.map((subject) => ({+ what: `${acceptance.what} · ${subject.what}`,+ echoable: echoableRefusal(stored(acceptance.owed), subject.baseline, subject.requested),+ accepted: acceptance.accepted,+ same: subject.same,+ })));+ expect(cells.filter((cell) => cell.echoable !== (cell.accepted && cell.same))).toEqual([]);+ // And the product is the whole point: neither fact on its own permits an+ // echo, so exactly one cell of the matrix does.+ expect(cells.filter((cell) => cell.echoable).map((cell) => cell.what))+ .toEqual(['every question answered · the write it refused']);+ });++ it('permits nothing when there is no refusal to echo', () => {+ // The state a fresh dialog saves from, and the one it returns to after a+ // reopen: there is no server plan, so there is nothing to force.+ expect(echoableRefusal(null, BASELINE, REQUESTED)).toBe(false);+ });+});diff --git a/ui/src/components/settings/models/backendCatalog.ts b/ui/src/components/settings/models/backendCatalog.tsindex 7d1e0178b..86e19b168 100644--- a/ui/src/components/settings/models/backendCatalog.ts+++ b/ui/src/components/settings/models/backendCatalog.ts@@ -11,8 +11,18 @@// model the Agent may select; which supplier serves it stays with the Route, and// mixing the two here is what the contract's 「no Source id, no upstream model// id, no priority, no fallback」 rule exists to prevent.+import { buildIdentifier, type StandardVendors } from './menus/identifiers';import type { ModelsApi } from './modelsApi';-import type { AgentBackend, AgentSupply, BackendModel, BackendModelOrigin, ModelsDevMatch } from './types';+import type {+ AgentBackend,+ AgentSupply,+ BackendModel,+ BackendModelCandidates,+ BackendModelOrigin,+ ModelCandidate,+ ModelsDevMatch,+ RouteHop,+} from './types';/*** The model list the server says this backend exposes, derived from the@@ -69,56 +79,437 @@ export function catalogModelIds(agent: AgentSupply): string[] {return [...new Set(agent.menu?.checked ?? [])].filter(Boolean);}-/** A new row's starting point: text in, text out, tools on — the floor for any- * model a coding-agent backend can actually drive. Reasoning stays off because- * an empty `reasoning_efforts` is a decision (「omit the effort parameter」),- * not a gap the UI may pre-fill on the user's behalf. */-export const blankBackendModel = (): BackendModel => ({+/**+ * A row that states nothing — the floor under every other floor here.+ *+ * It is the server's own default for a row it is told nothing about: no+ * modality, and no capability, where `null` is not `false` but 「the projection+ * omits this, so the backend's own default stands」.+ *+ * Every floor below is built from this one so that the direction of the default+ * is 「unstated unless stated」: a field added to `BackendModel` starts unstated+ * in every producer, and a value one of them wants has to be written down to+ * exist. Building the other way round is what put `supports_reasoning: false`+ * into rows nobody had opened — the runtime projection reads that as 「this model+ * does not reason」 and drops the very efforts the row was created with.+ */+const unstatedBackendModel = (): BackendModel => ({id: '',display_name: null,origin: 'manual',models_dev_id: null,context_window: null,max_output_tokens: null,+ input_modalities: [],+ output_modalities: [],+ supports_tools: null,+ supports_reasoning: null,+ reasoning_efforts: [],+ locked: false,+ routeable: true,+});++/** A row the user is about to WRITE BY HAND: text in, text out, tools on — the+ * floor for any model a coding-agent backend can actually drive. These four are+ * stated rather than unstated because the editor renders them before it saves+ * anything, so they are on screen to be changed; a row created without the+ * editor ever opening starts from `unstatedBackendModel` instead. Reasoning+ * stays off because an empty `reasoning_efforts` is a decision (「omit the+ * effort parameter」), not a gap the UI may pre-fill on the user's behalf. */+export const blankBackendModel = (): BackendModel => ({+ ...unstatedBackendModel(),input_modalities: ['text'],output_modalities: ['text'],supports_tools: true,supports_reasoning: false,- reasoning_efforts: [],- locked: false,- routeable: true,});/**- * A models.dev match, poured into a draft.+ * A picked candidate, poured into a draft row.+ *+ * Copies exactly the three values the server proposed (C2) and leaves every+ * other field unstated. That asymmetry is the contract: the proposal covers what+ * the product already knows about the model — its label and the efforts its+ * suppliers accept — and the rest stays empty until the user fills it, because+ * `PUT` stores the request literally and an invented context window would+ * persist as if the user had stated it.+ *+ * Unstated, NOT the blank floor. The blank floor's `text`/`text`/tools-on/+ * reasoning-off belong to a row the editor is about to show, where they are on+ * screen to be corrected. This row is created by clicking a checkbox in the+ * picker: no editor opens, so anything the floor asserts is a claim the user+ * never saw and the server never made. `supports_reasoning: false` was the+ * expensive one — the runtime projection suppresses `reasoning_efforts`+ * entirely for a row that says it, so a reasoning-capable candidate picked from+ * the list arrived with its tiers and lost them on the way to the Route editor.+ *+ * `origin` comes from the candidate rather than from the group the row was+ * rendered in: the server names the creation path, and reading it back off the+ * group would be this client re-deriving something it was told.+ */+export const candidateBackendModel = (candidate: ModelCandidate): BackendModel => ({+ ...unstatedBackendModel(),+ id: candidate.id,+ display_name: candidate.display_name,+ origin: candidate.origin,+ reasoning_efforts: [...candidate.reasoning_efforts],+});++/**+ * Which row an id already names — the single place that decides it.+ *+ * A row the draft or the baseline holds is this user's own description of that+ * model, carrying the context limits, modalities, capabilities and+ * `models_dev_id` they stated. Anything that produces a row for an id has to ask+ * this before building one, because the answer is 「theirs」 far more often than+ * the producer can see: the draft is what is on screen, but the baseline still+ * holds a row the user removed a moment ago and may be re-adding right now.+ * Building over one is how 「remove it, change my mind, re-add it」 came to clear+ * those fields — the baseline still held the full row, so the PUT's three-way+ * merge read the fresh blank one as an edit that emptied them and persisted the+ * emptying.+ *+ * `draftWithId` above owns which id a produced row carries; this owns which row+ * an id names. Both are one function rather than a rule each producer remembers,+ * for the same reason: the producer that is missing from the list is exactly the+ * one nobody checked.+ */+export const heldRowFor = (+ id: string,+ held: readonly BackendModel[],+ saved: readonly BackendModel[],+): BackendModel | null => (+ held.find((model) => model.id === id)+ ?? saved.find((model) => model.id === id)+ ?? null+);++/**+ * The row a draft write lands for one candidate.+ *+ * A candidate is the server's proposal ABOUT a model (C2): a label, and the+ * efforts its suppliers accept. It is not a description of the row, so it is+ * only ever what a row is built from when no description exists yet.+ * `candidateBackendModel` is therefore this function's last branch and is+ * reached through nothing else outside this module, which the boundary test+ * beside it is what keeps true.+ */+export const draftRowFor = (+ candidate: ModelCandidate,+ held: readonly BackendModel[],+ saved: readonly BackendModel[],+): BackendModel => heldRowFor(candidate.id, held, saved) ?? candidateBackendModel(candidate);++/**+ * One picked candidate, and the projection it was picked against.+ *+ * This is the agreement `expected_suppliers` states (C1): the id the user chose+ * and the suppliers the picker displayed for it. One object, because two records+ * of one agreement can disagree — a set of picked ids beside a map of+ * expectations lets an id leave the set while its promise stays behind, and the+ * next save then sends a projection nobody agreed to. Here, dropping a pick+ * drops its promise with it, and there is no second place for a stale+ * expectation to survive in.+ */+export type ChosenCandidate = {+ candidate: ModelCandidate;+ /** The suppliers on screen, in the shape the write sends them. */+ expected_suppliers: RouteHop[];+};++/** A candidate paired with the suppliers displayed for it — the agreement, taken+ * from exactly what the row shows. */+export const chosenCandidate = (candidate: ModelCandidate): ChosenCandidate => ({+ candidate,+ expected_suppliers: candidate.suppliers.map((supplier) => ({+ source_id: supplier.source_id,+ model_id: supplier.model_id,+ })),+});++/**+ * Every id this read OFFERS, and the candidate it offers for it.+ *+ * Withdrawal has one definition (C1) and this is its only evidence: an id is+ * withdrawn when the server stops offering it. A supplier list that came back+ * empty does not say so — `ModelCandidate.suppliers` is explicit that empty is+ * meaningful, an offered id nothing supplies yet, whose route starts empty — and+ * `origin` cannot say it either, because `origin` records the path a row was+ * created by (C2), not what supplies it now.+ *+ * Only the pickable groups count, in the order and with the first-wins dedupe+ * `pickerGroups` files them by, so 「offered」 means 「a row the picker would put+ * in front of the user」 rather than 「named somewhere in the response」. That+ * makes the answer here and the answer the picker reaches one answer. `in_list`+ * is not an offer: it names what the saved menu already holds.+ */+export const offeredCandidates = (+ candidates: BackendModelCandidates,+): Map<string, ModelCandidate> => {+ const offered = new Map<string, ModelCandidate>();+ for (const candidate of [...candidates.builtin, ...candidates.providers]) {+ if (!candidate.id || offered.has(candidate.id)) continue;+ offered.set(candidate.id, candidate);+ }+ return offered;+};++export type PickerGroups = {+ builtin: ModelCandidate[];+ providers: ModelCandidate[];+ /** Search-only, and never pickable. */+ listed: ModelCandidate[];+};++export const EMPTY_PICKER_GROUPS: PickerGroups = { builtin: [], providers: [], listed: [] };++/**+ * The three groups the picker renders, reconciled against the draft the catalog+ * dialog holds.+ *+ * The read projects the SAVED menu, and the list behind that dialog is a draft,+ * so `in_list` on its own would call a row the user just removed 「already in the+ * list」 and offer a row the user just added as though it were new. The draft+ * decides membership; the server still decides what a candidate is, which group+ * serves it, and which suppliers it has.+ *+ * A draft-removed row re-enters wherever `group_if_removed` says, which is the+ * server's own reading of what supplies the id right now (C4) — `null` and+ * absent alike meaning nowhere. Nothing else on the row is consulted for it, and+ * `origin` least of all: `origin` records the path a row was created by (C2), so+ * reading current availability out of it offers a model whose provider was+ * deleted months ago under 「From your providers」. Nor could the client derive+ * the answer if it wanted to — `builtin` is served 「minus menu ids」, so a row+ * still in the menu is by construction absent from it.+ *+ * `Add custom model…` is the way back for anything that ends up nowhere, so+ * being absent costs the user nothing — while being present under a heading that+ * claims a supplier costs them a row nothing can serve.+ *+ * Filing each id once, in group order, is what makes 「every candidate appears+ * exactly once」 a property of the code rather than of the response.+ */+export const pickerGroups = (+ candidates: BackendModelCandidates,+ listedIds: ReadonlySet<string>,+): PickerGroups => {+ const groups: PickerGroups = { builtin: [], providers: [], listed: [] };+ const filed = new Set<string>();+ const file = (candidate: ModelCandidate, group: 'builtin' | 'providers' | null) => {+ if (!candidate.id || filed.has(candidate.id)) return;+ filed.add(candidate.id);+ if (listedIds.has(candidate.id)) {+ groups.listed.push(candidate);+ return;+ }+ const target = group ?? candidate.group_if_removed ?? null;+ if (target) groups[target].push(candidate);+ };+ for (const candidate of candidates.in_list) file(candidate, null);+ for (const candidate of candidates.builtin) file(candidate, 'builtin');+ for (const candidate of candidates.providers) file(candidate, 'providers');+ return groups;+};++/** The provider segment `canonical_opencode_menu_identity` accepts, verbatim. */+const OPENCODE_PROVIDER_SEGMENT = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;++/**+ * Whether an id is a whole OpenCode menu identity, or only looks like one.*- * `id` is never touched: the backend model id is the routing identity the user- * typed, and models.dev is a metadata source, not an authority over it. `origin`- * is passed in rather than derived because the schema defines it as how the row- * was FIRST created — an existing row keeps its own answer no matter how often- * it is later re-filled.+ * `canonical_opencode_menu_identity` is the authority and stays the authority:+ * this decides nothing the server does not, it just decides it early enough for+ * the id field to say what is wrong while the user is still typing. Without it+ * the dialog calls `openai/` valid, saves, and the `PUT` rejects the whole list+ * for a row the user was told was fine.+ *+ * Both halves or neither. A provider prefix proves only that the left half is+ * admissible — `openai/` has no right half at all, and `custom/` is the same+ * hole behind the fallback prefix this file adds itself. This is the only rule+ * that judges admissibility, which is why `backendModelId` can hand a malformed+ * identity straight back instead of inventing a well-formed one. Splitting on+ * the FIRST separator is what the backend does, so a reseller id keeps its own+ * slashes (`openrouter/anthropic/claude-…` is provider `openrouter`, model+ * `anthropic/claude-…`).+ *+ * The credential-material rule is deliberately not mirrored. It is a heuristic+ * over secret shapes that the server can revise whenever it learns a new one,+ * and a copy here would be a second opinion about what a secret looks like,+ * drifting silently in whichever direction it was last edited. A row it catches+ * is refused by the `PUT` with its own message.+ */+export const opencodeMenuIdentity = (id: string, backend: AgentBackend): boolean => {+ if (backend !== 'opencode') return true;+ if (id !== id.trim()) return false;+ const separator = id.indexOf('/');+ if (separator <= 0) return false;+ const model = id.slice(separator + 1);+ return OPENCODE_PROVIDER_SEGMENT.test(id.slice(0, separator))+ && model !== ''+ && model === model.trim();+};++/**+ * An id the backend will accept, whoever proposed it.+ *+ * Every id this UI *produces* comes through here — the models.dev suggestion the+ * user chose and the 「use what I typed」 escape alike. That is the whole point of+ * one function: an id the backend rejects is discovered at save time, long after+ * the row was built, so the two places that mint one cannot each carry their own+ * rule. An id the user types character by character is not produced here; it is+ * theirs, and the id field validates it rather than rewriting it underneath them.+ *+ * OpenCode identifiers are `provider/model`, and what this function contributes+ * is the provider segment an id does not have. So the question it asks is+ * whether one is there at all, never whether the backend recognizes it:+ * `canonical_opencode_menu_identity` admits any segment matching its grammar,+ * `standard_vendors` membership included and not required, so `acme/model` is a+ * public identity the server accepts, and rewriting it to `custom/acme/model`+ * saves a different model than the user asked for — one the server accepts too,+ * because it splits on the first separator, so nothing downstream would notice.+ *+ * The vendor list answers a different question, and only that one: which+ * provider segment a SOURCE's vendor maps to, which has to byte-match+ * `opencode_model_id(source.vendor, model.id)` or the menu rejects the checked+ * value. That is what `vendor` is normalized through here — the proposing+ * provider when there is one, and nothing when there is not, which+ * `buildIdentifier` answers with `custom` for the same reason the backend does.+ * Every other backend takes the id verbatim, because its ids have no segment to+ * satisfy.+ *+ * An id that carries a provider segment is therefore taken as typed even when+ * the whole identity is malformed. `openai/` is not a bare model id, and+ * prefixing it would mint `custom/openai/` — a typo the server then accepts as+ * the model `openai/`. Admissibility is `opencodeMenuIdentity`'s question, asked+ * of this function's output at the field, and the only honest answer to a broken+ * identity is to refuse it rather than to complete it into a different one.+ */+export const backendModelId = (+ id: string,+ backend: AgentBackend,+ standardVendors: StandardVendors,+ vendor = '',+): string => {+ if (backend !== 'opencode' || id === '') return id;+ if (id.includes('/')) return id;+ return buildIdentifier(vendor, id, standardVendors);+};++/**+ * The one write that gives a draft row its id.+ *+ * Every id this UI produces lands through here — a models.dev fill, the picker's+ * 「add as a custom model」 seed, the 「use what I typed」 escape, and the row the+ * editor finally commits. One chokepoint rather than a rule each producer+ * remembers: a producer that skipped the resolver used to be a defect nobody+ * could see until the backend refused the saved id, and the answer to 「which+ * producers apply it?」 has to be 「there is no other way in」, not a list that a+ * later producer falls off.+ *+ * The id field's own keystrokes are the one thing that does not come through+ * here, and deliberately: while the user is typing, the value is theirs to+ * finish. What they typed is resolved once, when `commit` turns it into a row —+ * so the exemption cannot outlive the dialog.+ */+export const draftWithId = (+ draft: BackendModel,+ id: string,+ backend: AgentBackend,+ standardVendors: StandardVendors,+ vendor = '',+): BackendModel => ({ ...draft, id: backendModelId(id, backend, standardVendors, vendor) });++/**+ * A models.dev match, poured into a draft — the id included.+ *+ * Choosing a suggestion is choosing a model, not decorating one: the row it+ * creates is the model that was picked, so it carries that model's own id+ * (`model_id`, the id a backend accepts — not the catalog key `models_dev_id`),+ * resolved through `backendModelId` against the provider that offered it. The+ * user typed a search, and every filled field including the id stays editable+ * afterwards. Keeping what was typed is the 「use what I typed」 escape, which+ * never reaches this function — but reaches the same resolver.+ *+ * `origin` is passed in rather than derived because the schema defines it as how+ * the row was FIRST created — an existing row keeps its own answer no matter how+ * often it is later re-filled.*/export const applyModelsDevMatch = (draft: BackendModel,match: ModelsDevMatch,origin: BackendModelOrigin,-): BackendModel => ({- ...draft,- display_name: match.display_name,- origin,- models_dev_id: match.models_dev_id,- context_window: match.context_window,- max_output_tokens: match.max_output_tokens,- input_modalities: [...match.input_modalities],- output_modalities: [...match.output_modalities],- supports_tools: match.supports_tools,- supports_reasoning: match.supports_reasoning,- reasoning_efforts: [...match.reasoning_efforts],-});+ backend: AgentBackend,+ standardVendors: StandardVendors,+): BackendModel => draftWithId(+ {+ ...draft,+ display_name: match.display_name,+ origin,+ models_dev_id: match.models_dev_id,+ context_window: match.context_window,+ max_output_tokens: match.max_output_tokens,+ input_modalities: [...match.input_modalities],+ output_modalities: [...match.output_modalities],+ supports_tools: match.supports_tools,+ supports_reasoning: match.supports_reasoning,+ reasoning_efforts: [...match.reasoning_efforts],+ },+ match.model_id,+ backend,+ standardVendors,+ match.provider_id,+);-const sameList = (left: readonly string[], right: readonly string[]): boolean =>+const sameList = (left: readonly unknown[], right: readonly unknown[]): boolean =>left.length === right.length && left.every((value, index) => value === right[index]);+const sameValue = (left: unknown, right: unknown): boolean =>+ Array.isArray(left) && Array.isArray(right) ? sameList(left, right) : left === right;++/** The fields a models.dev answer decides. Stated once, beside the function that+ * writes them, and checked against it by a test that applies a match differing+ * from blank in every field — so a field added to `applyModelsDevMatch` is+ * retired by the same change that fills it, or the test says so. */+export const MODELS_DEV_FIELDS = [+ 'display_name',+ 'origin',+ 'models_dev_id',+ 'context_window',+ 'max_output_tokens',+ 'input_modalities',+ 'output_modalities',+ 'supports_tools',+ 'supports_reasoning',+ 'reasoning_efforts',+] as const satisfies readonly (keyof BackendModel)[];++/**+ * Un-apply a models.dev answer, because the id it answered about is being+ * retyped.+ *+ * `filled` is the draft exactly as that answer left it, which is what makes the+ * two halves separable. A field still equal to it is models.dev's statement+ * about a model the user is no longer naming — keeping one model's context+ * window under another model's id would save a fact nobody ever made — so it+ * goes back to the blank floor. A field that differs is the user's own typing+ * since, and correcting an id is not a decision to retype the rest of the form.+ *+ * `id` is set from the caller either way: it is the field being edited, never a+ * field being retired.+ */+export const retireModelsDevMatch = (+ draft: BackendModel,+ filled: BackendModel,+ id: string,+): BackendModel => {+ const blank = blankBackendModel();+ const next: BackendModel = { ...draft, id };+ for (const field of MODELS_DEV_FIELDS) {+ if (sameValue(draft[field], filled[field])) Object.assign(next, { [field]: blank[field] });+ }+ return next;+};+/** Equality over the fields a user owns. `locked` and `routeable` are server* projections, so a server that recomputed them has not made the row a user* edit — comparing them would turn every reconnect into a spurious write. */@@ -138,6 +529,70 @@ export const sameBackendModel = (left: BackendModel, right: BackendModel): booleexport const sameCatalog = (left: readonly BackendModel[], right: readonly BackendModel[]): boolean =>left.length === right.length && left.every((model, index) => sameBackendModel(model, right[index]));+/** A value written so that two equal values always read the same: object keys in+ * one fixed order, absent and undefined fields spelled the same way. */+const canonicalJson = (value: unknown): string => {+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;+ if (value !== null && typeof value === 'object') {+ const fields = Object.entries(value as Record<string, unknown>)+ .filter(([, field]) => field !== undefined)+ .sort(([left], [right]) => (left < right ? -1 : 1));+ return `{${fields.map(([key, field]) => `${JSON.stringify(key)}:${canonicalJson(field)}`).join(',')}}`;+ }+ return JSON.stringify(value) ?? 'null';+};++/**+ * Whether two halves of a guard plan name the same consequences, in whatever+ * order each of them happens to list them.+ *+ * It exists for one decision and produces nothing that is sent: it answers+ * 「is the server's refusal the one the user already confirmed?」, so a retry+ * that would ask the same question twice can be automatic instead. The arrays+ * the client echoes with `force` are always the server's own, verbatim and in+ * the server's order (C3) — which is exactly why comparing as a set is safe+ * here. Both orders are legitimate: the client's preview follows the order the+ * user clicked, the server's follows its own walk of the baseline, and neither+ * is a disagreement about what would happen.+ *+ * Only that outer list is read as a set. A list nested inside one element — a+ * gap's `agents`, say — has no such story: one side produced it, so an order+ * that differs there is a real change and the user is asked again. Strictness+ * costs a question; laxity would skip one.+ */+export const samePlanContents = (left: readonly unknown[], right: readonly unknown[]): boolean =>+ left.length === right.length+ && sameList(left.map(canonicalJson).sort(), right.map(canonicalJson).sort());++/**+ * Whether a stored guard refusal may still be echoed back with `force`.+ *+ * `force` is the client saying 「the user has been shown this consequence and+ * still wants it」, and two independent things have to be true before it can+ * say that honestly. `owed` empty is the acceptance: every removal the server+ * refused has been put to the user and confirmed. The two catalogs are the+ * subject: the refusal answers *this* save — same starting point, same request+ * — and not a later, different one.+ *+ * Neither implies the other, so neither alone is enough. A refusal the user+ * never answered must not be forced however exactly its catalogs match, and an+ * accepted one must not be carried onto a save it was never about. Either way+ * the fallback is the same and is not a failure: the save goes out unforced and+ * the server asks again.+ */+export const echoableRefusal = (+ refusal: {+ baseline: readonly BackendModel[];+ models: readonly BackendModel[];+ owed: ReadonlySet<string>;+ } | null,+ baseline: readonly BackendModel[],+ requested: readonly BackendModel[],+): boolean => refusal !== null+ && refusal.owed.size === 0+ && sameCatalog(refusal.baseline, baseline)+ && sameCatalog(refusal.models, requested);+export type BackendCatalogIntent = {removed: ReadonlySet<string>;/** Rows this caller added or changed, keyed by id. */@@ -165,6 +620,41 @@ export const backendCatalogIntent = (};};+/**+ * An order with cancelled removals put back where they were.+ *+ * A removal the server refuses was never a decision, so undoing it may not cost+ * the row its place: the requested order is the list with the row already gone,+ * and appending it back would answer 「are you sure?」 with a reordered catalog+ * the user never asked for. The baseline is what says where it belongs — each+ * restored id goes back after its nearest baseline predecessor that is still on+ * screen, or at the front when it had none — so a removal that is cancelled+ * leaves the draft byte-identical to the baseline, and the position is recovered+ * from the two lists rather than from a snapshot somebody has to remember to+ * take.+ *+ * Only the restored ids move. Anything else the user did to the order is a+ * separate edit the refusal said nothing about, and an independent reorder is+ * still theirs afterwards — which is why the baseline is read for positions+ * rather than replayed as the order. Walking the baseline in its own order is+ * what keeps two restored neighbours in their original sequence, since the+ * earlier one is on screen by the time the later one looks for its anchor.+ */+export const orderWithRestored = (+ requested: readonly string[],+ baseline: readonly string[],+ restored: ReadonlySet<string>,+): string[] => {+ const order = requested.filter((id) => !restored.has(id));+ const before = new Map(baseline.map((id, index) => [id, baseline.slice(0, index)]));+ for (const id of baseline) {+ if (!restored.has(id)) continue;+ const anchor = [...(before.get(id) ?? [])].reverse().find((previous) => order.includes(previous));+ order.splice(anchor === undefined ? 0 : order.indexOf(anchor) + 1, 0, id);+ }+ return order;+};+/*** The user's edits, replayed onto a newer catalog.*diff --git a/ui/src/components/settings/models/backendModelContract.test.ts b/ui/src/components/settings/models/backendModelContract.test.tsnew file mode 100644index 000000000..13bcabb22--- /dev/null+++ b/ui/src/components/settings/models/backendModelContract.test.ts@@ -0,0 +1,284 @@+// The catalog half of the registered mirror: what this client promises to send,+// and what it promises not to drop on the way in.+//+// Two anchors, on purpose. Where `docs/plans/model-hub-contracts/` states a+// shape, the schema is the authority and these tests read it — a field added+// there fails here rather than reaching a projection nobody renders. Where it+// does not, the property is the anchor instead: the real client is driven over+// a stubbed wire, and a typed fixture with no optional field left out is+// asserted to survive the round trip intact.+//+// The candidates read moved from the second anchor to the first when #1837+// merged its authority files, so `ModelCandidate` is now read out of+// `api-response.schema.json` rather than described here twice.+import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { apiFailure, CANDIDATE_ORIGINS, modelsApi } from './modelsApi';+import {+ BACKEND_MODEL_INPUT_MODALITIES,+ BACKEND_MODEL_OUTPUT_MODALITIES,+ CONTRACT_VERSION,+ type BackendModel,+ type BackendModelsPut,+ type ModelCandidate,+ type ModelsDevMatch,+ type RouteHopRef,+} from './types';++const contract = (name: string): Record<string, never> =>+ JSON.parse(+ readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), '../../../../..', 'docs/plans/model-hub-contracts', name),+ 'utf8',+ ),+ );++/**+ * One canned answer, and a record of the request that asked for it.+ *+ * The subject is the shipped client, not a second mapper written here: a double+ * that re-states the projection would agree with itself no matter what the real+ * one does with a field.+ */+const stubFetch = (status: number, body: unknown) => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => new Response(+ JSON.stringify(body),+ { status, headers: { 'Content-Type': 'application/json' } },+ ));+ vi.stubGlobal('document', { cookie: 'vibe_csrf_token=test-token' });+ vi.stubGlobal('fetch', fetchMock);+ return fetchMock;+};++const MODEL: BackendModel = {+ id: 'anthropic/claude-opus-4-6',+ display_name: 'Claude Opus 4.6',+ origin: 'models_dev',+ models_dev_id: 'anthropic/claude-opus-4-6',+ context_window: 200_000,+ max_output_tokens: 64_000,+ input_modalities: [...BACKEND_MODEL_INPUT_MODALITIES],+ output_modalities: [...BACKEND_MODEL_OUTPUT_MODALITIES],+ supports_tools: true,+ supports_reasoning: null,+ reasoning_efforts: ['low', 'high'],+ locked: false,+ routeable: true,+};++const HOP_REF: RouteHopRef = {+ backend: 'opencode',+ menu_model: 'custom/glm-5.2',+ source_id: 'src_relay0001',+ model_id: 'glm-5.2-air',+ position: 2,+};++/** Every field the projection states, optional one included — so the schema's+ * closed-object set equality below is a relation in both directions. */+const CANDIDATE: Required<ModelCandidate> = {+ id: 'glm-5.2',+ display_name: 'GLM 5.2',+ reasoning_efforts: ['low', 'high'],+ suppliers: [{ source_id: 'src_relay0001', source_name: 'relay.example', model_id: 'glm-5.2-air' }],+ origin: 'provider',+ group_if_removed: 'providers',+};++const MATCH: ModelsDevMatch = {+ provider_id: 'zhipuai',+ provider_name: 'Zhipu AI',+ model_id: 'glm-5.2',+ models_dev_id: 'zhipuai/glm-5.2',+ display_name: 'GLM 5.2',+ context_window: 128_000,+ max_output_tokens: 8_192,+ input_modalities: ['text', 'image'],+ output_modalities: ['text'],+ supports_tools: true,+ supports_reasoning: null,+ reasoning_efforts: ['low'],+ first_party: true,+};++/** A save that removes a routed row AND adds a candidate: every optional field+ * of the write is present at once, so nothing can pass by being absent. */+const PUT: BackendModelsPut = {+ baseline: [MODEL],+ models: [MODEL, { ...MODEL, id: 'glm-5.2', models_dev_id: null, origin: 'manual' }],+ force: true,+ would_remove_hops: [HOP_REF],+ would_interrupt: [{ backend: 'opencode', model_id: 'custom/glm-5.2', agents: ['pm'] }],+ expected_suppliers: { 'glm-5.2': [{ source_id: 'src_relay0001', model_id: 'glm-5.2-air' }] },+};++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('backend model catalog contract', () => {+ it('mirrors every field and vocabulary backend-model.schema.json states', () => {+ const schema = contract('backend-model.schema.json') as unknown as {+ required: string[];+ additionalProperties: boolean;+ properties: Record<string, { enum?: string[]; items?: { enum: string[] } }>;+ };++ // The schema closes its object and requires every property, so set equality+ // is the whole relation in both directions: a field it gains is missing+ // here, and one this mirror invents is not in it.+ expect(schema.additionalProperties).toBe(false);+ expect(new Set(Object.keys(MODEL))).toEqual(new Set(schema.required));++ // One row carrying every stated modality, so a member added to either+ // vocabulary fails to typecheck against the mirror's own constant.+ expect(new Set(MODEL.input_modalities)).toEqual(new Set(schema.properties.input_modalities.items?.enum));+ expect(new Set(MODEL.output_modalities)).toEqual(new Set(schema.properties.output_modalities.items?.enum));+ // The origin vocabulary, both directions now that `provider` has landed in+ // the schema: the runtime set the candidates read validates against is the+ // one the contract states, so a creation path either side gains fails here+ // instead of being read as the group's fallback.+ expect(new Set(CANDIDATE_ORIGINS)).toEqual(new Set(schema.properties.origin.enum));+ expect(new Set(CANDIDATE_ORIGINS)).toContain(MODEL.origin);+ });++ it('mirrors the candidate projection api-response.schema.json now states', () => {+ const schema = contract('api-response.schema.json') as unknown as {+ definitions: {+ ModelCandidate: {+ required: string[];+ additionalProperties: boolean;+ properties: Record<string, { anyOf?: { enum?: string[] }[] }>;+ };+ AddableModelCandidate: { allOf: [unknown, { not: { required: string[] } }] };+ AgentModelCandidatesResponse: { properties: { contract_version: { const: number } } };+ };+ };+ const candidate = schema.definitions.ModelCandidate;++ // The object is closed, so set equality over the fixture's keys is the+ // whole relation: a property the schema gains is missing from the mirror,+ // and one the mirror invents is not in the schema. `Required<…>` is what+ // makes the optional field participate.+ expect(candidate.additionalProperties).toBe(false);+ expect(new Set(Object.keys(CANDIDATE)))+ .toEqual(new Set([...candidate.required, ...Object.keys(candidate.properties)]));+ // And what the mirror calls optional is what the schema leaves out of+ // `required`, rather than a second opinion about the same field.+ expect(new Set(candidate.required))+ .toEqual(new Set(Object.keys(CANDIDATE).filter((field) => field !== 'group_if_removed')));++ // The re-entry vocabulary, and the reason it is a separate field: the schema+ // forbids it on the two addable groups, because a candidate not in the list+ // has no way back to state.+ expect(new Set(candidate.properties.group_if_removed?.anyOf?.[0]?.enum))+ .toEqual(new Set(['builtin', 'providers']));+ expect(schema.definitions.AddableModelCandidate.allOf[1].not.required).toEqual(['group_if_removed']);+ expect(CONTRACT_VERSION).toBe(schema.definitions.AgentModelCandidatesResponse.properties.contract_version.const);+ });++ it('mirrors the plan hop reference and the version the refusal schema registers', () => {+ const schema = contract('guard-refusal.schema.json') as unknown as {+ properties: { contract_version: { const: number } };+ definitions: { RouteHopRef: { required: string[]; additionalProperties: boolean } };+ };+ const hopRef = schema.definitions.RouteHopRef;++ expect(hopRef.additionalProperties).toBe(false);+ expect(new Set(Object.keys(HOP_REF))).toEqual(new Set(hopRef.required));+ expect(CONTRACT_VERSION).toBe(schema.properties.contract_version.const);+ });++ it('hands the picker each candidate group whole, from the registered path', async () => {+ const groups = {+ builtin: [{ ...CANDIDATE, id: 'gpt-6-codex', origin: 'builtin' as const, suppliers: [] }],+ providers: [CANDIDATE],+ in_list: [{ ...CANDIDATE, id: 'kimi-k3', origin: 'manual' as const }],+ };+ const fetchMock = stubFetch(200, { ok: true, contract_version: CONTRACT_VERSION, candidates: groups });++ const read = await modelsApi.getAgentModelCandidates('opencode');++ expect(fetchMock.mock.calls[0]?.[0]).toBe('/api/models/agents/opencode/models/candidates');+ // Deep equality against typed fixtures is the property, and the schema case+ // above is what keeps the fixtures honest: every field the contract states+ // is on `CANDIDATE`, so a field the projection gains is asserted to survive+ // the read rather than being dropped on the way in.+ expect(read).toEqual(groups);+ });++ it('keeps every models.dev field the ranking is stated in', async () => {+ stubFetch(200, { ok: true, contract_version: CONTRACT_VERSION, matches: [MATCH] });++ const [read] = await modelsApi.searchModelsDev('glm');++ expect(read).toEqual(MATCH);+ // `first_party` is optional in the mirror — a server that predates it leaves+ // the ranking to the order it served — so its survival is asserted rather+ // than inferred from a fixture that could have omitted it.+ expect(read?.first_party).toBe(true);+ });++ it('sends the guarded tail and the displayed suppliers verbatim', async () => {+ const fetchMock = stubFetch(200, { ok: true, contract_version: CONTRACT_VERSION, agent: { backend: 'opencode' } });++ await modelsApi.putAgentModels('opencode', PUT);++ const [path, init] = fetchMock.mock.calls[0] ?? [];+ expect(path).toBe('/api/models/agents/opencode/models');+ expect(init?.method).toBe('PUT');+ // The server stores this request literally, so the client's only correct+ // transformation of the body is none.+ expect(JSON.parse(String(init?.body))).toEqual(PUT);+ });++ it('projects a stale-candidate refusal and a guarded plan as different answers', async () => {+ const refusal = async (body: unknown) => {+ stubFetch(409, body);+ const failure = await modelsApi.putAgentModels('opencode', PUT).then(+ () => null,+ (error: unknown) => apiFailure(error),+ );+ expect(failure, 'a 409 must reject as one of ours').not.toBeNull();+ return failure as NonNullable<typeof failure>;+ };++ const changed = { 'glm-5.2': [{ source_id: 'src_relay0002', model_id: 'glm-5.2' }] };+ const stale = await refusal({+ ok: false,+ contract_version: CONTRACT_VERSION,+ error: 'candidate_suppliers_changed',+ // Registered on this shape too, because it is a `ModelHubError` like any+ // other. The copy it keys is the backend lane's, but the projection that+ // has to carry it here is this client's.+ detail: 'candidate_suppliers_changed.detail',+ changed,+ });++ // Each refusal is answerable from its own field alone. That is what lets the+ // picker refresh its chips and re-ask on one and echo a plan back on the+ // other, without reading the code to decide which arrays to trust.+ expect(stale.code).toBe('candidate_suppliers_changed');+ expect(stale.detail).toBe('candidate_suppliers_changed.detail');+ expect(stale.changedSuppliers).toEqual(changed);+ expect(stale.wouldRemoveHops).toEqual([]);+ expect(stale.serverNamed).toBe(true);++ const guarded = await refusal({+ ok: false,+ contract_version: CONTRACT_VERSION,+ error: 'backend_model_in_route',+ would_remove_hops: [HOP_REF],+ would_interrupt: [{ backend: 'opencode', model_id: 'custom/glm-5.2', agents: ['pm'] }],+ });++ expect(guarded.code).toBe('backend_model_in_route');+ expect(guarded.wouldRemoveHops).toEqual([HOP_REF]);+ expect(guarded.wouldInterrupt).toHaveLength(1);+ expect(guarded.changedSuppliers).toEqual({});+ });+});diff --git a/ui/src/components/settings/models/format.test.ts b/ui/src/components/settings/models/format.test.tsindex c17dd428b..ece6f4bf4 100644--- a/ui/src/components/settings/models/format.test.ts+++ b/ui/src/components/settings/models/format.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { cooldownEtaMinutes, formatCount, formatDayTime, formatNameList, formatPercent } from './format';+import { cooldownEtaMinutes, formatCount, formatDayTime, formatNameList, formatPercent, formatTokensCompact } from './format';describe('formatCount', () => {it('groups so a figure can be read against a vendor console', () => {@@ -21,6 +21,24 @@ describe('formatCount', () => {});});+describe('formatTokensCompact', () => {+ // The property: every window renders as the K/M figure the model is published+ // under — never grouped, never fractional, and never in a unit (万) no+ // provider's model card uses.+ it('renders the published K/M figure', () => {+ for (const value of [128_000, 163_840, 200_000, 1_047_576]) {+ expect(formatTokensCompact(value)).toMatch(/^\d+[KM]$/);+ }+ expect(formatTokensCompact(128_000)).toBe('128K');+ expect(formatTokensCompact(1_000_000)).toBe('1M');+ });++ it('renders nothing for a window nobody stated', () => {+ expect(formatTokensCompact(null)).toBe('');+ expect(formatTokensCompact(0)).toBe('');+ });+});+describe('formatPercent', () => {it('renders a share as whole percent', () => {expect(formatPercent(0, 'en-US')).toBe('0%');diff --git a/ui/src/components/settings/models/format.ts b/ui/src/components/settings/models/format.tsindex 5750322dd..ebd4de7d8 100644--- a/ui/src/components/settings/models/format.ts+++ b/ui/src/components/settings/models/format.ts@@ -28,6 +28,23 @@ export function formatCount(value: number, locale: string): string {return new Intl.NumberFormat(locale).format(Math.max(0, Math.floor(value)));}+/**+ * A context window as the figure a model is published under — 「128K」.+ *+ * Compact, and compacted the same way in every locale, because this is not a+ * quantity being reconciled: it is the number that appears on the vendor's own+ * model card, in its docs and in every comparison the reader has already seen,+ * and 「12.8万」 is that number in a unit no provider uses. The exact value is one+ * field below in the reader's own grouping, so nothing is hidden by rounding+ * here. `null` renders as nothing rather than as a zero the catalog never+ * claimed.+ */+export function formatTokensCompact(value: number | null): string {+ if (value === null || value < 1) return '';+ return new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 0 })+ .format(Math.floor(value));+}+/** A ratio in [0, 1] as a whole-percent string — 「65%」. */export function formatPercent(ratio: number, locale: string): string {return new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 0 }).format(ratio);diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex 58696a83e..2733e8167 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -1950,6 +1950,7 @@--model-hub-catalog-row-height: 62px;--model-hub-catalog-row-radius: 10px;--model-hub-catalog-row-pad-x: 16px;+ --model-hub-catalog-row-pad-y: 10px;--model-hub-catalog-row-gap: 14px;--model-hub-catalog-row-locked-fill: var(--model-hub-wash-05);--model-hub-catalog-grip-size: 16px;@@ -1961,6 +1962,9 @@--model-hub-catalog-foot-pad-y: 14px;--model-hub-catalog-count-size: 12px;--model-hub-catalog-note-size: 11px;+ --model-hub-catalog-consequence-size: 12px;+ --model-hub-catalog-confirm-height: 32px;+ --model-hub-catalog-confirm-pad-x: 14px;}.model-hub-catalog-head {@@ -1997,13 +2001,19 @@.model-hub-catalog-row {min-height: var(--model-hub-catalog-row-height);- padding: 10px var(--model-hub-catalog-row-pad-x);+ padding: var(--model-hub-catalog-row-pad-y) var(--model-hub-catalog-row-pad-x);border: 1px solid var(--border);border-radius: var(--model-hub-catalog-row-radius);background: var(--background);}.model-hub-catalog-row--locked { background: var(--model-hub-catalog-row-locked-fill); }.model-hub-catalog-row--static { min-height: 48px; }+/* A row being asked about is the row the answer applies to, so the question+ * stays inside it and the stronger border says which one is waiting. */+.model-hub-catalog-row.is-confirming { border-color: var(--border-strong); }+.model-hub-catalog-row.is-confirming .model-hub-catalog-action--danger {+ background: var(--model-hub-wash-14);+}.model-hub-catalog-grip {display: inline-flex;@@ -2061,6 +2071,37 @@font-weight: 600;color: var(--model-hub-danger-ink);}+/* The removal question, drawn as the row's own lower half: full-bleed to the+ * row's border on three sides, which is why the negative margins are the row's+ * own padding tokens rather than numbers. */+.model-hub-catalog-confirm {+ display: flex;+ flex-direction: column;+ gap: 10px;+ margin:+ var(--model-hub-catalog-row-pad-y)+ calc(-1 * var(--model-hub-catalog-row-pad-x))+ calc(-1 * var(--model-hub-catalog-row-pad-y));+ padding: 12px var(--model-hub-catalog-row-pad-x);+ border-top: 1px solid var(--border);+ background: var(--model-hub-wash-05);+}+/* The guard's evidence, at row scale. The body is the same one the Route dialog+ * shows and brings its own parts, so this only has to stack them and set the+ * scale — the dialog's own wrapper is sized for a dialog and would push the row+ * open. Same gap as the question it sits in. */+.model-hub-catalog-consequence {+ display: flex;+ flex-direction: column;+ gap: 10px;+ font-size: var(--model-hub-catalog-consequence-size);+ color: var(--foreground);+}+.model-hub-catalog-confirm-action {+ height: var(--model-hub-catalog-confirm-height);+ padding: 0 var(--model-hub-catalog-confirm-pad-x);+}+.model-hub-catalog-legacy {padding: 0 2px 4px;font-size: var(--model-hub-catalog-note-size);@@ -2089,7 +2130,7 @@--model-hub-model-chip-radius: 7px;--model-hub-model-chip-size: 12px;--model-hub-model-note-size: 11px;- --model-hub-model-strip-fill: var(--model-hub-wash-05);+ --model-hub-model-match-height: 31px;}.model-hub-model-editor-head {@@ -2169,50 +2210,56 @@.model-hub-model-chip--add { border-style: dashed; }.model-hub-model-chip--custom { padding-right: 6px; }-.model-hub-model-source-strip {- min-height: var(--model-hub-model-control-height);- padding: 0 12px;- border: 1px solid var(--border);- border-radius: var(--model-hub-model-control-radius);- background: var(--model-hub-model-strip-fill);-}-.model-hub-model-source-id {- font-size: 11.5px;- color: var(--foreground);-}-.model-hub-model-source-note {- font-size: 11px;- color: var(--muted);-}-.model-hub-model-source-view {- font-size: 11.5px;- font-weight: 600;- color: var(--mint-ink);-}-.model-hub-model-source-view:disabled { color: var(--muted); }-+/* The 「Model」 typeahead. It floats over the fields below it rather than+ * displacing them: the frame draws it in layout flow, but every field it can+ * fill sits underneath, and pushing them down on each keystroke moves the very+ * values the user is about to check. Same metrics, overlay layering. */.model-hub-model-match-list {- overflow: hidden;- border: 1px solid var(--border);+ /* Nine rows: the ranked read returns at most eight matches, and the 「use what+ * I typed」 escape is always the last one, so the cap is reached rather than+ * guessed — and a shorter list is still exactly as tall as its rows. */+ max-height: calc(var(--model-hub-model-match-height) * 9);+ overflow: hidden auto;+ border: 1px solid var(--border-strong);border-radius: var(--model-hub-model-control-radius);- background: var(--background);+ background: var(--surface-2);+ box-shadow: var(--model-hub-menu-shadow);}.model-hub-model-match {+ min-height: var(--model-hub-model-match-height);padding: 8px 12px;border-bottom: 1px solid var(--border);}.model-hub-model-match:last-child { border-bottom: none; }.model-hub-model-match:hover { background: var(--model-hub-wash-05); }.model-hub-model-match.is-selected { background: var(--model-hub-mint-14); }+/* The 「use what I typed」 row is an escape, not a suggestion: no fill, so it+ * reads as the plain sentence the frame draws. */+.model-hub-model-match--literal { border-bottom: none; }+.model-hub-model-match--literal.is-selected { background: var(--model-hub-wash-08); }.model-hub-model-match-name {font-size: 12.5px;font-weight: 600;color: var(--foreground);}-.model-hub-model-match-id {+/* The id, the vendor and the context window: one type, three facts, so they are+ * one rule. Which of them a match carries is the read's answer, not a style. */+.model-hub-model-match-id,+.model-hub-model-match-meta {font-size: 11px;color: var(--muted);}+.model-hub-model-match-literal {+ font-size: 12.5px;+ font-weight: 500;+ color: var(--foreground);+}+.model-hub-model-match-state {+ min-height: var(--model-hub-model-match-height);+ padding: 8px 12px;+ font-size: 12.5px;+ color: var(--muted);+}.model-hub-model-note {font-size: var(--model-hub-model-note-size);@@ -2223,3 +2270,142 @@font-weight: 600;color: var(--model-hub-danger-ink);}++/* ---------------------------------------------------------------------------+ * The 「Add models」 picker.+ *+ * It wears .model-hub-catalog-dialog for the shell — same width, head height,+ * title size, body padding, 40px search, footer padding — because it IS the+ * catalog's other half and the two are seen back to back. Only what the picker+ * has and the catalog does not lives here: the grouped list and its 36px+ * multi-select rows, a third of the catalog row's height because a pick is one+ * line of text, not an editable record.+ */++.model-hub-picker {+ --model-hub-picker-group-gap: 8px;+ --model-hub-picker-group-inner-gap: 4px;+ --model-hub-picker-head-size: 11px;+ --model-hub-picker-row-height: 36px;+ --model-hub-picker-row-radius: 8px;+ --model-hub-picker-row-pad-x: 12px;+ --model-hub-picker-row-gap: 10px;+ --model-hub-picker-name-size: 12.5px;+ --model-hub-picker-id-size: 11px;+ --model-hub-picker-suppliers-row-height: 52px;+ /* What a stacked row measures (frame B‴): the strip sits 4px under the name+ * it belongs to. The indent is not a length — the strip starts where the+ * entry does, which is already past the checkbox. */+ --model-hub-picker-stack-gap: 4px;+}++.model-hub-picker-list {+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-picker-group-gap);+}+.model-hub-picker-group {+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-picker-group-inner-gap);+}+.model-hub-picker-group-head {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 4px 0;+ font-size: var(--model-hub-picker-head-size);+ font-weight: 600;+ color: var(--muted);+}++.model-hub-picker-row {+ display: flex;+ align-items: center;+ gap: var(--model-hub-picker-row-gap);+ min-height: var(--model-hub-picker-row-height);+ padding: 0 var(--model-hub-picker-row-pad-x);+ border: 1px solid var(--border);+ border-radius: var(--model-hub-picker-row-radius);+ background: var(--background);+ text-align: left;+}+.model-hub-picker-row.is-picked {+ border-color: var(--mint);+ background: var(--mint-soft);+}+/* An already-listed row is shown, not offered: it stays legible so the search+ * answers 「it exists」, and greys its name so it never looks pickable. */+.model-hub-picker-row--listed .model-hub-picker-name { color: var(--muted); }++/* Everything the row says about one model, beside its checkbox: the label, and+ * the strip naming its suppliers when it has any. */+.model-hub-picker-entry {+ display: flex;+ flex: 1 1 auto;+ min-width: 0;+ align-items: center;+ gap: var(--model-hub-picker-row-gap);+}++.model-hub-picker-line {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+}+.model-hub-picker-name {+ font-size: var(--model-hub-picker-name-size);+ font-weight: 600;+ color: var(--foreground);+}+/* A row with no display name shows its id where the name would go — same size,+ * lighter weight, monospaced, because then the id IS the label. */+.model-hub-picker-name--id { font-weight: 500; }+.model-hub-picker-id {+ font-size: var(--model-hub-picker-id-size);+ color: var(--muted);+}++/* Chips wrap rather than overflow: what the row displays is exactly what+ * `expected_suppliers` sends, so a clipped strip would hide part of the+ * agreement the user is confirming. The row grows only when they wrap. */+.model-hub-picker-chips {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+}++.model-hub-picker-empty {+ display: flex;+ flex: 1;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 10px;+ font-size: var(--model-hub-picker-name-size);+ color: var(--muted);+}++@media (max-width: 767px) {+ /* Narrow enough that a name, an id, and a supplier strip cannot share one+ * line. Only rows that actually carry chips stack — declared by the row, not+ * inferred with :has(), so the height is decided where the data is known. */+ .model-hub-picker-row--suppliers {+ min-height: var(--model-hub-picker-suppliers-row-height);+ padding: 6px var(--model-hub-picker-row-pad-x);+ }+ /* The strip moves under the label, and the entry is what stacks it — so the+ * checkbox stays centred on both. Stacking the label's own contents instead+ * put a name above its id — two lines for one reading, which frame B‴ keeps+ * together — and left the strip still sharing the line it was supposed to+ * leave. It also broke the label's `truncate`: a column sizes its children+ * to their own text, so a long name overran the chips rather than being cut+ * at the row's edge. `stretch`, not `flex-start`, for the same reason. */+ .model-hub-picker-row--suppliers .model-hub-picker-entry {+ flex-direction: column;+ align-items: stretch;+ gap: var(--model-hub-picker-stack-gap);+ }+}diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex f5087bbf3..bdfcd0389 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -17,15 +17,19 @@ import type {AgentSupply,ApiKeySourceCreate,ApiKeySourceObservation,+ BackendModelCandidates,BackendModelsPut,CredentialReplace,CustomModelCreate,MigrationApplyResult,MigrationScan,+ ModelCandidate,+ ModelCandidateSupplier,ModelsDevMatch,OAuthFlow,ProbeResult,ResolutionEvent,+ RouteHop,RouteHopRef,RuntimeDependency,Source,@@ -133,6 +137,9 @@ export type ModelsApi = {* the order, the server-derived `locked`/`routeable`, and any concurrent* edit this caller never saw. */putAgentModels(backend: AgentBackend, body: BackendModelsPut): Promise<AgentSupply>;+ /** Everything the picker can offer for this backend, already grouped, deduped+ * and ordered by the server (C4). A pure read. */+ getAgentModelCandidates(backend: AgentBackend): Promise<BackendModelCandidates>;/** Normalized models.dev candidates for a free-text query. A pure read: it* persists nothing, so a fill the user abandons leaves no trace. */searchModelsDev(query: string, signal?: AbortSignal): Promise<ModelsDevMatch[]>;@@ -199,6 +206,22 @@ export class ApiCallError extends Error {* each client-invented transport summary as false at its construction site.*/serverNamed: boolean;+ /**+ * A stale-candidate refusal's `changed` map, keyed by added model id.+ *+ * Its own field, and deliberately not one of the two above: a guard refusal+ * reports what a write WOULD have destroyed and is answered by echoing that+ * plan back with `force`. This one destroys nothing and interrupts nothing —+ * the save simply did not happen, because the suppliers the picker displayed+ * are no longer the ones the server would seed. Forcing it would commit the+ * projection the user never saw, so the answer is the opposite: show these+ * suppliers and ask again. Collapsed into `wouldRemoveHops`, a caller could+ * not tell 「confirm this loss」 from 「re-read and re-ask」.+ *+ * `{}` on every other code, so a call site can read it without first proving+ * which error it has.+ */+ changedSuppliers: Record<string, RouteHop[]>;/** HTTP status observed by this client. Absent when no response arrived. */responseStatus?: number;/** Safe, structured add-time observation returned with a rejected create. */@@ -212,6 +235,7 @@ export class ApiCallError extends Error {wouldRemoveHops: RouteHopRef[] = [],responseStatus?: number,observation?: SourceObservation,+ changed: Record<string, RouteHop[]> = {},) {super(detail || code);this.name = 'ApiCallError';@@ -221,6 +245,7 @@ export class ApiCallError extends Error {this.wouldInterrupt = wouldInterrupt;this.interrupted = interrupted;this.wouldRemoveHops = wouldRemoveHops;+ this.changedSuppliers = changed;this.responseStatus = responseStatus;this.observation = observation;}@@ -240,11 +265,104 @@ const supplyGaps = (raw: unknown): SupplyGap[] =>})): [];+const candidateSuppliers = (raw: unknown): ModelCandidateSupplier[] =>+ Array.isArray(raw)+ ? raw.flatMap((entry) => {+ if (!entry || typeof entry !== 'object') return [];+ const row = entry as Record<string, unknown>;+ return typeof row.source_id === 'string' && typeof row.model_id === 'string'+ ? [{+ source_id: row.source_id,+ model_id: row.model_id,+ // The display name a chip renders. Falls back to the id rather than+ // to an empty chip: an unnamed supplier is still one the user must+ // be able to recognize.+ source_name: typeof row.source_name === 'string' && row.source_name+ ? row.source_name+ : row.source_id,+ }]+ : [];+ })+ : [];++type CandidateOrigin = ModelCandidate['origin'];+/** The creation paths a candidate may state. A runtime set, because the type it+ * mirrors erases — and asserted equal to the schema's own enum in+ * `backendModelContract.test.ts`, so a path the contract gains fails a test+ * rather than being quietly read as the group's fallback. */+export const CANDIDATE_ORIGINS: readonly CandidateOrigin[] = ['builtin', 'provider', 'models_dev', 'manual'];++/** The groups the server names as a removed row's way back (C4). A value it+ * does not state is not a group, and `null` is a value it states. */+const REENTRY_GROUPS: readonly ('builtin' | 'providers')[] = ['builtin', 'providers'];++/** What the server says would offer this id again if it left the menu, read+ * only when the server says it. Absent stays absent rather than becoming+ * `null`: the two mean the same thing to the picker, and inventing a stated+ * answer out of an unstated one is how a client starts deriving the field. */+const reentryGroup = (raw: Record<string, unknown>): Pick<ModelCandidate, 'group_if_removed'> => {+ if (!('group_if_removed' in raw)) return {};+ const stated = raw.group_if_removed;+ if (stated === null) return { group_if_removed: null };+ return REENTRY_GROUPS.includes(stated as 'builtin' | 'providers')+ ? { group_if_removed: stated as 'builtin' | 'providers' }+ : {};+};++/**+ * One candidate group, read defensively.+ *+ * `fallbackOrigin` is the group's own creation path (C2), used only when the+ * server omits `origin`. It is not a guess about the model: the group a+ * candidate arrives in IS its creation path, so the two can never disagree.+ */+const modelCandidates = (raw: unknown, fallbackOrigin: CandidateOrigin): ModelCandidate[] =>+ Array.isArray(raw)+ ? raw.flatMap((entry) => {+ if (!entry || typeof entry !== 'object') return [];+ const row = entry as Record<string, unknown>;+ if (typeof row.id !== 'string' || !row.id) return [];+ return [{+ id: row.id,+ display_name: typeof row.display_name === 'string' && row.display_name ? row.display_name : null,+ reasoning_efforts: Array.isArray(row.reasoning_efforts)+ ? row.reasoning_efforts.filter((effort): effort is string => typeof effort === 'string')+ : [],+ suppliers: candidateSuppliers(row.suppliers),+ origin: CANDIDATE_ORIGINS.includes(row.origin as CandidateOrigin)+ ? row.origin as CandidateOrigin+ : fallbackOrigin,+ ...reentryGroup(row),+ }];+ })+ : [];+const routeHopRefs = (raw: unknown): RouteHopRef[] =>Array.isArray(raw)? raw.filter((hop): hop is RouteHopRef => Boolean(hop) && typeof hop === 'object'): [];+/** The `changed` map of a stale-candidate refusal: the suppliers the server+ * matched at commit time, keyed by the added model id whose displayed+ * projection they disagree with. Ids the caller never listed are absent, and an+ * entry may be empty — 「nothing supplies this any more」 is itself the change+ * the user has to see. */+const changedSuppliers = (raw: unknown): Record<string, RouteHop[]> => {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};+ const changed: Record<string, RouteHop[]> = {};+ for (const [modelId, hops] of Object.entries(raw as Record<string, unknown>)) {+ if (!Array.isArray(hops)) continue;+ changed[modelId] = hops.flatMap((hop) => {+ if (!hop || typeof hop !== 'object') return [];+ const row = hop as Record<string, unknown>;+ return typeof row.source_id === 'string' && typeof row.model_id === 'string'+ ? [{ source_id: row.source_id, model_id: row.model_id }]+ : [];+ });+ }+ return changed;+};+/*** The one reader every call site uses instead of casting a caught `unknown`.*@@ -263,6 +381,7 @@ export const apiFailure = (wouldInterrupt: SupplyGap[];interrupted: SupplyGap[];wouldRemoveHops: RouteHopRef[];+ changedSuppliers: Record<string, RouteHop[]>;responseStatus?: number;observation?: SourceObservation;} | null =>@@ -274,6 +393,7 @@ export const apiFailure = (wouldInterrupt: err.wouldInterrupt,interrupted: err.interrupted,wouldRemoveHops: err.wouldRemoveHops,+ changedSuppliers: err.changedSuppliers,responseStatus: err.responseStatus,observation: err.observation,}@@ -324,6 +444,7 @@ async function call<T>(path: string, init?: RequestInit): Promise<T> {typeof envelope.observation === 'object' && envelope.observation !== null? envelope.observation as SourceObservation: undefined,+ changedSuppliers(envelope.changed),);}return payload as T;@@ -475,6 +596,18 @@ export const modelsApi: ModelsApi = {probeAgent: (backend, model) => call<{ probe: ProbeResult }>(`/api/models/agents/${backend}/probe`, jsonInit('POST', model ? { model } : {})).then((r) => r.probe),setAgentMode: (backend, mode) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mode`, jsonInit('PATCH', { mode })).then((r) => (r.agent ?? r) as AgentSupply),putAgentModels: (backend, body) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/models`, jsonInit('PUT', body)).then((r) => (r.agent ?? r) as AgentSupply),+ getAgentModelCandidates: (backend) => call<{ candidates?: Record<string, unknown> }>(+ `/api/models/agents/${backend}/models/candidates`,+ ).then((r) => ({+ builtin: modelCandidates(r.candidates?.builtin, 'builtin'),+ providers: modelCandidates(r.candidates?.providers, 'provider'),+ // An in-list row's origin is whatever it was created as, so this group has+ // no creation path of its own to fall back to. `manual` is the floor a row+ // with no stated origin already carries (`blankBackendModel`), and nothing+ // reads it here: these rows are disabled, and only a pickable candidate is+ // ever poured into a draft.+ in_list: modelCandidates(r.candidates?.in_list, 'manual'),+ })),searchModelsDev: (query, signal) => call<{ matches: ModelsDevMatch[] }>(`/api/models/catalog/models-dev?query=${encodeURIComponent(query)}`,{ signal },diff --git a/ui/src/components/settings/models/pickerExits.test.ts b/ui/src/components/settings/models/pickerExits.test.tsnew file mode 100644index 000000000..1345ffcea--- /dev/null+++ b/ui/src/components/settings/models/pickerExits.test.ts@@ -0,0 +1,59 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';++/**+ * Every way out of the model picker settles it through one call.+ *+ * `addCandidates` is where a picker exit's two consequences are decided: which+ * seeded ids the user has just declined — so a projection the server refused+ * stops being sendable — and which row an accepted id lands as, resolved id+ * included. Two exits went through it and a third, the custom-model hand-off,+ * reproduced half of it by hand. That is how a re-ask's refused promise survived+ * an exit, and how a typed id was asked about before it had been resolved: one+ * structural fact, reported as two defects.+ *+ * So the exits are read out of the source rather than listed here. The list is+ * the thing that failed: it reads as complete, and the door added next is absent+ * from it by construction. Taking the enumeration from the JSX makes a fourth+ * exit fail this test instead of costing a review round.+ *+ * A callback that genuinely settles nothing would trip this too, and that is the+ * intended cost: routing it through the call is one line, while the alternative+ * is a door whose consequences nobody stated.+ */+const CHOKEPOINT = 'addCandidates';+const MOUNT = '<BackendModelPickerDialog';++describe("the model picker's exits", () => {+ /** The mounted element, comments stripped — prose naming an exit is not one. */+ const mounted = (): string => {+ const source = readFileSync(join(__dirname, 'BackendModelCatalogDialog.tsx'), 'utf8');+ const start = source.indexOf(MOUNT);+ expect(start).toBeGreaterThan(-1);+ const lines = source.slice(start).split('\n');+ const close = lines.findIndex((line) => line.trim() === '/>');+ // A mount this cannot delimit fails here rather than passing vacuously: the+ // assertion below holds for an empty region no matter what the file says.+ expect(close).toBeGreaterThan(0);+ return lines+ .slice(0, close + 1)+ .filter((line) => !/^(?:\/\/|\/?\*)/.test(line.trim()))+ .join('\n');+ };++ it('settles every exit it is mounted with through the one call', () => {+ const element = mounted();+ const exits = element+ .split(/(?=\bon[A-Z]\w*=)/)+ .filter((chunk) => /^on[A-Z]\w*=/.test(chunk));+ // The scan has to find doors, or it asserts nothing about them.+ expect(exits.length).toBeGreaterThan(0);++ const bypassing = exits+ .filter((chunk) => !chunk.includes(CHOKEPOINT))+ .map((chunk) => chunk.slice(0, chunk.indexOf('=')));++ expect(bypassing).toEqual([]);+ });+});diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.tsindex b01d13330..001de3f8a 100644--- a/ui/src/components/settings/models/serverCopy.test.ts+++ b/ui/src/components/settings/models/serverCopy.test.ts@@ -265,12 +265,20 @@ describe('tierEditRefusedAsManaged', () => {describe('modelsDevFillFailureKey', () => {it('separates an upstream catalog outage from a lookup that simply failed', () => {- // The one cause that is not about this machine, and the one where retrying is- // the wrong advice: every field the fill would have set is typeable by hand.+ // Two different states of the same typeahead row, so the two keys must be+ // two sentences in every bundle: 「the catalog is down」 is not 「this lookup+ // failed」, and only the first one means retrying is the wrong advice. The+ // property is that they stay distinguishable and neither renders as a key —+ // the wording itself belongs to the copy table, not to this test.const down = modelsDevFillFailureKey('modelHub.errors.models_dev_unavailable');+ const failed = modelsDevFillFailureKey(undefined);expect(down).toBe('settings.models.gateway.modelEditor.fillUnavailable');- expect(t('en')(down)).toMatch(/by hand/i);- expect(t('zh')(down)).toContain('手动填写');+ for (const lng of ['en', 'zh'] as const) {+ const outage = t(lng)(down) as string;+ expect(outage).not.toBe('');+ expect(outage).not.toBe(down);+ expect(outage).not.toBe(t(lng)(failed) as string);+ }});it('keeps every other cause on the plain unreachable line', () => {diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 55ad4b879..26c3e1b14 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -205,10 +205,81 @@ export type BackendModel = {/** `baseline` is the last full list this caller observed; `models` is its* desired replacement. The server applies the difference to the latest saved- * list, so a concurrent editor's unrelated row survives. */+ * list, so a concurrent editor's unrelated row survives.+ *+ * The guarded tail (v2 C3) is the same echo-the-plan protocol every other+ * destructive supply mutation uses: a removal that would take route hops with+ * it is refused once with the plan, and only a retry carrying that exact plan+ * back executes. Absent on a save that removes nothing. */export type BackendModelsPut = {baseline: BackendModel[];models: BackendModel[];+ force?: true;+ would_remove_hops?: RouteHopRef[];+ would_interrupt?: SupplyGap[];+ /** What the picker SHOWED as each added id's suppliers, keyed by that id (v2+ * C1). The server matches an addition once, at commit time, against inventory+ * that may have moved since the candidates read; this states which projection+ * the user actually agreed to, so a changed one is refused (`409+ * candidate_suppliers_changed`, nothing committed) instead of seeding a route+ * the picker never displayed. Only ids added along a path that displayed+ * chips carry an entry — a hand-written custom row promised nothing. */+ expected_suppliers?: Record<string, RouteHop[]>;+};++/** One provider that supplies a candidate's id, as the server's own+ * `matching-v1` projection names it — so a Claude alias hop reads here exactly+ * as it will be seeded. `model_id` is the upstream id, which may differ from+ * the candidate id it answers for. */+export type ModelCandidateSupplier = {+ source_id: string;+ source_name: string;+ model_id: string;+};++/** One model the picker can add, projected by the server (v2 C4).+ *+ * Every rule that used to be re-derived in the browser — identity dedupe,+ * eligibility, Source order, alias matching, built-in snapshot merging — is+ * already applied here. The client renders the groups it is given, filters them+ * by the query, and copies `display_name` / `reasoning_efforts` / `origin` into+ * the catalog draft on selection (C2). */+export type ModelCandidate = {+ id: string;+ display_name: string | null;+ reasoning_efforts: string[];+ /** In the backend's Source order. Empty is meaningful: nothing supplies this+ * id yet, so adding it starts with an empty route. */+ suppliers: ModelCandidateSupplier[];+ /** The creation path a pick records (C2). */+ origin: BackendModelOrigin;+ /** Where the server would offer this id if it left the menu (C4). Set on+ * `in_list` candidates only, because they are the only ones already in it —+ * `null` means nowhere, which is a real answer. It exists because `origin`+ * cannot answer this: `origin` is the path a row was created by, not what+ * supplies it now.+ *+ * Optional because the schema leaves it optional: an `in_list` candidate may+ * omit it, and the reading of an absent answer is the same as a `null` one —+ * nowhere, reachable through `Add custom model…`. Never inferred from+ * anything else on the row. */+ group_if_removed?: 'builtin' | 'providers' | null;+};++/** The picker's one read. Groups are rendered in this order and a candidate id+ * appears in exactly one of them. `builtin` is empty for a backend with no+ * built-in list of its own (OpenCode).+ *+ * `in_list` is the same projection over the rows the menu ALREADY holds, and it+ * is what makes the search-only 「Already in the list」 group answerable: the+ * catalog row on its own knows neither which Sources supply it nor under what+ * upstream id, so a search for a provider's name could not find a model that+ * provider serves once it had been added, and its disabled row could only show+ * chips this client had guessed. */+export type BackendModelCandidates = {+ builtin: ModelCandidate[];+ providers: ModelCandidate[];+ in_list: ModelCandidate[];};/** One normalized models.dev candidate. Metadata only: choosing it fills the@@ -228,6 +299,10 @@ export type ModelsDevMatch = {supports_tools: boolean | null;supports_reasoning: boolean | null;reasoning_efforts: string[];+ /** Whether this provider is the model's own vendor rather than an aggregator+ * reselling it (v2 C7). Optional because it postdates the shipped shape: a+ * server that does not state it leaves the ranking to the order it served. */+ first_party?: boolean;};/** Why a source cannot serve this backend at all. A closed vocabulary — a newdiff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsxindex 07a3ad75a..dfdaa2ad3 100644--- a/ui/src/components/workbench/Composer.tsx+++ b/ui/src/components/workbench/Composer.tsx@@ -14,6 +14,7 @@ import clsx from 'clsx';import { useToast } from '../../context/ToastContext';import { apiFetch } from '../../lib/apiFetch';import { primeCloudToken } from '../../lib/avibeFetch';+import { isComposingKey } from '../../lib/imeComposition';import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard';import { cn, copyTextToClipboard } from '../../lib/utils';import {@@ -1624,8 +1625,8 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// Enter sends, Shift+Enter newline — EXCEPT while the on-screen// keyboard is open (mobile), where Enter inserts a newline and Send is// the button. Hardware keyboards (no soft keyboard) keep Enter-to-send.- // ``isComposing`` guards against submitting mid-IME composition (CJK).- if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && !isSoftKeyboardOpen()) {+ // ``isComposingKey`` guards against submitting mid-IME composition (CJK).+ if (e.key === 'Enter' && !e.shiftKey && !isComposingKey(e) && !isSoftKeyboardOpen()) {e.preventDefault();submit();}diff --git a/ui/src/components/workbench/MentionEditor.tsx b/ui/src/components/workbench/MentionEditor.tsxindex 5ad24e1c5..a34b9dac9 100644--- a/ui/src/components/workbench/MentionEditor.tsx+++ b/ui/src/components/workbench/MentionEditor.tsx@@ -54,6 +54,7 @@ import {voiceInsertionSnapshot,type VoiceInsertionSnapshot,} from '../../lib/voiceCleanup';+import { isComposingKey } from '@/lib/imeComposition';import { useLatestRef } from '@/lib/useLatestRef';export type AgentSearchResult = {@@ -385,7 +386,7 @@ function EnterSubmitPlugin({KEY_ENTER_COMMAND,(event: KeyboardEvent | null) => {if (!event || event.shiftKey) return false;- if (event.isComposing || event.keyCode === 229) return false;+ if (isComposingKey(event)) return false;if (menuOpenRef.current || isSoftKeyboardOpen()) return false;event.preventDefault();onSubmit();diff --git a/ui/src/components/workbench/TerminalView.tsx b/ui/src/components/workbench/TerminalView.tsxindex 90ae9ee92..b657facd5 100644--- a/ui/src/components/workbench/TerminalView.tsx+++ b/ui/src/components/workbench/TerminalView.tsx@@ -17,6 +17,7 @@ import {} from '../../lib/terminalFontSize';import { IS_APPLE } from '../../lib/platform';import { openLinkInNewContext } from '../../lib/pwaNavigation';+import { isComposingKey } from '@/lib/imeComposition';import { useLatestRef } from '@/lib/useLatestRef';import {REMOTE_AUTH_STATE_EVENT,@@ -503,7 +504,7 @@ export const TerminalView: React.FC<{const onSearchKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {// Mid-IME-composition (e.g. a CJK candidate), Enter/Escape belong to the IME — accepting or// cancelling the candidate — not to search navigation. Let them through untouched.- if (e.nativeEvent.isComposing) return;+ if (isComposingKey(e)) return;if (e.key === 'Enter') {e.preventDefault();runFind(e.shiftKey ? 'prev' : 'next');diff --git a/ui/src/components/workbench/search/SearchPalette.tsx b/ui/src/components/workbench/search/SearchPalette.tsxindex 218c24811..1e68a240c 100644--- a/ui/src/components/workbench/search/SearchPalette.tsx+++ b/ui/src/components/workbench/search/SearchPalette.tsx@@ -5,6 +5,7 @@ import * as DialogPrimitive from '@radix-ui/react-dialog';import { AlertCircle, Loader2, Search } from 'lucide-react';import { appTabHref, tabModifierLabel, type LaunchModifiers } from '../../../apps/appLaunch';+import { isComposingKey } from '@/lib/imeComposition';import { useMessageSearch } from '../../../lib/useMessageSearch';import { Dialog, DialogOverlay, DialogPortal, DialogTitle } from '../../ui/dialog';import { Input } from '../../ui/input';@@ -105,9 +106,9 @@ export const SearchPalette: React.FC<SearchPaletteProps> = ({ open, onClose }) =// While an IME composition is active (Chinese/Japanese/Korean candidate// selection), ArrowUp/Down/Enter belong to the IME — navigating candidates// and committing the chosen one. Intercepting them would steal those keys- // from the input. ``keyCode === 229`` is the legacy IME-in-progress signal- // for browsers that don't set ``isComposing`` on the synthetic event.- if (e.nativeEvent.isComposing || e.keyCode === 229) return;+ // from the input. The two signals a browser may announce this through are+ // read by the shared guard.+ if (isComposingKey(e)) return;if (e.key === 'ArrowDown') {e.preventDefault();moveSelection(1);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex aab8a2eff..ea2a8a913 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -946,7 +946,7 @@"title": "{{backend}} models","description": "Add, edit, reorder, and remove the models this backend offers. The order here is the order the Agent sees.","search": "Search name or model ID",- "add": "Add model",+ "add": "Add models","columnModel": "Model","columnActions": "Actions","columnState": "State",@@ -955,7 +955,7 @@"edit": "Edit {{model}}","remove": "Remove {{model}}","reorder": "Reorder {{model}}",- "removeBlocked": "This model still has a route. Clear its route first, then remove it.",+ "removeConfirm": "Remove","empty": "No models yet. Add the first one.","noMatch": "No model matches this search","legacy": "This model engine build does not offer an editable model list yet. These are the models it currently exposes.",@@ -982,6 +982,20 @@"dropped_other": "Dropped {{model}} at position {{position}} of {{count}}.","grabCancelled": "Cancelled moving {{model}} and restored its original position."},+ "picker": {+ "title": "Add {{backend}} models",+ "description": "Pick the models to add to this backend's list.",+ "search": "Search models or providers",+ "groupBuiltin": "{{backend}} built-in",+ "groupProviders": "From your providers",+ "groupListed": "Already in the list",+ "noMatch": "No model matches.",+ "unavailable": "The models you can add could not be read.",+ "customFromQuery": "Add \"{{query}}\" as a custom model…",+ "custom": "Add custom model…",+ "confirm_one": "Add {{count}} model",+ "confirm_other": "Add {{count}} models"+ },"modelEditor": {"eyebrow": "{{backend}} · Model list","addTitle": "Add model",@@ -993,22 +1007,21 @@"capabilities": "Capabilities"},"id": {- "label": "Backend model ID",- "placeholder": "The ID the backend requests this model by",+ "label": "Model",+ "placeholder": "Search models.dev or enter a model ID","required": "Enter a backend model ID.","tooLong": "A model ID may be at most 256 characters.",- "duplicate": "This list already has a model with this ID."+ "invalid": "An OpenCode model ID is provider/model, and needs both halves.",+ "duplicate": "This list already has a model with this ID."},"displayName": {"label": "Display name","placeholder": "Optional — the list shows the model ID when this is empty"},- "fill": "Fill from models.dev",- "fillEmpty": "models.dev has no model matching this ID.",- "fillFailed": "models.dev could not be reached.",- "fillUnavailable": "The models.dev catalog is unavailable right now. You can fill these fields in by hand.",- "filled": "Filled the fields below; every one stays editable.",- "viewMatches": "View",+ "lookupLoading": "Searching models.dev…",+ "useAsId": "Use \"{{query}}\" as the model ID",+ "fillFailed": "models.dev could not be reached",+ "fillUnavailable": "models.dev unavailable","matches": "models.dev matches","contextWindow": "Context window","maxOutput": "Maximum output",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 6ff3a0a49..e56e9bf22 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -955,7 +955,7 @@"edit": "编辑 {{model}}","remove": "移除 {{model}}","reorder": "调整 {{model}} 的顺序",- "removeBlocked": "该模型仍配置了路由,请先清空它的路由再移除。",+ "removeConfirm": "移除","empty": "还没有模型,先添加一个。","noMatch": "没有匹配的模型","legacy": "当前模型引擎版本还不支持编辑模型列表,以下是它当前提供的模型。",@@ -982,6 +982,20 @@"dropped_other": "已放下 {{model}},第 {{position}} / {{count}} 位。","grabCancelled": "已取消移动 {{model}},位置已还原。"},+ "picker": {+ "title": "添加 {{backend}} 模型",+ "description": "挑选要加入这个后端模型列表的模型。",+ "search": "搜索模型或供应商",+ "groupBuiltin": "{{backend}} 内置",+ "groupProviders": "来自你的供应商",+ "groupListed": "已在列表中",+ "noMatch": "没有匹配的模型。",+ "unavailable": "没能读取可添加的模型。",+ "customFromQuery": "把「{{query}}」添加为自定义模型…",+ "custom": "添加自定义模型…",+ "confirm_one": "添加 {{count}} 个模型",+ "confirm_other": "添加 {{count}} 个模型"+ },"modelEditor": {"eyebrow": "{{backend}} · 模型列表","addTitle": "添加模型",@@ -993,22 +1007,21 @@"capabilities": "能力"},"id": {- "label": "Backend 模型 ID",- "placeholder": "后端请求这个模型时使用的 ID",+ "label": "模型",+ "placeholder": "搜索 models.dev 或输入模型 ID","required": "请填写 Backend 模型 ID。","tooLong": "模型 ID 最多 256 个字符。",- "duplicate": "列表中已存在相同 ID 的模型。"+ "invalid": "OpenCode 模型 ID 的格式是 provider/model,两段都不能为空。",+ "duplicate": "列表中已存在相同 ID 的模型。"},"displayName": {"label": "显示名称","placeholder": "可选,留空时列表显示模型 ID"},- "fill": "从 models.dev 填充",- "fillEmpty": "models.dev 上没有匹配该 ID 的模型。",- "fillFailed": "没能访问 models.dev。",- "fillUnavailable": "models.dev 目录暂时不可用,你可以手动填写这些字段。",- "filled": "已填入下列字段,可逐项修改",- "viewMatches": "查看",+ "lookupLoading": "正在搜索 models.dev…",+ "useAsId": "把「{{query}}」作为模型 ID",+ "fillFailed": "没能访问 models.dev",+ "fillUnavailable": "models.dev 不可用","matches": "models.dev 匹配结果","contextWindow": "上下文窗口","maxOutput": "最大输出",diff --git a/ui/src/lib/backendModels.test.ts b/ui/src/lib/backendModels.test.tsindex 038a6f767..6d091a22f 100644--- a/ui/src/lib/backendModels.test.ts+++ b/ui/src/lib/backendModels.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { blankBackendModel } from '../components/settings/models/backendCatalog';+import { blankBackendModel, candidateBackendModel } from '../components/settings/models/backendCatalog';import type { AgentSupply, BackendModel } from '../components/settings/models/types';import { ApiError, type ApiContextType } from '../context/ApiContext';import { fetchBackendModels, loadBackendModelsWithRefresh, modelOptionLabel } from './backendModels';@@ -164,6 +164,38 @@ describe('fetchBackendModels in gateway mode', () => {}});+ it('keeps the efforts a picked candidate arrived with, all the way to the Route editor', async () => {+ // Built the way the picker builds it — a checkbox, no editor — so this is+ // the whole path from 「the server proposed these tiers」 to 「the Route+ // editor offers them」. A floor that answered `supports_reasoning: false`+ // on the row's behalf broke it here: the projection reads that as 「this+ // model does not reason」 and suppresses the very efforts the row was+ // created with, leaving a reasoning model with nothing to select.+ const picked = candidateBackendModel({+ id: 'glm-5.2',+ display_name: 'GLM 5.2',+ reasoning_efforts: ['low', 'high'],+ suppliers: [{ source_id: 'src_relay0001', source_name: 'relay.example', model_id: 'glm-5.2-air' }],+ origin: 'provider',+ });+ const api = {+ readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(+ hubAgent('codex', { catalog_models: [picked] }),+ ),+ codexModels: vi.fn(),+ } as unknown as ApiContextType;++ // The row states no capability at all: `null` leaves the backend's own+ // default in force, which is the only honest reading of a row nobody+ // opened.+ expect(picked.supports_reasoning).toBeNull();+ expect(picked.supports_tools).toBeNull();++ const result = await fetchBackendModels(api, 'codex');++ expect(resolveEffortOptions('codex', 'glm-5.2', result.reasoningOptions)).toEqual(['low', 'high']);+ });+it('treats model ids as data rather than Object properties', async () => {const api = {readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(diff --git a/ui/src/lib/imeComposition.test.ts b/ui/src/lib/imeComposition.test.tsnew file mode 100644index 000000000..9387b13c0--- /dev/null+++ b/ui/src/lib/imeComposition.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import { isComposingKey, type ComposingKeyEvent } from './imeComposition';++/**+ * One entry per channel a browser announces composition through, each carrying+ * only that signal. Seeded rather than enumerated as cases: a channel the guard+ * learns to read is added here once and every property below covers it in every+ * combination, so no combination can be the one nobody thought of.+ */+const SIGNALS: Record<string, ComposingKeyEvent> = {+ reactSynthetic: { nativeEvent: { isComposing: true } },+ nativeEvent: { isComposing: true },+ legacyKeyCode: { keyCode: 229 },+};++/** Every subset of the signals, the empty one first. */+const subsets = (): { names: string[]; event: ComposingKeyEvent }[] => {+ const names = Object.keys(SIGNALS);+ return Array.from({ length: 2 ** names.length }, (_, mask) => {+ const chosen = names.filter((_name, index) => (mask & (1 << index)) !== 0);+ return {+ names: chosen,+ event: chosen.reduce<ComposingKeyEvent>(+ (event, name) => ({ ...event, ...SIGNALS[name] }),+ {},+ ),+ };+ });+};++describe('a keystroke that belongs to the input method', () => {+ it('is recognised through any signal a browser announces it with', () => {+ const announced = subsets().filter(({ names }) => names.length > 0);+ expect(announced.length).toBeGreaterThan(0);+ expect(announced.filter(({ event }) => !isComposingKey(event))).toEqual([]);+ });++ it('is the only kind recognised: one announcing nothing belongs to the person typing', () => {+ const [silent] = subsets();+ expect(silent.names).toEqual([]);+ expect(isComposingKey(silent.event)).toBe(false);+ });++ it('is not read into an event that answers every signal in the negative', () => {+ expect(isComposingKey({+ nativeEvent: { isComposing: false },+ isComposing: false,+ keyCode: 13,+ })).toBe(false);+ });+});diff --git a/ui/src/lib/imeComposition.ts b/ui/src/lib/imeComposition.tsnew file mode 100644index 000000000..f56298266--- /dev/null+++ b/ui/src/lib/imeComposition.ts@@ -0,0 +1,40 @@+/** The signals a key event carries when it belongs to an input method rather+ * than to the person at the keyboard. Structural on purpose: React's synthetic+ * event exposes the standard flag on `nativeEvent`, a raw DOM event exposes it+ * directly, and neither is guaranteed to set it at all. */+export type ComposingKeyEvent = {+ isComposing?: boolean;+ keyCode?: number;+ nativeEvent?: { isComposing?: boolean };+};++/** The legacy IME-in-progress signal, for browsers that leave `isComposing`+ * unset on the event a key handler receives. */+const LEGACY_COMPOSING_KEY_CODE = 229;++/**+ * Whether this keystroke is the input method's and not the user's.+ *+ * Someone typing Chinese, Japanese, Korean, or Vietnamese types into a+ * candidate window and presses Enter to accept the characters they are+ * composing. The browser delivers that Enter to the field underneath, so a+ * handler that reads Enter as 「commit this」 takes a keystroke that was never+ * aimed at it and commits something the user did not ask for — and Arrow keys+ * move through the candidate list the same way. A handler that acts on keys at+ * all asks this first.+ *+ * Both signals are checked because neither alone is enough: `isComposing` is+ * the standard one, and `keyCode === 229` is what the browsers that omit it+ * from the delivered event set instead.+ *+ * Promoted here on its fifth repeat and the four earlier copies now call it —+ * `TerminalView`, `MentionEditor`, `Composer`, `SearchPalette` — so the next key+ * handler inherits the check instead of rediscovering it. Two of those four read+ * only `isComposing` and were missing the legacy signal, which is the whole+ * argument for one home: the same defect was present four times over and would+ * have been found one review round at a time.+ */+export const isComposingKey = (event: ComposingKeyEvent): boolean =>+ event.nativeEvent?.isComposing === true+ || event.isComposing === true+ || event.keyCode === LEGACY_COMPOSING_KEY_CODE;