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(ui): reasoning tier provenance in model hub source detail (#1835)
Max71c0ebdfd68b
diff --git a/ui/e2e/README.md b/ui/e2e/README.mdindex 6d6508935..02a58f015 100644--- a/ui/e2e/README.md+++ b/ui/e2e/README.md@@ -290,3 +290,10 @@ Recorded here so the gaps are visible rather than merely absent:a mock without a real OAuth provider.- **Malformed guard echoes** (G1). The echo is built by the product; a browsercannot corrupt it without a product-side hook.+- **Locked-tier provenance on a server that predates the field** (B10). The+ catalog and upstream lock specs `test.fixme` unless the live instance stamps+ `reasoning_efforts_source` as `catalog` / `upstream` on the seeded model.+ Ghost suggestions and the `source_model_tiers_managed` refusal copy still+ run: the copy is reached by intercepting that one PATCH, and Chinese is a+ config-GET rewrite for that page only — the instance's language is never+ saved.diff --git a/ui/e2e/b-source-detail.spec.ts b/ui/e2e/b-source-detail.spec.tsindex 41e35c05f..04d5cba2b 100644--- a/ui/e2e/b-source-detail.spec.ts+++ b/ui/e2e/b-source-detail.spec.ts@@ -5,6 +5,7 @@// The source these specs act on is created through the API, not through the Add// dialog: their subject is what happens AFTER a source exists, and re-driving// Add here would report Add's failures under a rename test's name.+import type { Source } from './support/api';import { hub as copy } from './support/copy';import { E2E_SOURCE_PREFIX, mockBaseUrl } from './support/env';import {@@ -16,7 +17,61 @@ import {requireSource,test,} from './support/fixtures';+import type { ModelHubPage } from './support/hub';import { anthropicInventory } from './support/mock';+import { PROTOCOL_TIER_SUGGESTIONS } from './support/vocabulary';++type Supplied = Source['models'][number];+type ManagedRung = 'upstream' | 'catalog';++/**+ * The lock this UI can show only exists once the server has stamped the rung.+ * The ladder ships, so a running instance that leaves the row editable is one+ * whose build predates it — the pre-ladder behavior, not a product failure+ * here. `test.fixme` rather than `test.skip`: the report names the instance's+ * missing rung, and the same spec asserts on an up-to-date one with no edit.+ */+const requireManagedRung = (+ model: Supplied | undefined,+ modelId: string,+ rung: ManagedRung,+): boolean => {+ const stamped = model?.reasoning_efforts_source;+ if (stamped === rung) return true;+ // `test.fixme` is the skip the report should show; the return is what+ // keeps this body from then asserting a lock the instance cannot draw.+ test.fixme(+ true,+ `this instance did not stamp reasoning_efforts_source=${rung} on ${modelId}`+ + ` (got ${stamped === undefined ? 'absent' : JSON.stringify(stamped)}); `+ + 'locked editor and provenance badge cannot be reached on this instance.',+ );+ return false;+};++const expectLockedRow = async (+ page: ModelHubPage,+ modelId: string,+ rung: ManagedRung,+): Promise<void> => {+ const cell = page.managedTierCell(modelId, rung);+ await expect(cell).toBeVisible();+ await expect(cell).toContainText(copy(`sourceDetail.tiers.managed.${rung}`));+ await expect(page.tierAddAffordance(modelId)).toHaveCount(0);+ await expect(page.modelRow(modelId).getByRole('textbox')).toHaveCount(0);+ await expect(page.tierSuggestions(modelId)).toHaveCount(0);+ await cell.click();+ await expect(page.modelRow(modelId).getByRole('textbox')).toHaveCount(0);+ await expect(page.tierSuggestions(modelId)).toHaveCount(0);+ for (const tier of await page.tierChips(modelId).allTextContents()) {+ await expect(+ page.modelRow(modelId).getByRole('button', {+ name: copy('sourceDetail.tiers.remove', { tier }),+ exact: true,+ }),+ ).toHaveCount(0);+ }+};test.describe('B · the source detail panel', () => {test.beforeEach(async ({ api, mock }) => {@@ -169,4 +224,181 @@ test.describe('B · the source detail panel', () => {// The discovered model is untouched: removing one model is not a refetch.await expect(hub.modelRow('e2e-discovered')).toBeVisible();});++ // B10 grows the provenance cases the spec's D-5 decision added: the editor+ // is a door only when the server does not own the list. Locked rows, the+ // badge that says which rung owns them, ghost suggestions matching the+ // protocol vocabulary, and the 409 copy that must never offer a retry.++ test('B10 · ghost suggestions match the protocol vocabulary', async ({ hub, mock, api }) => {+ await mock.configure({+ auth: 'ok',+ protocol: 'anthropic',+ models_endpoint: 'ok',+ models: anthropicInventory(['e2e-vocab']),+ });+ const name = `${E2E_SOURCE_PREFIX}tier-vocab`;+ const source = await requireSource(api, name, mockBaseUrl());+ const model = source.models.find((entry) => entry.id === 'e2e-vocab');+ expect(model, 'The precondition source did not take the seeded inventory, so there is no editor to open.').toBeTruthy();+ const expected = PROTOCOL_TIER_SUGGESTIONS[source.protocol];+ expect(expected, `no suggestion list for protocol ${source.protocol}`).toBeTruthy();+ if (!expected) return;++ await hub.goto();+ await hub.openSource(source.id);+ await hub.tierCell('e2e-vocab').click();++ await expect(hub.modelRow('e2e-vocab').getByRole('textbox')).toBeVisible();+ await expect(hub.tierSuggestions('e2e-vocab')).toHaveText([...expected]);+ await expect(hub.managedTierCell('e2e-vocab', 'upstream')).toHaveCount(0);+ await expect(hub.managedTierCell('e2e-vocab', 'catalog')).toHaveCount(0);+ });++ test('B10 · a catalog-declared model shows its provenance and cannot be edited', async ({ hub, mock, api }) => {+ // `claude-opus-4-6` is a real builtin-catalog id. A server that has landed+ // the provenance ladder stamps it `catalog` and re-applies the catalog+ // list on every refresh; a server that has not leaves the field absent+ // and the row editable — which is the pre-ladder behavior, not a lock+ // this UI can show.+ const catalogId = 'claude-opus-4-6';+ const siblingId = 'e2e-not-in-catalog';+ await mock.configure({+ auth: 'ok',+ protocol: 'anthropic',+ models_endpoint: 'ok',+ models: anthropicInventory([catalogId, siblingId]),+ });+ const name = `${E2E_SOURCE_PREFIX}tier-catalog`;+ const source = await requireSource(api, name, mockBaseUrl());+ const catalogModel = source.models.find((entry) => entry.id === catalogId);+ expect(catalogModel, 'The precondition source did not take the catalog id, so there is no row to lock.').toBeTruthy();+ if (!requireManagedRung(catalogModel, catalogId, 'catalog')) return;++ await hub.goto();+ await hub.openSource(source.id);+ await expectLockedRow(hub, catalogId, 'catalog');++ // Locking is per model: the sibling the catalog does not know stays a door.+ await hub.tierCell(siblingId).click();+ await expect(hub.modelRow(siblingId).getByRole('textbox')).toBeVisible();+ });++ test('B10 · an upstream-declared model shows its provenance and cannot be edited', async ({ hub, mock, api }) => {+ // OpenRouter-shape `supported_parameters` carrying a reasoning signal is+ // the v1 capture the spec names. The id is deliberately not a catalog+ // entry, so a server that has landed rung 1 stamps `upstream` rather+ // than falling through to rung 2.+ const upstreamId = 'e2e-reasoner';+ const siblingId = 'e2e-no-signal';+ await mock.configure({+ auth: 'ok',+ protocol: 'anthropic',+ models_endpoint: 'ok',+ models: [+ {+ id: upstreamId,+ type: 'model',+ display_name: `${upstreamId} (upstream label)`,+ supported_parameters: ['reasoning'],+ },+ ...anthropicInventory([siblingId]),+ ],+ });+ const name = `${E2E_SOURCE_PREFIX}tier-upstream`;+ const source = await requireSource(api, name, mockBaseUrl());+ const upstreamModel = source.models.find((entry) => entry.id === upstreamId);+ expect(upstreamModel, 'The precondition source did not take the seeded reasoner, so there is no row to lock.').toBeTruthy();+ if (!requireManagedRung(upstreamModel, upstreamId, 'upstream')) return;++ await hub.goto();+ await hub.openSource(source.id);+ await expectLockedRow(hub, upstreamId, 'upstream');++ await hub.tierCell(siblingId).click();+ await expect(hub.modelRow(siblingId).getByRole('textbox')).toBeVisible();+ });++ for (const locale of ['en', 'zh'] as const) {+ test(`B10 · a managed-tier refusal is a sentence in ${locale}, not a retry`, async ({ hub, mock, api, page }) => {+ // The UI does not offer the write on a locked row, so the authentic+ // browser path is a state race: the editor is open because this client+ // still believes the row is editable, and the PATCH comes back as the+ // server owning the list. Intercepting that one call is how the copy is+ // reached on an instance whose build predates the guard — and remains+ // the path on one that has it, because a locked row never sends the+ // write. The instance's language is not saved; Chinese is a+ // config-GET rewrite for this page only.+ if (locale === 'zh') {+ await page.route('**/api/config', async (route) => {+ if (route.request().method() !== 'GET') {+ await route.continue();+ return;+ }+ const response = await route.fetch();+ await route.fulfill({+ response,+ json: { ...(await response.json() as Record<string, unknown>), language: 'zh' },+ });+ });+ }+ await page.route('**/api/models/sources/*/models/*', async (route) => {+ if (route.request().method() !== 'PATCH') {+ await route.continue();+ return;+ }+ await route.fulfill({+ status: 409,+ json: { ok: false, error: 'source_model_tiers_managed' },+ });+ });++ await mock.configure({+ auth: 'ok',+ protocol: 'anthropic',+ models_endpoint: 'ok',+ models: anthropicInventory(['e2e-refusal']),+ });+ const name = `${E2E_SOURCE_PREFIX}tier-refusal-${locale}`;+ const source = await requireSource(api, name, mockBaseUrl());+ const expected = PROTOCOL_TIER_SUGGESTIONS[source.protocol];+ expect(expected, `no suggestion list for protocol ${source.protocol}`).toBeTruthy();+ const first = expected![0];+ expect(first, 'the protocol vocabulary is empty, so there is no suggestion to click').toBeTruthy();+ if (!first) return;++ await hub.goto();+ await hub.openSource(source.id);+ await expect(+ hub.sourceDetailDialog.getByRole('button', {+ name: copy('sourceDetail.action.refetch', undefined, locale),+ exact: true,+ }),+ ).toBeVisible();++ await hub.tierCell('e2e-refusal').click();+ await expect(hub.modelRow('e2e-refusal').getByRole('textbox')).toBeVisible();+ await hub.modelRow('e2e-refusal').getByRole('button', {+ name: copy('sourceDetail.tiers.suggest', { tier: first }, locale),+ exact: true,+ }).click();++ await expect(hub.tierFailure('e2e-refusal', 'managed')).toBeVisible();+ await expect(hub.tierFailure('e2e-refusal', 'managed')).toHaveText(+ copy('sourceDetail.fail.tierManaged', undefined, locale),+ );+ await expect(hub.tierFailure('e2e-refusal', 'retryable')).toHaveCount(0);+ await expect(+ hub.modelRow('e2e-refusal').getByRole('button', {+ name: copy('sourceDetail.retry', undefined, locale),+ exact: true,+ }),+ ).toHaveCount(0);+ await expectVisibleWithout(+ hub.modelRow('e2e-refusal'),+ copy('sourceDetail.fail.tier', undefined, locale),+ );+ await expect(hub.tierChips('e2e-refusal')).toHaveCount(0);+ });+ }});diff --git a/ui/e2e/support/api.ts b/ui/e2e/support/api.tsindex bd73b19b6..630d324e2 100644--- a/ui/e2e/support/api.ts+++ b/ui/e2e/support/api.ts@@ -27,7 +27,17 @@ export type Source = {base_url?: string | null;credential_ref?: string | null;client_nonce?: string | null;- models: { id: string; origin: string; reasoning_efforts: string[]; [key: string]: unknown }[];+ models: {+ id: string;+ origin: string;+ reasoning_efforts: string[];+ /**+ * Which rung of the provenance ladder produced `reasoning_efforts`.+ * Absent on a server that predates the field — the editable case.+ */+ reasoning_efforts_source?: 'upstream' | 'catalog' | 'user' | null;+ [key: string]: unknown;+ }[];state: SourceState;adopted_by?: { backend: string; model: string }[];};diff --git a/ui/e2e/support/copy.ts b/ui/e2e/support/copy.tsindex 0c4b6e96c..194ec5a79 100644--- a/ui/e2e/support/copy.ts+++ b/ui/e2e/support/copy.ts@@ -2,10 +2,12 @@//// Model Hub product code carries no `data-testid`, and this lane may not add// one. What it does carry is user-visible copy: every control is reachable by-// its accessible name, and every name comes from `src/i18n/en.json`. Reading-// the shipped bundle instead of pasting the strings means a copy change breaks-// the test at the key, where the diff is legible, rather than at a locator that-// silently stops matching.+// its accessible name, and every name comes from the shipped i18n bundles.+// Reading those instead of pasting the strings means a copy change breaks the+// test at the key, where the diff is legible, rather than at a locator that+// silently stops matching. Specs default to English — the hermetic instance's+// language — and pass `'zh'` only when they have already put the page in+// Chinese (a config-GET intercept, never a persisted save).//// The bundle is not plain nesting: leaves may carry dots of their own// (`addKey.field.apiKey` is a string AND `addKey.field.apiKey.reveal` exists@@ -16,10 +18,12 @@ import { readFileSync } from 'node:fs';type Bundle = { [key: string]: string | Bundle };type Vars = Record<string, string | number>;+export type CopyLocale = 'en' | 'zh';-const bundle = JSON.parse(- readFileSync(new URL('../../src/i18n/en.json', import.meta.url), 'utf8'),-) as Bundle;+const bundles: Record<CopyLocale, Bundle> = {+ en: JSON.parse(readFileSync(new URL('../../src/i18n/en.json', import.meta.url), 'utf8')) as Bundle,+ zh: JSON.parse(readFileSync(new URL('../../src/i18n/zh.json', import.meta.url), 'utf8')) as Bundle,+};const resolve = (node: string | Bundle | undefined, segments: string[]): string | undefined => {if (node === undefined) return undefined;@@ -37,13 +41,13 @@ const interpolate = (template: string, vars?: Vars): string =>vars && name in vars ? String(vars[name]) : whole);/** The rendered string for `key`, or `null` when the bundle has no such key. */-export const copyOrNull = (key: string, vars?: Vars): string | null => {+export const copyOrNull = (key: string, vars?: Vars, locale: CopyLocale = 'en'): string | null => {const count = vars?.count;const candidates = typeof count === 'number'- ? [`${key}_${new Intl.PluralRules('en-US').select(count)}`, key]+ ? [`${key}_${new Intl.PluralRules(locale === 'zh' ? 'zh-CN' : 'en-US').select(count)}`, key]: [key];for (const candidate of candidates) {- const template = resolve(bundle, candidate.split('.'));+ const template = resolve(bundles[locale], candidate.split('.'));if (template !== undefined) return interpolate(template, vars);}return null;@@ -54,9 +58,9 @@ export const copyOrNull = (key: string, vars?: Vars): string | null => {* locator built from `undefined` matches nothing and reports "element not* found" — an absent key has to fail as an absent key.*/-export const copy = (key: string, vars?: Vars): string => {- const text = copyOrNull(key, vars);- if (text === null) throw new Error(`i18n key missing from src/i18n/en.json: ${key}`);+export const copy = (key: string, vars?: Vars, locale: CopyLocale = 'en'): string => {+ const text = copyOrNull(key, vars, locale);+ if (text === null) throw new Error(`i18n key missing from src/i18n/${locale}.json: ${key}`);return text;};@@ -64,8 +68,9 @@ export const copy = (key: string, vars?: Vars): string => {export const hasCopy = (key: string): boolean => copyOrNull(key) !== null;/** `settings.models.` prefix, since every key this suite reads lives under it. */-export const hub = (key: string, vars?: Vars): string => copy(`settings.models.${key}`, vars);+export const hub = (key: string, vars?: Vars, locale: CopyLocale = 'en'): string =>+ copy(`settings.models.${key}`, vars, locale);/** Nullable form of {@link hub}. */-export const hubOrNull = (key: string, vars?: Vars): string | null =>- copyOrNull(`settings.models.${key}`, vars);+export const hubOrNull = (key: string, vars?: Vars, locale: CopyLocale = 'en'): string | null =>+ copyOrNull(`settings.models.${key}`, vars, locale);diff --git a/ui/e2e/support/hub.ts b/ui/e2e/support/hub.tsindex 80083c4b5..16ece57d0 100644--- a/ui/e2e/support/hub.ts+++ b/ui/e2e/support/hub.ts@@ -180,6 +180,68 @@ export class ModelHubPage {return this.sourceDetailDialog.locator('[data-manual-model-draft]');}+ // --- Reasoning tiers ------------------------------------------------------++ /**+ * The tiers cell of one model row.+ *+ * One name for two renderings on purpose. An editable cell is a button that+ * opens the editor; a cell whose tiers the server declared is a plain div with+ * no way in. A spec asserting "there is no way in here" has to be able to name+ * the cell without already knowing which of the two it got.+ */+ tierCell(modelId: string): Locator {+ return this.modelRow(modelId).locator('.model-hub-source-tier-cell');+ }++ /** The tiers the row carries right now, in the order the product lists them. */+ tierChips(modelId: string): Locator {+ return this.modelRow(modelId).locator('.model-hub-source-tier-chip');+ }++ /** The ghost tiers an open editor proposes — the protocol's vocabulary, minus+ * whatever the model already has. */+ tierSuggestions(modelId: string): Locator {+ return this.modelRow(modelId).locator('.model-hub-source-tier-suggest');+ }++ /**+ * The cell of a model whose tiers the SERVER declared, named by the rung that+ * declared them.+ *+ * The attribute is absent on an editable row rather than carrying some other+ * value, which is what makes `toHaveCount(0)` here a real assertion instead of+ * a spelling of "the rung is something else".+ */+ managedTierCell(modelId: string, rung: 'upstream' | 'catalog'): Locator {+ return this.modelRow(modelId).locator(attr('data-tier-provenance', rung));+ }++ /**+ * The note a tier write that did not land leaves on its row.+ *+ * Named by kind rather than found by looking for a retry button: `retryable`+ * and `managed` are two verdicts about whether the write could ever succeed,+ * and the button is only one of the things that follows from that.+ */+ tierFailure(modelId: string, kind: 'managed' | 'retryable'): Locator {+ return this.modelRow(modelId).locator(attr('data-tier-failure', kind));+ }++ /**+ * The "+ Add tier" / "+ Tier" pill. Present on an editable resting row (even+ * when CSS hides it until hover) and absent on a locked one, which is the+ * distinction a lock assertion needs — a disabled pill would still be a door.+ */+ tierAddAffordance(modelId: string): Locator {+ return this.modelRow(modelId).locator('.model-hub-source-tier-add');+ }++ /** The free-text field an open editor types a new tier into. */+ tierInput(modelId: string): Locator {+ return this.modelRow(modelId).getByPlaceholder(hub('sourceDetail.tiers.inputHint'), { exact: true });+ }+/*** The confirm-before-destroy dialog raised from the source panel.*diff --git a/ui/e2e/support/protocol-tiers.json b/ui/e2e/support/protocol-tiers.jsonnew file mode 100644index 000000000..e61313d71--- /dev/null+++ b/ui/e2e/support/protocol-tiers.json@@ -0,0 +1,5 @@+{+ "anthropic": ["low", "medium", "high", "xhigh", "max"],+ "openai_responses": ["minimal", "low", "medium", "high", "xhigh"],+ "openai_chat": ["minimal", "low", "medium", "high", "xhigh"]+}diff --git a/ui/e2e/support/vocabulary.ts b/ui/e2e/support/vocabulary.tsnew file mode 100644index 000000000..c07d229a8--- /dev/null+++ b/ui/e2e/support/vocabulary.ts@@ -0,0 +1,8 @@+// The protocol-family suggestion lists, read from the JSON `tierSuggestions.test.ts`+// holds equal to the product table. This file exists because the e2e tsconfig+// cannot import `@/` aliases; the vitest is what keeps the copy from drifting.+import { readFileSync } from 'node:fs';++export const PROTOCOL_TIER_SUGGESTIONS = JSON.parse(+ readFileSync(new URL('./protocol-tiers.json', import.meta.url), 'utf8'),+) as Record<string, readonly string[]>;diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxindex 325ead87d..752d182a8 100644--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -22,6 +22,7 @@ import { GuardGapList } from './GuardGapList';import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, repairAction, type RepairKind } from './repair';import { SourceDetailPanel } from './SourceDetailPanel';import { SourceMutationReport } from './SourceMutationReport';+import { MANAGED_TIER_SOURCES, type ManagedTierSource } from './tierMutation';import { TIER_SUGGESTIONS } from './tierSuggestions';import {COOLDOWN_DETAIL_KEYS,@@ -177,6 +178,19 @@ const renderProtocol = (protocol: SourceProtocol, models: Source['models'] = sou/** Read by the class the stylesheet owns: the ghost chip has no other identity. */const suggestedTiers = () => Array.from(document.querySelectorAll('.model-hub-source-tier-suggest')).map((chip) => chip.textContent?.trim() ?? '');+/** The tiers the row actually carries, in either branch that draws them. */+const chipTiers = () => Array.from(document.querySelectorAll('.model-hub-source-tier-chip'))+ .map((chip) => chip.textContent?.trim() ?? '');+/**+ * What the badge on a locked row says, per rung. Spelled out rather than read+ * back through `i18n.t`: a bundle missing the entry returns the key from both+ * sides of that comparison, so it would pass while the user reads+ * 「settings.models.sourceDetail.tiers.managed.upstream」.+ */+const MANAGED_BADGE: Readonly<Record<ManagedTierSource, RegExp>> = {+ upstream: /^From provider$|^供应商声明$/,+ catalog: /^Built-in catalog$|^内置目录$/,+};const EchoPanel: React.FC<{reconcile?: () => Promise<SourceMutationLanding['verdict'] | void> | SourceMutationLanding['verdict'] | void;@@ -1068,6 +1082,145 @@ describe('SourceDetailPanel', () => {}});+ // Rungs 1 and 2 of the provenance ladder are the server's own declaration,+ // re-applied on every refresh. There is nothing to add and nothing to delete,+ // so the cell stops being a way in rather than becoming a disabled one — and+ // it says which rung, because a row that just refused to open would leave+ // "why" as the user's problem.+ it.each(MANAGED_TIER_SOURCES)('locks a %s-declared row down to what it already carries', async (provenance) => {+ renderProtocol('anthropic', [{ ...source.models[0], reasoning_efforts_source: provenance }]);++ const cell = document.querySelector(`[data-tier-provenance="${provenance}"]`) as HTMLElement | null;+ expect(cell).toBeTruthy();+ expect(chipTiers()).toEqual(['high']);+ expect(within(cell as HTMLElement).getByText(MANAGED_BADGE[provenance])).toBeTruthy();++ // No door in, and none of the affordances the editor would have brought.+ await userEvent.click(cell as HTMLElement);+ expect(screen.queryByPlaceholderText(/Enter to add|回车添加/i)).toBeNull();+ expect(document.querySelector('.model-hub-source-tier-add')).toBeNull();+ expect(screen.queryByRole('button', { name: /^Remove high$|^移除 high$/ })).toBeNull();+ expect(suggestedTiers()).toEqual([]);+ });++ it('keeps a locked row legible when the server declared no tiers at all', () => {+ renderProtocol('anthropic', [{ ...source.models[0], reasoning_efforts: [], reasoning_efforts_source: 'upstream' }]);++ const cell = document.querySelector('[data-tier-provenance="upstream"]') as HTMLElement | null;+ expect(within(cell as HTMLElement).getByText(/No tiers set|未设置档位/i)).toBeTruthy();+ expect(within(cell as HTMLElement).getByText(MANAGED_BADGE.upstream)).toBeTruthy();+ });++ // The pencil is a second door into the same editor, so a locked row has to+ // close it too — a manual entry whose id matches a catalog model is locked+ // exactly like a discovered one. Removing the model is a different question.+ it('closes the pencil on a locked manual model while removal stays offered', () => {+ renderProtocol('anthropic', [{ ...source.models[0], origin: 'manual', reasoning_efforts_source: 'catalog' }]);++ expect(screen.queryByRole('button', { name: /reasoning tiers for model-a|model-a 的推理强度/i })).toBeNull();+ expect(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i })).toBeTruthy();+ });++ it.each([+ ['a user-declared list', 'user' as const],+ ['an explicitly unclaimed list', null],+ ['a server that predates the field', undefined],+ ])('leaves %s editable, suggestions and all', async (_case, provenance) => {+ renderProtocol('anthropic', [{+ ...source.models[0],+ ...(provenance === undefined ? {} : { reasoning_efforts_source: provenance }),+ }]);++ expect(document.querySelector('[data-tier-provenance]')).toBeNull();+ await userEvent.click(screen.getByRole('button', { name: /high/i }));+ expect(suggestedTiers()).toEqual(TIER_SUGGESTIONS.anthropic.filter((tier) => tier !== 'high'));+ });++ // Defensive, and reachable: a refresh can apply a rung while the editor is+ // open, another surface can change the source, and the call can come from+ // outside this page. The generic "The tier was not saved" would offer a retry+ // that cannot succeed, which is the one thing this user must not be invited to do.+ it('explains a refusal that says the server owns the list, and offers no retry', async () => {+ const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(+ new ApiCallError('bad_request', 'modelHub.errors.source_model_tiers_managed', true, [], [], [], 409),+ );+ renderPanel();+ await userEvent.click(screen.getByRole('button', { name: /high/i }));+ await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'low{Enter}');++ await waitFor(() => expect(update).toHaveBeenCalled());+ expect(await screen.findByText(/tiers are set automatically|档位是自动确定的/i)).toBeTruthy();+ expect(screen.queryByText(/tier was not saved|档位没保存上/i)).toBeNull();+ expect(screen.queryByRole('button', { name: /^Try again$|^重试$/i })).toBeNull();+ expect(chipTiers()).toEqual(['high']);+ });++ // The same conclusion by the other road: the write failed for its own reasons+ // and the row was managed by the time the rollback's re-read came back. "Try+ // again" would replay a write `tierMutationPayload` now declines, so the notice+ // that survives is the one that explains the lock — and it goes back to being a+ // retry if the server ever hands the list back, which is why the branch reads+ // provenance instead of freezing a verdict when the write failed.+ it('turns a pending retry into the locked explanation when provenance arrives after the failure', async () => {+ vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(new Error('write failed'));+ const panel = (models: Source['models']) => (+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <ReportOwnedPanel source={{ ...source, models }} trackMutation={immediateTrack} onReauth={noReauth} />+ </I18nextProvider>+ </ToastProvider>+ );+ const { rerender } = render(panel(source.models));+ await userEvent.click(screen.getByRole('button', { name: /high/i }));+ await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'low{Enter}');+ expect(await screen.findByText(/tier was not saved|档位没保存上/i)).toBeTruthy();+ expect(screen.getByRole('button', { name: /^Try again$|^重试$/i })).toBeTruthy();++ rerender(panel([{ ...source.models[0], reasoning_efforts_source: 'upstream' }]));++ expect(document.querySelector('[data-tier-provenance="upstream"]')).toBeTruthy();+ expect(await screen.findByText(/tiers are set automatically|档位是自动确定的/i)).toBeTruthy();+ expect(screen.queryByText(/tier was not saved|档位没保存上/i)).toBeNull();+ expect(screen.queryByRole('button', { name: /^Try again$|^重试$/i })).toBeNull();++ rerender(panel([{ ...source.models[0], reasoning_efforts_source: 'user' }]));++ expect(screen.getByRole('button', { name: /^Try again$|^重试$/i })).toBeTruthy();+ });++ // The copy obligation checked where the copy is actually read. A bundle+ // missing an entry reaches the user as the key itself, and these four strings+ // are the only thing on the surface that says why an edit is unavailable.+ it.each(['en', 'zh'] as const)('renders provenance and refusal copy as sentences in %s', async (lng) => {+ const spoken = i18n.language;+ await i18n.changeLanguage(lng);+ try {+ vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(+ new ApiCallError('bad_request', 'modelHub.errors.source_model_tiers_managed', true, [], [], [], 409),+ );+ renderProtocol('anthropic', [+ source.models[0],+ { id: 'model-b', display_name: null, origin: 'discovered', reasoning_efforts: ['high'], reasoning_efforts_source: 'upstream' },+ { id: 'model-c', display_name: null, origin: 'discovered', reasoning_efforts: ['high'], reasoning_efforts_source: 'catalog' },+ ]);++ expect(screen.getByText(lng === 'en' ? 'From provider' : '供应商声明')).toBeTruthy();+ expect(screen.getByText(lng === 'en' ? 'Built-in catalog' : '内置目录')).toBeTruthy();++ await userEvent.click(screen.getByRole('button', { name: /high/i }));+ await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'low{Enter}');+ const refusal = await screen.findByText(+ lng === 'en'+ ? "This model's tiers are set automatically, so the change was not saved"+ : '这个模型的档位是自动确定的,这次改动没有保存',+ );+ expect(refusal).toBeTruthy();+ } finally {+ cleanup();+ await i18n.changeLanguage(spoken);+ }+ });+it('adds a suggested tier through the same write typing it would take', async () => {const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockResolvedValueOnce({...source,@@ -1121,18 +1274,22 @@ describe('SourceDetailPanel', () => {// to the input's own blur, the collapse made every control inside it// pointer-only: Tab left the field and took the editor with it.it('lets the keyboard reach a suggestion and stays open around the write', async () => {+ // Whichever tier the protocol happens to offer first: what is under test is+ // that Tab lands on a suggestion at all, so naming one would make this fail+ // for a vocabulary change that never touched the focus rule.+ const [first] = TIER_SUGGESTIONS.openai_responses.filter((tier) => tier !== 'high');const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockResolvedValueOnce({...source,- models: [{ ...source.models[0], reasoning_efforts: ['high', 'low'] }],+ models: [{ ...source.models[0], reasoning_efforts: ['high', first] }],});renderProtocol('openai_responses');await userEvent.click(screen.getByRole('button', { name: /high/i }));await userEvent.tab();- const suggestion = screen.getByRole('button', { name: /^Add low$|^添加 low$/ });+ const suggestion = screen.getByRole('button', { name: new RegExp(`^Add ${first}$|^添加 ${first}$`) });expect(document.activeElement).toBe(suggestion);await userEvent.keyboard('{Enter}');- await waitFor(() => expect(update).toHaveBeenCalledWith(source.id, 'model-a', ['high', 'low']));+ await waitFor(() => expect(update).toHaveBeenCalledWith(source.id, 'model-a', ['high', first]));// The chip it was standing on is gone; focus is back on the one control the// edit state cannot lose, not on the body with the editor closed behind it.const input = screen.getByPlaceholderText(/Enter to add|回车添加/i);@@ -1147,8 +1304,8 @@ describe('SourceDetailPanel', () => {expect(document.activeElement).toBe(screen.getByRole('button', { name: /high/i }));});- // A write that was rolled back is the row's unfinished business, and 重试 is- // the only answer to it — so moving the editor elsewhere, which answers+ // A write that was rolled back is the row's unfinished business, and "Try again"+ // is the only answer to it — so moving the editor elsewhere, which answers// nothing, cannot be what takes the answer away.it('keeps a failed write answerable after the editor moves to another row', async () => {const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(new Error('write failed'));diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxindex 2aadf57bf..6dac18358 100644--- a/ui/src/components/settings/models/SourceDetailPanel.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -47,8 +47,14 @@ import {import { handOffProviderTab } from './providerTab';import { reconcileUnknownWrite } from './reconcileUnknownWrite';import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, reauthBodyKey, reauthCost, repairAction } from './repair';+import { tierEditRefusedAsManaged } from './serverCopy';import { activeSourceAdoption, sourceStatePresentation } from './sourceStatePresentation';-import { tierMutationPayload, type TierMutationIntent } from './tierMutation';+import {+ managedTierSource,+ tierMutationPayload,+ type ManagedTierSource,+ type TierMutationIntent,+} from './tierMutation';import { TIER_SUGGESTIONS } from './tierSuggestions';import { useDeadlineClock } from './useDeadlineClock';import { ACCENT_ICON, ACCENT_TILE, sourceVisual } from './vendorMeta';@@ -147,6 +153,25 @@ type SourceReconciliation =| { kind: 'source'; source: Source }| { kind: 'gone'; sources: Source[]; snapshot: number };+/** The badge that says which rung declared a locked model's tiers. */+const TIER_PROVENANCE_LABEL_KEY: Readonly<Record<ManagedTierSource, string>> = {+ upstream: 'settings.models.sourceDetail.tiers.managed.upstream',+ catalog: 'settings.models.sourceDetail.tiers.managed.catalog',+};++/**+ * A tier write that did not land, and whether anything is left to try.+ *+ * `retryable` carries the intent because "Try again" has to replay the exact+ * write the rollback undid. `managed` carries none on purpose: the server owns+ * that model's declaration, so there is no version of this write that succeeds,+ * and offering a button that re-asks a settled question would be the one wrong+ * affordance to put in front of this user.+ */+type TierFailure =+ | { kind: 'retryable'; intent: TierMutationIntent }+ | { kind: 'managed' };+const TierEditor: React.FC<{model: SuppliedModel;protocol: SourceProtocol;@@ -157,10 +182,11 @@ const TierEditor: React.FC<{trackMutation: TrackSourceMutation;}> = ({ model, protocol, editing, onEdit, onClose, onMutating, trackMutation }) => {const { t } = useTranslation();+ const managed = managedTierSource(model.reasoning_efforts_source);const [tiers, setTiers] = React.useState(model.reasoning_efforts ?? []);const [draft, setDraft] = React.useState('');const [saving, setSaving] = React.useState(false);- const [failedNext, setFailedNext] = React.useState<TierMutationIntent | null>(null);+ const [failed, setFailed] = React.useState<TierFailure | null>(null);const [returnFocus, setReturnFocus] = React.useState(false);const inputRef = React.useRef<HTMLInputElement>(null);const cellRef = React.useRef<HTMLButtonElement>(null);@@ -195,7 +221,7 @@ const TierEditor: React.FC<{}const { previous, next } = payload;onMutating();- setFailedNext(null);+ setFailed(null);setTiers(next);if (previous.length === next.length && previous.every((tier, index) => tier === next[index])) {settlement.release();@@ -207,8 +233,13 @@ const TierEditor: React.FC<{return true;} catch (error) {setTiers(previous);- setFailedNext(intent);- if (apiFailure(error)?.code === 'source_not_found') await settlement.gone(latest.id);+ const refusal = apiFailure(error);+ setFailed(tierEditRefusedAsManaged(refusal) ? { kind: 'managed' } : { kind: 'retryable', intent });+ if (refusal?.code === 'source_not_found') await settlement.gone(latest.id);+ // A managed refusal re-reads for the same reason every other failed+ // write does, and one more: this client believed the row was editable+ // and the server says otherwise, so the read is what replaces the+ // stale editor with the provenance the server actually holds.else await settlement.unread();return false;}@@ -223,19 +254,60 @@ const TierEditor: React.FC<{if (await commit({ kind: 'add', tier: value })) setDraft('');};const retry = async () => {- if (!failedNext) return;- if (await commit(failedNext) && failedNext.kind === 'add' && draft.trim() === failedNext.tier) setDraft('');+ if (failed?.kind !== 'retryable') return;+ const { intent } = failed;+ if (await commit(intent) && intent.kind === 'add' && draft.trim() === intent.tier) setDraft('');};// A rolled-back write is the row's own unfinished business: the tier list is- // already back to what the server holds, and 重试 is the only way forward from- // there. So the notice renders in whichever state the row is in and leaves only- // through a write that lands — never because the editor closed or moved on.- const failure = failedNext && (- <span className="model-hub-source-tier inline-flex items-center gap-1.5 text-destructive-ink">+ // already back to what the server holds, and "Try again" is the only way forward+ // from there. So the notice renders in whichever state the row is in and leaves+ // only through a write that lands — never because the editor closed or moved on.+ //+ // A refusal is the exception, and the one that outlives the editor: the re-read+ // it triggers turns the row into the locked one below, so its notice has to be+ // rendered by that branch too, or the only explanation the user gets would+ // disappear at the moment the row changes under them.+ //+ // Provenance can also reach that branch after an ordinary failure — the re-read+ // the rollback triggers, or a refresh from anywhere else, comes back with the+ // server owning the list — and it answers the retry the same way the refusal+ // did: `tierMutationPayload` declines a managed model, so the button would+ // replay a write that can no longer land. Which notice to show is therefore read+ // from the row's current provenance rather than frozen when the write failed;+ // that also lets the retry come back untouched if the server hands the list back.+ const failure = failed && (managed || failed.kind === 'managed' ? (+ <span data-tier-failure="managed" className="model-hub-source-tier inline-flex items-center gap-1.5 text-destructive-ink">+ {t('settings.models.sourceDetail.fail.tierManaged')}+ </span>+ ) : (+ <span data-tier-failure="retryable" className="model-hub-source-tier inline-flex items-center gap-1.5 text-destructive-ink">{t('settings.models.sourceDetail.fail.tier')}<button type="button" disabled={saving} onClick={() => void retry()} className="font-semibold underline underline-offset-2 disabled:opacity-50">{t('settings.models.sourceDetail.retry')}</button></span>- );+ ));+ // Rung 1 and 2 of the provenance ladder are the server's declaration, re-applied+ // on every refresh: there is nothing for the user to add and nothing to delete,+ // so the cell stops being a way in rather than becoming a disabled one. It says+ // which rung instead — a row that simply refused to open would leave "why" as+ // the user's problem.+ if (managed) {+ return (+ <div className="flex min-w-0 flex-col gap-1.5">+ <div data-tier-provenance={managed} className="model-hub-source-tier-cell flex min-w-0 flex-wrap items-center gap-1.5">+ {tiers.length > 0 ? tiers.map((tier) => (+ <span key={tier} className="model-hub-source-tier model-hub-source-tier-chip inline-flex rounded-full border border-border font-mono text-foreground">{tier}</span>+ )) : <span className="model-hub-source-tier-empty">{t('settings.models.sourceDetail.tiers.empty')}</span>}+ <span+ title={t('settings.models.sourceDetail.tiers.managedHint') as string}+ className="model-hub-source-pill model-hub-source-entry-pill w-fit rounded-full border font-semibold"+ >+ {t(TIER_PROVENANCE_LABEL_KEY[managed])}+ </span>+ </div>+ {failure}+ </div>+ );+ }if (!editing) {// The whole cell is the edit entry, which is what lets the add affordance be// drawn only under a pointer: 20 rows each carrying a permanent 「+ 添加档位」@@ -925,7 +997,11 @@ export const SourceDetailPanel: React.FC<{.finally(() => setBusy(false));}}} className="font-semibold underline underline-offset-2">{t('settings.models.sourceDetail.retry')}</button></span>}- {model.origin === 'manual' && <><button type="button" disabled={busy} aria-label={t('settings.models.sourceDetail.row.edit', { model: model.id }) as string} title={t('settings.models.sourceDetail.row.edit', { model: model.id }) as string} className="model-hub-source-row-action grid place-items-center text-muted hover:bg-surface-2 hover:text-foreground" onClick={() => setEditingTiers(model.id)}><Pencil className="size-3.5" /></button><ManualModelMenu model={model} busy={busy} onRemove={() => void remove(model)} /></>}+ {/* The pencil is a second door into the same tier editor, so a locked+ row has to close it too — a manual entry whose id matches a+ catalog model is locked exactly like a discovered one. Removing+ the model itself is a different question and stays offered. */}+ {model.origin === 'manual' && <>{!managedTierSource(model.reasoning_efforts_source) && <button type="button" disabled={busy} aria-label={t('settings.models.sourceDetail.row.edit', { model: model.id }) as string} title={t('settings.models.sourceDetail.row.edit', { model: model.id }) as string} className="model-hub-source-row-action grid place-items-center text-muted hover:bg-surface-2 hover:text-foreground" onClick={() => setEditingTiers(model.id)}><Pencil className="size-3.5" /></button>}<ManualModelMenu model={model} busy={busy} onRemove={() => void remove(model)} /></>}</div></div>))}diff --git a/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.ts b/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.tsnew file mode 100644index 000000000..9691a5da8--- /dev/null+++ b/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.ts@@ -0,0 +1,87 @@+import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import { REASONING_EFFORTS } from '@/lib/effortOptions';++import en from '../../../i18n/en.json';+import zh from '../../../i18n/zh.json';+import { TIER_SUGGESTIONS } from './tierSuggestions';++const HERE = dirname(fileURLToPath(import.meta.url));+const CATALOG_PY = resolve(HERE, '../../../../..', 'vibe/backend_model_catalog.py');++/**+ * Frozen spec pin (2026-09-03). The backend PR owns `REASONING_EFFORT_VOCABULARY`+ * and `PROTOCOL_REASONING_EFFORT_DEFAULTS`; this file holds the UI tables equal+ * to those exports when the names exist, and to this pin while they do not —+ * never a silent skip.+ */+const FROZEN_VOCABULARY = [+ 'minimal',+ 'low',+ 'medium',+ 'high',+ 'xhigh',+ 'max',+ 'ultra',+] as const;++const FROZEN_PROTOCOL_DEFAULTS: Readonly<Record<string, readonly string[]>> = {+ anthropic: ['low', 'medium', 'high', 'xhigh', 'max'],+ openai_responses: ['minimal', 'low', 'medium', 'high', 'xhigh'],+ openai_chat: ['minimal', 'low', 'medium', 'high', 'xhigh'],+};++const quotedStrings = (block: string): string[] =>+ [...block.matchAll(/['"]([^'"]+)['"]/g)].map((match) => match[1]);++const parseNamedTuple = (source: string, name: string): string[] | null => {+ const match = source.match(new RegExp(`${name}\\s*(?::[^=]+)?=\\s*\\(([^)]*)\\)`));+ return match ? quotedStrings(match[1]) : null;+};++const parseNamedStringTupleDict = (source: string, name: string): Record<string, string[]> | null => {+ const match = source.match(new RegExp(`${name}\\s*(?::[^=]+)?=\\s*\\{([\\s\\S]*?)\\n\\}`));+ if (!match) return null;+ const entries: Record<string, string[]> = {};+ for (const entry of match[1].matchAll(/['"]([^'"]+)['"]\s*:\s*\(([^)]*)\)/g)) {+ entries[entry[1]] = quotedStrings(entry[2]);+ }+ return Object.keys(entries).length > 0 ? entries : null;+};++const catalogSource = readFileSync(CATALOG_PY, 'utf8');+const namesVocabulary = /\bREASONING_EFFORT_VOCABULARY\b/.test(catalogSource);+const namesDefaults = /\bPROTOCOL_REASONING_EFFORT_DEFAULTS\b/.test(catalogSource);+const exportedVocabulary = parseNamedTuple(catalogSource, 'REASONING_EFFORT_VOCABULARY');+const exportedDefaults = parseNamedStringTupleDict(catalogSource, 'PROTOCOL_REASONING_EFFORT_DEFAULTS');++describe('reasoning-effort vocabulary UI ↔ backend mirror', () => {+ it('parses the backend export when the name is on the branch, rather than falling through to the frozen pin', () => {+ // A comment or a renamed binding that the regex cannot read must fail here.+ // Falling through to the frozen list would keep CI green while the tables drift.+ if (namesVocabulary) expect(exportedVocabulary).not.toBeNull();+ if (namesDefaults) expect(exportedDefaults).not.toBeNull();+ expect(namesVocabulary).toBe(namesDefaults);+ });++ it('holds REASONING_EFFORTS equal to the backend export, or the frozen 7-list while that name is absent', () => {+ expect([...REASONING_EFFORTS]).toEqual(exportedVocabulary ?? [...FROZEN_VOCABULARY]);+ });++ it('holds TIER_SUGGESTIONS equal to PROTOCOL_REASONING_EFFORT_DEFAULTS, or the frozen family lists while that name is absent', () => {+ expect(TIER_SUGGESTIONS).toEqual(exportedDefaults ?? FROZEN_PROTOCOL_DEFAULTS);+ });++ it.each(['en', 'zh'] as const)('gives %s picker copy for every vocabulary value, in vocabulary order', (lng) => {+ const options = (lng === 'en' ? en : zh).chat.picker.effortOptions;+ expect(Object.keys(options)).toEqual([...REASONING_EFFORTS]);+ for (const [key, value] of Object.entries(options)) {+ expect(value.trim().length, `${lng}.${key}`).toBeGreaterThan(0);+ expect(value, `${lng}.${key}`).not.toBe(key);+ }+ });+});diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.tsindex f5a1cf663..b0b48d544 100644--- a/ui/src/components/settings/models/serverCopy.test.ts+++ b/ui/src/components/settings/models/serverCopy.test.ts@@ -19,6 +19,8 @@ import {oauthFailureKey,oauthStartFailureKey,serverText,+ TIER_EDIT_MANAGED_FAILURE,+ tierEditRefusedAsManaged,} from './serverCopy';const t = (lng: 'en' | 'zh'): TFunction => {@@ -207,6 +209,59 @@ describe('catalogSaveFailureKey', () => {});});+describe('tierEditRefusedAsManaged', () => {+ const MANAGED_COPY = 'settings.models.sourceDetail.fail.tierManaged';++ it.each([+ ['code', { code: TIER_EDIT_MANAGED_FAILURE }],+ ['prefixed code', { code: `modelHub.errors.${TIER_EDIT_MANAGED_FAILURE}` }],+ ['detail', { code: 'bad_request', detail: TIER_EDIT_MANAGED_FAILURE }],+ ['prefixed detail', { code: 'bad_request', detail: `modelHub.errors.${TIER_EDIT_MANAGED_FAILURE}` }],+ ])('recognizes the refusal carried in the %s field', (_where, failure) => {+ // Both response shapes on this API are in play — `error` for+ // `source_not_found`, `detail` for the `modelHub.errors.*` refusals — and+ // which one the new guard picks is the backend's choice, not a fact this+ // client should encode.+ expect(tierEditRefusedAsManaged(failure)).toBe(true);+ });++ it('leaves every other failure on the retryable path', () => {+ for (const failure of [+ null,+ undefined,+ { code: 'source_not_found' },+ { code: 'engine_down', detail: 'modelHub.errors.engine_down' },+ // The neighbouring guard on `POST .../models`: a different write, refused+ // for a different reason, and one the user CAN act on by picking another+ // model id. Reading it as a locked tier list would replace that with a+ // sentence about a list they never edited.+ { code: 'source_model_managed_upstream' },+ { code: 'bad_request', detail: 'source_model_tiers_managed_by_someone_else' },+ ]) {+ expect(tierEditRefusedAsManaged(failure), JSON.stringify(failure)).toBe(false);+ }+ });++ it.each(['zh', 'en'] as const)('renders the refusal as a sentence, not a key, in %s', (lng) => {+ const text = t(lng)(MANAGED_COPY, { defaultValue: '' }) as string;+ expect(text, lng).not.toBe('');+ expect(text).not.toContain('settings.models');+ expect(text).not.toContain(TIER_EDIT_MANAGED_FAILURE);+ // Same sentence under the server-emitted key: a missing-key defect+ // (B1/D-3) would otherwise print `modelHub.errors.source_model_tiers_managed`+ // the moment a future path looks the code up instead of our fail.* alias.+ expect(t(lng)(`modelHub.errors.${TIER_EDIT_MANAGED_FAILURE}`, { defaultValue: '' })).toBe(text);+ });++ it('never invites a retry of a decision the server has already made', () => {+ // The generic tier-save line offers exactly that, which is why this refusal+ // needs copy of its own: retrying cannot succeed while the rung holds.+ expect(t('en')(MANAGED_COPY) as string).not.toMatch(/retry|try again/i);+ expect(t('zh')(MANAGED_COPY) as string).not.toContain('重试');+ expect(t('zh')(MANAGED_COPY) as string).not.toBe(t('zh')('settings.models.sourceDetail.fail.tier') as string);+ });+});+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 isdiff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.tsindex aa85fe7f9..7855e1204 100644--- a/ui/src/components/settings/models/serverCopy.ts+++ b/ui/src/components/settings/models/serverCopy.ts@@ -137,6 +137,33 @@ export const catalogSaveFailureKey = (detail: string | undefined): string =>export const catalogSaveLeftUnloaded = (code: string | undefined, detail: string | undefined): boolean =>code === 'engine_down' || detail === 'modelHub.errors.engine_down';+/**+ * The refusal a tier edit gets when the server owns that model's declaration.+ *+ * The UI does not normally offer the write — an `upstream`/`catalog` row renders+ * its provenance badge and no editor at all — so reaching this code means the+ * two disagreed: a refresh applied a rung while the editor was open, another+ * surface changed the source, or the call came from outside this page. That is+ * a state race, not a transport failure, which is why it needs copy of its own:+ * the generic "The tier was not saved" offers a retry that cannot succeed, and+ * retrying a decision the server has already made is the one thing this user+ * must not do.+ *+ * Matched on the code AND on the backend i18n key, because the two response+ * shapes in this API put the same fact in different fields (`error` for+ * `source_not_found`, `detail` for every `modelHub.errors.*` catalog refusal)+ * and this client should not depend on which one the new guard picks.+ */+export const TIER_EDIT_MANAGED_FAILURE = 'source_model_tiers_managed';++export const tierEditRefusedAsManaged = (+ failure: { code: string; detail?: string } | null | undefined,+): boolean =>+ failure?.code === TIER_EDIT_MANAGED_FAILURE+ || failure?.code === `modelHub.errors.${TIER_EDIT_MANAGED_FAILURE}`+ || failure?.detail === TIER_EDIT_MANAGED_FAILURE+ || failure?.detail === `modelHub.errors.${TIER_EDIT_MANAGED_FAILURE}`;+/*** Why a models.dev fill produced nothing.*diff --git a/ui/src/components/settings/models/sourceModelContract.test.ts b/ui/src/components/settings/models/sourceModelContract.test.tsindex fa977dc9a..b32e82b99 100644--- a/ui/src/components/settings/models/sourceModelContract.test.ts+++ b/ui/src/components/settings/models/sourceModelContract.test.ts@@ -28,9 +28,7 @@ describe('Source model wire contract', () => {for (const field of enumeratedFields) {expect(new Set(models.map((model) => model[field as keyof typeof model]))).toEqual(new Set(modelSchema.properties[field].enum));- // FIXME(#1835): Restore this assertion for reasoning_efforts_source once- // the tier editor actually reads model.reasoning_efforts_source.- if (field !== 'reasoning_efforts_source') expect(detail).toContain(`model.${field}`);+ expect(detail).toContain(`model.${field}`);}});});diff --git a/ui/src/components/settings/models/tierMutation.test.ts b/ui/src/components/settings/models/tierMutation.test.tsindex d9ff6b287..6ce14d3b9 100644--- a/ui/src/components/settings/models/tierMutation.test.ts+++ b/ui/src/components/settings/models/tierMutation.test.ts@@ -1,10 +1,10 @@import { describe, expect, it } from 'vitest';import { createPendingWrites } from './asyncLifetime';-import { tierMutationPayload, type TierMutationIntent } from './tierMutation';-import type { Source } from './types';+import { managedTierSource, MANAGED_TIER_SOURCES, tierMutationPayload, type TierMutationIntent } from './tierMutation';+import type { ReasoningEffortsSource, Source, SuppliedModel } from './types';-const source = (tiers: string[]): Source => ({+const source = (tiers: string[], provenance?: ReasoningEffortsSource | null): Source => ({id: 'source-a',last_discovered_at: null,kind: 'api_key',@@ -14,7 +14,19 @@ const source = (tiers: string[]): Source => ({supply_channel: 'hub',billing: 'metered',state: { status: 'active', retry_at: null, detail_key: null },- models: [{ id: 'model-a', display_name: null, origin: 'manual', reasoning_efforts: tiers }],+ models: [{+ id: 'model-a',+ display_name: null,+ origin: 'manual',+ reasoning_efforts: tiers,+ // `undefined` here means the key is absent, which is the payload a server+ // that predates the field sends and the parser is expected to tolerate. The+ // v7 type has no shape for that, so the omission is asserted at the one key+ // it concerns rather than by loosening the whole fixture.+ ...(provenance === undefined+ ? ({} as Pick<SuppliedModel, 'reasoning_efforts_source'>)+ : { reasoning_efforts_source: provenance }),+ }],});describe('queued tier mutation payloads', () => {@@ -39,4 +51,43 @@ describe('queued tier mutation payloads', () => {['medium'],]);});++ it.each(MANAGED_TIER_SOURCES)('builds no payload at all for a %s-declared model', (provenance) => {+ // Structural, not an affordance the editor has to remember to hide: a+ // refresh can land the rung while the editor is open, and this reads the+ // freshest Source the write is about to be sent against.+ const latest = source(['low', 'medium'], provenance);+ expect(tierMutationPayload(latest, 'model-a', { kind: 'add', tier: 'high' })).toBeNull();+ expect(tierMutationPayload(latest, 'model-a', { kind: 'remove', tier: 'low' })).toBeNull();+ });++ it.each([+ ['a user-declared list', 'user' as const],+ ['an explicitly unclaimed list', null],+ ['a server that predates the field', undefined],+ ])('still writes for %s', (_case, provenance) => {+ expect(tierMutationPayload(source(['low'], provenance), 'model-a', { kind: 'add', tier: 'high' }))+ .toEqual({ previous: ['low'], next: ['low', 'high'] });+ });+});++describe('managedTierSource', () => {+ it.each(MANAGED_TIER_SOURCES)('reports %s as the rung that locks the row', (provenance) => {+ expect(managedTierSource(provenance)).toBe(provenance);+ });++ it.each([+ ['user', 'user' as const],+ ['null', null],+ ['absent', undefined],+ ])('leaves %s editable', (_case, provenance) => {+ expect(managedTierSource(provenance)).toBeNull();+ });++ it('degrades a rung this build has never heard of to editable', () => {+ // Locking here would put the row behind a badge with no label and a rule+ // this build cannot state. Offering the edit and rendering the server's+ // refusal reaches the same outcome without the unverified claim.+ expect(managedTierSource('provider_pinned' as ReasoningEffortsSource)).toBeNull();+ });});diff --git a/ui/src/components/settings/models/tierMutation.ts b/ui/src/components/settings/models/tierMutation.tsindex b7cb28485..5cae57e9b 100644--- a/ui/src/components/settings/models/tierMutation.ts+++ b/ui/src/components/settings/models/tierMutation.ts@@ -1,4 +1,36 @@-import type { Source } from './types';+import type { ReasoningEffortsSource, Source } from './types';++/**+ * The rungs of the provenance ladder the SERVER owns: it re-applies them on+ * every refresh and refuses `PATCH .../models/{id}` tier edits against them+ * with `source_model_tiers_managed`. Everything else — `user`, an explicit+ * `null`, an absent field on an older server, or a rung a newer server names+ * that this build has never heard of — is editable.+ *+ * Unknown degrades to editable on purpose. Locking on an unrecognized value+ * would put the row behind a badge this build cannot label and a rule it cannot+ * state, for a claim it never verified; offering the edit and rendering the+ * server's refusal (`fail.tierManaged`) is the same outcome arrived at honestly.+ * The server is the authority either way — this reader only decides what the UI+ * proposes on its own initiative.+ */+export const MANAGED_TIER_SOURCES = ['upstream', 'catalog'] as const;++export type ManagedTierSource = (typeof MANAGED_TIER_SOURCES)[number];++const MANAGED = new Set<string>(MANAGED_TIER_SOURCES);++/**+ * The rung locking a model's tiers, or null when the user may edit them.+ *+ * Takes the field rather than the model so every call site spells+ * `model.reasoning_efforts_source` out loud: this is the one wire field whose+ * absence changes what the UI offers, and a rename that misses a reader would+ * otherwise unlock every row silently.+ */+export const managedTierSource = (+ source: ReasoningEffortsSource | null | undefined,+): ManagedTierSource | null => (source && MANAGED.has(source) ? (source as ManagedTierSource) : null);export type TierMutationIntent = Readonly<{kind: 'add' | 'remove';@@ -17,6 +49,11 @@ export const tierMutationPayload = (): TierMutationPayload | null => {const model = source.models.find((candidate) => candidate.id === modelId);if (!model) return null;+ // Read off the source the write is about to be sent against, which is the+ // freshest copy this client holds. That makes the lock structural rather than+ // a rule every affordance has to remember to hide, and closes the window+ // where a refresh landed the provenance after the editor was already open.+ if (managedTierSource(model.reasoning_efforts_source)) return null;const previous = [...model.reasoning_efforts];const next = intent.kind === 'add'? previous.includes(intent.tier) ? previous : [...previous, intent.tier]diff --git a/ui/src/components/settings/models/tierSuggestions.test.ts b/ui/src/components/settings/models/tierSuggestions.test.tsnew file mode 100644index 000000000..6c62992ab--- /dev/null+++ b/ui/src/components/settings/models/tierSuggestions.test.ts@@ -0,0 +1,98 @@+import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import { EFFORT_BY_BACKEND, REASONING_EFFORTS } from '@/lib/effortOptions';++import { TIER_SUGGESTIONS } from './tierSuggestions';+import { SOURCE_PROTOCOLS } from './types';++const HERE = dirname(fileURLToPath(import.meta.url));+const BACKEND_MODELS = resolve(HERE, '../../../../..', 'vibe/data/backend_models.json');+const E2E_PROTOCOL_TIERS = resolve(HERE, '../../../../e2e/support/protocol-tiers.json');++/**+ * Tiers the builtin catalog names that the unified vocabulary does not.+ *+ * Empty on purpose: the vocabulary is the ordered SUPERSET of every value a+ * catalog row legitimately declares (`ultra` included, because gpt-5.6-sol/terra+ * name it). A NEW catalog-only tier fails this equality rather than reaching+ * the UI unnamed; a future exemption is an explicit pin here, never a loosened+ * assertion.+ */+const KNOWN_CATALOG_DIVERGENCE: readonly string[] = [];++const vocabulary = REASONING_EFFORTS as readonly string[];+const rank = (effort: string) => vocabulary.indexOf(effort);++const catalogTiers = (): Map<string, string[]> => {+ const catalog = JSON.parse(readFileSync(BACKEND_MODELS, 'utf8'));+ return new Map(+ Object.entries(catalog.backends as Record<string, { models?: { reasoning_efforts?: string[] }[] }>)+ .map(([backend, entry]) => [+ backend,+ (entry.models ?? []).flatMap((model) => model.reasoning_efforts ?? []),+ ]),+ );+};++describe('unified reasoning-effort vocabulary', () => {+ it('is the spec\'s ordered superset, including catalog-only ultra', () => {+ // The UI-side pin of the frozen vocabulary. The cross-file mirror in+ // `reasoningEffortVocabulary.mirror.test.ts` holds this list equal to the+ // backend export when that name exists on the branch, and to this same+ // frozen 7-list while it does not.+ expect([...REASONING_EFFORTS]).toEqual([+ 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra',+ ]);+ });++ it('offers one suggestion list per source protocol, drawn from the vocabulary in its order', () => {+ expect(new Set(Object.keys(TIER_SUGGESTIONS))).toEqual(new Set(SOURCE_PROTOCOLS));++ for (const [protocol, tiers] of Object.entries(TIER_SUGGESTIONS)) {+ expect(tiers.length, protocol).toBeGreaterThan(0);+ expect(new Set(tiers).size, protocol).toBe(tiers.length);+ expect(tiers.filter((tier) => vocabulary.includes(tier)), protocol).toEqual([...tiers]);+ expect([...tiers].sort((a, b) => rank(a) - rank(b)), protocol).toEqual([...tiers]);+ // Family defaults are rung-1 over-claim protection, not the catalog+ // superset: an unknown relay must not be handed `ultra`.+ expect(tiers, protocol).not.toContain('ultra');+ }+ });++ it('keeps the agent-backend effort lists inside the same vocabulary and order', () => {+ for (const [backend, efforts] of Object.entries(EFFORT_BY_BACKEND)) {+ expect(efforts.filter((effort) => vocabulary.includes(effort)), backend).toEqual(efforts);+ expect([...efforts].sort((a, b) => rank(a) - rank(b)), backend).toEqual(efforts);+ }+ });++ it('says everything the builtin model catalog says, apart from the pinned divergence', () => {+ const declared = new Set([...catalogTiers().values()].flat());+ const divergent = [...declared].filter((tier) => !vocabulary.includes(tier));++ expect(new Set(divergent)).toEqual(new Set(KNOWN_CATALOG_DIVERGENCE));+ });++ it('suggests for the Anthropic protocol exactly what the claude catalog declares', () => {+ // The claim in tierSuggestions.ts is about THIS family only. The codex rows+ // answer a different question — which levels the Codex CLI accepts, not+ // which the OpenAI wire protocols name — so they are checked against the+ // vocabulary above and not against `TIER_SUGGESTIONS.openai_*`.+ const claude = catalogTiers().get('claude') ?? [];++ expect(claude.length).toBeGreaterThan(0);+ expect(new Set(claude)).toEqual(new Set(TIER_SUGGESTIONS.anthropic));+ });++ it('is the same table the Playwright suite asserts against the live editor', () => {+ // The e2e tsconfig cannot import `@/` aliases, so the suite reads this JSON+ // rather than `TIER_SUGGESTIONS` itself. Equality here is what keeps that+ // copy from silently describing a vocabulary the product no longer offers.+ const e2e = JSON.parse(readFileSync(E2E_PROTOCOL_TIERS, 'utf8')) as Record<string, string[]>;+ expect(e2e).toEqual(TIER_SUGGESTIONS);+ });+});diff --git a/ui/src/components/settings/models/tierSuggestions.ts b/ui/src/components/settings/models/tierSuggestions.tsindex cbcfc4c14..5a3c2cb72 100644--- a/ui/src/components/settings/models/tierSuggestions.ts+++ b/ui/src/components/settings/models/tierSuggestions.ts@@ -1,23 +1,34 @@+import type { ReasoningEffort } from '@/lib/effortOptions';+import type { SourceProtocol } from './types';/**- * What the tier editor offers as ghost chips, derived from the protocol this- * source was proved to speak. The OpenAI protocols name a fixed effort- * vocabulary, so those four are worth offering; the Anthropic Messages protocol- * expresses reasoning as a thinking budget rather than a named tier, so there is- * nothing protocol-derived to suggest and that source stays pure free text.+ * The effort vocabulary for a source's protocol family.+ *+ * One table, two readers. The tier editor offers these as ghost chips on a+ * model the user may still declare; the backend applies the SAME list when+ * discovery proves a model is reasoning-capable without naming levels (rung 1+ * of the provenance ladder — upstream capability signals are booleans, not+ * level enums). Suggesting one set while the ladder applies another would make+ * a user-typed list and an upstream-declared list disagree for no reason the+ * user could see.+ *+ * Members come from `REASONING_EFFORTS`, so nothing offered here is outside the+ * unified vocabulary. The lists themselves are per-family because the families+ * genuinely differ: the OpenAI protocols name a `minimal` tier and stop at+ * `xhigh`, while the Anthropic side runs `low`..`max` (matching the claude rows+ * in `vibe/data/backend_models.json` — see `tierSuggestions.test.ts`, which+ * reads that catalog rather than restating it).*- * These are suggestions, never a vocabulary: `reasoning_efforts` is an- * arbitrary-string capability declaration passed to the upstream verbatim, and a- * relay may accept tiers no protocol ever named. Nothing here is persisted,- * pre-filled at discovery, or sent to the API — a suggestion becomes data only- * when the user clicks it, through the same add path typing it would take.- * `lib/effortOptions.ts` is the sibling table for the OTHER axis — which efforts- * an agent BACKEND offers — and is deliberately not reused: it answers a- * different question and carries values (`minimal`, `max`) this one does not.+ * Suggestions are still not a vocabulary the user is held to: `reasoning_efforts`+ * is an arbitrary-string declaration passed to the upstream verbatim, the field+ * stays free text, and a relay may accept tiers no protocol ever named. Nothing+ * here is persisted, pre-filled at discovery, or sent to the API — a suggestion+ * becomes data only when the user clicks it, through the same add path typing it+ * would take.*/-export const TIER_SUGGESTIONS: Readonly<Record<SourceProtocol, readonly string[]>> = {- anthropic: [],- openai_responses: ['low', 'medium', 'high', 'xhigh'],- openai_chat: ['low', 'medium', 'high', 'xhigh'],+export const TIER_SUGGESTIONS: Readonly<Record<SourceProtocol, readonly ReasoningEffort[]>> = {+ anthropic: ['low', 'medium', 'high', 'xhigh', 'max'],+ openai_responses: ['minimal', 'low', 'medium', 'high', 'xhigh'],+ openai_chat: ['minimal', 'low', 'medium', 'high', 'xhigh'],};diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsxindex f05c428af..a02fdc6c1 100644--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx@@ -46,6 +46,7 @@ import type {} from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';import { errorMessage } from '@/lib/errorMessage';+import { EFFORT_BY_BACKEND, sortEffortsByVocabulary } from '@/lib/effortOptions';type FilterMode = 'all' | 'configured' | 'oauth' | 'local';type CustomProviderAdapter = 'openai-compatible' | 'anthropic-compatible';@@ -90,9 +91,14 @@ const SERVER_START_MAX_RETRIES = 5;const SERVER_START_RETRY_DELAY_MS = 3000;const FILTER_MODES: ReadonlyArray<FilterMode> = ['all', 'configured', 'oauth', 'local'];-const REASONING_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'];-const defaultReasoningEfforts = () => [...REASONING_EFFORTS];+// This form's save path is `_normalize_reasoning_variants` in+// `vibe/opencode_config.py`, which accepts `none` plus the OpenCode family+// fallback (`minimal`..`max`). `ultra` is in the unified vocabulary because+// catalog rows declare it, but offering it here would send a value the+// save path rejects. Checkboxes and the default-checked list are the same set.+const OPENCODE_PROVIDER_EFFORTS = EFFORT_BY_BACKEND.opencode;+const defaultReasoningEfforts = () => [...OPENCODE_PROVIDER_EFFORTS];const notifyOpenCodeModelOptionsChanged = () => {window.dispatchEvent(new CustomEvent('avibe:opencode-model-options-changed'));@@ -643,7 +649,7 @@ export const OpencodeProviderConfig: React.FC<{const next = current.reasoningEfforts.includes(effort)? current.reasoningEfforts.filter((item) => item !== effort): [...current.reasoningEfforts, effort];- updateEdit(providerId, { reasoningEfforts: next });+ updateEdit(providerId, { reasoningEfforts: sortEffortsByVocabulary(next) });};// ---- Default-provider selection ----@@ -1614,7 +1620,7 @@ export const OpencodeProviderConfig: React.FC<{<span className="text-[11px] font-medium uppercase text-muted">{t('settings.backends.opencodeProviderModelReasoning')}</span>- {REASONING_EFFORTS.map((effort) => (+ {OPENCODE_PROVIDER_EFFORTS.map((effort) => (<Buttonkey={effort}type="button"diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex f42998944..78df3f650 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -2378,7 +2378,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, on<Field label={t('agents.detail.effort')}><divclassName="grid gap-0.5 rounded-lg border border-border-strong bg-surface-2 p-0.5"- style={{ gridTemplateColumns: `repeat(${effortOptions.length}, minmax(0, 1fr))` }}+ style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(3.25rem, 1fr))' }}>{effortOptions.map((opt) => {const active = effort === opt;diff --git a/ui/src/components/workbench/NewAgentDialog.tsx b/ui/src/components/workbench/NewAgentDialog.tsxindex d9af942f5..79fa70ce2 100644--- a/ui/src/components/workbench/NewAgentDialog.tsx+++ b/ui/src/components/workbench/NewAgentDialog.tsx@@ -273,8 +273,8 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, o{t('agents.detail.effort')}</div><div- className="grid h-[38px] gap-0.5 rounded-md border border-border-strong bg-surface-2 p-0.5"- style={{ gridTemplateColumns: `repeat(${effortOptions.length}, minmax(0, 1fr))` }}+ className="grid min-h-[38px] gap-0.5 rounded-md border border-border-strong bg-surface-2 p-0.5"+ style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(3.25rem, 1fr))' }}>{effortOptions.map((opt) => (<button@@ -282,7 +282,7 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, otype="button"onClick={() => setEffort(opt)}className={clsx(- 'truncate rounded px-0.5 text-[11px] capitalize transition',+ 'truncate rounded px-0.5 py-1.5 text-[11px] capitalize transition',effort === opt ? 'bg-mint-soft font-bold text-mint-ink' : 'font-medium text-muted hover:text-foreground',)}>diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 05818a202..8caaf57b0 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1651,6 +1651,7 @@"fail": {"refetch": "The fetch did not come back. The list below is the last one this page actually read","tier": "The tier was not saved",+ "tierManaged": "This model's tiers are set automatically, so the change was not saved","addModel": "The model was not added","removeModel": "The model was not removed","deleteSource": "The source was not removed",@@ -1676,14 +1677,19 @@"inputHint": "Enter to add · any text","remove": "Remove {{tier}}","suggest": "Add {{tier}}",- "note": "Tiers are sent exactly as typed. A model with no tiers is still routable — its requests are sent without the effort parameter."+ "note": "Tiers are sent exactly as typed. A model with no tiers is still routable — its requests are sent without the effort parameter.",+ "managedHint": "Set automatically — these cannot be added or removed",+ "managed": {+ "upstream": "From provider",+ "catalog": "Built-in catalog"+ }},"addRow": {"hint": "Use this when a model is not discoverable, or when you only want one of them"},"empty": "This source returned no models. Add one by hand, or refetch.","emptyNeverFetched": "This source's model list has never come back. Deal with the status above, fetch again, or add a model by hand.",- "footnote": "This page answers only \"which models does this source have\". Which routing chain a model takes is set in the gateway module. Tiers are yours to type, the same for both entry kinds. The interface type is confirmed when the source is added, shown here, and not editable."+ "footnote": "This page answers only \"which models does this source have\". Which routing chain a model takes is set in the gateway module. Tiers the provider or the catalog declared cannot be edited; the rest are yours to type. The interface type is confirmed when the source is added, shown here, and not editable."},"guard": {"label": "Hops that will be removed",@@ -2044,6 +2050,11 @@"provider_error": "The provider rejected the request.","endpoint_not_configured": "The provider endpoint is not configured."},+ "modelHub": {+ "errors": {+ "source_model_tiers_managed": "This model's tiers are set automatically, so the change was not saved"+ }+ },"apps": {"title": "Apps","soon": "Soon",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 9e4be8052..a2af38380 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1651,6 +1651,7 @@"fail": {"refetch": "拉取没有回来,下面是这一页最后一次真的读到的列表","tier": "档位没保存上",+ "tierManaged": "这个模型的档位是自动确定的,这次改动没有保存","addModel": "这个模型没有添加","removeModel": "这个模型没有移除","deleteSource": "这个供应商没有移除",@@ -1676,14 +1677,19 @@"inputHint": "回车添加 · 任意文本","remove": "移除 {{tier}}","suggest": "添加 {{tier}}",- "note": "档位按你输入的原样发送。没有档位的模型照样可以路由,只是请求不带 effort 参数。"+ "note": "档位按你输入的原样发送。没有档位的模型照样可以路由,只是请求不带 effort 参数。",+ "managedHint": "自动确定,不能添加或移除",+ "managed": {+ "upstream": "供应商声明",+ "catalog": "内置目录"+ }},"addRow": {"hint": "拉取不到、或只想接入其中一个时用"},"empty": "这个供应商没有返回模型。可以手动添加,或重新拉取。","emptyNeverFetched": "还没有成功拉取过这个供应商的模型列表。先处理上面的状态,再拉一次,或者手动添加一个模型。",- "footnote": "这里只管理这个供应商提供哪些模型。模型使用哪条路由,在路由模块中调整。档位由你填写,两种录入方式都一样。接口类型在添加时确认并固定,页面会显示但不能修改。"+ "footnote": "这里只管理这个供应商提供哪些模型。模型使用哪条路由,在路由模块中调整。供应商或内置目录声明的档位不能改;其余由你填写。接口类型在添加时确认并固定,页面会显示但不能修改。"},"guard": {"label": "会被移除的路由项",@@ -2044,6 +2050,11 @@"provider_error": "提供商拒绝了请求。","endpoint_not_configured": "尚未配置提供商端点。"},+ "modelHub": {+ "errors": {+ "source_model_tiers_managed": "这个模型的档位是自动确定的,这次改动没有保存"+ }+ },"apps": {"title": "应用","soon": "即将上线",diff --git a/ui/src/lib/effortOptions.test.ts b/ui/src/lib/effortOptions.test.tsindex 2be7b7d17..2bb7ed518 100644--- a/ui/src/lib/effortOptions.test.ts+++ b/ui/src/lib/effortOptions.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from 'vitest';-import { isEffortSupported, resolveEffortOptions } from './effortOptions';+import {+ EFFORT_BY_BACKEND,+ isEffortSupported,+ REASONING_EFFORTS,+ resolveEffortOptions,+ sortEffortsByVocabulary,+} from './effortOptions';describe('effort options', () => {it('uses the backend fallback for an unknown model', () => {@@ -93,4 +99,20 @@ describe('effort options', () => {'xhigh',]);});++ it('orders selected efforts by the unified vocabulary, unknowns last', () => {+ expect(sortEffortsByVocabulary(['ultra', 'low', 'custom-b', 'max', 'custom-a'])).toEqual([+ 'low',+ 'max',+ 'ultra',+ 'custom-a',+ 'custom-b',+ ]);+ });++ it('keeps the OpenCode family fallback inside the vocabulary without ultra', () => {+ // Same set the OpenCode provider form offers and the save path accepts+ // (`vibe/opencode_config.py:_VALID_REASONING_VARIANTS` minus `none`).+ expect(EFFORT_BY_BACKEND.opencode).toEqual([...REASONING_EFFORTS].filter((effort) => effort !== 'ultra'));+ });});diff --git a/ui/src/lib/effortOptions.ts b/ui/src/lib/effortOptions.tsindex d2718d131..ff68e1ab0 100644--- a/ui/src/lib/effortOptions.ts+++ b/ui/src/lib/effortOptions.ts@@ -3,16 +3,59 @@// modules/agents/opencode/utils.py: Codex falls back to minimal..xhigh, Claude is// low/medium/high (+ xhigh/max on models that support it), OpenCode uses the// broad superset. Codex/Claude model catalogs override these fallbacks.-export const EFFORT_BY_BACKEND: Record<string, string[]> = {++/**+ * The unified reasoning-effort vocabulary, weakest to strongest.+ *+ * ONE ordered list for the whole UI, per the tier-provenance spec's "unified+ * vocabulary" section. Two tables used to answer overlapping questions with+ * different words — which efforts an agent BACKEND offers (below) and which+ * tiers the Model Hub editor SUGGESTS (`settings/models/tierSuggestions.ts`) —+ * and disagreed about `minimal` and `max`. Both now draw their members from+ * here, so a value can only be offered on one surface if it is sayable on the+ * other.+ *+ * It is a vocabulary, not a filter. A `reasoning_efforts` list that arrives+ * from a source is an arbitrary-string capability declaration forwarded to the+ * upstream verbatim, so a relay may legitimately declare a tier no protocol+ * ever named; those render and route unchanged. What this list bounds is+ * ordering, display, and what THIS UI proposes on its own initiative.+ *+ * `ultra` is in the ordered superset because catalog rows for gpt-5.6-sol/terra+ * declare it. Protocol-family defaults and backend fallbacks still omit it: an+ * unknown relay model must not be over-claimed.+ */+export const REASONING_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const;++export type ReasoningEffort = (typeof REASONING_EFFORTS)[number];++// Typed against the vocabulary rather than `string[]`: a backend list that+// drifts away from it then fails to compile, which is the check the spec asks+// for stated where it cannot be forgotten.+export const EFFORT_BY_BACKEND: Record<string, ReasoningEffort[]> = {claude: ['low', 'medium', 'high'],codex: ['minimal', 'low', 'medium', 'high', 'xhigh'],opencode: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'],};-const DEFAULT_EFFORTS = ['low', 'medium', 'high'];+const DEFAULT_EFFORTS: ReasoningEffort[] = ['low', 'medium', 'high'];export const effortOptionsFor = (backend: string): string[] => EFFORT_BY_BACKEND[backend] ?? DEFAULT_EFFORTS;+/** Rank in the unified vocabulary; unknown tokens sort after every named rung. */+const effortRank = (effort: string): number => {+ const index = (REASONING_EFFORTS as readonly string[]).indexOf(effort);+ // A finite sentinel — not Infinity — so two unknowns subtract to 0 instead of NaN.+ return index < 0 ? REASONING_EFFORTS.length : index;+};++/** Order a selected-effort list weakest → strongest, then alphabetically for unknowns. */+export const sortEffortsByVocabulary = (efforts: readonly string[]): string[] =>+ [...efforts].sort((left, right) => {+ const delta = effortRank(left) - effortRank(right);+ return delta !== 0 ? delta : left.localeCompare(right);+ });+/** Backends whose catalog carries a "" entry: the set an inherited or custom* model inherits when the catalog does not name it. */const SHARED_DEFAULT_EFFORT_BACKENDS = new Set(['claude', 'codex']);