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): Model Hub v2 — rebuild the Models page around per-Agent source order (V6) (#1096)
Call White20b4dfbb5103
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsxindex 7ff903bcd..23926dcec 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx@@ -19,8 +19,10 @@ import { Input } from '@/components/ui/input';import { Select } from '@/components/ui/select';import { cn } from '@/lib/utils';import { modelsApi } from './modelsApi';+import { AdoptionNote } from './AdoptionNote';+import { adoptionVerdict } from './sufficiency';import { DEFAULT_VENDOR, VENDOR_OPTIONS } from './vendorMeta';-import type { Source } from './types';+import type { AdoptedBy, Source } from './types';type Phase = 'edit' | 'submitting' | 'done' | 'error';@@ -58,6 +60,7 @@ export const AddApiKeyDialog: React.FC<{const [baseUrl, setBaseUrl] = React.useState('');const [phase, setPhase] = React.useState<Phase>('edit');const [discovered, setDiscovered] = React.useState(0);+ const [adoptedBy, setAdoptedBy] = React.useState<AdoptedBy[]>([]);const [error, setError] = React.useState<string | null>(null);const closeTimer = React.useRef<number | null>(null);// Bumped on every open/close so a test-and-add resolving after the dialog was@@ -73,6 +76,7 @@ export const AddApiKeyDialog: React.FC<{setBaseUrl(DEFAULT_VENDOR.base_url ?? '');setPhase('edit');setDiscovered(0);+ setAdoptedBy([]);setError(null);}return () => {@@ -93,7 +97,7 @@ export const AddApiKeyDialog: React.FC<{setPhase('submitting');setError(null);try {- const source = await modelsApi.createApiKeySource({+ const { source, adopted_by } = await modelsApi.createApiKeySource({kind: 'api_key',vendor,base_url: baseUrl.trim() || null,@@ -101,9 +105,20 @@ export const AddApiKeyDialog: React.FC<{});if (submitSeq.current !== seq) return; // dialog closed/reopened mid-requestsetDiscovered(source.models.length);+ setAdoptedBy(adopted_by);setPhase('done');onAdded(source);- closeTimer.current = window.setTimeout(onClose, 1500);+ // Auto-dismiss only when the note is pure confirmation. 「还没有 Agent+ // 启用它」 is an instruction, and 1.5s is not long enough to read one — a+ // dialog that closes itself over that sentence is how the user ends up+ // believing a working key is in service.+ //+ // `covered` and nothing weaker: a non-empty adopter list does not rule out a+ // `custom` backend that skipped the key, and that sentence is an instruction+ // too. Today's payload cannot prove `covered`, so this nicety is dormant until+ // the server sends `skipped_by` — a confirmation that can lie under a mixed+ // outcome is worth less than the second the user spends closing the dialog.+ if (adoptionVerdict(adopted_by).kind === 'covered') closeTimer.current = window.setTimeout(onClose, 1500);} catch (e: any) {if (submitSeq.current !== seq) return;const code = e?.code || e?.message || 'discovery_failed';@@ -169,9 +184,12 @@ export const AddApiKeyDialog: React.FC<{</div>{phase === 'done' && (- <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">- <CheckCircle2 className="size-4 shrink-0" />- <span>{t('settings.models.addKey.discovered', { count: discovered })}</span>+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">+ <CheckCircle2 className="size-4 shrink-0" />+ <span>{t('settings.models.addKey.discovered', { count: discovered })}</span>+ </div>+ <AdoptionNote adoptedBy={adoptedBy} /></div>)}{phase === 'error' && (@@ -183,8 +201,11 @@ export const AddApiKeyDialog: React.FC<{<DialogFooter><div className="flex items-center gap-2">+ {/* 关闭, not 取消, once the source exists: after a successful add this+ is the way out of a dialog that no longer auto-dismisses, and+ 「取消」 on a committed credential reads as an undo. */}<Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={phase === 'submitting'}>- {t('common.cancel')}+ {t(phase === 'done' ? 'common.close' : 'common.cancel')}</Button><Buttonvariant="brand"diff --git a/ui/src/components/settings/models/AdoptionNote.test.tsx b/ui/src/components/settings/models/AdoptionNote.test.tsxnew file mode 100644index 000000000..4c51d6c67--- /dev/null+++ b/ui/src/components/settings/models/AdoptionNote.test.tsx@@ -0,0 +1,93 @@+// The empty array is the case worth a test: `adopted_by: []` means the source is+// live and serving nothing, and a note that renders blank there is the same defect+// the note was added to fix. It cannot be reached from the mock store (every+// `follow` backend adopts an eligible source), so it is pinned here instead.+import { createInstance } from 'i18next';+import { renderToStaticMarkup } from 'react-dom/server';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { describe, expect, it } from 'vitest';++import en from '../../../i18n/en.json';+import zh from '../../../i18n/zh.json';+import { AdoptionNote } from './AdoptionNote';+import type { SkippedBy } from './sufficiency';+import type { AdoptedBy } from './types';++const instance = (lng: 'en' | 'zh') => {+ const i18n = createInstance();+ void i18n.use(initReactI18next).init({+ lng,+ fallbackLng: 'en',+ resources: { en: { translation: en }, zh: { translation: zh } },+ interpolation: { escapeValue: false },+ });+ return i18n;+};++const render = (adoptedBy: AdoptedBy[] | null, skippedBy?: SkippedBy[], lng: 'en' | 'zh' = 'zh') =>+ renderToStaticMarkup(+ <I18nextProvider i18n={instance(lng)}>+ <AdoptionNote adoptedBy={adoptedBy} skippedBy={skippedBy} />+ </I18nextProvider>,+ );++const text = (html: string) => html.replace(/<[^>]+>/g, '');++const entry = (backend: string, position: number): AdoptedBy => ({+ backend,+ policy: 'follow',+ position,+});++describe('AdoptionNote', () => {+ it.each(['zh', 'en'] as const)('says nobody enabled it yet in %s', (lng) => {+ const html = render([], undefined, lng);+ // Not blank, and not a raw key — an unresolved i18n key would still render+ // non-empty text, so assert the sentence is real.+ expect(html).not.toContain('adoption.none');+ expect(html.replace(/<[^>]+>/g, '').trim().length).toBeGreaterThan(8);+ });++ it('lists adopters by position, not by response order', () => {+ const html = render([entry('codex', 3), entry('claude', 1)]);+ const text = html.replace(/<[^>]+>/g, '');+ expect(text.indexOf('Claude Code')).toBeLessThan(text.indexOf('Codex'));+ expect(text).toContain('第 1 位');+ expect(text).toContain('第 3 位');+ // The page separator, so a joined list reads like the rest of the page.+ expect(text).toContain(' · ');+ });++ it('falls back to the raw backend id for an unknown backend', () => {+ // A backend shipped by the server before the UI has a label for it must still+ // be nameable — dropping it would understate who took the source.+ expect(render([entry('futurecli', 2)])).toContain('futurecli');+ });++ // 「谁没有」 is the answer this note exists for, and it is the one today's payload+ // cannot give: `_adopted_by` filters `policy == "follow"`, so a `custom` backend+ // that skipped the source is absent for the same reason an ineligible one is. The+ // note therefore says only what it can prove — and names the omission the moment+ // the server sends it.+ it('claims nothing about who skipped it while the server does not say', () => {+ const html = render([entry('claude', 1)]);+ expect(text(html)).toContain('Claude Code');+ expect(html).not.toContain('adoption.');+ expect(text(html)).not.toContain('自定义顺序');+ });++ it('names the skipped backends once the server sends them', () => {+ const html = render([entry('claude', 1)], [{ backend: 'codex', reason: 'custom-order-omission' }]);+ const body = text(html);+ expect(body).toContain('Claude Code');+ expect(body).toContain('Codex');+ expect(body).toContain('自定义顺序');+ });++ it('says nothing at all when the creation reported no adoption result', () => {+ // OAuthConnectDialog's unreported-creation path. An absent result is not an empty+ // one: 「没有 Agent 启用它」 would be a claim, and this is ignorance. The component+ // owns that distinction so its callers stop guarding it on the way in.+ expect(render(null)).toBe('');+ });+});diff --git a/ui/src/components/settings/models/AdoptionNote.tsx b/ui/src/components/settings/models/AdoptionNote.tsxnew file mode 100644index 000000000..e454cf2e2--- /dev/null+++ b/ui/src/components/settings/models/AdoptionNote.tsx@@ -0,0 +1,70 @@+// The 「so what now?」 line of both creation dialogs (api.md → `adopted_by`).+//+// A new credential is not automatically usable: only `follow` backends take it in,+// and only where their eligibility admits it. So the two answers a user needs+// before the dialog closes are 「哪些 Agent 已经用上了,排第几」 and 「谁没有」 —+// and the second one is the whole reason this exists, because a `custom` backend is+// simply ABSENT from the array. Reading nothing there as 「fine, nothing to say」 is+// how a connected key silently never serves a turn.+//+// Shared rather than written twice: an API key and a subscription differ in how they+// are added and in nothing at all afterwards, and the previous per-dialog success+// copy is exactly where the two drifted into saying different things.+//+// Which of those two answers can be given is `adoptionVerdict`'s call, not this+// component's: 「who did not」 is only answerable once the server sends the+// eligible-but-skipped complement, and until then the note says what it can prove.+import * as React from 'react';+import { useTranslation } from 'react-i18next';++import { adoptionVerdict, type SkippedBy } from './sufficiency';+import type { AdoptedBy } from './types';++export const AdoptionNote: React.FC<{ adoptedBy: AdoptedBy[] | null; skippedBy?: SkippedBy[] | null }> = ({+ adoptedBy,+ skippedBy,+}) => {+ const { t } = useTranslation();+ // No result at all — a creation that reported nothing about adoption. Not the same+ // as an empty result, and the only case with nothing true to say.+ if (!adoptedBy) return null;+ const verdict = adoptionVerdict(adoptedBy, skippedBy);+ const backendName = (backend: string) =>+ t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;++ if (verdict.kind === 'adopted_none') {+ // Not an error — the source exists and is healthy. It is a pointer to the one+ // action that makes it serve traffic, on the page the user is already on.+ return <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.adoption.none')}</p>;+ }++ // Position order, not response order: 「第 1 位」 before 「第 3 位」 reads as a+ // ranking, which is what it is.+ const list = [...adoptedBy]+ .sort((a, b) => a.position - b.position)+ .map((a) =>+ t('settings.models.adoption.entry', {+ name: backendName(a.backend),+ position: a.position,+ }),+ )+ // ' · ' is this page's separator everywhere else (source sub-lines, the+ // supply tooltip, the agent card's amber line) — locale-neutral on purpose.+ .join(' · ');++ return (+ <p className="text-[12px] leading-relaxed text-muted">+ {verdict.kind === 'partly_skipped'+ ? t('settings.models.adoption.partlySkipped', {+ list,+ skipped: verdict.backends.map(backendName).join(' · '),+ })+ : // `covered` and `indeterminate` render the same sentence, and it is the+ // sentence that is TRUE of both: these backends took it. Only the omission+ // needs the server half, so only the omission waits for it.+ t('settings.models.adoption.enabled', { list })}+ </p>+ );+};++export default AdoptionNote;diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxnew file mode 100644index 000000000..985ac2a0e--- /dev/null+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -0,0 +1,188 @@+// The Agent band's two contested behaviours: AC-7 (a Direct backend gets no Hub+// chain and no order editor, rather than an empty one) and AC-9 (a supply problem+// is named at the grain the server resolved it to — an Agent, or a model with no+// Agent, never a whole backend).+import { createInstance } from 'i18next';+import { renderToStaticMarkup } from 'react-dom/server';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { MemoryRouter } from 'react-router-dom';+import { describe, expect, it, vi } from 'vitest';++import en from '../../../i18n/en.json';+import zh from '../../../i18n/zh.json';+import { AgentCard } from './AgentCard';+import type { AgentSupply, Source, SourceState } from './types';++const COPY = zh.settings.models.agents;++const instance = (lng: 'en' | 'zh' = 'zh') => {+ const i18n = createInstance();+ void i18n.use(initReactI18next).init({+ lng,+ fallbackLng: 'en',+ resources: { en: { translation: en }, zh: { translation: zh } },+ interpolation: { escapeValue: false },+ });+ return i18n;+};++const ACTIVE: SourceState = { status: 'active', retry_at: null, detail_key: null };++const source = (id: string, name: string, state: SourceState = ACTIVE): Source => ({+ id,+ kind: 'api_key',+ vendor: 'anthropic',+ display_name: name,+ protocol: 'anthropic',+ supply_channel: 'hub',+ billing: 'metered',+ state,+ models: [],+});++const hubAgent = (over: Partial<AgentSupply> = {}): AgentSupply => ({+ backend: 'claude',+ mode: 'hub',+ menu_kind: 'fixed',+ selected_by_agent: null,+ selected_model_id: 'claude-opus-4-6',+ current: { model_id: 'claude-opus-4-6', source_id: 'src_a', channel: 'hub' },+ sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility: [] },+ supply_status: 'ok',+ model_supply: [],+ named_agents: [],+ mappings: [],+ menu: null,+ builtin_models: ['claude-opus-4-6'],+ standard_vendors: null,+ ...over,+});++const SOURCES = [source('src_a', 'Claude Pro 订阅'), source('src_b', 'Anthropic API Key')];++const render = (agents: AgentSupply[], sources: Source[] = SOURCES, lng: 'en' | 'zh' = 'zh') =>+ renderToStaticMarkup(+ <MemoryRouter>+ <I18nextProvider i18n={instance(lng)}>+ <AgentCard+ agents={agents}+ sources={sources}+ onConnectHub={vi.fn()}+ onOpenOrder={vi.fn()}+ connectingBackend={null}+ />+ </I18nextProvider>+ </MemoryRouter>,+ );++describe('AgentCard — Hub row', () => {+ it('draws the numbered chain in this backend’s order', () => {+ const html = render([hubAgent()]);+ expect(html).toContain('Claude Pro 订阅');+ expect(html).toContain('Anthropic API Key');+ expect(html.indexOf('Claude Pro 订阅')).toBeLessThan(html.indexOf('Anthropic API Key'));+ expect(html).toContain(COPY.sourceOrder);+ });++ it('says whether the chain is recommended or hand-picked', () => {+ expect(render([hubAgent()])).toContain(COPY.policy.follow);+ expect(render([hubAgent({ sources: { policy: 'custom', order: ['src_a'], eligibility: [] } })])).toContain(+ COPY.policy.custom,+ );+ });++ it('admits it when Hub is on but nothing can supply the backend', () => {+ const html = render([hubAgent({ sources: { policy: 'custom', order: [], eligibility: [] } })]);+ expect(html).toContain(COPY.hubNoSupply);+ });++ // The row used to reassure the reader that the turn 「会继续走直连」. It will not:+ // `model_hub.resolve()` returns a Direct launch only when the backend's own mode+ // is direct, so an empty Hub order reaches `source is None` and raises+ // `mapping_target_unavailable`. Promising a fallback that does not exist is worse+ // than saying nothing, because the user then has no reason to go fix it.+ it('promises no Direct fallback it cannot deliver, in either locale', () => {+ expect(COPY.hubNoSupply).not.toContain('直连');+ expect(en.settings.models.agents.hubNoSupply).not.toMatch(/\bDirect\b/);+ expect(zh.settings.models.order.enabledEmpty).toContain('失败');+ expect(en.settings.models.order.enabledEmpty).toMatch(/\bfail/);+ });+});++describe('AgentCard — Direct row (AC-7)', () => {+ const direct = hubAgent({+ backend: 'opencode',+ mode: 'direct',+ current: null,+ sources: null,+ supply_status: null,+ model_supply: null,+ named_agents: [{ name: 'opencode', effective_model_id: null, supply_status: null }],+ });++ it('offers 接入中枢 instead of the order editor', () => {+ const html = render([direct]);+ expect(html).toContain(COPY.connectHub);+ expect(html).not.toContain(COPY.sourceOrder);+ });++ it('draws no chain and no policy badge, and says why', () => {+ const html = render([direct]);+ expect(html).toContain(COPY.directNote);+ expect(html).not.toContain('Claude Pro 订阅');+ expect(html).not.toContain(COPY.policy.follow);+ expect(html).not.toContain(COPY.policy.custom);+ });+});++describe('AgentCard — attribution line (AC-9)', () => {+ it('names the interrupted and waiting Agents from the server’s projection', () => {+ const html = render([+ hubAgent({+ named_agents: [+ { name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'interrupted' },+ { name: 'pm', effective_model_id: 'claude-sonnet-4-6', supply_status: 'waiting' },+ { name: 'reviewer', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' },+ ],+ }),+ ]);+ expect(html).toContain('claude 供给中断');+ expect(html).toContain('pm 正在等待来源恢复');+ expect(html).not.toContain('reviewer');+ });++ it('names a ticked-but-unassigned model WITHOUT naming an Agent', () => {+ const html = render([+ hubAgent({+ named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' }],+ model_supply: [+ { model_id: 'claude-opus-4-6', chain_length: 2 },+ { model_id: 'claude-haiku-4-5', chain_length: 0 },+ ],+ }),+ ]);+ expect(html).toContain('claude-haiku-4-5 暂无来源可供给');+ expect(html).not.toContain('供给中断');+ });++ // Two names need a separator, and a literal 、 in the component shipped Chinese+ // punctuation into the English UI ("No supply for agent-a、agent-b").+ it('separates several names in the reader’s own punctuation', () => {+ const agent = hubAgent({+ named_agents: [+ { name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'interrupted' },+ { name: 'pm', effective_model_id: 'claude-opus-4-6', supply_status: 'interrupted' },+ ],+ });+ expect(render([agent], SOURCES, 'zh')).toContain('claude、pm');+ expect(render([agent], SOURCES, 'en')).toContain('claude, pm');+ });++ it('stays silent when every named Agent is fine', () => {+ const html = render([+ hubAgent({ named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' }] }),+ ]);+ expect(html).not.toContain('供给中断');+ expect(html).not.toContain('暂无来源可供给');+ });+});diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsxindex 9ed1b8fa3..f36744c22 100644--- a/ui/src/components/settings/models/AgentCard.tsx+++ b/ui/src/components/settings/models/AgentCard.tsx@@ -1,147 +1,288 @@-// The Agent band (frame 01r): one row per backend — icon + name + menu-kind-// badge, the current supply as a composite pill (hub only), the supply-mode-// chip, and the row action (模型菜单 for hub / 接入中枢 for direct). 模型菜单-// links into L5's drawers; until L5 lands (MODEL_MENUS_ENABLED) it explains-// itself rather than opening a missing surface.+// The Agent band (design.pen 「产品改造 V6 01」 / 「V6 04」, mobile 「V6 M01」): one+// row per backend — identity + menu-kind badge, then the whole of this backend's+// supply on one line (the model it runs · the numbered source chain it walks ·+// whether that chain is recommended or hand-picked), the supply-mode pill, and+// 来源顺序 / 接入中枢.+//+// V6 replaced the old `model | ● source` composite pill with the chain, because+// the pill could only ever say what is serving RIGHT NOW — the question the page+// actually has to answer is what happens when that stops working. The chain shows+// the fallback path, marks the position the resolver is on, and dims what it has+// already walked past, so the V6 04 failover moment reads off the row directly.+//+// Ordering itself is not editable here: it belongs to the 来源顺序 drawer, which+// only exists for Hub-mode backends (AC-7 — a Direct backend gets no chain and no+// drawer, since the Hub supplies nothing for it).import * as React from 'react';import { Link } from 'react-router-dom';-import { ArrowDownToLine, ArrowRight, ChevronRight, TriangleAlert } from 'lucide-react';+import { ArrowDownUp, ArrowRight, ChevronRight, Download, TriangleAlert, Zap } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { cn } from '@/lib/utils';-import { useToast } from '@/context/ToastContext';-import { CompositePill, ModeChip } from './chips';-import { ACCENT_ICON, ACCENT_TILE, backendVisual, sourceAccent } from './vendorMeta';-import { friendlyModelName } from './format';-import { MODEL_MENUS_ENABLED } from './featureFlags';+import { ModeChip } from './chips';+import { ACCENT_ICON, ACCENT_TILE, backendVisual } from './vendorMeta';+import { formatNameList, friendlyModelName } from './format';+import { attribution, chainChips, hasAttribution, type ChainChip } from './supply';import type { AgentSupply, Source } from './types';+/** 菜单固定 / 菜单开放 — desktop only (M01 drops it: at 360px the badge and the+ * mode pill fought over the name line, and menu shape is a detail you go looking+ * for, not something you scan a phone list for). */+const MenuKindBadge: React.FC<{ agent: AgentSupply }> = ({ agent }) => {+ const { t } = useTranslation();+ return (+ <Badge+ variant="secondary"+ className="hidden shrink-0 rounded-md bg-foreground/[0.02] px-[7px] py-0.5 text-[10.5px] font-medium sm:inline-flex"+ >+ {t(`settings.models.agents.menuKind.${agent.menu_kind === 'open' ? 'open' : 'fixed'}`)}+ </Badge>+ );+};++/**+ * The model the next turn asks for. Border + inner tint are one element here: the+ * frame's inner fill spans the box exactly, so a second node would only add a+ * rounding seam.+ *+ * An open-menu backend has no single model — its named Agents each pick their own+ * — so the box counts the ticked menu instead of inventing a headline model.+ */+const ModelBox: React.FC<{ agent: AgentSupply; sources: Source[] }> = ({ agent, sources }) => {+ const { t } = useTranslation();+ const label =+ agent.menu_kind === 'open' && agent.menu+ ? (t('settings.models.agents.modelCount', { count: agent.menu.checked.length }) as string)+ : friendlyModelName(agent, sources);+ if (!label) return null;+ return (+ <span className="inline-flex min-w-0 shrink-0 rounded-lg border border-border bg-foreground/[0.03] px-[9px] py-1">+ <span className="truncate font-mono text-[11.5px] font-semibold text-foreground">{label}</span>+ </span>+ );+};++const CHIP_TONE: Record<ChainChip['tone'], string> = {+ // 当前 — the position the resolver is on.+ current: 'border-mint/40 bg-mint-soft',+ // Already walked past, and unhealthy: the reason the resolver moved on.+ skipped: 'border-border bg-foreground/[0.02] opacity-75',+ neutral: 'border-border bg-foreground/[0.02]',+};++const Chip: React.FC<{ chip: ChainChip }> = ({ chip }) => (+ <span+ className={cn(+ 'inline-flex min-w-0 items-center gap-[3px] rounded-md border px-1.5 py-0.5 sm:gap-[5px] sm:px-2 sm:py-[3px]',+ CHIP_TONE[chip.tone],+ )}+ >+ <span+ className={cn(+ 'font-mono text-[10px] font-bold sm:text-[10.5px]',+ chip.tone === 'current' ? 'text-mint' : 'text-muted',+ )}+ >+ {chip.position}+ </span>+ <span+ className={cn(+ 'truncate text-[10px] font-semibold sm:text-[11px]',+ chip.tone === 'current' ? 'text-mint' : chip.tone === 'skipped' ? 'text-muted' : 'text-foreground',+ )}+ >+ {chip.label}+ </span>+ {/* Gold dot = this source cannot serve right now. It rides the chip even when+ the resolver has not reached it yet, which is the row's early warning: the+ next failover will skip this position too. */}+ {chip.unhealthy && <span className="size-1 shrink-0 rounded-full bg-gold sm:size-[5px]" aria-hidden />}+ </span>+);++/** The numbered fallback path: 1 → 2 → 3, in this backend's own order. Wraps on a+ * phone (M01 gives it its own full-width line); one line on desktop, where the+ * frame reads left-to-right as a single path and a mid-chain break would suggest+ * two of them — long names truncate inside their chip instead. */+const SupplyChain: React.FC<{ chips: ChainChip[] }> = ({ chips }) => (+ <span className="flex min-w-0 flex-wrap items-center gap-[3px] sm:flex-nowrap sm:gap-2">+ {chips.map((chip, i) => (+ <React.Fragment key={chip.sourceId}>+ {i > 0 && <ChevronRight className="size-[9px] shrink-0 text-muted opacity-50 sm:size-[11px]" aria-hidden />}+ <Chip chip={chip} />+ </React.Fragment>+ ))}+ </span>+);++/** 跟随推荐 (cyan) / 自定义 (neutral) — whether the chain above is the server's+ * recommendation, which absorbs newly added sources, or a frozen hand-picked+ * subset the server will never touch. */+const PolicyBadge: React.FC<{ agent: AgentSupply; className?: string }> = ({ agent, className }) => {+ const { t } = useTranslation();+ const follow = agent.sources?.policy === 'follow';+ return (+ <Badge+ variant={follow ? 'info' : 'secondary'}+ className={cn(+ 'shrink-0 px-2 py-[3px] text-[10px] font-semibold sm:px-[9px] sm:text-[10.5px]',+ !follow && 'bg-foreground/[0.02]',+ className,+ )}+ >+ {t(`settings.models.agents.policy.${follow ? 'follow' : 'custom'}`)}+ </Badge>+ );+};++/**+ * AC-9: name WHO a supply problem is about, from the server's per-Agent+ * projection.+ *+ * Deliberately one line under the chain rather than a badge on it: a failure can+ * hit a named Agent, or only a ticked-but-unassigned menu model, and those two+ * cannot share a slot. A ticked model nobody runs is named WITHOUT an Agent —+ * saying 「Agent X 受影响」 there would be false, which is exactly the half of+ * AC-9 that a per-backend rollup gets wrong.+ */+const AttributionLine: React.FC<{ agent: AgentSupply }> = ({ agent }) => {+ const { t, i18n } = useTranslation();+ const a = attribution(agent);+ if (!hasAttribution(a)) return null;+ // Names come from the payload, so the punctuation between them has to come from+ // the reader's locale rather than from this file — see `formatNameList`.+ const list = (names: string[]) => formatNameList(names, i18n.language);+ const parts: string[] = [];+ if (a.interrupted.length > 0) {+ parts.push(t('settings.models.agents.attribution.interrupted', { names: list(a.interrupted) }) as string);+ }+ if (a.waiting.length > 0) {+ parts.push(t('settings.models.agents.attribution.waiting', { names: list(a.waiting) }) as string);+ }+ if (a.unassignedModels.length > 0) {+ parts.push(t('settings.models.agents.attribution.unassigned', { models: list(a.unassignedModels) }) as string);+ }+ return <span className="text-[11px] leading-relaxed text-gold sm:text-[11.5px]">{parts.join(' · ')}</span>;+};+const AgentRow: React.FC<{agent: AgentSupply;sources: Source[];onConnectHub: (agent: AgentSupply) => void;- onOpenMenu?: (agent: AgentSupply) => void;+ onOpenOrder: (agent: AgentSupply) => void;connecting: boolean;-}> = ({ agent, sources, onConnectHub, onOpenMenu, connecting }) => {+}> = ({ agent, sources, onConnectHub, onOpenOrder, connecting }) => {const { t } = useTranslation();- const { showToast } = useToast();const { Icon, accent } = backendVisual(agent.backend);+ const hub = agent.mode === 'hub';+ const chips = chainChips(agent, sources);- const openMenu = () => {- // L5's mapping / menu drawers are gated by MODEL_MENUS_ENABLED; until it- // flips, keep the buttons visible (pixel fidelity) but explain themselves.- if (!MODEL_MENUS_ENABLED || !onOpenMenu) {- showToast(t('settings.models.agents.menuComingSoon') as string, 'warning');- return;- }- onOpenMenu(agent);- };-- // Composite pill content. Fixed-menu → model | source; open-menu → count |- // multi-source (+ custom count).- let pill: React.ReactNode = null;- if (agent.mode === 'hub' && agent.current) {- if (agent.menu_kind === 'open' && agent.menu) {- const customCount = sources.reduce(- (n, s) => n + s.models.filter((m) => m.provenance === 'manual').length,- 0,- );- const right =- customCount > 0- ? (t('settings.models.agents.multiSourceCustom', { count: customCount }) as string)- : (t('settings.models.agents.multiSource') as string);- pill = <CompositePill left={t('settings.models.agents.modelCount', { count: agent.menu.checked.length }) as string} dot={accent} right={right} />;- } else {- const source = sources.find((s) => s.id === agent.current?.source_id);- pill = (- <CompositePill- left={friendlyModelName(agent, sources)}- dot={source ? sourceAccent(source) : accent}- right={source?.display_name ?? agent.current.source_id}- />- );- }- } else if (agent.mode === 'hub') {- // Honest state: hub is selected but no eligible source can supply this agent- // yet, so the next turn silently falls back to Direct. Say so plainly instead- // of showing an empty (falsely "fine") row.- pill = (- <span className="flex items-center gap-1.5 text-[12px] font-medium text-gold">- <TriangleAlert className="size-3.5 shrink-0" />- {t('settings.models.agents.hubNoSupply')}- </span>- );- }-- // Direct mode had no second line at all, which read as "nothing to see here" —- // the truth is that this backend is still supplied by its own CLI config and the- // Hub isn't involved. Phones only: the desktop row keeps 直连 Direct beside its- // 接入中枢 button on one line, where a sentence has nowhere to go.- const mobileNote =- agent.mode === 'hub' ? null : (- <span className="text-[11.5px] leading-relaxed text-muted">{t('settings.models.agents.directNote')}</span>- );-- const action =- agent.mode === 'hub' ? (- <Button variant="secondary" size="sm" className="h-11 w-full sm:h-9 sm:w-auto" onClick={openMenu}>- {t('settings.models.agents.modelMenu')}- <ChevronRight className="size-3.5" />- </Button>- ) : (- <Button- variant="brand"- size="sm"- className="h-11 w-full sm:h-9 sm:w-auto"- onClick={() => onConnectHub(agent)}- disabled={connecting}- >- <ArrowDownToLine className="size-3.5" />- {t('settings.models.agents.connectHub')}- </Button>- );+ const action = hub ? (+ <Button+ variant="secondary"+ className="h-[41px] w-full gap-1.5 rounded-[10px] bg-foreground/[0.02] text-[13px] font-semibold text-foreground sm:h-[31px] sm:w-28 sm:gap-[5px] sm:text-[12px]"+ onClick={() => onOpenOrder(agent)}+ >+ <ArrowDownUp className="size-[15px] text-muted sm:hidden" />+ {t('settings.models.agents.sourceOrder')}+ <ChevronRight className="hidden size-[13px] text-muted sm:inline-block" />+ </Button>+ ) : (+ <Button+ variant="secondary"+ className="h-[41px] w-full gap-1.5 rounded-[10px] border-mint/40 bg-mint-soft text-[13px] font-semibold text-mint hover:bg-mint-soft/70 sm:h-[31px] sm:w-28 sm:gap-[5px] sm:text-[12px]"+ onClick={() => onConnectHub(agent)}+ disabled={connecting}+ >+ {/* The frames use two glyphs for one action: `zap` on mobile, where it+ echoes the 中枢 Hub pill it is offering to become, and `download` on+ desktop, where the pill is already visible in its own column. */}+ <Zap className="size-[15px] sm:hidden" />+ <Download className="hidden size-[13px] sm:inline-block" />+ {t('settings.models.agents.connectHub')}+ </Button>+ );return (- // Mobile is three full-width tiers (design.pen M01 m01Ag*): identity + mode- // badge, the supply line, then the action. Squeezed into one row at 390px the- // mode chip overlapped the composite pill and the pill's model id wrapped to- // three lines; nesting the pill under the name (the desktop shape) also left- // it inset by the icon tile instead of spanning the row.+ // A grid, not nested flex rows: the frames disagree about the supply block's+ // parent — desktop nests it under the name (indented past the icon tile),+ // mobile spans it across the full row width — and flex cannot re-parent+ // between breakpoints. Grid places the same single element in both, so there+ // is no double mount and no duplicated a11y tree.//- // The supply pill has two mount points because the desktop frame nests it- // under the name while mobile needs it as a full-width sibling — CSS cannot- // re-parent. It's stateless presentation and the inactive copy is- // display:none (so out of the a11y tree), which is the cheap half of the- // trade; the win is that the sm+ DOM stays exactly the reviewed desktop row.- <div className="flex flex-col gap-2.5 border-b border-border px-4 py-4 last:border-b-0 sm:flex-row sm:items-center sm:gap-4 sm:px-5">- <div className="flex min-w-0 items-center gap-2.5 sm:flex-1 sm:gap-4">- <span className={cn('flex size-[34px] shrink-0 items-center justify-center rounded-[10px] sm:size-11', ACCENT_TILE[accent])}>- <Icon className={cn('size-[18px] sm:size-[22px]', ACCENT_ICON[accent])} />- </span>-- <div className="flex min-w-0 flex-1 flex-col items-start gap-2">- {/* truncate only on phones; sm+ keeps the desktop row's wrap behaviour. */}- <span className="truncate text-[14px] font-bold text-foreground sm:whitespace-normal sm:text-[15px] sm:font-semibold">- {t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}- </span>- {pill && <span className="hidden sm:block">{pill}</span>}- </div>+ // mobile [tile] [name ......] [mode] desktop [tile] [name .....] [mode] [action]+ // [supply ........... ......] [tile] [supply ...] [mode] [action]+ // [action ........... ......]+ <div+ className={cn(+ 'grid grid-cols-[34px_minmax(0,1fr)_auto] items-center gap-x-2.5 gap-y-2.5 border-b border-border px-3.5 py-3.5 last:border-b-0',+ 'sm:grid-cols-[34px_minmax(0,1fr)_auto_auto] sm:gap-x-3.5 sm:gap-y-1.5 sm:px-5 sm:py-[13px]',+ )}+ >+ <span+ className={cn(+ 'col-start-1 row-start-1 flex size-[34px] items-center justify-center rounded-[10px] sm:row-span-2 sm:self-center',+ ACCENT_TILE[accent],+ )}+ >+ <Icon className={cn('size-4', ACCENT_ICON[accent])} />+ </span>- {/* The mode badge belongs on the identity line on phones. */}- <span className="shrink-0 sm:hidden">- <ModeChip mode={agent.mode} />+ <span className="col-start-2 row-start-1 flex min-w-0 items-center gap-2">+ <span className="truncate text-[14px] font-bold text-foreground sm:text-[13.5px] sm:font-semibold">+ {t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}</span>- </div>+ <MenuKindBadge agent={agent} />+ </span>- <div className="sm:hidden">{pill ?? mobileNote}</div>+ <span className="col-start-3 row-start-1 justify-self-end sm:row-span-2 sm:ml-2 sm:self-center">+ <ModeChip mode={agent.mode} />+ </span>- <div className="flex items-center gap-2.5 sm:shrink-0">- <span className="hidden sm:inline-flex">- <ModeChip mode={agent.mode} />- </span>+ {/* Supply — row 2, full-width on mobile, under the name on desktop. Direct+ mode has no chain to draw, so it says why instead (mobile only: the+ desktop row is a single line in the frame, where a sentence has nowhere+ to sit beside the 接入中枢 button). */}+ <span className="col-span-3 row-start-2 flex min-w-0 flex-col gap-2 sm:col-span-1 sm:col-start-2 sm:row-start-2 sm:gap-1">+ {hub ? (+ <>+ {/* One line in the frame: 模型 · 链路 · 策略. Mobile (M01) breaks it+ after 策略 and gives the chain its own line, so the badge takes an+ explicit order rather than trailing the chain into the wrap. */}+ <span className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-2 sm:flex-nowrap">+ <ModelBox agent={agent} sources={sources} />+ <PolicyBadge agent={agent} className="order-2 sm:order-3" />+ {chips.length > 0 ? (+ <span className="order-3 flex w-full min-w-0 items-center sm:order-2 sm:w-auto">+ <SupplyChain chips={chips} />+ </span>+ ) : (+ // Hub is selected but this backend has no enabled source at all.+ // There is no silent Direct fallback to reassure anyone with:+ // `model_hub.resolve()` only returns a Direct launch when the+ // backend's own `mode` is direct, so here it hits `source is None`+ // and raises `mapping_target_unavailable` — the turn fails. Say+ // that, in the same word the rollup uses (供给中断 / interrupted).+ <span className="order-3 flex w-full items-center gap-1.5 text-[11.5px] font-medium text-gold sm:order-2 sm:w-auto">+ <TriangleAlert className="size-3.5 shrink-0" />+ {t('settings.models.agents.hubNoSupply')}+ </span>+ )}+ </span>+ <AttributionLine agent={agent} />+ </>+ ) : (+ <span className="text-[11.5px] leading-relaxed text-muted sm:hidden">+ {t('settings.models.agents.directNote')}+ </span>+ )}+ </span>++ <span className="col-span-3 row-start-3 sm:col-span-1 sm:col-start-4 sm:row-start-1 sm:row-span-2 sm:self-center">{action}- </div>+ </span></div>);};@@ -150,20 +291,22 @@ export const AgentCard: React.FC<{agents: AgentSupply[];sources: Source[];onConnectHub: (agent: AgentSupply) => void;- onOpenMenu?: (agent: AgentSupply) => void;+ onOpenOrder: (agent: AgentSupply) => void;connectingBackend: string | null;-}> = ({ agents, sources, onConnectHub, onOpenMenu, connectingBackend }) => {+}> = ({ agents, sources, onConnectHub, onOpenOrder, connectingBackend }) => {const { t } = useTranslation();return (<section className="rounded-xl border border-border bg-background">- <div className="flex items-start justify-between gap-4 border-b border-border px-4 py-4 sm:px-5">- <div className="flex min-w-0 flex-col gap-1">- <h2 className="text-[15px] font-semibold text-foreground">{t('settings.models.agents.title')}</h2>- <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.agents.subtitle')}</p>+ <div className="flex items-start justify-between gap-4 border-b border-border px-3.5 py-3.5 sm:px-5 sm:py-4">+ <div className="flex min-w-0 flex-col gap-[3px]">+ <h2 className="text-[15px] font-bold text-foreground">{t('settings.models.agents.title')}</h2>+ <p className="text-[11.5px] leading-relaxed text-muted sm:text-[12px]">+ {t('settings.models.agents.subtitle')}+ </p></div><Linkto="/admin/settings/backends"- className="inline-flex min-h-10 shrink-0 items-center gap-1 text-[13px] font-medium text-mint transition-colors hover:text-mint/80 sm:min-h-0"+ className="inline-flex min-h-10 shrink-0 items-center gap-1 text-[12px] font-semibold text-cyan transition-colors hover:text-cyan/80 sm:min-h-0 sm:text-[12.5px]">{t('settings.models.agents.backendSettings')}<ArrowRight className="size-3.5" />@@ -176,7 +319,7 @@ export const AgentCard: React.FC<{agent={agent}sources={sources}onConnectHub={onConnectHub}- onOpenMenu={onOpenMenu}+ onOpenOrder={onOpenOrder}connecting={connectingBackend === agent.backend}/>))}diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.tsxindex eb3036f37..3752095ec 100644--- a/ui/src/components/settings/models/BackendSupplyModeCard.tsx+++ b/ui/src/components/settings/models/BackendSupplyModeCard.tsx@@ -15,6 +15,7 @@ import { cn } from '@/lib/utils';import { useToast } from '@/context/ToastContext';import { modelsApi } from './modelsApi';import { MigrationDialog } from './MigrationDialog';+import { connectOutcome, isSupplyWarning } from './sufficiency';import type { AgentBackend, AgentMode, AgentSupply, MigrationItem } from './types';const RadioDot: React.FC<{ selected: boolean }> = ({ selected }) => (@@ -121,12 +122,18 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bacsetAgent(next);if (mode === 'direct') {showToast(t('settings.models.supplyMode.switchedDirect') as string, 'success');- } else if (next.mode === 'hub' && next.current) {- showToast(t('settings.models.supplyMode.switchedHub') as string, 'success');} else {- // Hub selected but nothing can supply this backend yet → the launch- // silently falls back to Direct. Tell the truth, don't claim success.- showToast(t('settings.models.supplyMode.switchedHubNoSupply') as string, 'warning');+ // Same rule as the Models page's 接入中枢 button, and the same strings for+ // every non-ok outcome — this surface used to keep its own paraphrase of+ // 「still on Direct」, which is how one wrong promise became two.+ // `null` sources: this card holds no source inventory, so a null grade is+ // 「did not check」 (indeterminate) rather than 「fine」. It falls to the+ // neutral 已切换到中枢 — a statement about the mode, which is the only thing+ // this surface actually observed.+ const outcome = connectOutcome(next, null);+ if (outcome === 'failed') showToast(t('settings.models.supplyMode.switchFailed') as string, 'error');+ else if (isSupplyWarning(outcome)) showToast(t(`settings.models.supply.${outcome}`) as string, 'warning');+ else showToast(t('settings.models.supplyMode.switchedHub') as string, 'success');}} catch {if (aliveRef.current) showToast(t('settings.models.supplyMode.switchFailed') as string, 'error');@@ -138,6 +145,7 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bacif (!agent) return null;const mode = agent.mode;+ const hubOutcome = connectOutcome(agent, null);// Only surface the import strip for configs the migration dialog can actually// apply — a reauth-only scan would open a dead-end dialog (reauth rows are// disabled and excluded from apply), so those don't count as importable.@@ -181,10 +189,20 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bacbackend: t(`settings.models.backends.${backend}`, { defaultValue: backend }),}) as string}>- {mode === 'hub' && !agent.current && (+ {/* The banner asks the supply question, not the pin question: a Hub+ backend with no pinned model has `current: null` and is perfectly+ healthy, so keying the warning off that field warned the wrong+ people — and reassured the interrupted ones with a Direct fallback+ that does not exist. `fixHint` is appended only where a human can+ actually do something; a cooling source needs no instructions. */}+ {mode === 'hub' && isSupplyWarning(hubOutcome) && (<div className="flex items-start gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-2.5 text-[12px] leading-relaxed text-foreground"><Info className="mt-0.5 size-3.5 shrink-0 text-gold" />- <span>{t('settings.models.supplyMode.hubNoSupply')}</span>+ <span>+ {t(`settings.models.supply.${hubOutcome}`)}+ {(hubOutcome === 'noSources' || hubOutcome === 'interrupted') &&+ ` ${t('settings.models.supplyMode.fixHint')}`}+ </span></div>)}</OptionCard>diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsxindex eaea9f34b..d390e5767 100644--- a/ui/src/components/settings/models/MigrationDialog.tsx+++ b/ui/src/components/settings/models/MigrationDialog.tsx@@ -21,6 +21,7 @@ import {import { cn } from '@/lib/utils';import { useToast } from '@/context/ToastContext';import { modelsApi } from './modelsApi';+import { serverText } from './serverCopy';import { ACCENT_ICON, ACCENT_TILE, type Accent } from './vendorMeta';import type { AgentBackend, MigrationItem, MigrationAction } from './types';@@ -54,6 +55,7 @@ const ActionBadge: React.FC<{ action: MigrationAction }> = ({ action }) => {const ItemRow: React.FC<{ item: MigrationItem; onToggle: () => void }> = ({ item, onToggle }) => {const { t } = useTranslation();const { Icon, accent } = migrationVisual(item);+ const note = serverText(t, item.notes_key);// reauth needs the interactive browser flow, so it can't be bulk-applied here.const selectable = item.proposed_action !== 'reauth';return (@@ -75,7 +77,9 @@ const ItemRow: React.FC<{ item: MigrationItem; onToggle: () => void }> = ({ item</span><div className="flex min-w-0 flex-1 flex-col gap-0.5"><span className="truncate text-[14px] font-semibold text-foreground">{item.masked_detail}</span>- {item.notes_key && <span className="truncate text-[12px] text-muted">{t(item.notes_key)}</span>}+ {/* `notes_key` is runtime-declared and optional, so an entry this+ bundle doesn't carry drops the line instead of printing the key. */}+ {note && <span className="truncate text-[12px] text-muted">{note}</span>}</div></div><div className="shrink-0 pl-[46px] sm:pl-0">diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsxindex ef6342e56..0f875cfda 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx@@ -6,7 +6,7 @@// mirrors BackendOAuthPanel: start → 2s poll → verifying → success, 15-min// timeout, cancel.import * as React from 'react';-import { CheckCircle2, Loader2, Sparkles, TriangleAlert } from 'lucide-react';+import { CheckCircle2, Sparkles, TriangleAlert } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';@@ -14,16 +14,39 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/uimport { cn } from '@/lib/utils';import { useToast } from '@/context/ToastContext';import { OAuthDeviceCodeRow, OAuthLinkRow, OAuthSubmitRow } from '../oauth/OAuthFlowParts';+import { AdoptionNote } from './AdoptionNote';+import {+ createFlowAuthority,+ initialFlowView,+ isDone,+ type FlowAuthority,+ type FlowView,+} from './asyncLifetime';import { ExperimentalConsentDialog } from './ExperimentalConsentDialog';import { SUBSCRIPTION_HUB_EXPERIMENTAL } from './featureFlags';-import { modelsApi } from './modelsApi';+import { modelsApi, type OAuthResult } from './modelsApi';+import { serverText } from './serverCopy';+import { adoptionVerdict } from './sufficiency';import { ACCENT_ICON, ACCENT_TILE } from './vendorMeta';-import type { OAuthFlow, SupplyChannel } from './types';+import type { AdoptedBy, SupplyChannel } from './types';const POLL_MS = 2000;const DEADLINE_MS = 16 * 60 * 1000;const TERMINAL = ['success', 'failed', 'cancelled'];+// The creation half of a terminal status/submit response fails with its own+// codes (api.md → POST /sources errors, raised while materializing the Source).+const CREATION_CODES = ['discovery_failed', 'engine_down', 'migration_item_conflict'];++/** Terminal-response failure code → copy, keeping 「授权没成」 distinct from+ * 「授权成了但来源没建起来」 instead of collapsing both into 连接失败. */+const errorKeyFor = (code?: string): string =>+ code === 'consent_required'+ ? 'settings.models.oauth.error.consent'+ : code && CREATION_CODES.includes(code)+ ? 'settings.models.oauth.error.finalize'+ : 'settings.models.oauth.error.generic';+const Step: React.FC<{ n: number; label: string; children: React.ReactNode }> = ({ n, label, children }) => (<div className="flex flex-col gap-2.5 rounded-lg border border-border bg-surface-2/40 px-4 py-3"><span className="text-[13px] font-medium text-foreground">@@ -44,21 +67,25 @@ export const OAuthConnectDialog: React.FC<{const { t } = useTranslation();const { showToast } = useToast();- const [flow, setFlow] = React.useState<OAuthFlow | null>(null);+ const [view, setView] = React.useState<FlowView>(initialFlowView);const [code, setCode] = React.useState('');const [submitting, setSubmitting] = React.useState(false);- const [errorKey, setErrorKey] = React.useState<string | null>(null);const [channel, setChannel] = React.useState<SupplyChannel>('native_cli');const [consentOpen, setConsentOpen] = React.useState(false);- // Between flow success and the Source being persisted (createOAuthSource):- // holds the "Connected" banner so we never claim success before the Source- // actually exists, and lets a finalize failure surface honestly.- const [finalizing, setFinalizing] = React.useState(false);+ // Which Agents took the new subscription in, frozen at commit (api.md). Same+ // note as the API-key dialog: connecting a credential is not the same as+ // putting it into service, and a `custom` Agent is silently absent.+ //+ // `null` means the terminal response did not report a creation — which is not+ // 「没有 Agent 采用」 and must not be rendered as it.+ const [adoptedBy, setAdoptedBy] = React.useState<AdoptedBy[] | null>(null);const [, tick] = React.useReducer((x) => x + 1, 0);- // One-shot latch so the finalize handoff runs exactly once per flow.- const finalizedRef = React.useRef(false);- const flowRef = React.useRef<OAuthFlow | null>(null);+ // Set by the flow effect so `submit` lands through the very same owners as a+ // poll response: one authority owns the complete view and one handler owns+ // terminal side effects.+ const flowAuthorityRef = React.useRef<FlowAuthority | null>(null);+ const settleRef = React.useRef<((result: OAuthResult) => void) | null>(null);const successTimer = React.useRef<number | null>(null);const onConnectedRef = React.useRef(onConnected);onConnectedRef.current = onConnected;@@ -95,79 +122,70 @@ export const OAuthConnectDialog: React.FC<{if (pollTimer !== null) window.clearTimeout(pollTimer);pollTimer = null;};- const apply = (f: OAuthFlow | null) => {- flowRef.current = f;- setFlow(f);+ const authority = createFlowAuthority(setView);+ flowAuthorityRef.current = authority;+ const transition = authority.transition;++ // The single place a terminal result becomes a finished (or failed) connect.+ // Shared by the poll and the paste submit because api.md gives both the SAME+ // terminal shape — written twice, one of them ends up reading a different+ // half of the envelope, which is exactly the bug this replaces. WHICH arrival+ // is allowed to change what is shown is `flowStep`'s call (asyncLifetime.ts);+ // this function only carries out the side effects. Returns whether the flow is+ // done, so the caller stops polling.+ const settle = (result: OAuthResult): boolean => {+ const { created } = result;+ const step = transition({ kind: 'response', flow: result.flow });+ if (step.action === 'succeed') {+ // The Source already exists. The status/submit call that first reports+ // success materializes it server-side and consumes the flow binding doing+ // it — there is nothing left to finalize, and a POST /sources afterwards+ // is refused as `flow_not_found` on a connect that in fact succeeded.+ setAdoptedBy(created ? created.adopted_by : null);+ showToast(t('settings.models.oauth.status.success') as string, 'success');+ onConnectedRef.current();+ // Same rule as the API-key dialog, through the same owner: 1.4s auto-dismiss+ // is for a pure 「连接成功」, and every other verdict leaves an instruction on+ // screen that 1.4s is not long enough to read. The old `!== 0` also read an+ // ABSENT creation as adopted, which auto-dismissed the one case that knows+ // least — `adoptionVerdict(null)` is indeterminate, so it now waits.+ if (adoptionVerdict(created?.adopted_by ?? null).kind === 'covered')+ successTimer.current = window.setTimeout(() => onCloseRef.current(), 1400);+ }+ // A paste submit can terminate the flow while a poll timer is still armed;+ // the guard above already makes that poll harmless, but there is no reason+ // to let it fire.+ if (isDone(step.action)) stop();+ return isDone(step.action);};+ settleRef.current = settle;const poll = async (flowId: string) => {if (cancelled) return;- if (Date.now() > deadline) {- setErrorKey('settings.models.oauth.error.timeout');- if (flowRef.current) apply({ ...flowRef.current, state: 'failed' });- return;- }+ const overdue = transition({ kind: 'tick', overdue: Date.now() > deadline });+ if (isDone(overdue.action)) return;try {- const next = await modelsApi.getOAuthStatus(flowId);+ const result = await modelsApi.getOAuthStatus(flowId);if (cancelled) return;- apply(next);- if (next.state === 'success') {- // P0: a completed flow is NOT yet a Source. Finalize the handoff- // (POST /sources with oauth_flow_ref) — the server assigns the source- // id from the flow binding and discovers models. Only then is the- // connect truly done. `experimental_consent` goes only to the hub- // channel; native_cli must not send it (server rejects otherwise).- if (finalizedRef.current) return;- finalizedRef.current = true;- setFinalizing(true);- try {- await modelsApi.createOAuthSource({- kind: 'subscription',- vendor,- oauth_flow_ref: next.flow_id,- supply_channel: next.channel,- ...(next.channel === 'hub' ? { experimental_consent: true } : {}),- });- } catch (err) {- // OAuth succeeded but the Source wasn't persisted — say so, don't- // flash a false "Connected". The Source may exist server-side if the- // request landed, so a refetch still runs on the honest paths below.- if (cancelled) return;- const code = (err as { code?: string } | null)?.code;- setErrorKey(- code === 'consent_required'- ? 'settings.models.oauth.error.consent'- : 'settings.models.oauth.error.finalize',- );- apply({ ...next, state: 'failed' });- setFinalizing(false);- return;- }- if (cancelled) return;- setFinalizing(false);- showToast(t('settings.models.oauth.status.success') as string, 'success');- onConnectedRef.current();- successTimer.current = window.setTimeout(() => onCloseRef.current(), 1400);- return;- }- if (next.state === 'failed' || next.state === 'cancelled') {- setErrorKey(next.error_key ?? 'settings.models.oauth.error.generic');- return;- }+ if (settle(result)) return;pollTimer = window.setTimeout(() => void poll(flowId), POLL_MS);- } catch {- if (!cancelled) setErrorKey('settings.models.oauth.error.generic');+ } catch (err) {+ if (cancelled) return;+ // A poll that lands on a just-succeeded flow is also the call that+ // materializes the Source, so it can fail for creation reasons+ // (consent_required / discovery_failed / engine_down): the vendor said+ // yes and the Source still doesn't exist. Naming that separately is the+ // difference between 「重试授权」 and 「授权成功但没能建立来源」.+ transition({ kind: 'error', errorKey: errorKeyFor((err as { code?: string } | null)?.code) });}};// Clear any stale flow from a prior open so the previous success/failure// isn't shown while the new startOAuth request is in flight.- apply(null);- setErrorKey(null);+ transition({ kind: 'reset' });setCode('');setSubmitting(false);- setFinalizing(false);- finalizedRef.current = false;+ setAdoptedBy(null);void (async () => {try {// A hub-held subscription connect (channel === 'hub' only when the user@@ -175,23 +193,31 @@ export const OAuthConnectDialog: React.FC<{// the server returns consent_required.const started = await modelsApi.startOAuth(vendor, channel, channel === 'hub');if (cancelled) return;- apply(started);+ transition({ kind: 'response', flow: started });if (started.expires_at) deadline = new Date(started.expires_at).getTime() + 60_000;pollTimer = window.setTimeout(() => void poll(started.flow_id), POLL_MS);} catch (err) {if (cancelled) return;const code = (err as { code?: string } | null)?.code;- setErrorKey(code === 'consent_required' ? 'settings.models.oauth.error.consent' : 'settings.models.oauth.error.start');+ transition({+ kind: 'error',+ errorKey:+ code === 'consent_required'+ ? 'settings.models.oauth.error.consent'+ : 'settings.models.oauth.error.start',+ });}})();return () => {cancelled = true;stop();+ settleRef.current = null;if (successTimer.current !== null) window.clearTimeout(successTimer.current);- const cur = flowRef.current;+ const cur = authority.current().flow;+ transition({ kind: 'reset' });+ if (flowAuthorityRef.current === authority) flowAuthorityRef.current = null;if (cur && !TERMINAL.includes(cur.state)) modelsApi.cancelOAuth(cur.flow_id).catch(() => {});- flowRef.current = null;};}, [open, vendor, channel, t, showToast]);@@ -211,32 +237,39 @@ export const OAuthConnectDialog: React.FC<{}, [open]);const submit = async () => {- const cur = flowRef.current;+ const authority = flowAuthorityRef.current;+ const cur = authority?.current().flow;if (!cur || !code.trim()) return;+ const isCurrent = () =>+ flowAuthorityRef.current === authority && authority.current().flow?.flow_id === cur.flow_id;setSubmitting(true);try {- const next = await modelsApi.submitOAuth(cur.flow_id, code.trim());+ const result = await modelsApi.submitOAuth(cur.flow_id, code.trim());// Drop the response if the dialog closed or a new flow started meanwhile.- if (flowRef.current?.flow_id !== cur.flow_id) return;- flowRef.current = next;- setFlow(next);- } catch {- if (flowRef.current?.flow_id !== cur.flow_id) return;- setErrorKey('settings.models.oauth.error.generic');+ if (!isCurrent()) return;+ // Submit can terminate the flow outright (the contract gives status and+ // submit the same terminal shape), so it goes through the same handler+ // rather than storing the flow and waiting for a poll to notice.+ settleRef.current?.(result);+ } catch (err) {+ if (!isCurrent()) return;+ authority.transition({ kind: 'error', errorKey: errorKeyFor((err as { code?: string } | null)?.code) });} finally {- if (flowRef.current?.flow_id === cur.flow_id) setSubmitting(false);+ if (isCurrent()) setSubmitting(false);}};+ const { flow, errorKey } = view;const presentation = flow?.presentation;const expects = presentation?.expects;const isDevice = expects === 'none';const state = flow?.state;- // "Connected" only once the Source is persisted — never during finalize, and- // never if the finalize handoff failed.- const success = state === 'success' && !finalizing && !errorKey;- const failed = state === 'failed' || state === 'cancelled' || Boolean(errorKey);- const active = !success && !failed && !finalizing;+ // A `success` state now means the Source exists: the server materializes it in+ // the same call, so there is no in-between to hold the banner for. The complete+ // rendered state comes from the authority's landed view.+ const success = view.settled && flow?.state === 'success';+ const failed = view.settled && Boolean(errorKey);+ const active = !view.settled;const remainingMs = flow?.expires_at ? Math.max(0, new Date(flow.expires_at).getTime() - Date.now()) : null;const mmss =@@ -244,17 +277,19 @@ export const OAuthConnectDialog: React.FC<{? `${String(Math.floor(remainingMs / 60000)).padStart(2, '0')}:${String(Math.floor((remainingMs % 60000) / 1000)).padStart(2, '0')}`: '';- const step2Label = presentation?.instructions_key- ? (t(presentation.instructions_key) as string)- : isDevice- ? (t('settings.models.oauth.deviceCode.hint') as string)- : expects === 'paste_callback_url'- ? (t('settings.models.oauth.callback.hint') as string)- : (t('settings.models.oauth.pasteCode.hint') as string);+ // `instructions_key` is runtime-declared (a new adapter can ship one this+ // bundle has never seen), so it falls back to the copy for the `expects` shape+ // instead of printing the key at the user.+ const step2Fallback = isDevice+ ? 'settings.models.oauth.deviceCode.hint'+ : expects === 'paste_callback_url'+ ? 'settings.models.oauth.callback.hint'+ : 'settings.models.oauth.pasteCode.hint';+ const step2Label = serverText(t, presentation?.instructions_key, step2Fallback) ?? '';return (<>- <Dialog open={open} onOpenChange={(v) => !v && !finalizing && onClose()}>+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}><DialogContent className="max-w-[520px] gap-5"><DialogHeader><DialogTitle className="flex items-center gap-2.5 text-[17px] font-bold">@@ -270,19 +305,22 @@ export const OAuthConnectDialog: React.FC<{{failed && (<div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive"><TriangleAlert className="mt-0.5 size-4 shrink-0" />- <span>{t(errorKey ?? 'settings.models.oauth.error.generic')}</span>+ {/* errorKey may be the flow's own runtime-declared `error_key`, so+ an unknown one degrades to 连接失败 rather than rendering itself. */}+ <span>{serverText(t, errorKey, 'settings.models.oauth.error.generic')}</span></div>)}{success ? (- <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">- <CheckCircle2 className="size-4 shrink-0" />- {t('settings.models.oauth.connected')}- </div>- ) : finalizing ? (- <div className="flex items-center gap-2 rounded-lg border border-border bg-surface-2/40 px-4 py-3 text-[13px] font-medium text-muted">- <Loader2 className="size-4 shrink-0 animate-spin" />- {t('settings.models.oauth.status.finalizing')}+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">+ <CheckCircle2 className="size-4 shrink-0" />+ {t('settings.models.oauth.connected')}+ </div>+ {/* Only when the response actually reported the creation: an absent+ `adopted_by` is not an empty one, and 「没有 Agent 采用」 would be+ a claim this response never made. */}+ <AdoptionNote adoptedBy={adoptedBy} /></div>) : (active && (@@ -370,7 +408,7 @@ export const OAuthConnectDialog: React.FC<{) : (<span />)}- <Button variant={active ? 'ghost' : 'outline'} size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={finalizing}>+ <Button variant={active ? 'ghost' : 'outline'} size="sm" className="h-10 sm:h-9" onClick={onClose}>{active ? t('common.cancel') : t('common.close')}</Button></div>diff --git a/ui/src/components/settings/models/RecentSwitchesCard.test.tsx b/ui/src/components/settings/models/RecentSwitchesCard.test.tsxnew file mode 100644index 000000000..eedf8841b--- /dev/null+++ b/ui/src/components/settings/models/RecentSwitchesCard.test.tsx@@ -0,0 +1,129 @@+// AC-18: the feed is a historical record. Its sentence is whatever was recorded;+// the only thing the UI adds is a render-time 已删除 observation when a source the+// sentence names no longer resolves.+import { createInstance } from 'i18next';+import { renderToStaticMarkup } from 'react-dom/server';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { describe, expect, it } from 'vitest';++import en from '../../../i18n/en.json';+import zh from '../../../i18n/zh.json';+import { RecentSwitchesCard, eventAccent } from './RecentSwitchesCard';+import type { ResolutionEvent, Source } from './types';++const instance = (lng: 'en' | 'zh') => {+ const i18n = createInstance();+ void i18n.use(initReactI18next).init({+ lng,+ fallbackLng: 'en',+ resources: { en: { translation: en }, zh: { translation: zh } },+ interpolation: { escapeValue: false },+ });+ return i18n;+};++const source = (id: string): Source => ({+ id,+ kind: 'api_key',+ vendor: 'anthropic',+ display_name: id,+ protocol: 'anthropic',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active', retry_at: null, detail_key: null },+ models: [],+});++const event = (over: Partial<ResolutionEvent> = {}): ResolutionEvent => ({+ id: 'evt_1',+ ts: '2026-07-29T09:12:00Z',+ agent: 'claude',+ kind: 'switch',+ model_id: 'claude-opus-4-6',+ from_source: 'src_gone01',+ to_source: 'src_live01',+ reason: 'quota_exhausted',+ human_zh: 'Claude Code 从 ChatGPT Plus 订阅 切到 Anthropic API Key(额度用完)',+ human_en: 'Claude Code switched from ChatGPT Plus to Anthropic API Key (quota used up)',+ ...over,+});++const render = (events: ResolutionEvent[], sources: Source[], lng: 'en' | 'zh' = 'zh') =>+ renderToStaticMarkup(+ <I18nextProvider i18n={instance(lng)}>+ <RecentSwitchesCard events={events} sources={sources} />+ </I18nextProvider>,+ );++describe('RecentSwitchesCard (AC-18)', () => {+ it('renders the recorded sentence verbatim, in the UI language', () => {+ const e = event();+ expect(render([e], [source('src_live01')], 'zh')).toContain(e.human_zh);+ expect(render([e], [source('src_live01')], 'en')).toContain(e.human_en);+ });++ it('keeps the sentence intact when the source it names is gone', () => {+ // The whole point: re-deriving the wording from today's inventory would blank+ // this row out or silently rewrite history.+ const html = render([event()], [source('src_live01')]);+ expect(html).toContain('ChatGPT Plus');+ expect(html).toContain(zh.settings.models.recent.deletedSource);+ });++ it('marks nothing when both endpoints still resolve', () => {+ const html = render([event()], [source('src_gone01'), source('src_live01')]);+ expect(html).not.toContain(zh.settings.models.recent.deletedSource);+ });++ it('marks nothing for an event that names no source at all', () => {+ // A supply interruption is about a backend: both endpoints are null by+ // contract, and null is not a deleted source.+ const html = render(+ [event({ kind: 'supply_interrupted', model_id: null, from_source: null, to_source: null })],+ [source('src_live01')],+ );+ expect(html).not.toContain(zh.settings.models.recent.deletedSource);+ });++ it('offers no action on a deleted source — there is nothing left to act on', () => {+ const html = render([event()], [source('src_live01')]);+ expect(html).not.toContain('<button');+ });++ it('shows three events and expands only when there are more', () => {+ const three = [1, 2, 3].map((n) => event({ id: `evt_${n}` }));+ expect(render(three, [source('src_live01')])).not.toContain(zh.settings.models.recent.viewAll);+ const four = [...three, event({ id: 'evt_4' })];+ expect(render(four, [source('src_live01')])).toContain(zh.settings.models.recent.viewAll);+ });+});++// The contract puts `severity` in the payload as 「Feed and Models-page presentation+// metadata」. The feed used to ignore it and grade rows off `kind`, which left the+// two action_required kinds in the same cyan as an ordinary switch.+describe('eventAccent', () => {+ it('takes the server’s grading over anything it could infer', () => {+ expect(eventAccent(event({ severity: 'action_required' }))).toBe('gold');+ // Even on a kind that would otherwise read as routine traffic.+ expect(eventAccent(event({ kind: 'switch', severity: 'action_required' }))).toBe('gold');+ });++ it('leaves an info-graded event to the kind vocabulary', () => {+ expect(eventAccent(event({ kind: 'switch', severity: 'info' }))).toBe('cyan');+ expect(eventAccent(event({ kind: 'recover', severity: 'info' }))).toBe('mint');+ expect(eventAccent(event({ kind: 'cooldown', severity: 'info' }))).toBe('muted');+ expect(eventAccent(event({ kind: 'skip', severity: 'info' }))).toBe('muted');+ });++ // Only for a journal row written before the field existed: re-grading an outage+ // as ordinary traffic would hide the one row nobody may scroll past.+ it('falls back to the two kinds the contract pins action_required on', () => {+ expect(eventAccent(event({ kind: 'needs_action', severity: null }))).toBe('gold');+ expect(eventAccent(event({ kind: 'supply_interrupted', severity: undefined }))).toBe('gold');+ expect(eventAccent(event({ kind: 'switch', severity: null }))).toBe('cyan');+ });++ it('still golds a metered crossing, which is a billing fact rather than a severity', () => {+ expect(eventAccent(event({ kind: 'switch', severity: 'info', billing_note: 'entered_metered' }))).toBe('gold');+ });+});diff --git a/ui/src/components/settings/models/RecentSwitchesCard.tsx b/ui/src/components/settings/models/RecentSwitchesCard.tsxindex 6c9e7a4b4..7b60773fc 100644--- a/ui/src/components/settings/models/RecentSwitchesCard.tsx+++ b/ui/src/components/settings/models/RecentSwitchesCard.tsx@@ -1,16 +1,46 @@-// 最近切换 — the human-readable resolution-event feed (frame 01r). Shows the-// three most recent by default; 查看全部 expands to the full fetched set. Text-// uses the locale-matched human_zh / human_en the adapter already produced.+// 最近切换 — the human-readable resolution-event feed (design.pen 「产品改造 V6+// 01」). Shows the three most recent by default; 查看全部 opens the list and walks+// the endpoint's `before` cursor page by page, so 全部 means the whole feed and not+// just the rows the page happened to fetch first.+//+// AC-18: an event's sentence is rendered VERBATIM from the recorded human_zh /+// human_en. It is a historical record — the source it names may have been renamed+// or deleted since, and re-deriving the wording from today's inventory would+// silently rewrite history (or, worse, blank the row out). What the UI adds is a+// render-time observation, not a rewrite: when a canonical `src_*` endpoint no+// longer resolves against the live sources, the row gets a 已删除 marker so the+// reader knows why looking for that source in the list above will fail. No action+// is offered — there is nothing left to act on.import * as React from 'react';import { useTranslation } from 'react-i18next';+import { Badge } from '@/components/ui/badge';import { Dot } from './chips';import type { Accent } from './vendorMeta';-import type { ResolutionEvent } from './types';+import type { ResolutionEvent, Source } from './types';const COLLAPSED = 3;-function eventAccent(e: ResolutionEvent): Accent {+/**+ * 需处理 — read off the server's own grading rather than re-derived here.+ *+ * `severity` is in the contract precisely as 「Feed and Models-page presentation+ * metadata」, pinned to `action_required` on the needs_action and supply_interrupted+ * branches. Ignoring it left those two rows falling through to the same cyan as an+ * ordinary switch: the one kind of event nobody may scroll past looked like traffic.+ *+ * The kind fallback covers only a journal row written before the field existed —+ * where re-grading an outage as cyan would hide it — and never overrides a severity+ * the server did send.+ */+const isActionRequired = (e: ResolutionEvent): boolean =>+ e.severity === 'action_required' ||+ (e.severity == null && (e.kind === 'needs_action' || e.kind === 'supply_interrupted'));++export function eventAccent(e: ResolutionEvent): Accent {+ // Gold is the page's one attention colour (`needsAttention`'s sub-line, the chain's+ // dot). An action-required event earns it rather than a treatment of its own.+ if (isActionRequired(e)) return 'gold';if (e.billing_note === 'entered_metered') return 'gold';if (e.kind === 'recover' || e.reason === 'recovery') return 'mint';if (e.kind === 'cooldown' || e.kind === 'skip') return 'muted';@@ -35,14 +65,32 @@ function useEventTime() {};}-export const RecentSwitchesCard: React.FC<{ events: ResolutionEvent[] }> = ({ events }) => {+export const RecentSwitchesCard: React.FC<{+ events: ResolutionEvent[];+ /** Live inventory — read only to tell a still-present source from a deleted one. */+ sources: Source[];+ /** The feed has older pages than the ones held here (`/events` pages by cursor). */+ hasMore?: boolean;+ loadingMore?: boolean;+ /** Fetch the next older page. Required for 查看全部 to mean 全部. */+ onLoadMore?: () => void;+}> = ({ events, sources, hasMore = false, loadingMore = false, onLoadMore }) => {const { t, i18n } = useTranslation();const [expanded, setExpanded] = React.useState(false);const formatTime = useEventTime();const zh = i18n.language.startsWith('zh');+ const liveIds = React.useMemo(() => new Set(sources.map((s) => s.id)), [sources]);+ const namesDeletedSource = (e: ResolutionEvent) =>+ [e.from_source, e.to_source].some((id) => typeof id === 'string' && id !== '' && !liveIds.has(id));const shown = expanded ? events : events.slice(0, COLLAPSED);- const canExpand = events.length > COLLAPSED;+ // 查看全部 opens the fetched rows AND asks for the next page, so the label is+ // true the moment it is pressed rather than only for feeds under one page.+ const canExpand = events.length > COLLAPSED || hasMore;+ const expand = () => {+ setExpanded(true);+ if (hasMore && !loadingMore) onLoadMore?.();+ };return (<section className="rounded-xl border border-border bg-background">@@ -51,7 +99,7 @@ export const RecentSwitchesCard: React.FC<{ events: ResolutionEvent[] }> = ({ ev{canExpand && (<buttontype="button"- onClick={() => setExpanded((v) => !v)}+ onClick={() => (expanded ? setExpanded(false) : expand())}className="inline-flex min-h-10 items-center text-[13px] font-medium text-mint transition-colors hover:text-mint/80 sm:min-h-0">{expanded ? t('settings.models.recent.collapse') : t('settings.models.recent.viewAll')}@@ -78,9 +126,27 @@ export const RecentSwitchesCard: React.FC<{ events: ResolutionEvent[] }> = ({ ev</span><span className="min-w-0 flex-1 text-[12.5px] leading-relaxed text-foreground sm:order-3 sm:text-[13px]">{zh ? event.human_zh : event.human_en}+ {namesDeletedSource(event) && (+ <Badge+ variant="secondary"+ className="ml-1.5 translate-y-[-1px] bg-foreground/[0.03] px-2 py-0 text-[10px] font-medium"+ >+ {t('settings.models.recent.deletedSource')}+ </Badge>+ )}</span></div>))}+ {expanded && hasMore && (+ <button+ type="button"+ onClick={() => onLoadMore?.()}+ disabled={loadingMore}+ className="min-h-11 border-t border-border px-4 py-3 text-[12.5px] font-medium text-mint transition-colors hover:text-mint/80 disabled:text-muted sm:px-5 sm:text-[13px]"+ >+ {loadingMore ? t('settings.models.recent.loadingMore') : t('settings.models.recent.loadMore')}+ </button>+ )}</div>)}</section>diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex 99cf744d8..a727a96d8 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -1,42 +1,83 @@-// 设置 · 模型 — the Model Hub main page (design.pen 产品改造 V4 01r). Owns data-// fetching + the ordered source list; composes the 来源 band, Agent band,-// 最近切换 feed, and the 高级 row, plus the add-source dialogs. Talks to the hub-// through modelsApi (mock fixtures until L2's REST API is live — see-// featureFlags.ts).+// 设置 · 模型 — the Model Hub main page (design.pen 「产品改造 V6 01」, failover+// state 「V6 04」, mobile 「V6 M01」). Owns data fetching; composes the 来源 band,+// Agent band, 最近切换 feed and the 高级 row, plus the add-source dialogs, the+// per-Agent 来源顺序 drawer and the L5 menu drawers. Talks to the hub through+// modelsApi (mock fixtures until L2's REST API is live — see featureFlags.ts).import * as React from 'react';-import { CheckCircle2, TriangleAlert } from 'lucide-react';+import { CheckCircle2, Info, TriangleAlert } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Badge } from '@/components/ui/badge';import { useToast } from '@/context/ToastContext';import { SettingsPageShell } from '../SettingsPageShell';+import { MODEL_MENUS_ENABLED } from './featureFlags';import { SourcesCard } from './SourcesCard';import { AgentCard } from './AgentCard';import { MigrationBanner } from './MigrationBanner';import { RecentSwitchesCard } from './RecentSwitchesCard';+import { SourceOrderDrawer } from './SourceOrderDrawer';import { AdvancedRow } from './AdvancedRow';import { AddApiKeyDialog } from './AddApiKeyDialog';import { OAuthConnectDialog } from './OAuthConnectDialog';+import { createLatestAsyncAuthority } from './asyncLifetime';import { MappingDrawer } from './menus/MappingDrawer';import { OpenCodeMenuDrawer } from './menus/OpenCodeMenuDrawer';import { modelsApi } from './modelsApi';+import { connectOutcome, isSupplyWarning } from './sufficiency';+import { pageStatus, type PageStatus } from './supply';import type { AgentBackend, AgentSupply, ResolutionEvent, RuntimeDependency, Source } from './types';-const StatusPill: React.FC<{ healthy: boolean; hubCount: number }> = ({ healthy, hubCount }) => {+/**+ * The header pill — the one line that says whether the Hub is doing its job.+ *+ * V6 04 is why it can't be a boolean: a source ran out of quota, the chain covered+ * for it, and the honest headline is 「已自动切换,恢复后切回」 — a warning about+ * something already handled, which neither 一切正常 nor 需要处理 can express. The+ * ladder itself lives in supply.ts (a rule, unit-tested); this only renders it.+ */+const StatusPill: React.FC<{ status: PageStatus }> = ({ status }) => {const { t } = useTranslation();- return healthy ? (- <Badge variant="success" className="gap-1.5 rounded-full px-3 py-1.5 text-[12px]">- <CheckCircle2 className="size-3.5" />- {t('settings.models.statusPill.ok', { count: hubCount })}- </Badge>- ) : (- <Badge variant="warning" className="gap-1.5 rounded-full px-3 py-1.5 text-[12px]">- <TriangleAlert className="size-3.5" />- {t('settings.models.statusPill.degraded', { count: hubCount })}+ const k = `settings.models.statusPill.${status.kind}`;+ const text =+ status.kind === 'ok'+ ? (t(k, { count: status.hubCount }) as string)+ : status.kind === 'interrupted' || status.kind === 'waiting'+ ? (t(k, { count: status.count }) as string)+ : status.kind === 'needsAction' || status.kind === 'cooldown'+ ? [+ t(k, {+ source: status.source.display_name,+ // `detail_key` is required on needs_action / error but optional on+ // cooldown, so a missing one falls back to the status label rather+ // than interpolating an empty segment.+ detail: t(+ status.source.state.detail_key ?? `settings.models.state.${status.source.state.status}`,+ ) as string,+ }) as string,+ // 「另有 N 个来源」 — one shared suffix instead of a per-branch+ // singular/plural pair. The pill names the worst source; the count+ // says the list has more of them.+ status.others > 0 ? (t('settings.models.statusPill.andMore', { count: status.others }) as string) : '',+ ]+ .filter(Boolean)+ .join(' · ')+ : (t(k) as string);++ const variant = status.tone === 'ok' ? 'success' : status.tone === 'warn' ? 'warning' : 'secondary';+ const Icon = status.tone === 'ok' ? CheckCircle2 : status.tone === 'warn' ? TriangleAlert : Info;+ return (+ <Badge variant={variant} className="gap-1.5 rounded-full px-3 py-1.5 text-[12px]">+ <Icon className="size-3.5" />+ {text}</Badge>);};+// 最近切换 is a cursor feed, not a fixed window: `/events` pages with `before`,+// so 「查看全部」 over one fetched page could never reach row 21. One page size for+// the first read and every 加载更早 read after it.+const EVENT_PAGE = 20;+export const SettingsModelsPage: React.FC = () => {const { t } = useTranslation();const { showToast } = useToast();@@ -44,6 +85,10 @@ export const SettingsModelsPage: React.FC = () => {const [sources, setSources] = React.useState<Source[]>([]);const [agents, setAgents] = React.useState<AgentSupply[]>([]);const [events, setEvents] = React.useState<ResolutionEvent[]>([]);+ // A short page is the end of the feed — the only end-of-list signal the+ // endpoint gives (there is no total).+ const [eventsExhausted, setEventsExhausted] = React.useState(true);+ const [loadingEvents, setLoadingEvents] = React.useState(false);const [runtime, setRuntime] = React.useState<RuntimeDependency | null>(null);const [loading, setLoading] = React.useState(true);const [loadError, setLoadError] = React.useState<string | null>(null);@@ -51,33 +96,51 @@ export const SettingsModelsPage: React.FC = () => {const [apiKeyOpen, setApiKeyOpen] = React.useState(false);const [oauthVendor, setOauthVendor] = React.useState<string | null>(null);- // Which backend's 模型菜单 drawer is open. Tracked by backend id (not the agent- // object) so a background refresh keeps feeding the drawer the freshest agent.+ // Which backend's 模型菜单 / 来源顺序 drawer is open. Tracked by backend id (not+ // the agent object) so a background refresh keeps feeding the drawer the+ // freshest agent.const [menuBackend, setMenuBackend] = React.useState<AgentBackend | null>(null);+ const [orderBackend, setOrderBackend] = React.useState<AgentBackend | null>(null);- // Mirror the latest ordered sources for reorder-commit (drag end reads the- // freshest order without threading it through the framer callback).- const sourcesRef = React.useRef<Source[]>(sources);- sourcesRef.current = sources;- // Bumped per reorder-commit so an out-of-order PUT /priority response from a- // superseded drag can't overwrite the newest order.- const reorderSeq = React.useRef(0);// Guards event-handler async writes (refresh / connect) from landing after// the page unmounts — the whole class of stale-async writes the review flagged.+ //+ // The effect must re-arm the flag, not only clear it: an unmount-only cleanup+ // makes the guard one-way, and StrictMode's mount → cleanup → mount leaves it+ // false on a page that is very much alive. Every guarded write is then dropped+ // in silence — 查看更多 sticks on 加载中… forever because the `finally` that+ // clears it is guarded too. Found by clicking it in dev.const aliveRef = React.useRef(true);- React.useEffect(() => () => {- aliveRef.current = false;+ React.useEffect(() => {+ aliveRef.current = true;+ return () => {+ aliveRef.current = false;+ };}, []);+ const [refreshAuthority] = React.useState(() =>+ createLatestAsyncAuthority<[Source[], AgentSupply[]]>(([nextSources, nextAgents]) => {+ if (!aliveRef.current) return;+ setSources(nextSources);+ setAgents(nextAgents);+ }),+ );+React.useEffect(() => {let cancelled = false;setLoading(true);- Promise.all([modelsApi.listSources(), modelsApi.listAgents(), modelsApi.listEvents(20), modelsApi.getRuntimeStatus()])+ Promise.all([+ modelsApi.listSources(),+ modelsApi.listAgents(),+ modelsApi.listEvents(EVENT_PAGE),+ modelsApi.getRuntimeStatus(),+ ]).then(([s, a, e, r]) => {if (cancelled) return;setSources(s);setAgents(a);setEvents(e);+ setEventsExhausted(e.length < EVENT_PAGE);setRuntime(r);setLoading(false);})@@ -93,72 +156,51 @@ export const SettingsModelsPage: React.FC = () => {const refreshSourcesAgents = React.useCallback(async () => {try {- const [s, a] = await Promise.all([modelsApi.listSources(), modelsApi.listAgents()]);- if (!aliveRef.current) return;- setSources(s);- setAgents(a);+ await refreshAuthority.run(() => Promise.all([modelsApi.listSources(), modelsApi.listAgents()]));} catch {// A mutation may have succeeded server-side but the re-read failed — tell// the user the view might be stale rather than silently swallowing it.if (aliveRef.current) showToast(t('settings.models.toast.refreshFailed') as string, 'error');}- }, [showToast, t]);-- const reorderPreview = (ids: string[]) => {- setSources((prev) => {- const byId = new Map(prev.map((s) => [s.id, s]));- return ids.map((id) => byId.get(id)).filter((s): s is Source => Boolean(s));- });- };+ }, [refreshAuthority, showToast, t]);- const commitOrder = (order: string[]) => {- const seq = ++reorderSeq.current;- modelsApi- .putPriority(order)- .then((priority) => {- if (reorderSeq.current !== seq) return; // superseded by a newer reorder- // Re-echo the server's authoritative order.- setSources((prev) => {- const byId = new Map(prev.map((s) => [s.id, s]));- return priority.order.map((id) => byId.get(id)).filter((s): s is Source => Boolean(s));- });- })- .catch(() => {- if (reorderSeq.current !== seq) return;- showToast(t('settings.models.toast.reorderFailed') as string, 'error');- // The optimistic preview order diverged from the server; re-fetch so the- // list reflects the persisted (unchanged) order rather than a phantom one.- void refreshSourcesAgents();+ const loadOlderEvents = React.useCallback(async () => {+ const oldest = events[events.length - 1]?.id;+ if (!oldest) return;+ setLoadingEvents(true);+ try {+ const page = await modelsApi.listEvents(EVENT_PAGE, oldest);+ if (!aliveRef.current) return;+ // Merged by id rather than concatenated: the feed grows at the head while+ // we page from the tail, so an overlapping row is normal, not a bug.+ setEvents((prev) => {+ const seen = new Set(prev.map((e) => e.id));+ return [...prev, ...page.filter((e) => !seen.has(e.id))];});- };-- // Drag end: the ordered state has already been re-rendered by the preview- // callbacks, so the mirror ref holds the freshest order.- const reorderCommit = () => commitOrder(sourcesRef.current.map((s) => s.id));-- // Step reorder (the row menu's 上移/下移). Deliberately NOT preview-then-commit:- // the mirror ref is assigned during render, so a synchronous commit right after- // setSources would still read the pre-move order and persist it. Passing the- // order explicitly keeps both halves on the same value.- const reorderTo = (order: string[]) => {- reorderPreview(order);- commitOrder(order);- };+ setEventsExhausted(page.length < EVENT_PAGE);+ } catch {+ if (aliveRef.current) showToast(t('settings.models.toast.refreshFailed') as string, 'error');+ } finally {+ if (aliveRef.current) setLoadingEvents(false);+ }+ }, [events, showToast, t]);const connectHub = async (agent: AgentSupply) => {setConnecting(agent.backend);try {- // The PATCH echoes a fresh AgentSupply whose `current` is the honest- // "what the next turn uses" projection: it's null when the mode flipped to- // hub but no eligible+available source can supply — i.e. the launch would- // silently fall back to Direct. Report the true state, never a green lie.- const next = await modelsApi.setAgentMode(agent.backend, 'hub');+ // What the PATCH echo means is a rule, not an ad-hoc read of one field —+ // see connectOutcome, which exists because `current: null` conflates four+ // unrelated states and the copy behind it promised a Direct fallback the+ // resolver does not perform.+ const outcome = connectOutcome(await modelsApi.setAgentMode(agent.backend, 'hub'), sources);await refreshSourcesAgents();if (!aliveRef.current) return;- if (next.mode === 'hub' && next.current) {- showToast(t('settings.models.toast.connected') as string, 'success');+ if (outcome === 'failed') {+ showToast(t('settings.models.toast.connectFailed') as string, 'error');+ } else if (isSupplyWarning(outcome)) {+ showToast(t(`settings.models.supply.${outcome}`) as string, 'warning');} else {- showToast(t('settings.models.toast.connectedNoSupply') as string, 'warning');+ showToast(t('settings.models.toast.connected') as string, 'success');}} catch {if (aliveRef.current) showToast(t('settings.models.toast.connectFailed') as string, 'error');@@ -167,20 +209,21 @@ export const SettingsModelsPage: React.FC = () => {}};- // Resolve the open drawer's agent from live state so edits see fresh data.+ // Resolve an open drawer's agent from live state so edits see fresh data.const menuAgent = agents.find((a) => a.backend === menuBackend) ?? null;+ // AC-7: the 来源顺序 drawer exists for Hub-mode backends only. Gating here as+ // well as on the button means a mode flip while the drawer is open closes it,+ // instead of leaving an editor open over an order nothing reads.+ const orderAgent = agents.find((a) => a.backend === orderBackend && a.mode === 'hub') ?? null;- const hubCount = agents.filter((a) => a.mode === 'hub').length;- // Only a fully-ok runtime + no errored source is "一切正常"; degraded / down /- // not_installed / unknown all warrant the warning pill.- const healthy = runtime?.status.health === 'ok' && !sources.some((s) => s.state.status === 'error');+ const status = pageStatus(sources, agents, runtime);return (<SettingsPageShellactiveTab="models"title={t('settings.models.title')}subtitle={t('settings.models.subtitle')}- actions={!loading && !loadError ? <StatusPill healthy={healthy} hubCount={hubCount} /> : undefined}+ actions={!loading && !loadError ? <StatusPill status={status} /> : undefined}>{loading ? (<div className="text-[13px] text-muted">{t('common.loading')}</div>@@ -194,9 +237,6 @@ export const SettingsModelsPage: React.FC = () => {<MigrationBanner onApplied={() => void refreshSourcesAgents()} /><SourcesCardsources={sources}- onReorderPreview={reorderPreview}- onReorderCommit={reorderCommit}- onReorderTo={reorderTo}onConnectClaude={() => setOauthVendor('anthropic')}onConnectChatGPT={() => setOauthVendor('openai')}onAddApiKey={() => setApiKeyOpen(true)}@@ -206,10 +246,16 @@ export const SettingsModelsPage: React.FC = () => {agents={agents}sources={sources}onConnectHub={connectHub}- onOpenMenu={(agent) => setMenuBackend(agent.backend)}+ onOpenOrder={(agent) => setOrderBackend(agent.backend)}connectingBackend={connecting}/>- <RecentSwitchesCard events={events} />+ <RecentSwitchesCard+ events={events}+ sources={sources}+ hasMore={!eventsExhausted}+ loadingMore={loadingEvents}+ onLoadMore={() => void loadOlderEvents()}+ /><AdvancedRow /></div>)}@@ -222,6 +268,29 @@ export const SettingsModelsPage: React.FC = () => {onConnected={() => void refreshSourcesAgents()}/>+ {orderAgent && (+ <SourceOrderDrawer+ open+ agent={orderAgent}+ agents={agents}+ sources={sources}+ onClose={() => setOrderBackend(null)}+ onSaved={() => void refreshSourcesAgents()}+ // 模型菜单与映射 hands off to the menu drawer: the two answer adjacent+ // questions (which sources, which models), and V6 02's footer is the only+ // way into the menu now that the row's action is 来源顺序. Withheld while+ // the menus are flagged off, rather than opening onto nothing.+ onOpenMenu={+ MODEL_MENUS_ENABLED+ ? () => {+ setOrderBackend(null);+ setMenuBackend(orderAgent.backend);+ }+ : undefined+ }+ />+ )}+{menuAgent && menuAgent.menu_kind === 'open' ? (<OpenCodeMenuDraweropendiff --git a/ui/src/components/settings/models/SourceOrderDrawer.tsx b/ui/src/components/settings/models/SourceOrderDrawer.tsxnew file mode 100644index 000000000..4309eb23a--- /dev/null+++ b/ui/src/components/settings/models/SourceOrderDrawer.tsx@@ -0,0 +1,553 @@+// 来源顺序 · <Agent> — the per-Agent source order editor (design.pen 「产品改造+// V6 02」 desktop-custom, 「V6 03」 desktop-follow, 「V6 M02」 mobile).+//+// V6's central move: an order is a property of an AGENT, not of the source+// inventory. Each backend holds an ordered SUBSET of the eligible sources, so+// this drawer owns three groups — 启用 (the ordered subset, drag to reorder),+// 未启用 (eligible but left out), 不适用 (ineligible here, with the server's+// reason) — and the policy state machine behind them:+//+// follow 跟随推荐 server-computed order; a newly added source joins it+// custom 自定义 user-owned subset; new sources do NOT join it+//+// Any manual edit under `follow` forks to `custom` implicitly (that is what the+// user just did), and 恢复推荐顺序 goes back. Every edit persists immediately+// instead of batching behind 完成, unlike the sibling menu drawers: ● 当前 and+// 暂不可用 are server-derived, so a held draft would either show a stale head or+// force re-deriving §4.3's resolution in the UI to keep those pills honest.+// 完成 just closes.+//+// Reachable in Hub mode only (AC-7): a Direct backend has no Hub order, no chain+// and no probe, so the affordance is withdrawn rather than shown empty.+import * as React from 'react';+import { Reorder, useDragControls } from 'framer-motion';+import { ChevronRight, CirclePlus, GripVertical, List, WandSparkles, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { cn } from '@/lib/utils';+import { useIsMobile } from '@/lib/useIsMobile';+import { useToast } from '@/context/ToastContext';+import { initialSeedState, savedSourcesKey, seedStep } from './asyncLifetime';+import { CurrentChip, StateChip } from './chips';+import { eligibilityOf } from './eligibility';+import { cooldownEtaMinutes } from './format';+import { MenuDrawer } from './menus/MenuDrawer';+import { modelsApi } from './modelsApi';+import { movedOrder, sameIds } from './reorder';+import { orderSufficiency } from './sufficiency';+import { isUnhealthy, needsAttention } from './supply';+import { ACCENT_ICON, ACCENT_TILE, backendVisual, sourceVisual } from './vendorMeta';+import type { AgentSourcesPut, AgentSupply, Source, SourcePolicy } from './types';++// ── Row parts ───────────────────────────────────────────────────────────+//+// The three row shapes share one geometry so their tiles and names line up down+// the list: the leading column is a 16–18px glyph (grip / ⊕ / nothing) and the+// gaps do the rest, which reproduces the frames' 12→38→68 (phone) and+// 14→42→76→122 (desktop) columns exactly.+const ROW = 'flex items-center gap-2.5 rounded-xl border px-3 py-2.5 sm:gap-3 sm:px-3.5 sm:py-3';+const NUMBER =+ 'grid size-5 shrink-0 place-items-center rounded-md border border-border bg-foreground/[0.03] text-[10.5px] font-bold text-muted sm:size-[22px] sm:rounded-[7px] sm:text-[11px]';++const SourceTile: React.FC<{ source: Source }> = ({ source }) => {+ const { Icon, accent } = sourceVisual(source);+ return (+ <span+ className={cn(+ 'flex size-[30px] shrink-0 items-center justify-center rounded-[9px] sm:size-[34px] sm:rounded-[10px]',+ ACCENT_TILE[accent],+ )}+ >+ <Icon className={cn('size-3.5 sm:size-4', ACCENT_ICON[accent])} />+ </span>+ );+};++/**+ * Name over sub-line. Gold on the same predicate as the source list's sub-line+ * (`needsAttention`): one source cannot mean two different things on two surfaces,+ * and here the 暂不可用 pill already carries "not serving right now", so gold is+ * reserved for "and it needs you".+ */+const Identity: React.FC<{ name: string; subline: string; amber?: boolean }> = ({ name, subline, amber }) => (+ <span className="flex min-w-0 flex-1 flex-col gap-0.5 sm:gap-[3px]">+ <span className="truncate text-[13px] font-semibold text-foreground sm:text-[13.5px]">{name}</span>+ {subline && (+ <span className={cn('truncate text-[10px] sm:text-[11px]', amber ? 'text-gold' : 'text-muted')}>{subline}</span>+ )}+ </span>+);++const GroupHeader: React.FC<{ label: string; first?: boolean; children?: React.ReactNode }> = ({+ label,+ first,+ children,+}) => (+ <div className={cn('flex items-center justify-between gap-3 px-1 sm:pt-1', first ? 'pt-0.5 sm:pt-0' : 'pt-2')}>+ <span className="text-[10px] font-bold tracking-[1px] text-muted">{label}</span>+ {children}+ </div>+);++// ── Drawer ──────────────────────────────────────────────────────────────++export const SourceOrderDrawer: React.FC<{+ open: boolean;+ agent: AgentSupply;+ /** Every Agent's supply — read only to name the client a wrong-client+ * subscription DOES serve (see `sanctionedBackend`). */+ agents: AgentSupply[];+ sources: Source[];+ onClose: () => void;+ /** Re-read sources + agents: an order change moves ● 当前 on the page too. */+ onSaved: () => void;+ /** Desktop footer 模型菜单与映射 — hand off to this backend's menu drawer.+ * Omitted while the menus are flagged off. */+ onOpenMenu?: () => void;+}> = ({ open, agent, agents, sources, onClose, onSaved, onOpenMenu }) => {+ const { t } = useTranslation();+ const { showToast } = useToast();+ const { Icon, accent } = backendVisual(agent.backend);+ // The frames shorten three strings for the 390px sheet — the subtitle, the+ // 未启用 mapping note and the 跟随推荐中 badge — and at full length the first two+ // wrap to three lines and truncate mid-word respectively, so the shortening is+ // load-bearing rather than cosmetic. A JS branch, against `useIsMobile`'s own+ // advice to prefer responsive classes, because two of the three are composed+ // strings: the subtitle is a `string` prop of the shared shell, and the note is+ // one ` · `-joined segment of a sub-line. Rendering both variants would mean+ // duplicating the join, so the whole file takes its short copy from here.+ const mobile = useIsMobile();++ const [policy, setPolicy] = React.useState<SourcePolicy>(agent.sources?.policy ?? 'follow');+ const [order, setOrder] = React.useState<string[]>(agent.sources?.order ?? []);+ const [saving, setSaving] = React.useState(false);+ /** Last state the server confirmed — the revert target and the no-op test.+ * `order` alone can serve neither: a drag has already moved it by the time+ * the commit fires. */+ const saved = React.useRef<{ policy: SourcePolicy; order: string[] }>({ policy, order });++ // Seed from the saved order the server holds. `seedStep` owns *when*, because+ // when is the part that has to survive a save landing after the drawer that+ // issued it was closed and reopened — see asyncLifetime.ts.+ const seed = React.useRef(initialSeedState);+ const authoritative = savedSourcesKey(agent);+ React.useEffect(() => {+ if (!open) return;+ const step = seedStep(seed.current, authoritative);+ seed.current = step.state;+ if (!step.reseed) return;+ const next = { policy: agent.sources?.policy ?? 'follow', order: agent.sources?.order ?? [] };+ saved.current = next;+ setPolicy(next.policy);+ setOrder(next.order);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, authoritative]);++ const backendLabel = (backend: string) =>+ t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;+ const backendName = backendLabel(agent.backend);+ const byId = React.useMemo(() => new Map(sources.map((s) => [s.id, s])), [sources]);+ const builtins = React.useMemo(() => new Set(agent.builtin_models ?? []), [agent.builtin_models]);++ // Everything below is driven by `enabledSources` / `enabledIds` rather than by+ // `order` directly: an id in the order with no matching source (a row deleted+ // between the two reads) simply drops out, and the next commit persists the+ // pruned list — the same self-heal the server's own sync performs.+ const enabledSources = order.map((id) => byId.get(id)).filter((s): s is Source => s !== undefined);+ const enabledIds = enabledSources.map((s) => s.id);+ // Asked about the order the user is CURRENTLY editing, not about the saved one —+ // the warning is about what pressing 保存 would leave this backend with.+ const orderVerdict = orderSufficiency(order, sources);+ const rest = sources.filter((s) => !order.includes(s.id));+ const disabledSources = rest.filter((s) => eligibilityOf(agent, s.id).eligible);+ const ineligible = rest+ .map((source) => ({ source, ...eligibilityOf(agent, source.id) }))+ .filter((e) => !e.eligible);++ /**+ * Sub-line vocabulary (design.pen V6 02/03) — always at most two segments:+ *+ * 启用 `[email protected] · 供 Claude 全系`, `key …9c1 · 47 分后重试`+ * 未启用 `供 GLM 全系 · 经模型菜单改写后可供 Claude 使用`+ * 不适用 the server's eligibility reason, alone+ *+ * The 供 segment names a model FAMILY, which is a vendor label, so a source with+ * no family (a relay / custom endpoint) omits it rather than inventing one. The+ * mapping note is read off the payload — none of this backend's own built-in ids+ * is supplied here, so the source is only reachable through a 模型菜单 rewrite —+ * never from a UI-side guess about which vendor belongs to which backend, which+ * is the mirror this lane deletes.+ */+ const vendorLabel = (source: Source) =>+ t(`settings.models.addKey.vendors.${source.vendor}`, { defaultValue: source.vendor }) as string;+ const supplies = (source: Source) => {+ const family = t(`settings.models.order.family.${source.vendor}`, { defaultValue: '' }) as string;+ return family ? (t('settings.models.order.supplies', { family }) as string) : '';+ };+ const identity = (source: Source) => source.account_label ?? source.masked_credential ?? '';+ const join = (parts: (string | false)[]) => parts.filter(Boolean).join(' · ');++ const enabledSubline = (source: Source): string =>+ join([+ identity(source),+ // A cooling source spends its second segment on the ETA instead of the+ // family — the chip says 暂不可用, this says until when.+ source.state.status === 'cooldown'+ ? (t('settings.models.source.retryIn', { minutes: cooldownEtaMinutes(source.state.retry_at) }) as string)+ : isUnhealthy(source.state)+ ? ''+ : supplies(source),+ ]);++ const disabledSubline = (source: Source): string => {+ // Only a fixed-menu backend rewrites ids through mappings; the open-menu+ // backend picks a supplied id directly, so the note would be false there.+ const viaMapping =+ agent.menu_kind === 'fixed' && builtins.size > 0 && !source.models.some((m) => builtins.has(m.id));+ return viaMapping+ ? join([+ supplies(source),+ t(mobile ? 'settings.models.order.viaMappingShort' : 'settings.models.order.viaMapping', {+ backend: backendName,+ }) as string,+ ])+ : join([identity(source), supplies(source)]);+ };++ /**+ * The one OTHER backend this source may serve, or null when that isn't a single+ * definite answer. Read off the other Agents' server-published eligibility —+ * the vendor→sanctioned-client map is exactly the mirror this lane deleted, so+ * when the payload can't name the client the copy doesn't either.+ */+ const sanctionedBackend = (sourceId: string): string | null => {+ const owners = agents.filter((a) => a.backend !== agent.backend && eligibilityOf(a, sourceId).eligible);+ return owners.length === 1 ? backendLabel(owners[0].backend) : null;+ };++ const ineligibleSubline = (source: Source, reasonKey: string | null): string => {+ if (!reasonKey) {+ // A payload with no reason still grays the row out — better than offering an+ // 启用 the PUT would reject with `invalid_source_order`.+ return t('settings.models.order.ineligibleUnknown', { backend: backendName }) as string;+ }+ const vendor = vendorLabel(source);+ if (reasonKey === 'models.eligibility.subscription_wrong_client') {+ const client = sanctionedBackend(source.id);+ return client+ ? (t(reasonKey, { vendor, backend: client }) as string)+ : (t('settings.models.order.ineligibleClientUnknown', { vendor }) as string);+ }+ // The server's own i18n key (contract v3's closed vocabulary), rendered as-is.+ return t(reasonKey, { vendor }) as string;+ };++ /**+ * Persist one edit, showing it immediately and rolling back if the server+ * refuses. The echoed AgentSupply always wins over the optimistic guess: under+ * `follow` the server owns the order outright, so 恢复推荐顺序 learns the+ * recommended order from the response and nowhere else.+ *+ * Two edits in flight resolve last-write-wins, which is correct here because+ * every PUT carries the whole list rather than a delta.+ *+ * Runs to completion even if the drawer closes mid-flight, and deliberately so.+ * Both of the things this does on the way out belong to components that stay+ * mounted — `onSaved()` re-reads the page whose ● 当前 the write just moved, and+ * the failure toast lives at the app root — so a mounted-ref guard here would+ * not be protecting anything, it would be dropping the only report that a+ * rejected reorder ever gets. (The setState calls need no guard either: since+ * React 18 they are a no-op on an unmounted component, not a warning.)+ */+ const persist = async (body: AgentSourcesPut, next: { policy: SourcePolicy; order: string[] }) => {+ const previous = saved.current;+ setPolicy(next.policy);+ setOrder(next.order);+ setSaving(true);+ try {+ // No `contract_version` in the body — the route rejects unknown keys.+ const echoed = await modelsApi.putAgentSources(agent.backend, body);+ const adopted = {+ policy: echoed.sources?.policy ?? next.policy,+ order: echoed.sources?.order ?? next.order,+ };+ saved.current = adopted;+ setPolicy(adopted.policy);+ setOrder(adopted.order);+ onSaved();+ } catch {+ saved.current = previous;+ setPolicy(previous.policy);+ setOrder([...previous.order]);+ showToast(t('settings.models.toast.reorderFailed') as string, 'error');+ } finally {+ setSaving(false);+ }+ };++ // Any manual edit is a fork to `custom`: the user just said which sources, in+ // which order — that is the definition of a user-owned subset.+ //+ // Which makes the no-op test policy-INDEPENDENT, because `follow` is the policy+ // that has something to lose. Both edit paths can arrive here having changed+ // nothing: `movedOrder` returns the list untouched at either boundary, and a drag+ // can land back where it started. Forking a backend off the server's+ // recommendation because someone pressed ArrowUp on row 1 is a silent, invisible+ // consequence for an input that did nothing.+ const commitOrder = (nextOrder: string[]) => {+ if (sameIds(saved.current.order, nextOrder)) {+ // Still re-seat local state: a drag has already moved `order` past the saved+ // list by the time this fires, and the row it dropped on must snap back.+ setOrder([...saved.current.order]);+ return;+ }+ void persist({ policy: 'custom', order: nextOrder }, { policy: 'custom', order: nextOrder });+ };++ const restoreRecommended = () => void persist({ policy: 'follow' }, { policy: 'follow', order });++ return (+ <MenuDrawer+ open={open}+ onClose={onClose}+ Icon={Icon}+ accent={accent}+ title={t('settings.models.order.title', { backend: backendName }) as string}+ subtitle={+ t(mobile ? 'settings.models.order.subtitleShort' : 'settings.models.order.subtitle', {+ backend: backendName,+ }) as string+ }+ footer={+ <>+ <div className="flex min-w-0 items-center gap-2.5">+ {/* 恢复推荐顺序 lives in the 启用 group header on desktop (V6 02) and+ in the footer on phones (M02), where that header has no room. */}+ {policy === 'custom' && (+ <Button+ variant="secondary"+ className="h-[46px] rounded-xl px-4 text-[13px] font-semibold text-muted sm:hidden"+ onClick={restoreRecommended}+ disabled={saving}+ >+ {t('settings.models.order.restore')}+ </Button>+ )}+ {/* Desktop home for 模型菜单与映射 (V6 02's footer). The phone's home is+ the row at the end of the list — M02 gives this footer to 恢复推荐+ 顺序 + 完成, and there is no width where the flow may be missing. */}+ {onOpenMenu && (+ <Button variant="outline" size="sm" className="hidden sm:inline-flex" onClick={onOpenMenu}>+ <List className="size-3.5" />+ {t('settings.models.order.openMenu')}+ </Button>+ )}+ </div>+ <Button+ variant="brand"+ size="sm"+ className="h-[46px] flex-1 rounded-xl text-[13.5px] sm:h-9 sm:flex-none sm:rounded-[10px] sm:px-[18px] sm:text-[12.5px]"+ onClick={onClose}+ >+ {t('settings.models.menus.done')}+ </Button>+ </>+ }+ >+ <div className="flex flex-col gap-2 sm:gap-2.5">+ <GroupHeader label={t('settings.models.order.groupEnabled', { count: enabledIds.length }) as string} first>+ {policy === 'custom' ? (+ <button+ type="button"+ onClick={restoreRecommended}+ disabled={saving}+ className="hidden shrink-0 text-[12px] font-semibold text-cyan transition-colors hover:text-cyan/80 disabled:opacity-50 sm:inline"+ >+ {t('settings.models.order.restore')}+ </button>+ ) : (+ <Badge variant="info" className="shrink-0 gap-1 py-1 text-[10px] font-semibold sm:gap-1.5 sm:text-[11px]">+ <WandSparkles className="size-2.5 sm:size-3" />+ {/* The phone frame drops the trailing clause for width, not meaning. */}+ {t(mobile ? 'settings.models.order.following' : 'settings.models.order.followingLong')}+ </Badge>+ )}+ </GroupHeader>++ {orderVerdict.kind === 'adopted_none' ? (+ // V6 doesn't draw this state, but emptying the list is a legal thing to+ // ask for (§4.4: an omitted id IS 未启用) — an unexplained empty area+ // would be worse than one line saying what it means.+ <p className="rounded-xl border border-gold/40 bg-gold/[0.08] px-3.5 py-3 text-[12.5px] leading-relaxed text-gold">+ {t('settings.models.order.enabledEmpty', { backend: backendName })}+ </p>+ ) : (+ <Reorder.Group axis="y" values={enabledIds} onReorder={setOrder} className="flex list-none flex-col gap-2 sm:gap-2.5">+ {orderVerdict.kind === 'nothing_runnable' && (+ // A full list is not a working list. Each row already carries its own+ // state chip, but reading five 暂不可用 chips and concluding 「so the+ // next turn fails」 is the user doing the rollup by hand — and the row+ // that says it is the one nobody reads, because the list looks fine.+ <li className="list-none rounded-xl border border-gold/40 bg-gold/[0.08] px-3.5 py-3 text-[12.5px] leading-relaxed text-gold">+ {t('settings.models.order.enabledNoneRunnable', { backend: backendName })}+ </li>+ )}+ {enabledSources.map((source, index) => (+ <EnabledRow+ key={source.id}+ source={source}+ index={index}+ isCurrent={agent.current?.source_id === source.id}+ subline={enabledSubline(source)}+ busy={saving}+ onCommit={() => commitOrder(enabledIds)}+ onMove={(delta) => commitOrder(movedOrder(enabledIds, index, delta))}+ onRemove={() => commitOrder(enabledIds.filter((id) => id !== source.id))}+ />+ ))}+ </Reorder.Group>+ )}++ {disabledSources.length > 0 && (+ <>+ <GroupHeader label={t('settings.models.order.groupDisabled', { count: disabledSources.length }) as string} />+ {disabledSources.map((source) => (+ // The whole row enables the source: on a phone the frame's 44×28+ // button is a mis-tap, and "enable this source" is one intent, so the+ // row is the control and the pill is its label (no nested button).+ <button+ key={source.id}+ type="button"+ aria-label={t('settings.models.order.enableAria', { name: source.display_name }) as string}+ onClick={() => commitOrder([...enabledIds, source.id])}+ disabled={saving}+ className={cn(ROW, 'w-full border-border text-left opacity-85 transition hover:opacity-100 disabled:opacity-50')}+ >+ <CirclePlus className="size-[17px] shrink-0 text-mint sm:size-[18px]" aria-hidden />+ <SourceTile source={source} />+ <Identity name={source.display_name} subline={disabledSubline(source)} />+ <span className="shrink-0 rounded-lg border border-border-strong bg-card px-3 py-1.5 text-[11px] font-semibold text-foreground sm:text-[11.5px]">+ {t('settings.models.order.enable')}+ </span>+ </button>+ ))}+ </>+ )}++ {ineligible.length > 0 && (+ <>+ <GroupHeader label={t('settings.models.order.groupIneligible', { count: ineligible.length }) as string} />+ {ineligible.map(({ source, reasonKey }) => (+ <div key={source.id} className={cn(ROW, 'border-border opacity-[0.55]')}>+ <SourceTile source={source} />+ <Identity name={source.display_name} subline={ineligibleSubline(source, reasonKey)} />+ </div>+ ))}+ </>+ )}++ {/* The phone's home for 模型菜单与映射. A frame that doesn't draw a control+ at 390px is saying where to move it, not that a phone user may not+ have it — the two configuration surfaces answer adjacent questions+ (which sources, which models) and this drawer is the only way into+ the second one now that the Agent row's action is 来源顺序. */}+ {onOpenMenu && (+ <Button+ variant="outline"+ className="mt-1 h-[46px] w-full justify-between rounded-xl px-4 text-[13px] font-semibold sm:hidden"+ onClick={onOpenMenu}+ >+ <span className="flex items-center gap-2">+ <List className="size-4" />+ {t('settings.models.order.openMenu')}+ </span>+ <ChevronRight className="size-4 text-muted" />+ </Button>+ )}+ </div>+ </MenuDrawer>+ );+};++const EnabledRow: React.FC<{+ source: Source;+ index: number;+ isCurrent: boolean;+ subline: string;+ busy: boolean;+ /** Drag ended — persist whatever order the list settled into. */+ onCommit: () => void;+ /** Keyboard path beside drag; the grip is a real button, not a decoration. */+ onMove: (delta: -1 | 1) => void;+ onRemove: () => void;+}> = ({ source, index, isCurrent, subline, busy, onCommit, onMove, onRemove }) => {+ const { t } = useTranslation();+ const controls = useDragControls();++ return (+ <Reorder.Item+ value={source.id}+ dragListener={false}+ dragControls={controls}+ onDragEnd={onCommit}+ className={cn(+ ROW,+ 'list-none',+ isCurrent ? 'border-mint/35 bg-mint/[0.03]' : 'border-border',+ )}+ >+ {/* Disabled while a PUT is in flight, like every other control in this+ drawer — and for a sharper reason than symmetry. Both reorder paths land+ in the same `persist`, which holds ONE `saved.current` and captures its+ own rollback: two overlapping writes let the older echo replace the+ newer order, or a late failure roll back past a write that succeeded.+ One handle carries both paths, so gating it closes both. */}+ <button+ type="button"+ aria-label={t('settings.models.source.reorder') as string}+ aria-keyshortcuts="ArrowUp ArrowDown"+ disabled={busy}+ onPointerDown={(e) => controls.start(e)}+ onKeyDown={(e) => {+ if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;+ e.preventDefault();+ onMove(e.key === 'ArrowUp' ? -1 : 1);+ }}+ className="relative flex size-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted/55 transition-colors hover:text-muted active:cursor-grabbing disabled:cursor-default disabled:opacity-50"+ >+ <GripVertical className="size-4" />+ {/* A 16px handle is unhittable with a thumb. A real child box (not a+ pseudo-element, which takes no pointer events) grows the target to+ 40×40 on phones without moving the glyph off the frame's column. */}+ <span className="absolute -inset-3 sm:hidden" aria-hidden />+ </button>++ <span className={NUMBER}>{index + 1}</span>+ <SourceTile source={source} />+ <Identity name={source.display_name} subline={subline} amber={needsAttention(source.state)} />++ {isCurrent ? <CurrentChip /> : <StateChip state={source.state} />}++ {/* 取消启用 is one of the two things this drawer exists for, so it can't be+ desktop-only — M02 drew the row without a ✕, but a frame omitting a+ control is not the product deciding phones may not use it. The mis-tap+ worry is answered where mis-taps happen: an enlarged hit box that stops+ well clear of the grip at the row's other end, and an action that only+ moves the source down to 未启用 (re-add is one tap away). */}+ <button+ type="button"+ aria-label={t('settings.models.order.disable') as string}+ onClick={onRemove}+ disabled={busy}+ className="relative flex size-6 shrink-0 items-center justify-center rounded-md text-muted/60 transition-colors hover:bg-surface-2 hover:text-foreground disabled:opacity-50"+ >+ <X className="size-4" />+ <span className="absolute -inset-2 sm:hidden" aria-hidden />+ </button>+ </Reorder.Item>+ );+};++export default SourceOrderDrawer;diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsxindex 742c04f9b..b0ace8066 100644--- a/ui/src/components/settings/models/SourceRow.tsx+++ b/ui/src/components/settings/models/SourceRow.tsx@@ -1,17 +1,20 @@-// One row of the 来源 list (frame 01r): drag handle · priority number · icon +-// name/mono-sub (supply tooltip on hover) · fixed-width usage column · billing-// chip · state chip. Presentation-only; drag + reorder live in SourcesCard.+// One row of the 来源 list (design.pen 「产品改造 V6 01」): icon + name/mono-sub+// (supply tooltip on hover) · fixed-width usage column · billing chip · state+// column · overflow menu. Presentation-only.//-// Mobile (< sm): the frame's single aligned row cannot hold eight columns in+// V6 removed the drag handle and the priority number: a source is an asset here,+// and ordering is a per-Agent property that lives in the 来源顺序 drawer. The+// state column is still reserved on sm+ even though a healthy source draws no+// chip in V6, so the billing column stays aligned down the list.+//+// Mobile (< sm): the frame's single aligned row cannot hold that many columns in// 390px — it squeezed the name to zero width and pushed the state chip and the// row menu off-screen entirely (clipped, not scrollable, so unreachable). So the// row stacks into two tiers per design.pen M01 (m01SrcL1 / m01SrcL2): identity +// the row menu on top, then billing · state · usage on a single second line,-// inset 26px so it starts under the priority number. The sm+ layout is-// byte-for-byte the desktop frame, so the fixed-width chip columns still align-// down the list.+// indented to match the frame. The sm+ layout is byte-for-byte the desktop+// frame, so the fixed-width chip columns still align down the list.import * as React from 'react';-import { GripVertical } from 'lucide-react';import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';@@ -20,26 +23,41 @@ import { SupplyTooltip } from './SupplyTooltip';import { SourceRowMenu } from './SourceRowMenu';import { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, sourceVisual } from './vendorMeta';import { cooldownEtaMinutes, formatSpend } from './format';+import { isUnhealthy, needsAttention } from './supply';import type { Source } from './types';// The mono sub-line shows the source identity: account_label (subscriptions)// or masked_credential (api keys) — both server-provided display data (contract// v1.1, 07-23, from the L4 finding). Falls back to the supply channel / endpoint// (原生供给 / 中枢托管 / 官方地址 / 自定义地址) when neither is set, e.g. hub-held-// experimental sources before a later adapter rev. Cooldown ETA is appended.+// experimental sources before a later adapter rev.+//+// A custom endpoint is named even when an identity exists (V6 01's relay row+// reads `key …9c1 · 自定义地址 · 47 分后重试`): a relay is a materially different+// thing to route through, while 官方地址 / 原生供给 / 中枢托管 beside an identity+// is just noise.+//+// An unhealthy source appends WHY and (when it heals itself) WHEN, which is the+// whole of V6 04's amber sub-line 「[email protected] · 本周期额度用完 · 明天 08:00+// 恢复」. `detail_key` is already a full i18n key in the frozen contract, so it+// is translated as-is — the UI never maps upstream text to copy of its own.function useSubline(source: Source): string {const { t } = useTranslation();- const fallback =+ const customEndpoint = source.kind === 'api_key' && isCustomEndpoint(source);+ const channel =source.kind === 'subscription'? source.supply_channel === 'native_cli'? (t('settings.models.source.nativeSupply') as string): (t('settings.models.source.hubHosted') as string)- : isCustomEndpoint(source)+ : customEndpoint? (t('settings.models.source.customEndpoint') as string): (t('settings.models.source.officialEndpoint') as string);- const parts = [source.account_label ?? source.masked_credential ?? fallback];+ const identity = source.account_label ?? source.masked_credential ?? null;+ const parts = identity ? [identity] : [channel];+ if (identity && customEndpoint) parts.push(channel);+ if (isUnhealthy(source.state) && source.state.detail_key) parts.push(t(source.state.detail_key) as string);if (source.state.status === 'cooldown') {parts.push(t('settings.models.source.retryIn', { minutes: cooldownEtaMinutes(source.state.retry_at) }) as string);}@@ -50,7 +68,7 @@ function useSubline(source: Source): string {// (design.pen M01 m01Use: fill_container + justify end), which also puts it after// the chips — hence `order-last`. On sm+ it reverts to the desktop frame's// leading fixed-width column.-const USAGE_CELL = 'order-last flex-1 sm:order-none sm:w-[150px] sm:flex-none';+const USAGE_CELL = 'order-last flex-1 sm:order-none sm:w-[130px] sm:flex-none';const UsageCell: React.FC<{ source: Source }> = ({ source }) => {const { t } = useTranslation();@@ -58,40 +76,50 @@ const UsageCell: React.FC<{ source: Source }> = ({ source }) => {const spend = source.usage?.month_spend_cents;if (source.billing === 'monthly' && typeof pct === 'number') {+ const clamped = Math.min(100, Math.max(0, pct));return (<div className={cn(USAGE_CELL, 'flex items-center justify-end gap-2')}>- <div className="h-1.5 w-14 overflow-hidden rounded-full bg-border sm:w-[92px]">- <div className="h-full rounded-full bg-mint" style={{ width: `${Math.min(100, Math.max(0, pct))}%` }} />+ <div className="h-[5px] w-14 overflow-hidden rounded-[3px] bg-foreground/[0.07] sm:w-16">+ {/* Gold at a full cycle: the bar itself carries the 「用完了」 the amber+ sub-line spells out, so a glance down the column finds it. */}+ <div+ className={cn('h-full rounded-[3px]', clamped >= 100 ? 'bg-gold' : 'bg-mint')}+ style={{ width: `${clamped}%` }}+ /></div>- <span className="text-right font-mono text-[10.5px] text-muted sm:w-9 sm:text-[12px]">{Math.round(pct)}%</span>+ <span className="w-8 text-right font-mono text-[10.5px] text-muted sm:text-[11px]">{Math.round(pct)}%</span></div>);}if (typeof spend === 'number') {return (- <div className={cn(USAGE_CELL, 'truncate text-right font-mono text-[10.5px] text-muted sm:font-sans sm:text-[12px]')}>+ <div className={cn(USAGE_CELL, 'truncate text-right font-mono text-[10.5px] text-muted sm:text-[11px]')}>{t('settings.models.usage.monthSpend', { amount: formatSpend(spend, source.usage?.currency) })}</div>);}// No usage data: on mobile the chips just stay left-aligned, so the spacer only// exists to hold the desktop column open.- return <div className="hidden sm:block sm:w-[150px] sm:shrink-0" />;+ return <div className="hidden sm:block sm:w-[130px] sm:shrink-0" />;};+// V6 draws a state chip only when the source is NOT serving normally, so the+// healthy majority of rows stays quiet. The column is still held open on sm+ —+// otherwise the one cooling row would push its own billing chip 86px left of+// every other row's.+const StateCell: React.FC<{ source: Source }> = ({ source }) => (+ // sm:ml-1.5 is the 6px the frame gets from right-aligning an 86px chip inside a+ // 92px column — spent as a margin here so the row keeps one flat flex line.+ <div className={cn('sm:ml-1.5 sm:w-[86px] sm:shrink-0', !isUnhealthy(source.state) && 'hidden sm:block')}>+ <StateChip state={source.state} />+ </div>+);+export const SourceRow: React.FC<{source: Source;- priority: number;- onDragHandlePointerDown: (e: React.PointerEvent) => void;- /** False at the ends of the list — the matching menu action is disabled. */- canMoveUp: boolean;- canMoveDown: boolean;- /** Keyboard/screen-reader path for reordering; drag stays the primary one. */- onMove: (delta: -1 | 1) => void;/** Re-fetch after a row action (rename / re-discover / delete). */onChanged: () => void;-}> = ({ source, priority, onDragHandlePointerDown, canMoveUp, canMoveDown, onMove, onChanged }) => {- const { t } = useTranslation();+}> = ({ source, onChanged }) => {const { Icon, accent } = sourceVisual(source);const subline = useSubline(source);const isExperimental = source.kind === 'subscription' && source.supply_channel === 'hub';@@ -102,68 +130,55 @@ export const SourceRow: React.FC<{// sm+, which no amount of CSS can do if it lives inside one of two sibling// containers. So identity / menu / metrics are siblings here and `order`// rearranges them per breakpoint — one menu instance, one set of dialogs.- <div className="group flex flex-wrap items-center gap-x-2.5 gap-y-2.5 border-b border-border px-4 py-3 last:border-b-0 sm:flex-nowrap sm:gap-x-3 sm:px-5 sm:py-3.5">+ <div className="group flex flex-wrap items-center gap-x-2.5 gap-y-2.5 border-b border-border px-4 py-3 last:border-b-0 sm:flex-nowrap sm:gap-x-3.5 sm:px-5 sm:py-3">{/* Identity — the leading segment on both breakpoints. */}- <div className="order-1 flex min-w-0 flex-1 items-center gap-2.5 sm:gap-3">- <button- type="button"- aria-label={t('settings.models.source.reorder') as string}- onPointerDown={onDragHandlePointerDown}- // 40px touch target on phones (the 24px desktop handle is unhittable- // with a thumb); the glyph size is unchanged.- className="flex size-10 shrink-0 cursor-grab touch-none items-center justify-center rounded text-muted/50 transition-colors hover:text-muted active:cursor-grabbing sm:size-6"- >- <GripVertical className="size-4" />- </button>-- <span className="grid size-[22px] shrink-0 place-items-center rounded-[7px] border border-border bg-surface font-mono text-[11px] font-bold text-muted sm:size-7 sm:rounded-md sm:text-[13px] sm:font-normal">- {priority}- </span>-- <SupplyTooltip models={source.models} className="flex min-w-0 flex-1 items-center gap-2.5 sm:gap-3">- <span className={cn('flex size-[34px] shrink-0 items-center justify-center rounded-[10px] sm:size-11', ACCENT_TILE[accent])}>- <Icon className={cn('size-[18px] sm:size-[22px]', ACCENT_ICON[accent])} />+ <div className="order-1 flex min-w-0 flex-1 items-center gap-2.5 sm:gap-3.5">+ <SupplyTooltip models={source.models} className="flex min-w-0 flex-1 items-center gap-2.5 sm:gap-3.5">+ <span className={cn('flex size-[34px] shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>+ <Icon className={cn('size-4', ACCENT_ICON[accent])} /></span>- <span className="flex min-w-0 flex-col gap-0.5">+ <span className="flex min-w-0 flex-col gap-0.5 sm:gap-[3px]"><span className="flex min-w-0 items-center gap-2">- <span className="truncate text-[13.5px] font-semibold text-foreground sm:text-[15px]">{source.display_name}</span>+ <span className="truncate text-[13.5px] font-semibold text-foreground">{source.display_name}</span>{isExperimental && <ExperimentalChip />}</span>- <span className="truncate font-mono text-[10.5px] text-muted sm:text-[12px]">{subline}</span>+ {/* Gold when the outage is waiting on a person (V6 04's exhausted+ subscription), muted when it will heal on its own (V6 01's timed-out+ relay) — see `needsAttention`. */}+ <span+ className={cn(+ 'truncate font-mono text-[10.5px] sm:text-[11px]',+ needsAttention(source.state) ? 'text-gold' : 'text-muted',+ )}+ >+ {subline}+ </span></span></SupplyTooltip></div>- {/* Metric / state strip — a full-width second line on phones, inset 26px- (handle glyph + gap) so it starts under the priority number; the aligned- desktop chip columns on sm+.+ {/* Metric / state strip — a full-width second line on phones, indented to+ the V6 M01 frame's second tier; the aligned desktop chip columns on sm+.flex-wrap here is the safety net, not the plan: measured at 360/390/430in both locales every row stays on one line, including the widest Englishcombination ("$3.2 this month" · "Metered $" · "Cooling down"). It stayswrap-capable so an unusually long future state label degrades to twolines instead of clipping. sm:flex-nowrap keeps the desktop row- single-line. */}- <div className="order-3 flex w-full flex-wrap items-center gap-x-2 gap-y-2 pl-[26px] sm:order-2 sm:w-auto sm:shrink-0 sm:flex-nowrap sm:gap-4 sm:pl-0">+ single-line.++ The desktop gaps are the frame's uniform 14px row gap (sm:gap-3.5 here+ and on the row itself), with the 6px each pill is inset by right-aligning+ it in its wider column spent as an sm:ml-1.5 on the pill. */}+ <div className="order-3 flex w-full flex-wrap items-center gap-x-2 gap-y-2 pl-[26px] sm:order-2 sm:w-auto sm:shrink-0 sm:flex-nowrap sm:gap-3.5 sm:pl-0"><UsageCell source={source} />- <BillingChip billing={source.billing} currency={source.usage?.currency} />- <StateChip state={source.state} />+ <BillingChip billing={source.billing} currency={source.usage?.currency} className="sm:ml-1.5" />+ <StateCell source={source} /></div>{/* Thumb-reachable on the identity line on phones (design.pen M01 m01More,- 36×36 on the handle/priority axis); trailing the desktop row on sm+.- sm:ml-1 restores the desktop frame's 16px gap before the menu — it used- to come from the metrics strip's own gap-4, and the row's gap-3 alone- pulled every chip column 4px right of the reviewed desktop layout- (caught by diffing the rendered geometry against master). */}- <div className="order-2 shrink-0 sm:order-3 sm:ml-1">- <SourceRowMenu- source={source}- priority={priority}- canMoveUp={canMoveUp}- canMoveDown={canMoveDown}- onMove={onMove}- onChanged={onChanged}- />+ 36×36), trailing the desktop row on sm+. */}+ <div className="order-2 shrink-0 sm:order-3">+ <SourceRowMenu source={source} onChanged={onChanged} /></div></div>);diff --git a/ui/src/components/settings/models/SourceRowMenu.tsx b/ui/src/components/settings/models/SourceRowMenu.tsxindex e896cc374..9f0990a64 100644--- a/ui/src/components/settings/models/SourceRowMenu.tsx+++ b/ui/src/components/settings/models/SourceRowMenu.tsx@@ -1,19 +1,20 @@-// Per-row lifecycle actions for the 来源 list (frame 01r): an overflow menu that-// stays out of the way (hidden until row hover / focus on desktop) and exposes-// the contracted source mutations the list otherwise couldn't reach — rename-// (PATCH), re-discover (POST /test, hub sources only), reorder by one step, and-// delete (DELETE, with the only-supplier guard escalating to a forced delete).-// Presentation lives in SourceRow; this owns the actions + their dialogs so the-// row stays declarative.+// Per-row lifecycle actions for the 来源 list (design.pen 「产品改造 V6 01」): an+// overflow menu that stays out of the way (hidden until row hover / focus on+// desktop) and exposes the contracted source mutations the list otherwise+// couldn't reach — rename (PATCH), re-discover (POST /test, hub sources only),+// and delete (DELETE, with the only-supplier guard escalating to a forced+// delete). Presentation lives in SourceRow; this owns the actions + their+// dialogs so the row stays declarative.+//+// No reorder actions: in V6 an order belongs to an Agent, not to the source+// inventory, so 上移/下移 moved into the per-Agent 来源顺序 drawer (which keeps a+// keyboard/screen-reader path of its own alongside drag).//// On phones the menu presents as a bottom sheet (design.pen M02 m02SheetA) with// the row's identity in the header and a one-line rationale under each action,-// because a thumb menu has no hover to explain itself. 上移一位 / 下移一位 live-// here rather than as a visible button column: drag is the primary reordering-// gesture, and these exist so the same thing is reachable by keyboard and screen-// reader.+// because a thumb menu has no hover to explain itself.import * as React from 'react';-import { ArrowDown, ArrowUp, MoreHorizontal, Pencil, RefreshCw, Trash2 } from 'lucide-react';+import { MoreHorizontal, Pencil, RefreshCw, Trash2 } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';@@ -63,13 +64,9 @@ const MenuAction: React.FC<{export const SourceRowMenu: React.FC<{source: Source;- priority: number;- canMoveUp: boolean;- canMoveDown: boolean;- onMove: (delta: -1 | 1) => void;/** Re-fetch sources + agents after any successful mutation. */onChanged: () => void;-}> = ({ source, priority, canMoveUp, canMoveDown, onMove, onChanged }) => {+}> = ({ source, onChanged }) => {const { t } = useTranslation();const { showToast } = useToast();const isMobile = useIsMobile();@@ -85,9 +82,15 @@ export const SourceRowMenu: React.FC<{const [forceMode, setForceMode] = React.useState(false);const [testing, setTesting] = React.useState(false);+ // Re-armed on mount, not only cleared on unmount: a cleanup-only guard is+ // one-way, so StrictMode's mount → cleanup → mount would leave every 测试+ // result and delete outcome silently discarded on a live menu.const aliveRef = React.useRef(true);- React.useEffect(() => () => {- aliveRef.current = false;+ React.useEffect(() => {+ aliveRef.current = true;+ return () => {+ aliveRef.current = false;+ };}, []);// Re-discovery only applies to hub sources; native_cli subscriptions are@@ -136,11 +139,6 @@ export const SourceRowMenu: React.FC<{}};- const move = (delta: -1 | 1) => {- setMenuOpen(false);- onMove(delta);- };-const openDelete = () => {setMenuOpen(false);setForceMode(false);@@ -190,7 +188,6 @@ export const SourceRowMenu: React.FC<{<span className="truncate text-[15px] font-bold text-foreground">{source.display_name}</span><span className="truncate text-[12px] text-muted">{[- t('settings.models.sourceActions.priorityLabel', { position: priority }),t(`settings.models.state.${source.state.status}`),t(`settings.models.billing.${source.billing}`),].join(' · ')}@@ -235,20 +232,6 @@ export const SourceRowMenu: React.FC<{onClick={() => void rediscover()}/>)}- <MenuAction- Icon={ArrowUp}- label={t('settings.models.sourceActions.moveUp') as string}- description={hint(canMoveUp ? 'moveUpHint' : 'moveUpHintAtTop', { position: priority })}- onClick={() => move(-1)}- disabled={!canMoveUp}- />- <MenuAction- Icon={ArrowDown}- label={t('settings.models.sourceActions.moveDown') as string}- description={hint(canMoveDown ? 'moveDownHint' : 'moveDownHintAtBottom')}- onClick={() => move(1)}- disabled={!canMoveDown}- /><MenuActionIcon={Trash2}label={t('settings.models.sourceActions.delete') as string}diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsxindex d907fc233..f5a3cdb6d 100644--- a/ui/src/components/settings/models/SourcesCard.tsx+++ b/ui/src/components/settings/models/SourcesCard.tsx@@ -1,82 +1,33 @@-// The 来源 band (frame 01r): header (policy sub-line + 添加来源 menu) over a-// drag-to-reorder priority list. Fully controlled — the ordered `sources` and-// the reorder handlers live in the page, so this card holds no derived state.-// Drag is restricted to each row's handle via framer-motion drag controls.+// The 来源 band (design.pen 「产品改造 V6 01」): header (asset sub-line + 添加来源+// menu) over a plain inventory list. Fully controlled — `sources` comes from the+// page and this card holds no derived state.+//+// V6 turned this card into a pure asset inventory: identity · usage · billing ·+// health, and nothing else. Ordering is no longer a property of a source, it is a+// property of an Agent (a per-backend ordered subset), so the drag handle, the+// priority number and the one-step move actions moved into the per-Agent 来源顺序+// drawer. The list order here is whatever the server returns.//// Mobile header (design.pen M01 m01SrcHead): the title block and 添加来源 stack// instead of competing for one line, with 添加来源 as a full-width primary// button — at 360px the side-by-side desktop header squeezed the sub-line to two// or three lines and left the button a cramped tap target.import * as React from 'react';-import { Reorder, useDragControls } from 'framer-motion';import { useTranslation } from 'react-i18next';import { AddSourceMenu } from './AddSourceMenu';import { SourceRow } from './SourceRow';-import { movedOrder } from './reorder';import type { Source } from './types';-const SourceReorderItem: React.FC<{- source: Source;- priority: number;- canMoveUp: boolean;- canMoveDown: boolean;- onMove: (delta: -1 | 1) => void;- onCommit: () => void;- onChanged: () => void;-}> = ({ source, priority, canMoveUp, canMoveDown, onMove, onCommit, onChanged }) => {- const controls = useDragControls();- return (- <Reorder.Item- value={source.id}- dragListener={false}- dragControls={controls}- onDragEnd={onCommit}- className="list-none bg-background"- >- <SourceRow- source={source}- priority={priority}- onDragHandlePointerDown={(e) => controls.start(e)}- canMoveUp={canMoveUp}- canMoveDown={canMoveDown}- onMove={onMove}- onChanged={onChanged}- />- </Reorder.Item>- );-};-export const SourcesCard: React.FC<{sources: Source[];- /** Fires continuously during drag with the new id order (visual only). */- onReorderPreview: (orderedIds: string[]) => void;- /** Fires on drag end — persist the current order. */- onReorderCommit: () => void;- /** Preview + persist an explicit order (the row menu's one-step reorder). */- onReorderTo: (orderedIds: string[]) => void;onConnectClaude: () => void;onConnectChatGPT: () => void;onAddApiKey: () => void;/** Re-fetch after a per-row action (rename / re-discover / delete). */onSourceChanged: () => void;-}> = ({- sources,- onReorderPreview,- onReorderCommit,- onReorderTo,- onConnectClaude,- onConnectChatGPT,- onAddApiKey,- onSourceChanged,-}) => {+}> = ({ sources, onConnectClaude, onConnectChatGPT, onAddApiKey, onSourceChanged }) => {const { t } = useTranslation();- const ids = sources.map((s) => s.id);-- const moveByOneStep = (index: number, delta: -1 | 1) => {- const next = movedOrder(ids, index, delta);- onReorderTo(next);- };return (// Not overflow-hidden: the row supply tooltip must escape the card bounds.@@ -93,23 +44,14 @@ export const SourcesCard: React.FC<{/></div>- {ids.length === 0 ? (+ {sources.length === 0 ? (<div className="px-4 py-12 text-center sm:px-5 text-[13px] text-muted">{t('settings.models.sources.empty')}</div>) : (- <Reorder.Group axis="y" values={ids} onReorder={onReorderPreview} className="flex flex-col">- {sources.map((source, index) => (- <SourceReorderItem- key={source.id}- source={source}- priority={index + 1}- canMoveUp={index > 0}- canMoveDown={index < sources.length - 1}- onMove={(delta) => moveByOneStep(index, delta)}- onCommit={onReorderCommit}- onChanged={onSourceChanged}- />+ <div className="flex flex-col">+ {sources.map((source) => (+ <SourceRow key={source.id} source={source} onChanged={onSourceChanged} />))}- </Reorder.Group>+ </div>)}</section>);diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.tsnew file mode 100644index 000000000..0405eec71--- /dev/null+++ b/ui/src/components/settings/models/asyncLifetime.test.ts@@ -0,0 +1,278 @@+// Two interleavings that shipped broken, both of the same shape: an async arrival+// changed what the user sees without first checking the state the arrival landed+// in. They are pinned here as sequences, because neither is reachable from a+// single call — only from a specific ORDER of calls.+//+// 1. close-during-PUT, reopen-before-land. The drawer saves, the user closes it+// (which unmounts it) and reopens it before the PUT lands, so it seeds from+// props that still carry the pre-save order. When the PUT does land and the+// refetch delivers the new saved order, the reopened drawer keeps showing the+// old one — and its next edit diffs against that stale snapshot and writes the+// old order back, silently undoing the save the user already saw succeed.+//+// 2. late-poll-after-settle. The connect dialog reaches success, and the poll+// request already in flight comes back `verifying`. The flow the dialog shows+// is replaced by a non-terminal one, so a connect that succeeded renders as+// still running — and the same hole in the deadline branch stamps `failed`+// over a success once the timeout passes.+import { describe, expect, it } from 'vitest';++import {+ createFlowAuthority,+ createLatestAsyncAuthority,+ flowStep,+ initialSeedState,+ isDone,+ savedMappingsKey,+ savedMenuKey,+ savedSourcesKey,+ seedStep,+ type FlowView,+} from './asyncLifetime';+import type { AgentSupply, OAuthFlow } from './types';++const agent = (over: Partial<AgentSupply> = {}): AgentSupply => ({+ backend: 'claude',+ mode: 'hub',+ menu_kind: 'fixed',+ sources: { policy: 'custom', order: ['src_a', 'src_b'] },+ ...over,+});++const flow = (state: OAuthFlow['state']): OAuthFlow => ({+ flow_id: 'oaf_1',+ vendor: 'anthropic',+ channel: 'native_cli',+ state,+ presentation: { auth_url: null, device_code: null, expects: 'none', instructions_key: null },+});++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+};++describe('latest async authority', () => {+ it('drops an older refresh that lands after the newer refresh', async () => {+ const older = deferred<string>();+ const newer = deferred<string>();+ const landed: string[] = [];+ const authority = createLatestAsyncAuthority<string>((value) => landed.push(value));++ const olderRun = authority.run(() => older.promise);+ const newerRun = authority.run(() => newer.promise);++ newer.resolve('server order: b,a');+ await newerRun;+ older.resolve('server order: a,b');+ await olderRun;++ expect(landed).toEqual(['server order: b,a']);+ });+});++describe('savedSourcesKey / savedMappingsKey / savedMenuKey', () => {+ it('moves when the saved state moves', () => {+ expect(savedSourcesKey(agent({ sources: { policy: 'custom', order: ['src_b', 'src_a'] } }))).not.toBe(+ savedSourcesKey(agent()),+ );+ expect(savedSourcesKey(agent({ sources: { policy: 'follow', order: ['src_a', 'src_b'] } }))).not.toBe(+ savedSourcesKey(agent()),+ );+ });++ it('holds still across a refetch that changed nothing', () => {+ // The whole point of comparing content: a background page refresh rebuilds+ // every object, and an inert refresh must stay inert.+ expect(savedSourcesKey(agent())).toBe(savedSourcesKey(agent()));+ });++ it('cannot be spoofed by an id that contains the separator', () => {+ expect(savedSourcesKey(agent({ sources: { policy: 'custom', order: ['src_a src_b'] } }))).not.toBe(+ savedSourcesKey(agent()),+ );+ });++ it('reads the mapping overrides and the menu the drawers seed from', () => {+ const base = agent({ mappings: [{ builtin_id: 'claude-opus-4-6', target_model_id: 'm1', enabled: true }] });+ expect(savedMappingsKey(base)).not.toBe(+ savedMappingsKey(agent({ mappings: [{ builtin_id: 'claude-opus-4-6', target_model_id: 'm1', enabled: false }] })),+ );+ expect(savedMenuKey({ view: 'featured', checked: ['zhipuai/glm-5.2'] })).not.toBe(+ savedMenuKey({ view: 'full', checked: ['zhipuai/glm-5.2'] }),+ );+ expect(savedMenuKey(null)).toBe(savedMenuKey({ view: 'featured', checked: [] }));+ });+});++describe('seedStep', () => {+ it('seeds the drawer once on open', () => {+ const { state, reseed } = seedStep(initialSeedState, savedSourcesKey(agent()));+ expect(reseed).toBe(true);+ expect(state.baseline).toBe(savedSourcesKey(agent()));+ });++ it('ignores a refetch that did not move the saved state', () => {+ // This is the rule the fix must not break: a background refresh must never+ // discard an edit the user is in the middle of making.+ const opened = seedStep(initialSeedState, savedSourcesKey(agent())).state;+ expect(seedStep(opened, savedSourcesKey(agent())).reseed).toBe(false);+ });++ it('re-seats a drawer reopened before its own save landed', () => {+ // Interleaving 1. Saved order is [a, b]; the user drags to [b, a], the PUT+ // goes out, the drawer is closed and reopened while it is still in flight —+ // so it seeds from the pre-save props — and only then does the save land and+ // the refetch deliver [b, a]. Whatever the drawer is holding at that point+ // came from a snapshot the server has since replaced.+ const stale = savedSourcesKey(agent({ sources: { policy: 'custom', order: ['src_a', 'src_b'] } }));+ const landed = savedSourcesKey(agent({ sources: { policy: 'custom', order: ['src_b', 'src_a'] } }));++ const reopened = seedStep(initialSeedState, stale).state;+ const after = seedStep(reopened, landed);++ expect(after.reseed).toBe(true);+ expect(after.state.baseline).toBe(landed);+ });++ it('re-seats only once per move, so a redundant refetch stays inert', () => {+ const landed = savedSourcesKey(agent({ sources: { policy: 'custom', order: ['src_b', 'src_a'] } }));+ const reseated = seedStep(seedStep(initialSeedState, savedSourcesKey(agent())).state, landed).state;+ expect(seedStep(reseated, landed).reseed).toBe(false);+ });+});++describe('flowStep', () => {+ const fresh: FlowView = { flow: null, errorKey: null, settled: false };++ it('keeps polling while the flow is running', () => {+ const step = flowStep(fresh, { kind: 'response', flow: flow('awaiting_action') });+ expect(step.action).toBe('continue');+ expect(isDone(step.action)).toBe(false);+ expect(step.view.flow?.state).toBe('awaiting_action');+ });++ it('reports the first success once', () => {+ const step = flowStep(fresh, { kind: 'response', flow: flow('success') });+ expect(step.action).toBe('succeed');+ expect(step.view.errorKey).toBeNull();+ expect(step.view.settled).toBe(true);+ expect(flowStep(step.view, { kind: 'response', flow: flow('success') }).action).toBe('ignore');+ });++ it('discards a poll that comes back non-terminal after success', () => {+ // Interleaving 2. The request in flight when success landed resolves next,+ // carrying the state the server held BEFORE it completed the flow. Showing it+ // turns a finished connect back into a running one.+ const settled = flowStep(fresh, { kind: 'response', flow: flow('success') }).view;+ const late = flowStep(settled, { kind: 'response', flow: flow('verifying') });++ expect(late.action).toBe('ignore');+ expect(late.view.flow?.state).toBe('success');+ expect(late.view.settled).toBe(true);+ });++ it('discards a late failure after success', () => {+ const settled = flowStep(fresh, { kind: 'response', flow: flow('success') }).view;+ const late = flowStep(settled, { kind: 'response', flow: flow('failed') });+ expect(late.action).toBe('ignore');+ expect(late.view.flow?.state).toBe('success');+ });++ it('does not let the deadline overwrite a settled flow', () => {+ // Same hole, other entry point: the dialog stays open after success (nothing+ // adopted the source, so there is no auto-close), the deadline passes, and the+ // tick stamps `failed` over a connect that succeeded.+ const settled = flowStep(fresh, { kind: 'response', flow: flow('success') }).view;+ const tick = flowStep(settled, { kind: 'tick', overdue: true });++ expect(tick.action).toBe('ignore');+ expect(tick.view.flow?.state).toBe('success');+ });++ it('still times out a flow that never finished', () => {+ const running = flowStep(fresh, { kind: 'response', flow: flow('awaiting_action') }).view;+ const tick = flowStep(running, { kind: 'tick', overdue: true });+ expect(tick.action).toBe('timeout');+ expect(tick.view.flow?.state).toBe('failed');+ expect(tick.view.errorKey).toBe('settings.models.oauth.error.timeout');+ expect(isDone(tick.action)).toBe(true);+ });++ it('leaves an unfinished flow alone before the deadline', () => {+ const running = flowStep(fresh, { kind: 'response', flow: flow('awaiting_action') }).view;+ expect(flowStep(running, { kind: 'tick', overdue: false })).toEqual({ view: running, action: 'continue' });+ });++ it('settles on a failure and ignores what follows it', () => {+ const failed = flowStep(fresh, { kind: 'response', flow: flow('cancelled') });+ expect(failed.action).toBe('fail');+ expect(failed.view.errorKey).toBe('settings.models.oauth.error.generic');+ expect(failed.view.settled).toBe(true);+ expect(flowStep(failed.view, { kind: 'response', flow: flow('success') }).action).toBe('ignore');+ });+});++describe('flow authority', () => {+ it('ignores a poll flow_not_found that lands after success settled', () => {+ const authority = createFlowAuthority(() => {});++ authority.transition({ kind: 'response', flow: flow('verifying') });+ authority.transition({ kind: 'response', flow: flow('success') });+ const latePoll = authority.transition({+ kind: 'error',+ errorKey: 'settings.models.oauth.error.generic',+ });++ expect(latePoll.action).toBe('ignore');+ expect(authority.current()).toEqual({+ flow: expect.objectContaining({ state: 'success' }),+ errorKey: null,+ settled: true,+ });+ });++ it('ignores a paste rejection that lands after success settled', () => {+ const authority = createFlowAuthority(() => {});++ authority.transition({ kind: 'response', flow: flow('awaiting_action') });+ authority.transition({ kind: 'response', flow: flow('success') });+ const latePaste = authority.transition({+ kind: 'error',+ errorKey: 'settings.models.oauth.error.finalize',+ });++ expect(latePaste.action).toBe('ignore');+ expect(authority.current()).toEqual({+ flow: expect.objectContaining({ state: 'success' }),+ errorKey: null,+ settled: true,+ });+ });++ it('keeps the deadline terminal when a paste success resolves afterward', () => {+ const landed: FlowView[] = [];+ const authority = createFlowAuthority((view) => landed.push(view));+ let connected = 0;++ authority.transition({ kind: 'response', flow: flow('success') });+ authority.transition({ kind: 'reset' });+ authority.transition({ kind: 'response', flow: flow('awaiting_action') });+ const timeout = authority.transition({ kind: 'tick', overdue: true });+ const latePaste = authority.transition({ kind: 'response', flow: flow('success') });+ if (latePaste.action === 'succeed') connected += 1;++ expect(timeout.action).toBe('timeout');+ expect(latePaste.action).toBe('ignore');+ expect(connected).toBe(0);+ expect(authority.current()).toEqual({+ flow: expect.objectContaining({ state: 'failed' }),+ errorKey: 'settings.models.oauth.error.timeout',+ settled: true,+ });+ expect(landed.at(-1)).toEqual(authority.current());+ });+});diff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.tsnew file mode 100644index 000000000..aecff6503--- /dev/null+++ b/ui/src/components/settings/models/asyncLifetime.ts@@ -0,0 +1,170 @@+// Async ownership rules extracted from the Models components so interleavings can+// be exercised directly: which request may land, when a drawer re-seeds, and+// whether a connect-flow transition may change an already terminal view.+import type { AgentMenu, AgentSupply, OAuthFlow } from './types';++// ── Latest async result ────────────────────────────────────────────────────+/**+ * Owns request ordering and the only path that may land a result. Callers start+ * reads; they never reconstruct whether a response is still current.+ */+export const createLatestAsyncAuthority = <T>(land: (value: T) => void) => {+ let latestRequest = 0;++ return {+ run: async (read: () => Promise<T>): Promise<'landed' | 'stale'> => {+ const request = ++latestRequest;+ try {+ const value = await read();+ if (request !== latestRequest) return 'stale';+ land(value);+ return 'landed';+ } catch (error) {+ if (request !== latestRequest) return 'stale';+ throw error;+ }+ },+ };+};++// ── The drawers' seed ──────────────────────────────────────────────────────+// A drawer seeds its editable state from the server's saved state, and needs to+// know when that saved state MOVED. Comparing the props object is useless (every+// page refresh builds a new one), so each drawer reduces the fields it seeds from+// to a signature and compares that. The separator is NUL because these parts are+// ids: a separator that cannot occur inside one is what keeps ['a','b'] from+// colliding with ['a b'].+const sig = (parts: readonly (string | number | boolean)[]): string => parts.join('\u0000');++/** 来源顺序 drawer: the per-backend policy + ordered subset it edits. */+export const savedSourcesKey = (agent: AgentSupply): string =>+ sig([agent.sources?.policy ?? 'follow', ...(agent.sources?.order ?? [])]);++/** 映射 drawer: the stored overrides its draft is seeded from. */+export const savedMappingsKey = (agent: AgentSupply): string =>+ sig((agent.mappings ?? []).flatMap((m) => [m.builtin_id, m.target_model_id, m.enabled]));++/** OpenCode 模型菜单 drawer: the stored view + checked identifiers. */+export const savedMenuKey = (menu: AgentMenu | null | undefined): string =>+ sig([menu?.view ?? 'featured', ...(menu?.checked ?? [])]);++/** What a drawer remembers about the saved state it last seeded from. */+export type SeedState = { seeded: boolean; baseline: string | null };++export const initialSeedState: SeedState = { seeded: false, baseline: null };++/**+ * Whether a drawer holding `state` must re-seat itself now that the server's+ * saved state reads `authoritative`.+ *+ * Seeds on open, and again whenever the saved state MOVED under it. Keying on+ * open alone is not enough: the page unmounts a drawer when it closes, so a+ * drawer closed and reopened while its own PUT is in flight seeds from the+ * pre-save props and then never learns that the save landed — and its next edit+ * diffs against that superseded snapshot and writes the old state back over the+ * save the user already saw succeed.+ *+ * A refetch that changed nothing is still inert, which is the whole reason this+ * compares content rather than the props object: that is what protects an edit in+ * flight from a background page refresh. When the saved state genuinely moved,+ * re-seating is the only honest option — a draft built on a base the server has+ * replaced can only be written back as a regression.+ */+export const seedStep = (state: SeedState, authoritative: string): { state: SeedState; reseed: boolean } => {+ if (state.seeded && state.baseline === authoritative) return { state, reseed: false };+ return { state: { seeded: true, baseline: authoritative }, reseed: true };+};++// ── The OAuth dialog's terminal ordering ───────────────────────────────────+/**+ * Every way flow state can reach the connect dialog. A `tick` is the dialog's+ * own deadline check; `reset` starts a new attempt from an unsettled view.+ */+export type FlowEvent =+ | { kind: 'reset' }+ | { kind: 'error'; errorKey: string }+ | { kind: 'response'; flow: OAuthFlow }+ | { kind: 'tick'; overdue: boolean };++/**+ * What the caller must DO about an event. The side effects (toast, refetch,+ * auto-close, stop polling) stay in the component; only the decision lives here.+ *+ * continue not finished, keep polling+ * succeed first terminal success: fire the connected side effects, once+ * fail first terminal failure: show the authority-owned error+ * timeout the deadline passed with the flow unfinished+ * ignore stale arrival — the dialog already finished+ */+export type FlowAction = 'continue' | 'succeed' | 'fail' | 'timeout' | 'ignore';++/** Everything that decides what the dialog shows, including its terminal latch. */+export type FlowView = { flow: OAuthFlow | null; errorKey: string | null; settled: boolean };++export const initialFlowView: FlowView = { flow: null, errorKey: null, settled: false };++export const flowStep = (view: FlowView, event: FlowEvent): { view: FlowView; action: FlowAction } => {+ if (event.kind === 'reset') return { view: { ...initialFlowView }, action: 'continue' };+ // Nothing gets to change a finished flow — checked before the event is read, so+ // it holds for EVERY entry point (a poll still in flight when success landed, a+ // paste submit racing that poll, and the deadline tick, which used to stamp+ // `failed` over a success on a dialog left open because nothing adopted the+ // source).+ if (view.settled) return { view, action: 'ignore' };+ if (event.kind === 'error') {+ return { view: { flow: view.flow, errorKey: event.errorKey, settled: true }, action: 'fail' };+ }+ if (event.kind === 'tick') {+ if (!event.overdue) return { view, action: 'continue' };+ return {+ view: {+ flow: view.flow ? { ...view.flow, state: 'failed' } : null,+ errorKey: 'settings.models.oauth.error.timeout',+ settled: true,+ },+ action: 'timeout',+ };+ }+ const flow = event.flow;+ if (flow.state === 'success') return { view: { flow, errorKey: null, settled: true }, action: 'succeed' };+ // `settled` means terminal, not successful: a failed flow is just as finished,+ // and a later arrival has just as little business reopening it.+ if (flow.state === 'failed' || flow.state === 'cancelled') {+ return {+ view: {+ flow,+ errorKey: flow.error_key ?? 'settings.models.oauth.error.generic',+ settled: true,+ },+ action: 'fail',+ };+ }+ return { view: { flow, errorKey: null, settled: false }, action: 'continue' };+};++export type FlowAuthority = {+ current: () => FlowView;+ transition: (event: FlowEvent) => ReturnType<typeof flowStep>;+};++/**+ * Owns the complete view, including its terminal latch, and is the only path+ * that may land a new one. Keeping only `flow` at the landing site would let a+ * caller silently drop `settled` and reopen an already terminal flow.+ */+export const createFlowAuthority = (land: (view: FlowView) => void): FlowAuthority => {+ let current: FlowView = { ...initialFlowView };++ return {+ current: () => current,+ transition: (event) => {+ const step = flowStep(current, event);+ current = step.view;+ land(current);+ return step;+ },+ };+};++/** Whether an action ends the flow, so the caller stops polling. */+export const isDone = (action: FlowAction): boolean => action !== 'continue';diff --git a/ui/src/components/settings/models/chips.tsx b/ui/src/components/settings/models/chips.tsxindex 5ea6f7e13..222fcfd5b 100644--- a/ui/src/components/settings/models/chips.tsx+++ b/ui/src/components/settings/models/chips.tsx@@ -3,7 +3,7 @@// 来源 and Agent bands stay visually consistent and the fixed-width chip// columns (frame 01r) align across rows.import * as React from 'react';-import { FlaskConical, Hourglass, Zap } from 'lucide-react';+import { FlaskConical, Hourglass, TriangleAlert, Unplug, Zap } from 'lucide-react';import { Badge } from '@/components/ui/badge';import { cn } from '@/lib/utils';@@ -13,7 +13,7 @@ import { currencySymbol } from './format';import { ACCENT_DOT, type Accent } from './vendorMeta';import type { AgentMode, SourceState } from './types';-/** Status dot used in the composite pill and the 最近切换 list. */+/** Status dot used in the ● 当前 chip and the 最近切换 list. */export const Dot: React.FC<{ accent: Accent; className?: string }> = ({ accent, className }) => (<span className={cn('inline-block size-1.5 shrink-0 rounded-full', ACCENT_DOT[accent], className)} aria-hidden />);@@ -26,7 +26,7 @@ export const Dot: React.FC<{ accent: Accent; className?: string }> = ({ accent,* still align down the list, which is the whole point of them on a wide screen.*/const CHIP_MOBILE = 'rounded-full py-1';-const BILLING_CHIP = cn(CHIP_MOBILE, 'font-medium sm:w-16 sm:justify-center');+const BILLING_CHIP = cn(CHIP_MOBILE, 'font-medium sm:w-[58px] sm:justify-center');/*** 包月 / 按量 $ — content-width on phones, fixed-width column on sm+.@@ -37,21 +37,22 @@ const BILLING_CHIP = cn(CHIP_MOBILE, 'font-medium sm:w-16 sm:justify-center');* format.ts's single map, never hand-written here; an unmappable code drops the* symbol rather than printing a wrong one (the amount cell carries the truth).*/-export const BillingChip: React.FC<{ billing: 'monthly' | 'metered'; currency?: string | null }> = ({- billing,- currency,-}) => {+export const BillingChip: React.FC<{+ billing: 'monthly' | 'metered';+ currency?: string | null;+ className?: string;+}> = ({ billing, currency, className }) => {const { t } = useTranslation();if (billing === 'monthly') {return (- <Badge variant="secondary" className={cn(BILLING_CHIP, 'sm:rounded-md')}>+ <Badge variant="secondary" className={cn(BILLING_CHIP, 'bg-foreground/[0.03]', className)}>{t('settings.models.billing.monthly')}</Badge>);}const symbol = currencySymbol(currency);return (- <Badge variant="warning" className={cn(BILLING_CHIP, 'sm:rounded-md')}>+ <Badge variant="warning" className={cn(BILLING_CHIP, className)}>{symbol? t('settings.models.billing.meteredWithSymbol', { symbol }): t('settings.models.billing.metered')}@@ -59,18 +60,19 @@ export const BillingChip: React.FC<{ billing: 'monthly' | 'metered'; currency?:);};-/** 使用中 / 备用 / 暂不可用 / 不可用 — fixed-width aligned column. */+/**+ * 暂不可用 / 需要处理 / 不可用 — nothing at all while the source is healthy.+ *+ * A source that is serving normally (active / standby) draws NO chip in V6:+ * health surfaces as an exception, not as a per-row label (design.pen 「产品改造+ * V6 01」 — only the cooling relay carries one). Callers that reserve an aligned+ * column ask `isUnhealthy(state)` (supply.ts) to tell an empty cell from a+ * missing one.+ */export const StateChip: React.FC<{ state: SourceState }> = ({ state }) => {const { t } = useTranslation();const base = cn(CHIP_MOBILE, 'sm:w-[86px] sm:justify-center');switch (state.status) {- case 'active':- return (- <Badge variant="success" className={base}>- <Dot accent="mint" />- {t('settings.models.state.active')}- </Badge>- );case 'cooldown':return (<Badge variant="warning" className={base}>@@ -78,32 +80,61 @@ export const StateChip: React.FC<{ state: SourceState }> = ({ state }) => {{t('settings.models.state.cooldown')}</Badge>);+ case 'needs_action':+ return (+ <Badge variant="warning" className={base}>+ <TriangleAlert className="size-3" />+ {t('settings.models.state.needs_action')}+ </Badge>+ );case 'error':return (<Badge variant="destructive" className={base}>{t('settings.models.state.error')}</Badge>);+ case 'active':case 'standby':default:- return (- <Badge variant="secondary" className={base}>- {t('settings.models.state.standby')}- </Badge>- );+ return null;}};-/** 中枢 Hub / 直连 Direct — sized to sit beside the row's action button. */+/**+ * ● 当前 — the source this Agent is resolved onto right now (§4.3), which is a+ * per-Agent fact: the same source is 当前 for one backend and merely enabled for+ * another. Sits in the state chip's column, and the two are mutually exclusive by+ * construction — a source that isn't serving normally can't be the current one.+ */+export const CurrentChip: React.FC = () => {+ const { t } = useTranslation();+ return (+ <Badge variant="success" className={cn(CHIP_MOBILE, 'text-[10px] sm:text-[11px]')}>+ <Dot accent="mint" />+ {t('settings.models.current')}+ </Badge>+ );+};++/**+ * 中枢 Hub / 直连 Direct — a fixed 104px column on desktop so the pills line up+ * down the Agent list (V6 01), content-width beside the name on a phone (M01).+ *+ * Direct carries the `unplug` glyph on mobile only: the desktop frame drops it+ * because the pill sits in a labelled column, while the mobile row has it inline+ * next to the Agent name where a bare word reads as part of the title.+ */export const ModeChip: React.FC<{ mode: AgentMode }> = ({ mode }) => {const { t } = useTranslation();+ const base = 'h-[26px] rounded-full px-2.5 text-[11px] sm:w-[104px] sm:justify-center';return mode === 'hub' ? (- <Badge variant="success" className="h-8 gap-1.5 rounded-lg px-3 text-[12px]">- <Zap className="size-3.5" />+ <Badge variant="success" className={cn(base, 'font-bold')}>+ <Zap className="size-3 sm:size-[11px]" />{t('settings.models.mode.hub')}</Badge>) : (- <Badge variant="secondary" className="h-8 gap-1.5 rounded-lg px-3 text-[12px]">+ <Badge variant="secondary" className={cn(base, 'bg-foreground/[0.03]')}>+ <Unplug className="size-3 sm:hidden" />{t('settings.models.mode.direct')}</Badge>);@@ -120,20 +151,3 @@ export const ExperimentalChip: React.FC = () => {);};-/**- * Agent-card composite pill: `left | ● right` (UI, not copy). Fixed-menu- * backends show `model | ● source`; the open-menu backend shows- * `N 个模型 | ● 多来源…`.- */-export const CompositePill: React.FC<{ left: string; dot: Accent; right: string }> = ({ left, dot, right }) => (- // max-w-full + truncating halves: on a phone the model id would otherwise wrap- // to three lines and blow the Agent row's height open.- <div className="inline-flex max-w-full items-center gap-2.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[13px]">- <span className="truncate font-mono font-medium text-foreground">{left}</span>- <span className="h-3.5 w-px shrink-0 bg-border-strong" aria-hidden />- <span className="inline-flex min-w-0 items-center gap-1.5 text-muted">- <Dot accent={dot} />- <span className="truncate">{right}</span>- </span>- </div>-);diff --git a/ui/src/components/settings/models/contractLocaleKeys.test.ts b/ui/src/components/settings/models/contractLocaleKeys.test.tsnew file mode 100644index 000000000..40fb1c4db--- /dev/null+++ b/ui/src/components/settings/models/contractLocaleKeys.test.ts@@ -0,0 +1,118 @@+// AC-19, mechanically: the frozen contracts publish closed vocabularies of i18n+// keys (eligibility reasons, source detail keys), and this page renders them+// as-is. So the locale files must hold a string for EVERY member of every such+// enum — checked against the schemas themselves, not against a hand-copied list,+// because a hand-copied list is the drift it is meant to prevent.+//+// The extension rule this enforces: a new cause ships its enum member (L1's+// schema) and its locale copy (L4's `ui/src/i18n/*.json`) in the same change.+import { readdirSync, readFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import en from '../../../i18n/en.json';+import zh from '../../../i18n/zh.json';++const CONTRACTS = resolve(dirname(fileURLToPath(import.meta.url)), '../../../../..', 'docs/plans/model-hub-contracts');++/**+ * Every `models.*` i18n key the given schema documents declare.+ *+ * Both ways a schema can close a vocabulary count: `enum` for a set, and `const`+ * for the degenerate one-member set. JSON Schema treats `const: X` as exactly+ * `enum: [X]`, so reading only `enum` silently skips whole branches — today+ * `source.schema.json` pins the `error` status's `detail_key` with a `const`.+ *+ * Takes its input rather than reading the directory itself, so the collector can+ * be checked against a fixture: a coverage test whose own collector is wrong+ * reports coverage it never had.+ */+export function collectKeys(schemas: unknown[]): string[] {+ const keys = new Set<string>();+ const add = (member: unknown) => {+ if (typeof member === 'string' && member.startsWith('models.')) keys.add(member);+ };+ const walk = (node: unknown) => {+ if (Array.isArray(node)) {+ node.forEach(walk);+ return;+ }+ if (!node || typeof node !== 'object') return;+ for (const [prop, value] of Object.entries(node as Record<string, unknown>)) {+ if (prop === 'enum' && Array.isArray(value)) value.forEach(add);+ if (prop === 'const') add(value);+ walk(value);+ }+ };+ schemas.forEach(walk);+ return [...keys].sort();+}++function contractKeys(): string[] {+ return collectKeys(+ readdirSync(CONTRACTS)+ .filter((f) => f.endsWith('.schema.json'))+ .map((f) => JSON.parse(readFileSync(join(CONTRACTS, f), 'utf8'))),+ );+}++const lookup = (bundle: unknown, key: string): unknown =>+ key.split('.').reduce<unknown>((node, part) => {+ if (!node || typeof node !== 'object') return undefined;+ return (node as Record<string, unknown>)[part];+ }, bundle);++describe('contract i18n key coverage (AC-19)', () => {+ const keys = contractKeys();++ it('reads a non-trivial vocabulary out of the frozen schemas', () => {+ // Guards the check itself: a broken path or a renamed contract directory+ // would otherwise make every assertion below pass over an empty list.+ expect(keys).toContain('models.eligibility.subscription_wrong_client');+ expect(keys).toContain('models.eligibility.opencode_api_key_only');+ expect(keys).toContain('models.eligibility.consent_required');+ // Declared by a `const` in source.schema.json — today ALSO by probe-result's+ // enum, which is why the enum-only collector still covered it. Asserting it+ // here keeps the coverage from silently depending on that coincidence.+ expect(keys).toContain('models.source.error.unclassified');+ expect(keys.length).toBeGreaterThanOrEqual(13);+ });++ it('collects a key a schema closes with `const`, not only with `enum`', () => {+ // The forward guard, on a fixture rather than on today's schemas: a single+ // status branch pinned with `const` is a complete one-member vocabulary, and+ // the enum-only collector reported such a key as "not declared" — i.e. it+ // passed while the bundles had no copy for it.+ const fixture = {+ properties: {+ state: {+ allOf: [+ { then: { properties: { detail_key: { const: 'models.source.error.fixture_only' } } } },+ { then: { properties: { detail_key: { enum: ['models.source.cooldown.fixture_enum'] } } } },+ ],+ },+ },+ // Non-`models.` constants stay out; this collects contract vocabularies,+ // not every string literal in a schema.+ examples: [{ notes_key: { const: 'settings.models.source.nativeSupply' } }],+ };+ expect(collectKeys([fixture])).toEqual([+ 'models.source.cooldown.fixture_enum',+ 'models.source.error.fixture_only',+ ]);+ });++ it.each(['zh', 'en'] as const)('translates every declared key in %s', (lng) => {+ const bundle = lng === 'zh' ? zh : en;+ const missing = keys.filter((k) => typeof lookup(bundle, k) !== 'string' || lookup(bundle, k) === '');+ expect(missing).toEqual([]);+ });++ it('keeps the two locales on the same key set', () => {+ const enOnly = keys.filter((k) => typeof lookup(en, k) === 'string' && typeof lookup(zh, k) !== 'string');+ const zhOnly = keys.filter((k) => typeof lookup(zh, k) === 'string' && typeof lookup(en, k) !== 'string');+ expect({ enOnly, zhOnly }).toEqual({ enOnly: [], zhOnly: [] });+ });+});diff --git a/ui/src/components/settings/models/copyAgreement.test.ts b/ui/src/components/settings/models/copyAgreement.test.tsnew file mode 100644index 000000000..3f8d47838--- /dev/null+++ b/ui/src/components/settings/models/copyAgreement.test.ts@@ -0,0 +1,81 @@+// A redline over English grammatical number, wherever copy interpolates a QUANTITY.+//+// Round 7 reported 「{{names}} has no supply」: `formatNameList` joins any number of+// Agents into one placeholder, so two of them render 「agent-a, agent-b has no+// supply」. Chinese needs no agreement, which is why the zh bundle these strings were+// translated from reads correctly and the English silently did not.+//+// The reported string was not the class. The same page also wrote 「{{count}} agents+// have no supply」, which breaks at the MOST common count — one. So the rule below is+// TOTAL rather than a list of known-bad keys; that is the only way it catches copy+// that does not exist yet. Two shapes, two scopes:+//+// 1. a list placeholder in front of a singular verb — checked over the WHOLE+// bundle, because no string anywhere passes a joined list to a singular verb.+// 2. `{{count}}` in front of a plural noun — checked over `settings.models`, this+// page's own copy, with no allowances. The wider bundle has a long-standing+// 「{{count}} items」 habit across File Browser, Vaults, Skills and Chat;+// rewriting forty strings on other surfaces is not this lane's change to make,+// so the rule stops at the page boundary rather than carrying an exception list.+//+// Neither shape is fixed with a plural key. This bundle has no `_one`/`_other` keys+// at all, and adding them would mean dead `_one` entries in zh (whose plural rule has+// only `other`) — a trap for the next translator, and a break of the zh/en key+// correspondence that `supplyCopyRedline.test.ts` guards. `attribution.unassigned`+// and `order.groupDisabled` already show the cheaper answer that this file enforces:+// word it so the subject's number stops mattering.+import { describe, expect, it } from 'vitest';++import en from '../../../i18n/en.json';++/** Placeholders a join can fill with more than one item. */+const LIST_PLACEHOLDER = /\{\{(?:names|models|agents|sources|backends|list|skipped)\}\}/;++/**+ * A list placeholder used as the subject of a verb that only agrees with ONE thing.+ * Auxiliaries and copulas only: a general third-person `-s` rule would also match+ * plural nouns, and a check that cries wolf gets deleted.+ */+const SINGULAR_VERB =+ /\{\{(?:names|models|agents|sources|backends|list|skipped)\}\}\s+(?:has|is|was|does|hasn't|isn't|wasn't|doesn't)\b/i;++/**+ * `{{count}}` followed by a noun that has already committed to plural.+ *+ * `{{count}} model(s)` passes on purpose: it is correct at every count, and it is+ * what the rest of this subtree already writes (`migration.applied`,+ * `sourceActions.rediscovered`, `migrationBanner.body`).+ */+const PLURAL_NOUN = /\{\{count\}\}\s+(?:more\s+)?[a-z]+s\b/i;++type Leaf = { key: string; text: string };++const leaves = (node: unknown, path: string[] = []): Leaf[] =>+ typeof node === 'string'+ ? [{ key: path.join('.'), text: node }]+ : node && typeof node === 'object'+ ? Object.entries(node as Record<string, unknown>).flatMap(([k, v]) => leaves(v, [...path, k]))+ : [];++describe('English copy agrees with the number of things it interpolates', () => {+ const all = leaves(en);+ const models = leaves(en.settings.models);++ it('walks a non-trivial bundle, so the rules have something to check', () => {+ // Guards the walks themselves: a renamed namespace would otherwise make every+ // assertion below pass over an empty list.+ expect(all.filter((l) => LIST_PLACEHOLDER.test(l.text)).length).toBeGreaterThan(0);+ expect(models.length).toBeGreaterThan(100);+ expect(models.map((l) => l.key)).toContain('statusPill.interrupted');+ });++ it('never gives a joined list a singular verb, anywhere in the bundle', () => {+ const broken = all.filter((l) => SINGULAR_VERB.test(l.text));+ expect(broken.map((l) => `${l.key}: ${l.text}`)).toEqual([]);+ });++ it('never gives a count a plural noun on the Models page', () => {+ const broken = models.filter((l) => PLURAL_NOUN.test(l.text));+ expect(broken.map((l) => `${l.key}: ${l.text}`)).toEqual([]);+ });+});diff --git a/ui/src/components/settings/models/eligibility.test.ts b/ui/src/components/settings/models/eligibility.test.tsnew file mode 100644index 000000000..ba0f3c702--- /dev/null+++ b/ui/src/components/settings/models/eligibility.test.ts@@ -0,0 +1,80 @@+// §4.4 eligibility is the server's answer. These cases pin the four branches the+// UI is allowed to take — the reason this module replaced the deleted+// `isSourceEligible` mirror rather than moving it.+import { describe, expect, it } from 'vitest';++import { eligibilityOf, eligibleSources } from './eligibility';+import type { AgentSupply, Source } from './types';++const source = (id: string): Source => ({+ id,+ kind: 'api_key',+ vendor: 'anthropic',+ display_name: id,+ protocol: 'anthropic',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active', retry_at: null, detail_key: null },+ models: [],+});++type Agent = Pick<AgentSupply, 'sources'>;++const agent = (sources: AgentSupply['sources']): Agent => ({ sources });++describe('eligibilityOf', () => {+ it('returns the server’s verdict verbatim, reason included', () => {+ const a = agent({+ policy: 'custom',+ order: [],+ eligibility: [+ { source_id: 'src_ok', eligible: true, reason_key: null },+ { source_id: 'src_no', eligible: false, reason_key: 'models.eligibility.subscription_wrong_client' },+ ],+ });+ expect(eligibilityOf(a, 'src_ok')).toEqual({ eligible: true, reasonKey: null });+ expect(eligibilityOf(a, 'src_no')).toEqual({+ eligible: false,+ reasonKey: 'models.eligibility.subscription_wrong_client',+ });+ });++ it('grays out an ineligible row whose reason the payload omitted', () => {+ const a = agent({ policy: 'custom', order: [], eligibility: [{ source_id: 'src_x', eligible: false }] });+ expect(eligibilityOf(a, 'src_x')).toEqual({ eligible: false, reasonKey: null });+ });++ // §4.4 forbids an ineligible id in the order, so the order itself is an answer+ // when the optional field is missing (or when a source is created between the+ // /sources and /agents reads).+ it('trusts the order when `eligibility` does not mention the id', () => {+ const a = agent({ policy: 'follow', order: ['src_in'] });+ expect(eligibilityOf(a, 'src_in')).toEqual({ eligible: true, reasonKey: null });+ expect(eligibilityOf(a, 'src_out')).toEqual({ eligible: false, reasonKey: null });+ });++ // AC-7: Hub eligibility is undefined for a Direct backend, and every Hub+ // surface that would consume it is unreachable there.+ it('is ineligible for everything in Direct mode (AC-7)', () => {+ expect(eligibilityOf(agent(null), 'src_anything')).toEqual({ eligible: false, reasonKey: null });+ });+});++describe('eligibleSources', () => {+ it('keeps inventory order and drops what the server refused', () => {+ const sources = [source('src_a'), source('src_b'), source('src_c')];+ const a = agent({+ policy: 'custom',+ order: ['src_c'],+ eligibility: [+ { source_id: 'src_a', eligible: true, reason_key: null },+ { source_id: 'src_b', eligible: false, reason_key: 'models.eligibility.opencode_api_key_only' },+ ],+ });+ expect(eligibleSources(sources, a).map((s) => s.id)).toEqual(['src_a', 'src_c']);+ });++ it('offers nothing at all in Direct mode', () => {+ expect(eligibleSources([source('src_a')], agent(null))).toEqual([]);+ });+});diff --git a/ui/src/components/settings/models/eligibility.ts b/ui/src/components/settings/models/eligibility.tsnew file mode 100644index 000000000..75e239b2f--- /dev/null+++ b/ui/src/components/settings/models/eligibility.ts@@ -0,0 +1,44 @@+// Per-Agent source eligibility — read from the server, never re-derived (spec+// §4.4).+//+// This replaces `isSourceEligible` in `menus/identifiers.ts`, a UI mirror of the+// backend predicate that was escalated at review time and is deleted with this+// module. The mirror could not be right: eligibility depends on the+// `subscription_hub_experimental` flag and on recorded consent, neither of which+// the UI can see, so it was guaranteed to drift and to offer rows the live API+// rejects. Contract v3 publishes `sources.eligibility` on+// `GET /api/models/agents`, and this file is the only place the UI reads it.+import type { AgentSupply, EligibilityReasonKey, Source } from './types';++export type Eligibility = { eligible: boolean; reasonKey: EligibilityReasonKey | null };++const ELIGIBLE: Eligibility = { eligible: true, reasonKey: null };+const INELIGIBLE: Eligibility = { eligible: false, reasonKey: null };++/**+ * Whether `sourceId` may serve this Agent, and why not when it may not.+ *+ * Total over every id, including one the payload does not mention:+ * - `sources === null` — Direct mode. Hub eligibility is undefined there and no+ * Hub surface (order drawer, model menu, mapping targets) is reachable.+ * - listed in `eligibility` — the server's answer, verbatim.+ * - absent from `eligibility` but present in `order` — the server validated it+ * into the order and §4.4 forbids an ineligible id there, so it is eligible+ * with no reason to render. Covers a server that omits the optional field and+ * the race where a source is created between the `/sources` and `/agents`+ * reads.+ * - otherwise ineligible with no reason: graying a row out is better than+ * offering an 启用 the PUT would reject with `invalid_source_order`.+ */+export function eligibilityOf(agent: Pick<AgentSupply, 'sources'>, sourceId: string): Eligibility {+ const sources = agent.sources;+ if (!sources) return INELIGIBLE;+ const entry = sources.eligibility?.find((e) => e.source_id === sourceId);+ if (entry) return entry.eligible ? ELIGIBLE : { eligible: false, reasonKey: entry.reason_key ?? null };+ return sources.order.includes(sourceId) ? ELIGIBLE : INELIGIBLE;+}++/** The subset of `sources` this Agent may use — the menu/mapping surfaces' input. */+export function eligibleSources(sources: Source[], agent: Pick<AgentSupply, 'sources'>): Source[] {+ return sources.filter((s) => eligibilityOf(agent, s.id).eligible);+}diff --git a/ui/src/components/settings/models/featureFlags.ts b/ui/src/components/settings/models/featureFlags.tsindex d26242fe7..fd8b17c6e 100644--- a/ui/src/components/settings/models/featureFlags.ts+++ b/ui/src/components/settings/models/featureFlags.ts@@ -22,8 +22,9 @@ export const modelHubEnabledFromConfig = (config: unknown): boolean => {export const MODELS_API_MODE: 'mock' | 'live' = 'live';/**- * Wires the 模型菜单 buttons on the Agent card to L5's mapping / menu drawers.- * ON now that L5 is merged.+ * Wires 模型菜单与映射 — the 来源顺序 drawer's hand-off into L5's mapping / menu+ * drawers, which is the only way in since V6 gave the Agent row's action slot to+ * 来源顺序. ON now that L5 is merged.*/export const MODEL_MENUS_ENABLED = true;diff --git a/ui/src/components/settings/models/format.test.ts b/ui/src/components/settings/models/format.test.tsindex 1c54884d0..280e57a85 100644--- a/ui/src/components/settings/models/format.test.ts+++ b/ui/src/components/settings/models/format.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';-import { cooldownEtaMinutes, currencySymbol, formatSpend } from './format';+import { cooldownEtaMinutes, currencySymbol, formatNameList, formatSpend, friendlyModelName } from './format';+import type { AgentSupply, Source, SuppliedModel } from './types';describe('currencySymbol', () => {it('falls back to USD when the backend reports no currency', () => {@@ -64,6 +65,33 @@ describe('formatSpend', () => {});});+describe('formatNameList', () => {+ // The regression: `names.join('、')` shipped Chinese punctuation into the English+ // UI, where the attribution line read "No supply for agent-a、agent-b".+ it('separates with the punctuation of the reader, not of the author', () => {+ expect(formatNameList(['agent-a', 'agent-b'], 'zh')).toBe('agent-a、agent-b');+ expect(formatNameList(['agent-a', 'agent-b'], 'en')).toBe('agent-a, agent-b');+ });++ it('works from the regional tags a browser actually reports', () => {+ expect(formatNameList(['a', 'b'], 'zh-CN')).toBe('a、b');+ expect(formatNameList(['a', 'b'], 'en-US')).toBe('a, b');+ });++ // `narrow` + `conjunction` is load-bearing, not a taste: `unit` joins Chinese+ // with NOTHING ("ab"), and the wider styles add a 和 / "and" that the 11px line+ // has no room for. Three names is where those differ, so three names is the test.+ it('stays a plain separated list at three names, in both locales', () => {+ expect(formatNameList(['a', 'b', 'c'], 'zh')).toBe('a、b、c');+ expect(formatNameList(['a', 'b', 'c'], 'en')).toBe('a, b, c');+ });++ it('adds nothing around a single name', () => {+ expect(formatNameList(['only'], 'zh')).toBe('only');+ expect(formatNameList(['only'], 'en')).toBe('only');+ });+});+describe('cooldownEtaMinutes', () => {it('is 0 for a missing or already-elapsed retry_at', () => {expect(cooldownEtaMinutes(null)).toBe(0);@@ -75,3 +103,158 @@ describe('cooldownEtaMinutes', () => {expect(cooldownEtaMinutes(new Date(Date.now() + 5 * 60_000 + 1_000).toISOString())).toBe(5);});});++describe('friendlyModelName', () => {+ const model = (id: string, display_name: string | null = null): SuppliedModel => ({+ id,+ display_name,+ provenance: 'discovered',+ });++ const src = (id: string, models: SuppliedModel[], vendor = 'custom'): Source => ({+ id,+ kind: 'api_key',+ vendor,+ display_name: id,+ protocol: 'openai_compatible',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active' },+ models,+ });++ const agent = (over: Partial<AgentSupply>): AgentSupply => ({+ backend: 'claude',+ mode: 'hub',+ menu_kind: 'fixed',+ ...over,+ });++ // An opencode agent: prefixed identifiers are its shape, and `standard_vendors`+ // is the server's mirror of the vendor ids that may head one.+ const opencode = (over: Partial<AgentSupply>): AgentSupply =>+ agent({ backend: 'opencode', menu_kind: 'open', standard_vendors: ['anthropic', 'zhipuai'], ...over });++ it('renders nothing when no model resolves', () => {+ expect(friendlyModelName(agent({ current: null, selected_model_id: null }), [])).toBe('');+ });++ it('prefers the supplying source name over another source that also lists the model', () => {+ const sources = [src('src_b', [model('m1', 'Wrong One')]), src('src_a', [model('m1', 'Right One')])];+ const a = agent({ current: { model_id: 'm1', source_id: 'src_a', channel: 'hub' } });+ expect(friendlyModelName(a, sources)).toBe('Right One');+ });++ it('falls back from 「what is serving」 to 「what was selected」', () => {+ // `current` is null by contract while waiting or interrupted, and a model box+ // that empties out exactly then hides WHICH model has no supply.+ const a = agent({ current: null, selected_model_id: 'm1' });+ expect(friendlyModelName(a, [src('src_a', [model('m1', 'Opus')])])).toBe('Opus');+ });++ // The 「bare id」 in the contract means NO PROVIDER PREFIX, which is not the same+ // as no slash: `SuppliedModel.id` carries no `pattern`, so a relay endpoint or a+ // manual entry may legitimately supply a slash-bearing id under its own name.+ it('keeps a slash-bearing supplied id whole', () => {+ const id = 'accounts/fireworks/models/llama-v3';+ const sources = [src('relay', [model(id, 'Llama v3 (Fireworks)')])];+ expect(friendlyModelName(agent({ selected_model_id: id }), sources)).toBe('Llama v3 (Fireworks)');+ });++ it('never collides a relay id with another source’s same-suffix model', () => {+ // The bug: cutting through the last slash turned this into `llama-v3` and+ // rendered the OTHER source's name for it. Rebuilt, that model is+ // `custom/llama-v3` — not what was selected — so nothing matches.+ const sources = [src('other', [model('llama-v3', 'Llama v3 (Together)')])];+ const a = agent({ selected_model_id: 'accounts/fireworks/models/llama-v3' });+ expect(friendlyModelName(a, sources)).toBe('accounts/fireworks/models/llama-v3');+ });++ it('renders an unknown id as selected rather than as its tail', () => {+ expect(friendlyModelName(agent({ selected_model_id: 'vendor/x/unknown' }), [])).toBe('vendor/x/unknown');+ });++ it('renders a supplied id with no display name as itself', () => {+ const sources = [src('relay', [model('accounts/f/models/llama-v3')])];+ const a = agent({ selected_model_id: 'accounts/f/models/llama-v3' });+ expect(friendlyModelName(a, sources)).toBe('accounts/f/models/llama-v3');+ });++ // The counter-example that keeps the second lookup alive: an opencode SELECTION+ // is a prefixed identifier (`zhipuai/glm-5.2`) whose SuppliedModel.id is bare, so+ // the full form is absent from the inventory and only the rebuild resolves it.+ it('resolves a prefixed identifier against the source that supplies it bare', () => {+ const sources = [src('glm', [model('glm-5.2', 'GLM-5.2')], 'zhipuai')];+ expect(friendlyModelName(opencode({ selected_model_id: 'zhipuai/glm-5.2' }), sources)).toBe('GLM-5.2');+ });++ it('resolves to the bare id even when nothing names it', () => {+ const sources = [src('glm', [model('glm-5.2')], 'zhipuai')];+ expect(friendlyModelName(opencode({ selected_model_id: 'zhipuai/glm-5.2' }), sources)).toBe('glm-5.2');+ });++ // `custom/` is the identifier scheme's catch-all provider, so a non-standard+ // vendor heads NO identifier of its own — a slash-count rule would have missed+ // this one, and the rebuild gets it for free.+ it('resolves a custom/ identifier supplied by a non-standard vendor', () => {+ const sources = [src('relay', [model('glm-5.2-air', 'GLM-5.2 Air')], 'relay.example')];+ expect(friendlyModelName(opencode({ selected_model_id: 'custom/glm-5.2-air' }), sources)).toBe('GLM-5.2 Air');+ });++ it('does not resolve a standard-vendor prefix the supplying source does not carry', () => {+ // The relay's `glm-5.2` is `custom/glm-5.2`; claiming it for `zhipuai/glm-5.2`+ // would name a vendor the user is not actually reaching.+ const sources = [src('relay', [model('glm-5.2', 'GLM-5.2 (relay)')], 'relay.example')];+ expect(friendlyModelName(opencode({ selected_model_id: 'zhipuai/glm-5.2' }), sources)).toBe('zhipuai/glm-5.2');+ });++ it('prefers the supplying source when two sources supply the same model', () => {+ // `current.model_id` is the RESOLVED upstream id — bare even on an open menu,+ // per the contract ("NOT a valid input to the chain query"). An earlier version+ // of this test fed it prefixed, which the payload cannot produce.+ const sources = [+ src('glm_b', [model('glm-5.2', 'Wrong One')], 'zhipuai'),+ src('glm_a', [model('glm-5.2', 'Right One')], 'zhipuai'),+ ];+ const a = opencode({ current: { model_id: 'glm-5.2', source_id: 'glm_a', channel: 'hub' } });+ expect(friendlyModelName(a, sources)).toBe('Right One');+ });++ // ── Where the two axes DISAGREE ──────────────────────────────────────+ // The 12 cases above all pin agreement: 「which source」 and 「which reading of+ // the id」 point the same way, so they stayed green through a regression that+ // nested the axes the wrong way round. These three make them conflict and+ // assert which wins.++ it('does not walk past the serving source to a source that can name the model', () => {+ // The server named `glm_a`; its inventory does not (yet) list what it is+ // running. The bare upstream id is the honest answer — `glm_b`'s name is for+ // `glm_b`'s model, and borrowing it claims a route the user does not have.+ const sources = [src('glm_b', [model('glm-5.2', 'Borrowed Name')], 'zhipuai'), src('glm_a', [], 'zhipuai')];+ const a = opencode({ current: { model_id: 'glm-5.2', source_id: 'glm_a', channel: 'hub' } });+ expect(friendlyModelName(a, sources)).toBe('glm-5.2');+ });++ it('reads an open-menu selection as an identifier even where another source lists it literally', () => {+ // A relay can supply a model whose literal id looks like an identifier. On an+ // open menu the selection IS an identifier, so the relay's `zhipuai/glm-5.2`+ // rebuilds to `custom/zhipuai/glm-5.2` and does not answer for it — the+ // exact-looking match is the wrong reading, not the stronger one.+ const sources = [+ src('relay', [model('zhipuai/glm-5.2', 'Wrong (relay)')], 'relay.example'),+ src('glm', [model('glm-5.2', 'GLM-5.2')], 'zhipuai'),+ ];+ expect(friendlyModelName(opencode({ selected_model_id: 'zhipuai/glm-5.2' }), sources)).toBe('GLM-5.2');+ });++ it('names what is running, read as an upstream id, when a mapping redirected the selection', () => {+ // 「我选的 anthropic/claude-opus-4-6, 实际在跑 glm-5.2」. Applying the identifier+ // reading to a RESOLVED id would look for `zhipuai/glm-5.2` and miss.+ const sources = [src('glm', [model('glm-5.2', 'GLM-5.2')], 'zhipuai')];+ const a = opencode({+ selected_model_id: 'anthropic/claude-opus-4-6',+ current: { model_id: 'glm-5.2', source_id: 'glm', channel: 'hub' },+ });+ expect(friendlyModelName(a, sources)).toBe('GLM-5.2');+ });+});diff --git a/ui/src/components/settings/models/format.ts b/ui/src/components/settings/models/format.tsindex 4ccba4bf7..6518a13bc 100644--- a/ui/src/components/settings/models/format.ts+++ b/ui/src/components/settings/models/format.ts@@ -1,6 +1,7 @@// Pure formatting helpers for the Model Hub UI (no i18n — callers wrap the// returned values in translated templates).-import type { AgentSupply, Source } from './types';+import { buildIdentifier } from './menus/identifiers';+import type { AgentSupply, Source, SuppliedModel } from './types';const CURRENCY_SYMBOL: Record<string, string> = { USD: '$', CNY: '¥', EUR: '€' };@@ -22,6 +23,20 @@ export function formatSpend(cents: number, currency?: string | null): string {return `${currencySymbol(currency)}${(cents / 100).toFixed(1)}`;}+/**+ * A list of names in the reader's own punctuation — 「A、B、C」 for a Chinese+ * reader, "A, B, C" for an English one.+ *+ * Joining on a literal `、` looked locale-neutral and is not: it is Chinese+ * punctuation, and it shipped into the English UI. `narrow` + `conjunction` is the+ * pair that separates in BOTH locales and adds an "and" to neither — `unit` joins+ * Chinese with nothing at all, and the wider styles grow a 和 / "and" that an+ * 11px attribution line has no room for.+ */+export function formatNameList(names: readonly string[], locale: string): string {+ return new Intl.ListFormat(locale, { style: 'narrow', type: 'conjunction' }).format(names);+}+/** Whole minutes until a cooldown retry_at (never negative). */export function cooldownEtaMinutes(retryAt?: string | null): number {if (!retryAt) return 0;@@ -29,12 +44,77 @@ export function cooldownEtaMinutes(retryAt?: string | null): number {return Math.max(0, Math.round(ms / 60_000));}-/** Friendly model name for a backend's current supply: prefer the supplying- * source's display_name for the model id, else the bare id. */+/**+ * Friendly name for the model a backend is set to run.+ *+ * Falls back from 「what is serving」 to 「what was selected」 on purpose: while an+ * Agent is waiting or interrupted `current` is null by contract, and a model box+ * that empties out at exactly the moment something went wrong hides the one fact+ * the user needs — WHICH model has no supply. The display name is then looked up+ * across all sources, since the source that used to name it may be the one that+ * just failed.+ *+ * A prefixed identifier is RESOLVED, never stripped. The old code cut through the+ * last slash first and unconditionally, on the reading that `SuppliedModel.id` is a+ * 「bare model id (no provider prefix)」 — but the contract puts no `pattern` on that+ * field, and 「no provider prefix」 is not 「no slash」. A relay endpoint supplies+ * `accounts/fireworks/models/llama-v3` under exactly that name, so the cut both lost+ * the metadata the id carries and matched some OTHER source's `llama-v3`, rendering+ * a model the user never selected.+ *+ * The fix is not a smarter cut — a bare tail is ambiguous in both directions, and+ * nothing about `llama-v3` says whether a prefix was dropped. It is to rebuild the+ * identifier the way the backend does. Per the frozen opencode overlay an identifier+ * is `inferProvider(source.vendor)/model.id`, so a supplied model can be matched on+ * provider AND id through the one function that owns that scheme, and a tail+ * collision becomes impossible rather than merely unlikely: `llama-v3` from a+ * `custom` source rebuilds to `custom/llama-v3`, which is not what was selected.+ *+ * An identifier neither lookup resolves renders as selected: verbose beats wrong.+ *+ * Two axes decide the lookup — WHICH SOURCE may answer, and WHICH READING of the id+ * to match on — and nesting them the wrong way round is a bug of its own. The source+ * axis outranks the form axis, because the server has already resolved which source+ * serves: an ordered scan that tries a stronger *form* match in a source the server+ * did NOT name walks past the serving source and renders someone else's model. So the+ * source is settled first, and the reading is not searched at all — it is dictated by+ * WHICH FIELD supplied the id, since the two fields are not the same shape:+ *+ * `current.model_id` the RESOLVED upstream id, mapping already applied — bare+ * even on an open menu ("NOT a valid input to the chain+ * query … the caller-facing identifier is prefixed").+ * Read exactly, and only against `current.source_id`.+ * `selected_model_id` the caller-facing MENU identifier — the built-in id for a+ * fixed menu, `vendor/model` for an open one. Read per+ * `menu_kind`, against every source: `current` is null+ * exactly when nothing is serving, so no source is+ * authoritative and none can be preferred honestly.+ */export function friendlyModelName(agent: AgentSupply, sources: Source[]): string {- const modelId = agent.current?.model_id;- if (!modelId) return '';- const source = sources.find((s) => s.id === agent.current?.source_id);- const named = source?.models.find((m) => m.id === modelId)?.display_name;- return named || modelId;+ const current = agent.current ?? null;+ if (current) {+ // One source, one reading. A miss renders the upstream id — which is the honest+ // answer when the serving source's inventory cannot name what it is running,+ // and strictly better than a name borrowed from a source that is not serving.+ const serving = sources.find((s) => s.id === current.source_id);+ const model = serving?.models.find((m) => m.id === current.model_id);+ return model?.display_name || current.model_id;+ }++ const selected = agent.selected_model_id ?? null;+ if (!selected) return '';++ const standardVendors = new Set(agent.standard_vendors ?? []);+ // `display_name || id`, not a `display_name` predicate: a supplied model with no+ // name still owns its id and must not fall through to a later source.+ const holds = (source: Source, model: SuppliedModel): boolean =>+ agent.menu_kind === 'open'+ ? buildIdentifier(source.vendor, model.id, standardVendors) === selected+ : model.id === selected;+ for (const source of sources) {+ const model = source.models.find((m) => holds(source, m));+ if (model) return model.display_name || model.id;+ }++ return selected;}diff --git a/ui/src/components/settings/models/menus/MappingDrawer.tsx b/ui/src/components/settings/models/menus/MappingDrawer.tsxindex cb4456f26..8f8c4c99d 100644--- a/ui/src/components/settings/models/menus/MappingDrawer.tsx+++ b/ui/src/components/settings/models/menus/MappingDrawer.tsx@@ -11,11 +11,13 @@ import { Button } from '@/components/ui/button';import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';import { cn } from '@/lib/utils';import { useToast } from '@/context/ToastContext';+import { initialSeedState, savedMappingsKey, seedStep } from '../asyncLifetime';import { modelsApi } from '../modelsApi';import { backendVisual } from '../vendorMeta';import type { AgentBackend, AgentMapping, AgentSupply, Source } from '../types';import { MenuDrawer } from './MenuDrawer';-import { buildTargetModels, isSourceEligible, type TargetModel } from './identifiers';+import { eligibleSources } from '../eligibility';+import { buildTargetModels, type TargetModel } from './identifiers';import { SupplyDots } from './supplyBits';import { useCompactSourceLabel } from './sourceLabel';@@ -146,22 +148,26 @@ export const MappingDrawer: React.FC<{const { t } = useTranslation();const { showToast } = useToast();const { Icon, accent } = backendVisual(backend);- // Override targets follow the backend eligibility predicate (isSourceEligible):- // hub-supplied API-key sources PLUS this backend's own native subscription.- // Anything else is rejected by the live API with `mapping_target_unavailable`.- const targets = React.useMemo(- () => buildTargetModels(sources.filter((s) => isSourceEligible(s, backend))),- [sources, backend],- );+ // Override targets are the sources the SERVER says may serve this backend+ // (`agent.sources.eligibility`) — anything else is rejected by the live API+ // with `mapping_target_unavailable`.+ const targets = React.useMemo(() => buildTargetModels(eligibleSources(sources, agent)), [sources, agent]);const [draft, setDraft] = React.useState<AgentMapping[]>(() => seedDraft(agent));const initialRef = React.useRef<AgentMapping[]>(draft);const [saving, setSaving] = React.useState(false);- // Reseed only on open so an in-flight edit isn't clobbered by a background- // refresh of the agent prop.+ // Seed from the stored overrides; `seedStep` owns *when*, so a save that lands+ // after this drawer was closed and reopened re-seats the draft instead of being+ // written back over (asyncLifetime.ts). A background refresh that changed+ // nothing is still inert, which is what protects an edit in flight.+ const seed = React.useRef(initialSeedState);+ const authoritative = savedMappingsKey(agent);React.useEffect(() => {if (!open) return;+ const step = seedStep(seed.current, authoritative);+ seed.current = step.state;+ if (!step.reseed) return;const raw = seedDraft(agent);// Self-heal: an enabled override whose target's supplier was deleted is no// longer selectable — display it as 跟随原生. Seed initialRef with the RAW@@ -174,7 +180,7 @@ export const MappingDrawer: React.FC<{setDraft(healed);initialRef.current = raw;// eslint-disable-next-line react-hooks/exhaustive-deps- }, [open]);+ }, [open, authoritative]);const backendName = t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;diff --git a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsxindex 0719c0229..485a6b344 100644--- a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx+++ b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx@@ -12,12 +12,14 @@ import { Button } from '@/components/ui/button';import { Checkbox } from '@/components/ui/checkbox';import { SegmentedRadio } from '@/components/ui/segmented';import { useToast } from '@/context/ToastContext';+import { initialSeedState, savedMenuKey, seedStep } from '../asyncLifetime';import { modelsApi } from '../modelsApi';import { backendVisual } from '../vendorMeta';import type { AgentMenu, AgentSupply, Source } from '../types';import { MenuDrawer } from './MenuDrawer';import { AddCustomModelDialog } from './AddCustomModelDialog';-import { buildMenuGroups, isSourceEligible, type MenuModelRow } from './identifiers';+import { eligibleSources as filterEligible } from '../eligibility';+import { buildMenuGroups, type MenuModelRow } from './identifiers';import { SupplyDots } from './supplyBits';type EditTarget = { sourceId: string; modelId: string; displayName: string | null } | null;@@ -83,11 +85,10 @@ export const OpenCodeMenuDrawer: React.FC<{// identifiers byte-match the backend's opencode_model_id — never hand-mirrored.const standardVendors = React.useMemo(() => new Set(agent.standard_vendors ?? []), [agent.standard_vendors]);- // Only OpenCode-eligible sources materialize as providers (isSourceEligible):- // API-key sources only — subscriptions (native_cli AND hub-held experimental)- // are excluded, matching the backend predicate, so we never offer a row the- // live `set_opencode_menu` would reject.- const eligibleSources = React.useMemo(() => sources.filter((s) => isSourceEligible(s, 'opencode')), [sources]);+ // Only sources the SERVER says may serve OpenCode materialize as providers —+ // `agent.sources.eligibility`, not a UI-side predicate — so we never offer a+ // row the live `set_opencode_menu` would reject.+ const eligibleSources = React.useMemo(() => filterEligible(sources, agent), [sources, agent]);const groups = React.useMemo(() => buildMenuGroups(eligibleSources, standardVendors), [eligibleSources, standardVendors]);const allRows = React.useMemo(() => groups.flatMap((g) => g.rows), [groups]);// Identifiers a source currently supplies. Persisted `checked` is self-healed@@ -103,8 +104,17 @@ export const OpenCodeMenuDrawer: React.FC<{const [customOpen, setCustomOpen] = React.useState(false);const [editTarget, setEditTarget] = React.useState<EditTarget>(null);+ // Seed from the stored menu; `seedStep` owns *when*, so a save that lands after+ // this drawer was closed and reopened re-seats it instead of being written back+ // over (asyncLifetime.ts). A refresh that changed nothing stays inert, which is+ // what keeps an edit in flight safe.+ const seed = React.useRef(initialSeedState);+ const authoritative = savedMenuKey(agent.menu);React.useEffect(() => {if (!open) return;+ const step = seedStep(seed.current, authoritative);+ seed.current = step.state;+ if (!step.reseed) return;const v = agent.menu?.view ?? 'featured';const raw = agent.menu?.checked ?? [];// Self-heal the DISPLAY: drop checked ids whose supplier no longer exists@@ -116,7 +126,7 @@ export const OpenCodeMenuDrawer: React.FC<{setChecked(new Set(healed));initialRef.current = { view: v, checked: [...raw] };// eslint-disable-next-line react-hooks/exhaustive-deps- }, [open]);+ }, [open, authoritative]);const featuredCount = allRows.filter((r) => checked.has(r.identifier)).length;const fullCount = allRows.length;diff --git a/ui/src/components/settings/models/menus/identifiers.ts b/ui/src/components/settings/models/menus/identifiers.tsindex 1dec1b05a..732f6e999 100644--- a/ui/src/components/settings/models/menus/identifiers.ts+++ b/ui/src/components/settings/models/menus/identifiers.ts@@ -7,7 +7,7 @@// generate and preview it.import type { Accent } from '../vendorMeta';import { sourceAccent } from '../vendorMeta';-import type { AgentBackend, Source } from '../types';+import type { Source } from '../types';// The standard OpenCode vendor ids come from the backend via the opencode// agent's `standard_vendors` projection (agent-supply v1.2), server-populated@@ -34,33 +34,12 @@ export function buildIdentifier(sourceVendor: string, modelId: string, standardVreturn `${inferProvider(sourceVendor, standardVendors)}/${modelId}`;}-// Which backend a fixed-menu backend's own native subscription belongs to-// (its sanctioned native_cli client): Claude sub → claude, ChatGPT sub → codex.-const NATIVE_SUB_VENDOR: Partial<Record<AgentBackend, string>> = {- claude: 'anthropic',- codex: 'openai',-};--/**- * SINGLE chokepoint mirroring the backend `_eligible_for_agent` predicate — the- * one place that decides whether a source may feed an agent's menu/mapping, so- * the drawers never re-derive eligibility from `supply_channel` piecemeal.- *- * - OpenCode (open menu): only API-key sources materialize as providers;- * subscriptions (native_cli AND hub-held experimental) are excluded.- * - Fixed-menu (Claude / Codex mapping targets): any hub-supplied API-key- * source, PLUS this backend's own native subscription (a Claude sub is a- * valid target for Claude Code, a ChatGPT sub for Codex).- *- * ESCALATED (2026-07-23): this mirrors backend logic the UI can't read; the- * integration pass should drive it from a backend-provided signal (like- * `builtin_models`). This function is the swap point.- */-export function isSourceEligible(source: Source, backend: AgentBackend): boolean {- if (backend === 'opencode') return source.kind === 'api_key';- if (source.kind === 'api_key') return true;- return source.kind === 'subscription' && source.vendor === NATIVE_SUB_VENDOR[backend];-}+// `isSourceEligible` lived here and is gone: it mirrored the backend+// `_eligible_for_agent` predicate, which the UI cannot compute (it depends on the+// `subscription_hub_experimental` flag and on recorded consent), so it was+// guaranteed to drift and to offer rows the live API rejects. Contract v3+// publishes the answer as `AgentSupply.sources.eligibility`; read it through+// `../eligibility`.// ── Grouped menu model, derived from the ordered sources list ──────────────diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.tsindex 1cc4d3889..c87e2ed95 100644--- a/ui/src/components/settings/models/mockData.ts+++ b/ui/src/components/settings/models/mockData.ts@@ -1,26 +1,34 @@// Typed fixtures for the Model Hub UI while the L2 REST API is unmerged.-// Mirrors the V4 design mock story (design.pen `产品改造 V4 01r`) and the frozen-// contract example payloads. Timestamps are computed relative to "now" at fetch-// time so the 最近切换 list always renders 今天 / 昨天 correctly.+// Mirrors the V6 design mock story (design.pen `产品改造 V6 01`) and the frozen+// v3 contract example payloads. Timestamps are computed relative to "now" at+// fetch time so the 最近切换 list always renders 今天 / 昨天 correctly.+//+// The two exported predicates at the bottom (`mockEligibility`,+// `mockRecommendedOrder`) implement spec §4.4 and §4.2. They belong to the FAKE+// SERVER, not to the UI: production reads `AgentSources.eligibility` /+// `.order` off the wire and never re-derives either. They live here so the+// fixture and the MockStore share one implementation.import type {+ AgentBackend,AgentSupply,MigrationScan,- Priority,ResolutionEvent,RuntimeDependency,Source,+ SourceEligibility,} from './types';-import { CONTRACT_VERSION } from './types';import { SUBSCRIPTION_HUB_EXPERIMENTAL } from './featureFlags';const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString();const MIN = 60_000;const HOUR = 60 * MIN;+const DAY = 24 * HOUR;export function buildMockSources(): Source[] {return [{id: 'src_claudepro1',+ created_at: iso(-30 * DAY),kind: 'subscription',vendor: 'anthropic',display_name: 'Claude Pro 订阅',@@ -41,6 +49,7 @@ export function buildMockSources(): Source[] {},{id: 'src_chatgptplus',+ created_at: iso(-20 * DAY),kind: 'subscription',vendor: 'openai',display_name: 'ChatGPT Plus 订阅',@@ -60,6 +69,7 @@ export function buildMockSources(): Source[] {},{id: 'src_anthkey01',+ created_at: iso(-10 * DAY),kind: 'api_key',vendor: 'anthropic',display_name: 'Anthropic API Key',@@ -80,6 +90,7 @@ export function buildMockSources(): Source[] {},{id: 'src_zhipukey01',+ created_at: iso(-4 * DAY),kind: 'api_key',vendor: 'zhipuai',display_name: '智谱 API Key',@@ -101,6 +112,10 @@ export function buildMockSources(): Source[] {},{id: 'src_relay9c1x',+ // Older than the 智谱 key on purpose: 「V6 01」 draws Codex's recommended+ // chain as ChatGPT Plus › relay.example › 智谱 API Key, and under §4.2 an+ // api_key's place in that chain is its created_at.+ created_at: iso(-6 * DAY),kind: 'api_key',vendor: 'custom',display_name: 'relay.example',@@ -108,7 +123,7 @@ export function buildMockSources(): Source[] {base_url: 'https://relay.example/v1',supply_channel: 'hub',billing: 'metered',- state: { status: 'cooldown', retry_at: iso(47 * MIN), detail_key: 'settings.models.source.cooldown.timeout' },+ state: { status: 'cooldown', retry_at: iso(47 * MIN), detail_key: 'models.source.cooldown.timeout' },usage: { cycle_used_pct: null, month_spend_cents: 320, currency: 'USD' },account_label: null,masked_credential: 'key …9c1',@@ -120,26 +135,47 @@ export function buildMockSources(): Source[] {];}-export function buildMockPriority(): Priority {- return {- contract_version: CONTRACT_VERSION,- order: ['src_claudepro1', 'src_chatgptplus', 'src_anthkey01', 'src_zhipukey01', 'src_relay9c1x'],- };-}--export function buildMockAgents(): AgentSupply[] {+// The V6 01 story: Claude Code and Codex are on the hub (「2 个 Agent 已接入中枢」),+// OpenCode still runs its native config (直连). Claude Code owns a 自定义 subset+// that leaves 智谱 out — which is what makes the drawer's 未启用 section non-empty+// in frame V6 02; Codex 跟随推荐, so its order IS §4.2's output.+export function buildMockAgents(sources: Source[] = buildMockSources()): AgentSupply[] {+ const claudeOrder = ['src_claudepro1', 'src_anthkey01', 'src_relay9c1x'];return [{backend: 'claude',mode: 'hub',menu_kind: 'fixed',+ selected_by_agent: null,+ selected_model_id: 'claude-opus-4-6',current: { model_id: 'claude-opus-4-6', source_id: 'src_claudepro1', channel: 'native_cli' },+ sources: {+ policy: 'custom',+ order: claudeOrder,+ eligibility: mockEligibility(sources, 'claude'),+ },+ // Serving from the head of the chain for the CURRENT selection, and no+ // member of that chain is blocked — relay.example is cooling, but it does+ // not supply Opus at all, so it is not a member and cannot degrade it.+ supply_status: 'ok',+ // claude-haiku-4-5 is mapped onto glm-5.2, which only 智谱 supplies — and+ // 智谱 is 未启用 here. Depth 0 is the honest answer, and AC-9's Case A: a+ // menu-model gap that must NOT render any Agent as interrupted.+ model_supply: [+ { model_id: 'claude-opus-4-6', chain_length: 2 },+ { model_id: 'claude-sonnet-4-6', chain_length: 2 },+ { model_id: 'claude-haiku-4-5', chain_length: 0 },+ ],+ named_agents: [+ { name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' },+ { name: 'pm', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' },+ ],// Fixed-menu backends surface their full built-in id list as mappings; an// enabled entry is an override (frame 04), disabled = 跟随原生 (identity).mappings: [- { builtin_id: 'claude-opus-4-6', target_model_id: 'glm-5.2', enabled: true },+ { builtin_id: 'claude-opus-4-6', target_model_id: '', enabled: false },{ builtin_id: 'claude-sonnet-4-6', target_model_id: '', enabled: false },- { builtin_id: 'claude-haiku-4-5', target_model_id: '', enabled: false },+ { builtin_id: 'claude-haiku-4-5', target_model_id: 'glm-5.2', enabled: true },],menu: null,// Fixed-menu backends carry the server-populated built-in catalog@@ -149,9 +185,23 @@ export function buildMockAgents(): AgentSupply[] {},{backend: 'codex',- mode: 'direct',+ mode: 'hub',menu_kind: 'fixed',- current: null,+ selected_by_agent: 'codex',+ selected_model_id: 'gpt-5.6',+ current: { model_id: 'gpt-5.6', source_id: 'src_chatgptplus', channel: 'native_cli' },+ sources: {+ policy: 'follow',+ // Recomputed on every read: 跟随推荐 means a new source joins by itself.+ order: mockRecommendedOrder(sources, 'codex'),+ eligibility: mockEligibility(sources, 'codex'),+ },+ supply_status: 'ok',+ model_supply: [+ { model_id: 'gpt-5.6', chain_length: 1 },+ { model_id: 'gpt-5.6-mini', chain_length: 1 },+ ],+ named_agents: [{ name: 'codex', effective_model_id: 'gpt-5.6', supply_status: 'ok' }],mappings: [{ builtin_id: 'gpt-5.6', target_model_id: '', enabled: false },{ builtin_id: 'gpt-5.6-mini', target_model_id: '', enabled: false },@@ -161,16 +211,22 @@ export function buildMockAgents(): AgentSupply[] {standard_vendors: null,},{+ // 直连: the CLI runs its own native config. Every hub-side projection is+ // null by contract — no order, no chain, no probe (AC-7's gate).backend: 'opencode',- mode: 'hub',+ mode: 'direct',menu_kind: 'open',- current: { model_id: 'glm-5.2', source_id: 'src_zhipukey01', channel: 'hub' },+ selected_by_agent: null,+ selected_model_id: null,+ current: null,+ sources: null,+ supply_status: null,+ model_supply: null,+ named_agents: [{ name: 'opencode', effective_model_id: null, supply_status: null }],mappings: [],// Prefixed identifiers (opencode-overlay.md): provider = the SOURCE's- // vendor (custom fallback), and only hub-channel sources materialize as- // OpenCode providers — so every checked id is backed by a hub source in- // buildMockSources (the two native_cli subscriptions never appear here).- // checked = 精选 (in the picker); the rest live under 全量.+ // vendor (custom fallback). Retained across the mode switch — it is stored+ // config, not live state, and applies again the moment OpenCode rejoins.menu: {view: 'featured',checked: [@@ -206,6 +262,7 @@ export function buildMockEvents(): ResolutionEvent[] {to_source: 'src_anthkey01',reason: 'quota_exhausted',billing_note: 'entered_metered',+ severity: 'info',human_zh: 'Claude Code:Claude Pro 本周期额度用完 → 已切到 Anthropic API Key(按量)',human_en: 'Claude Code: Claude Pro cycle quota exhausted → switched to Anthropic API Key (metered)',},@@ -219,12 +276,13 @@ export function buildMockEvents(): ResolutionEvent[] {to_source: 'src_claudepro1',reason: 'recovery',billing_note: 'left_metered',+ severity: 'info',human_zh: 'Claude Code:Claude Pro 额度恢复 → 已切回订阅',human_en: 'Claude Code: Claude Pro quota recovered → switched back to the subscription',},{id: 'evt_c',- ts: iso(-1 * 24 * HOUR - 30 * MIN),+ ts: iso(-1 * DAY - 30 * MIN),agent: 'system',kind: 'cooldown',model_id: 'glm-5.2-air',@@ -232,12 +290,64 @@ export function buildMockEvents(): ResolutionEvent[] {to_source: null,reason: 'network',billing_note: null,+ severity: 'info',human_zh: 'relay.example 连续超时 → 暂停使用 1 小时,期间自动跳过',human_en: 'relay.example timed out repeatedly → paused for 1 hour, skipped automatically',},+ // AC-18's render-time 「已删除」 case: a retained event whose endpoint no+ // longer resolves. The recorded sentence still names the source, because it+ // was composed when the source existed — that string IS the snapshot.+ {+ id: 'evt_d',+ ts: iso(-2 * DAY - 4 * HOUR),+ agent: 'codex',+ kind: 'needs_action',+ model_id: 'gpt-5.6',+ from_source: 'src_oldkey0099',+ to_source: null,+ reason: 'credential_revoked',+ billing_note: null,+ severity: 'action_required',+ human_zh: 'Codex:旧 OpenAI API Key 凭证已失效 → 已跳过,需要重新授权',+ human_en: 'Codex: the old OpenAI API Key credential was revoked → skipped, re-authorization needed',+ },+ // A history tail, so 「查看全部」 crosses a page boundary in the mock. With+ // four rows the cursor path was unreachable in dev — the very case the feed's+ // pagination exists for could only be seen against a real server.+ // Deep enough that the feed needs THREE pages at the page size 最近切换 asks+ // for (20): expanding 查看全部 pulls the second page on its own, so anything+ // shallower exhausts the cursor before 查看更多 is ever clickable — which is+ // how the button shipped unexercised in the first place.+ ...olderHistory(45),];}+/** Filler older events, oldest last, ids stable so `before` cursors are stable. */+function olderHistory(count: number): ResolutionEvent[] {+ return Array.from({ length: count }, (_, i) => {+ const n = i + 1;+ const cooling = n % 3 === 0;+ return {+ id: `evt_h${String(n).padStart(2, '0')}`,+ ts: iso(-3 * DAY - i * (5 * HOUR + 20 * MIN)),+ agent: 'claude',+ kind: cooling ? 'cooldown' : 'switch',+ model_id: 'claude-opus-4-6',+ from_source: cooling ? 'src_relay9c1x' : 'src_claudepro1',+ to_source: cooling ? null : 'src_anthkey01',+ reason: cooling ? 'rate_limited' : 'quota_exhausted',+ billing_note: cooling ? null : 'entered_metered',+ severity: 'info',+ human_zh: cooling+ ? 'relay.example 触发限流 → 暂停使用 10 分钟,期间自动跳过'+ : 'Claude Code:Claude Pro 本周期额度用完 → 已切到 Anthropic API Key(按量)',+ human_en: cooling+ ? 'relay.example hit a rate limit → paused for 10 minutes, skipped automatically'+ : 'Claude Code: Claude Pro cycle quota exhausted → switched to Anthropic API Key (metered)',+ } satisfies ResolutionEvent;+ });+}+export function buildMockRuntime(): RuntimeDependency {return {manifest: {@@ -315,3 +425,61 @@ export function mockDiscoveredCount(vendor: string): number {const table: Record<string, number> = { anthropic: 8, openai: 31, zhipuai: 12, kimi: 6, xai: 4, custom: 23 };return table[vendor] ?? 23;}++// ── Fake-server predicates (spec §4.4 + §4.2) ───────────────────────────+// The vendor→client binding an eligible subscription must satisfy. OpenCode has+// no subscription channel at all, so it has no own vendor.+const OWN_VENDOR: Record<AgentBackend, string | null> = {+ claude: 'anthropic',+ codex: 'openai',+ opencode: null,+};++/** §4.4 — server-authoritative eligibility, one row per source. api_key sources+ * serve every backend; a subscription is bound to its own client, and the+ * hub-held channel additionally needs the flag plus explicit consent. */+export function mockEligibility(sources: Source[], backend: AgentBackend): SourceEligibility[] {+ return sources.map((s): SourceEligibility => {+ if (s.kind === 'api_key') return { source_id: s.id, eligible: true, reason_key: null };+ if (backend === 'opencode') {+ return { source_id: s.id, eligible: false, reason_key: 'models.eligibility.opencode_api_key_only' };+ }+ if (s.vendor !== OWN_VENDOR[backend]) {+ return { source_id: s.id, eligible: false, reason_key: 'models.eligibility.subscription_wrong_client' };+ }+ if (s.supply_channel === 'hub' && !(SUBSCRIPTION_HUB_EXPERIMENTAL && s.experimental_consent_at)) {+ return { source_id: s.id, eligible: false, reason_key: 'models.eligibility.consent_required' };+ }+ return { source_id: s.id, eligible: true, reason_key: null };+ });+}++// An absent created_at sorts before every present one (types.ts: the stamp may+// be null on rows persisted before the field existed).+const createdKey = (s: Source) => s.created_at ?? '';++/** §4.2 — the deterministic recommendation, exhaustive over eligible sources:+ * (1) the backend's own-vendor subscription, native_cli before a hub-held one;+ * (2) every eligible api_key by created_at ascending; (3) id ascending as the+ * tie-break anywhere. No health, latency, cost or usage input. */+export function mockRecommendedOrder(sources: Source[], backend: AgentBackend): string[] {+ const eligible = new Set(+ mockEligibility(sources, backend).filter((e) => e.eligible).map((e) => e.source_id),+ );+ const pool = sources.filter((s) => eligible.has(s.id));+ const byId = (a: Source, b: Source) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);+ const subs = pool+ .filter((s) => s.kind === 'subscription')+ .sort((a, b) => {+ const rank = (s: Source) => (s.supply_channel === 'native_cli' ? 0 : 1);+ return rank(a) - rank(b) || byId(a, b);+ });+ const keys = pool+ .filter((s) => s.kind === 'api_key')+ .sort((a, b) => {+ const ca = createdKey(a);+ const cb = createdKey(b);+ return (ca < cb ? -1 : ca > cb ? 1 : 0) || byId(a, b);+ });+ return [...subs, ...keys].map((s) => s.id);+}diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 1ba84b901..a948236be 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -12,24 +12,29 @@ import {buildMockAgents,buildMockEvents,buildMockMigration,- buildMockPriority,buildMockRuntime,buildMockSources,mockDiscoveredCount,+ mockEligibility,+ mockRecommendedOrder,} from './mockData';+import { isUnhealthy } from './supply';import type {+ AdoptedBy,AgentBackend,+ AgentChain,+ AgentChainLink,AgentMapping,AgentMenu,AgentMode,+ AgentSourcesPut,AgentSupply,ApiKeySourceCreate,CustomModelCreate,MigrationApplyResult,MigrationScan,OAuthFlow,- OAuthSourceCreate,- Priority,+ ProbeResult,ResolutionEvent,RuntimeDependency,Source,@@ -38,19 +43,54 @@ import type {} from './types';import { CONTRACT_VERSION } from './types';+/**+ * The terminal result of BOTH creation paths (api.md 「The terminal result of both+ * ordinary API-key creation and OAuth creation is」).+ *+ * `adopted_by` travels with the source rather than being re-read from+ * `/agents` afterwards, and that is the whole point: it is a snapshot frozen at+ * commit time, listing only the eligible `follow` backends that took the source+ * in and at which one-based position. A `custom` backend is absent — not because+ * nothing happened to it, but because nothing did, which is exactly the case the+ * user has to be told about while the dialog is still open.+ */+export type SourceCreated = { source: Source; adopted_by: AdoptedBy[] };++/**+ * The response of BOTH oauth status and submit (api.md → OAuth completion): the+ * flow, plus — once a `create` flow reaches success — the source the server+ * materialized while answering THAT request, and who took it in.+ *+ * `created` is the half a client must not throw away. The server creates the+ * source inside the very call that first reports success and consumes the flow+ * binding doing it, so a client that keeps only `flow` and then posts to+ * `/sources` to "finalize" gets `flow_not_found` on a connection that in fact+ * succeeded. `null` means this response did not report a creation (still+ * pending, failed, cancelled, or a `reauth` flow, which reports recovery+ * instead and which no UI path starts yet) — NOT that nothing adopted the+ * source. That distinction is why this is nullable rather than `[]`.+ */+export type OAuthResult = { flow: OAuthFlow; created: SourceCreated | null };+export type ModelsApi = {listSources(): Promise<Source[]>;- createApiKeySource(draft: ApiKeySourceCreate): Promise<Source>;- /** Finalize a completed subscription OAuth flow into a persisted Source. */- createOAuthSource(draft: OAuthSourceCreate): Promise<Source>;+ createApiKeySource(draft: ApiKeySourceCreate): Promise<SourceCreated>;/** Rename / re-point a source (display_name, base_url). */patchSource(id: string, patch: SourcePatch): Promise<Source>;/** Re-run discovery on a hub source; resolves with the discovered count. */testSource(id: string): Promise<number>;/** Delete a source. `force` overrides the only-supplier guard. */deleteSource(id: string, force?: boolean): Promise<void>;- putPriority(order: string[]): Promise<Priority>;listAgents(): Promise<AgentSupply[]>;+ /** Per-backend enabled subset + order + policy (the 来源顺序 drawer's read). */+ getAgentSources(backend: AgentBackend): Promise<AgentSupply>;+ /** Total write: `follow` hands the order back to the server, `custom` freezes+ * exactly the ids sent. The response re-echoes the canonical order. */+ putAgentSources(backend: AgentBackend, body: AgentSourcesPut): Promise<AgentSupply>;+ /** Resolution chain for one model. Hub mode only — direct answers `direct_mode`. */+ getAgentChain(backend: AgentBackend, model: string): Promise<AgentChain>;+ /** One real request through the chain. Hub mode only, same reason. */+ probeAgent(backend: AgentBackend, model?: string): Promise<ProbeResult>;setAgentMode(backend: AgentBackend, mode: AgentMode): Promise<AgentSupply>;putMappings(backend: AgentBackend, mappings: AgentMapping[]): Promise<AgentSupply>;putMenu(menu: AgentMenu): Promise<AgentSupply>;@@ -58,13 +98,14 @@ export type ModelsApi = {deleteCustomModel(sourceId: string, modelId: string): Promise<Source>;scanMigration(): Promise<MigrationScan>;applyMigration(itemIds: string[]): Promise<MigrationApplyResult>;- listEvents(limit?: number): Promise<ResolutionEvent[]>;+ /** `before` is an event id cursor (「查看全部」 pagination). */+ listEvents(limit?: number, before?: string): Promise<ResolutionEvent[]>;getRuntimeStatus(): Promise<RuntimeDependency>;/** `experimentalConsent` MUST be true for a consent-gated hub-held* subscription connect, or the server returns consent_required. */startOAuth(vendor: string, channel: SupplyChannel, experimentalConsent?: boolean): Promise<OAuthFlow>;- getOAuthStatus(flowId: string): Promise<OAuthFlow>;- submitOAuth(flowId: string, value: string): Promise<OAuthFlow>;+ getOAuthStatus(flowId: string): Promise<OAuthResult>;+ submitOAuth(flowId: string, value: string): Promise<OAuthResult>;cancelOAuth(flowId: string): Promise<void>;};@@ -102,15 +143,52 @@ const jsonInit = (method: string, body?: unknown): RequestInit => ({body: body === undefined ? undefined : JSON.stringify(body),});+/** api.md pins the shape to `{source, adopted_by}` with no extra nesting; the+ * bare-`Source` arm is the same tolerance every other write here keeps. */+type SourceCreatedResponse = { source?: Source; adopted_by?: AdoptedBy[] } & Source;+const created = (r: SourceCreatedResponse): SourceCreated => ({+ source: (r.source ?? r) as Source,+ // Absent is not the same as empty in the contract only for reauth, which never+ // reaches here; for creation an absent array means nothing adopted it.+ adopted_by: r.adopted_by ?? [],+});++/** The oauth terminal envelope, unwrapped without discarding the create half. */+export type OAuthResultResponse = { flow?: OAuthFlow } & OAuthFlow & { source?: Source; adopted_by?: AdoptedBy[] };+/** Exported for its own test: this is where the create half was being dropped. */+export const oauthResult = (r: OAuthResultResponse): OAuthResult => {+ const flow = (r.flow ?? r) as OAuthFlow;+ // Discriminate on the payload's own `intent`, not on which dialog is open:+ // `reauth` also terminates with a `source` but carries recovery counts instead+ // of adoption, and reading those as an adoption list would report the wrong+ // thing about the wrong flow. Absent `intent` is a `create` flow (the field+ // postdates the first shipped payloads, and create is all this UI starts).+ const isCreate = flow.intent !== 'reauth';+ return {+ flow,+ // No bare-`Source` tolerance here, unlike `created()`: this envelope always+ // nests the source under `source`, beside the flow it accompanies. An absent+ // `adopted_by` beside a present `source` still means nothing adopted it.+ created: isCreate && r.source ? { source: r.source, adopted_by: r.adopted_by ?? [] } : null,+ };+};+const liveApi: ModelsApi = {listSources: () => call<{ sources: Source[] }>('/api/models/sources').then((r) => r.sources),- createApiKeySource: (draft) => call<{ source?: Source } & Source>('/api/models/sources', jsonInit('POST', draft)).then((r) => (r.source ?? r) as Source),- createOAuthSource: (draft) => call<{ source?: Source } & Source>('/api/models/sources', jsonInit('POST', draft)).then((r) => (r.source ?? r) as Source),+ // Both keep `adopted_by`. The old unwrap-to-`source` dropped it on the floor,+ // and no later read can put it back: `/agents` shows today's orders, not which+ // of them this commit changed.+ createApiKeySource: (draft) => call<SourceCreatedResponse>('/api/models/sources', jsonInit('POST', draft)).then(created),patchSource: (id, patch) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(id)}`, jsonInit('PATCH', patch)).then((r) => (r.source ?? r) as Source),testSource: (id) => call<{ discovered: number }>(`/api/models/sources/${encodeURIComponent(id)}/test`, jsonInit('POST')).then((r) => r.discovered),deleteSource: (id, force) => call(`/api/models/sources/${encodeURIComponent(id)}${force ? '?force=1' : ''}`, jsonInit('DELETE')).then(() => undefined),- putPriority: (order) => call<{ priority?: Priority } & Priority>('/api/models/priority', jsonInit('PUT', { contract_version: CONTRACT_VERSION, order })).then((r) => (r.priority ?? r) as Priority),listAgents: () => call<{ agents: AgentSupply[] }>('/api/models/agents').then((r) => r.agents),+ getAgentSources: (backend) => call<{ agent: AgentSupply }>(`/api/models/agents/${backend}/sources`).then((r) => r.agent),+ // The body is TOTAL and closed: the route rejects unknown keys, so+ // `contract_version` is deliberately absent (unlike every other write here).+ putAgentSources: (backend, body) => call<{ agent: AgentSupply }>(`/api/models/agents/${backend}/sources`, jsonInit('PUT', body)).then((r) => r.agent),+ getAgentChain: (backend, model) => call<{ chain: AgentChain }>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`).then((r) => r.chain),+ 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),putMappings: (backend, mappings) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mappings`, jsonInit('PUT', { mappings })).then((r) => (r.agent ?? r) as AgentSupply),putMenu: (menu) => call<{ agent?: AgentSupply } & AgentSupply>('/api/models/agents/opencode/menu', jsonInit('PUT', { menu })).then((r) => (r.agent ?? r) as AgentSupply),@@ -118,15 +196,18 @@ const liveApi: ModelsApi = {deleteCustomModel: (sourceId, modelId) => call<{ source?: Source } & Source>('/api/models/custom-models', jsonInit('DELETE', { source_id: sourceId, model_id: modelId })).then((r) => (r.source ?? r) as Source),scanMigration: () => call<{ scan?: MigrationScan } & MigrationScan>('/api/models/migration/scan', jsonInit('POST')).then((r) => (r.scan ?? r) as MigrationScan),applyMigration: (itemIds) => call<MigrationApplyResult>('/api/models/migration/apply', jsonInit('POST', { item_ids: itemIds })),- listEvents: (limit = 20) => call<{ events: ResolutionEvent[] }>(`/api/models/events?limit=${limit}`).then((r) => r.events),+ listEvents: (limit = 20, before) =>+ call<{ events: ResolutionEvent[] }>(+ `/api/models/events?limit=${limit}${before ? `&before=${encodeURIComponent(before)}` : ''}`,+ ).then((r) => r.events),getRuntimeStatus: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/status').then((r) => (r.runtime ?? r) as RuntimeDependency),startOAuth: (vendor, channel, experimentalConsent) =>call<{ flow?: OAuthFlow } & OAuthFlow>('/api/models/oauth/start',jsonInit('POST', { vendor, channel, ...(experimentalConsent ? { experimental_consent: true } : {}) }),).then((r) => (r.flow ?? r) as OAuthFlow),- getOAuthStatus: (flowId) => call<{ flow?: OAuthFlow } & OAuthFlow>(`/api/models/oauth/status/${encodeURIComponent(flowId)}`).then((r) => (r.flow ?? r) as OAuthFlow),- submitOAuth: (flowId, value) => call<{ flow?: OAuthFlow } & OAuthFlow>('/api/models/oauth/submit', jsonInit('POST', { flow_id: flowId, value })).then((r) => (r.flow ?? r) as OAuthFlow),+ getOAuthStatus: (flowId) => call<OAuthResultResponse>(`/api/models/oauth/status/${encodeURIComponent(flowId)}`).then(oauthResult),+ submitOAuth: (flowId, value) => call<OAuthResultResponse>('/api/models/oauth/submit', jsonInit('POST', { flow_id: flowId, value })).then(oauthResult),cancelOAuth: (flowId) => call('/api/models/oauth/cancel', jsonInit('POST', { flow_id: flowId })).then(() => undefined),};@@ -140,27 +221,113 @@ const delay = <T>(value: T, ms = 260): Promise<T> => new Promise((r) => setTimeoclass MockStore {sources = buildMockSources();- priority = buildMockPriority();- agents = buildMockAgents();+ agents = buildMockAgents(this.sources);events = buildMockEvents();runtime = buildMockRuntime();flows = new Map<string, MockFlow>();- private ordered(): Source[] {+ // ── Fake server-side recomputation ───────────────────────────────────+ // Every read of an agent re-derives what the real server derives: the+ // per-backend order (recommended under `follow`, pruned under `custom`),+ // eligibility, and the supply rollup. That is what makes a drag-reorder or a+ // source deletion move 使用中 in the demo instead of leaving it stale.+ private syncAgents() {+ for (const a of this.agents) {+ if (a.mode === 'direct') {+ a.sources = null;+ } else {+ const policy = a.sources?.policy ?? 'follow';+ const eligibility = mockEligibility(this.sources, a.backend);+ const eligible = new Set(eligibility.filter((e) => e.eligible).map((e) => e.source_id));+ const order =+ policy === 'follow'+ ? mockRecommendedOrder(this.sources, a.backend)+ : // A `custom` subset is frozen, never extended — but a deleted or+ // newly ineligible id drops out (the invariant the server enforces).+ (a.sources?.order ?? []).filter((id) => eligible.has(id));+ a.sources = { policy, order, eligibility };+ }+ this.deriveSupply(a);+ }+ }++ /** §4.3 + §4.5 in miniature: capability (supplies the mapped id) split from+ * runnability (not blocked), then the rollup over the resulting chain. */+ private deriveSupply(a: AgentSupply) {+ if (a.mode === 'direct') {+ a.current = null;+ a.selected_model_id = null;+ a.selected_by_agent = null;+ a.supply_status = null;+ a.model_supply = null;+ a.named_agents = (a.named_agents ?? []).map((n) => ({ ...n, effective_model_id: null, supply_status: null }));+ return;+ }const byId = new Map(this.sources.map((s) => [s.id, s]));- const ranked = this.priority.order.map((id) => byId.get(id)).filter((s): s is Source => Boolean(s));- const extras = this.sources.filter((s) => !this.priority.order.includes(s.id));- return [...ranked, ...extras];+ const order = (a.sources?.order ?? []).map((id) => byId.get(id)).filter((s): s is Source => Boolean(s));+ const target = (model: string) => {+ const m = a.mappings?.find((x) => x.builtin_id === model && x.enabled && x.target_model_id);+ return m ? m.target_model_id : model;+ };+ const chainFor = (model: string) => order.filter((s) => s.models.some((mm) => mm.id === target(model)));+ if (a.builtin_models) {+ a.model_supply = a.builtin_models.map((m) => ({ model_id: m, chain_length: chainFor(m).length }));+ }+ const selected = a.selected_model_id ?? null;+ if (!selected) {+ a.current = null;+ a.supply_status = null;+ } else {+ const chain = chainFor(selected);+ const head = chain.find(isRunnable) ?? null;+ const blocked = chain.filter((s) => !isRunnable(s));+ if (!head) {+ a.current = null;+ a.supply_status =+ chain.length > 0 && blocked.every((s) => s.state.status === 'cooldown') ? 'waiting' : 'interrupted';+ } else {+ a.current = { model_id: selected, source_id: head.id, channel: head.supply_channel };+ a.supply_status = head.id === chain[0]?.id && blocked.length === 0 ? 'ok' : 'degraded';+ }+ }+ const rollup = a.supply_status ?? null;+ a.named_agents = (a.named_agents ?? []).map((n) =>+ n.effective_model_id ? { ...n, supply_status: rollup } : n,+ );}listSources() {- return delay(structuredClone(this.ordered()));+ // api.md: the inventory is explicitly UNORDERED — order is per-backend.+ return delay(structuredClone(this.sources));+ }++ /**+ * The `adopted_by` projection, derived the same way the server derives it:+ * re-run the recommendation, then report where the new id actually landed.+ *+ * It is deliberately NOT a guess from the source's vendor — a `follow` backend+ * adopts only what its eligibility admits, so the answer for one credential can+ * be 「claude 第 2 位」 and nothing at all for opencode. Anything on `custom` is+ * omitted by the contract; that omission is the signal the dialogs read.+ */+ private adoptionOf(sourceId: string): AdoptedBy[] {+ this.syncAgents();+ return this.agents+ .filter((a) => a.mode === 'hub' && a.sources?.policy === 'follow')+ .map((a) => ({ backend: a.backend, order: a.sources?.order ?? [] }))+ .filter(({ order }) => order.includes(sourceId))+ .map(({ backend, order }) => ({+ backend,+ policy: 'follow' as const,+ position: order.indexOf(sourceId) + 1, // one-based, per api.md+ }));}createApiKeySource(draft: ApiKeySourceCreate) {const count = mockDiscoveredCount(draft.vendor);const source: Source = {id: rid('src'),+ created_at: new Date().toISOString(),kind: 'api_key',vendor: draft.vendor,display_name: draft.vendor === 'custom' ? hostLabel(draft.base_url) : vendorLabel(draft.vendor),@@ -182,8 +349,8 @@ class MockStore {credential_ref: rid('cred'),};this.sources.push(source);- this.priority.order.push(source.id);- return delay(structuredClone(source), 900); // simulate probe latency+ // simulate probe latency+ return delay({ source: structuredClone(source), adopted_by: this.adoptionOf(source.id) }, 900);}deleteSource(id: string, force = false) {@@ -193,36 +360,121 @@ class MockStore {throw new ApiCallError('mode_switch_blocked');}this.sources = this.sources.filter((s) => s.id !== id);- this.priority.order = this.priority.order.filter((x) => x !== id);- for (const a of this.agents) if (a.current?.source_id === id) a.current = null;+ // Orders and the rollup are recomputed on the next read (syncAgents).return delay(undefined);}- putPriority(order: string[]) {- // Server echoes the authoritative full order (every non-deleted source once).- const known = new Set(this.sources.map((s) => s.id));- const cleaned = order.filter((id) => known.has(id));- const missing = this.sources.map((s) => s.id).filter((id) => !cleaned.includes(id));- this.priority = { contract_version: CONTRACT_VERSION, order: [...cleaned, ...missing] };- return delay(structuredClone(this.priority));- }-listAgents() {+ this.syncAgents();return delay(structuredClone(this.agents));}- setAgentMode(backend: AgentBackend, mode: AgentMode) {+ private agentOr404(backend: AgentBackend): AgentSupply {const agent = this.agents.find((a) => a.backend === backend);if (!agent) throw new ApiCallError('source_not_found');+ return agent;+ }++ getAgentSources(backend: AgentBackend) {+ this.syncAgents();+ return delay(structuredClone(this.agentOr404(backend)));+ }++ putAgentSources(backend: AgentBackend, body: AgentSourcesPut) {+ const agent = this.agentOr404(backend);+ if (agent.mode === 'direct') throw new ApiCallError('direct_mode');+ if (body.policy === 'follow') {+ // 恢复推荐顺序 discards the frozen subset; the order comes back from §4.2.+ agent.sources = { policy: 'follow', order: [], eligibility: null };+ } else {+ // §4.4's invariants, server-side: every id exists, is eligible here, and+ // appears once. Omitting one is how the user says 未启用 — not an error.+ const eligible = new Set(+ mockEligibility(this.sources, backend).filter((e) => e.eligible).map((e) => e.source_id),+ );+ const seen = new Set<string>();+ for (const id of body.order) {+ if (!eligible.has(id) || seen.has(id)) throw new ApiCallError('invalid_source_order', id);+ seen.add(id);+ }+ agent.sources = { policy: 'custom', order: [...body.order], eligibility: null };+ }+ this.syncAgents();+ return delay(structuredClone(agent), 380);+ }++ getAgentChain(backend: AgentBackend, model: string) {+ this.syncAgents();+ const agent = this.agentOr404(backend);+ // AC-7: direct mode has no src_* identity to report, so the route refuses+ // rather than answering with an empty (falsely alarming) chain.+ if (agent.mode === 'direct') throw new ApiCallError('direct_mode');+ const byId = new Map(this.sources.map((s) => [s.id, s]));+ const mapping = agent.mappings?.find((x) => x.builtin_id === model && x.enabled && x.target_model_id);+ const resolved = mapping ? mapping.target_model_id : model;+ const chain: AgentChainLink[] = (agent.sources?.order ?? [])+ .map((id) => byId.get(id))+ .filter((s): s is Source => s !== undefined && s.models.some((mm) => mm.id === resolved))+ .map((s) => ({+ source_id: s.id,+ via_mapping: Boolean(mapping),+ resolved_model_id: mapping ? resolved : null,+ health: chainHealth(s),+ runnable: isRunnable(s),+ retry_at: s.state.status === 'cooldown' ? s.state.retry_at ?? null : null,+ }));+ const runnable = chain.some((l) => l.runnable);+ const supply_state: AgentChain['supply_state'] = runnable+ ? 'ok'+ : chain.length > 0 && chain.every((l) => l.health === 'cooldown')+ ? 'waiting'+ : 'interrupted';+ return delay({ contract_version: CONTRACT_VERSION, backend, model_id: model, chain, supply_state });+ }++ probeAgent(backend: AgentBackend, model?: string) {+ this.syncAgents();+ const agent = this.agentOr404(backend);+ if (agent.mode === 'direct') throw new ApiCallError('direct_mode');+ const modelId = model ?? agent.selected_model_id;+ if (!modelId) throw new ApiCallError('model_unsupported');+ const byId = new Map(this.sources.map((s) => [s.id, s]));+ const mapping = agent.mappings?.find((x) => x.builtin_id === modelId && x.enabled && x.target_model_id);+ const resolved = mapping ? mapping.target_model_id : modelId;+ const head = (agent.sources?.order ?? [])+ .map((id) => byId.get(id))+ .find((s): s is Source => s !== undefined && s.models.some((mm) => mm.id === resolved) && isRunnable(s));+ // `probe_no_candidate` is the contract's code for this; `no_runnable_source`+ // was invented here and is in no error vocabulary, so the L5 dry-run button+ // would have been written against a code the server never sends.+ if (!head) throw new ApiCallError('probe_no_candidate');+ const probe: ProbeResult = {+ contract_version: CONTRACT_VERSION,+ backend,+ reachable: true,+ source_id: head.id,+ model_id: modelId,+ latency_ms: 180 + Math.floor(Math.random() * 420),+ via_mapping: Boolean(mapping),+ error: null,+ };+ return delay(probe, 1200); // one real request takes a real moment+ }++ setAgentMode(backend: AgentBackend, mode: AgentMode) {+ const agent = this.agentOr404(backend);agent.mode = mode;- if (mode === 'direct') {- agent.current = null;- } else if (!agent.current) {- const top = this.ordered().find((s) => s.state.status !== 'error');- agent.current = top- ? { model_id: top.models[0]?.id ?? 'unknown', source_id: top.id, channel: top.supply_channel }- : null;+ if (mode === 'hub') {+ // Rejoining the hub starts on the recommendation, and picks up whatever+ // model the backend defaults to (first built-in / first supplied id).+ agent.sources = { policy: 'follow', order: [], eligibility: null };+ agent.selected_model_id = agent.builtin_models?.[0] ?? this.sources[0]?.models[0]?.id ?? null;+ agent.named_agents = (agent.named_agents ?? []).map((n) => ({+ ...n,+ effective_model_id: agent.selected_model_id ?? null,+ }));}+ this.syncAgents();return delay(structuredClone(agent));}@@ -283,6 +535,7 @@ class MockStore {const channel: SupplyChannel = item.proposed_action === 'keep_native' ? 'native_cli' : 'hub';this.sources.push({id: rid('src'),+ created_at: new Date().toISOString(),kind: isKey ? 'api_key' : 'subscription',vendor: item.backend === 'opencode' ? 'zhipuai' : item.backend === 'codex' ? 'openai' : 'anthropic',display_name: item.masked_detail.split(' · ')[0] || 'Imported',@@ -305,12 +558,13 @@ class MockStore {const agent = this.agents.find((a) => a.backend === backend);if (agent) agent.mode = 'hub';}- this.priority.order = this.sources.map((s) => s.id);- return delay({ applied: chosen.length, sources: structuredClone(this.ordered()) }, 700);+ this.syncAgents();+ return delay({ applied: chosen.length, sources: structuredClone(this.sources) }, 700);}- listEvents(limit = 20) {- return delay(structuredClone(this.events.slice(0, limit)));+ listEvents(limit = 20, before?: string) {+ const start = before ? this.events.findIndex((e) => e.id === before) + 1 : 0;+ return delay(structuredClone(this.events.slice(start, start + limit)));}getRuntimeStatus() {@@ -324,8 +578,8 @@ class MockStore {const flow: OAuthFlow = {flow_id: rid('oaf'),// Deterministic pending-source binding (schema: hub flows always set it),- // consumed by createOAuthSource on finalize — mirrors the server, where- // create_source assigns source.id = flow.source_id.+ // consumed when the flow completes — mirrors the server, where the+ // materialized source takes source.id = flow.source_id.source_id: rid('src'),vendor,channel,@@ -356,7 +610,7 @@ class MockStore {entry.polls += 1;const { flow } = entry;if (flow.state === 'success' || flow.state === 'failed' || flow.state === 'cancelled') {- return delay(structuredClone(flow));+ return delay(this.oauthResult(entry));}if (flow.presentation.expects === 'none') {// Device flow self-completes after a few polls.@@ -365,7 +619,7 @@ class MockStore {// Paste flows: verifying → success on the next poll.this.completeFlow(entry);}- return delay(structuredClone(flow));+ return delay(this.oauthResult(entry));}submitOAuth(flowId: string, _value: string) {@@ -373,7 +627,7 @@ class MockStore {if (!entry) throw new ApiCallError('flow_not_found');entry.submitted = true;entry.flow.state = 'verifying';- return delay(structuredClone(entry.flow));+ return delay(this.oauthResult(entry));}cancelOAuth(flowId: string) {@@ -382,48 +636,58 @@ class MockStore {return delay(undefined);}- // A completed flow reaches `success` but does NOT itself materialize a Source- // (mirrors the server, where flow completion and source creation are split):- // the UI must finalize via createOAuthSource. Earlier the mock appended here,- // which hid the live P0 gap the audit flagged.+ // Reaching `success` IS the creation, as on the server: status/submit+ // materialize the Source inside the same call that first reports success, and+ // consume the flow binding doing it. Splitting the two here is what let a+ // client that finalized with a second POST look correct against the mock while+ // failing `flow_not_found` against the real server.private completeFlow(entry: MockFlow) {entry.flow.state = 'success';- }-- createOAuthSource(draft: OAuthSourceCreate) {- const entry = this.flows.get(draft.oauth_flow_ref);- if (!entry || entry.flow.state !== 'success') throw new ApiCallError('flow_not_found');const flow = entry.flow;- const isOpenai = flow.vendor === 'openai';const id = flow.source_id ?? rid('src');- // Idempotent finalize: a duplicate browser retry must not double-create- // (the server raises migration_item_conflict; here we just re-echo).- const existing = this.sources.find((s) => s.id === id);- if (existing) return delay(structuredClone(existing), 300);- const source: Source = {+ flow.source_id = id;+ // Idempotent, like `_create_oauth_source(idempotent=True)`: re-polling a+ // completed flow re-echoes the same source instead of creating a second one.+ if (this.sources.some((s) => s.id === id)) return;+ const isOpenai = flow.vendor === 'openai';+ this.sources.push({id,+ created_at: new Date().toISOString(),kind: 'subscription',vendor: flow.vendor,- display_name: draft.display_name ?? (isOpenai ? 'ChatGPT 订阅' : 'Claude 订阅'),+ display_name: isOpenai ? 'ChatGPT 订阅' : 'Claude 订阅',protocol: isOpenai ? 'openai_responses' : 'anthropic',base_url: null,- supply_channel: draft.supply_channel,- experimental_consent_at: draft.supply_channel === 'hub' ? new Date().toISOString() : null,+ supply_channel: flow.channel,+ experimental_consent_at: flow.channel === 'hub' ? new Date().toISOString() : null,billing: 'monthly',state: { status: 'standby', retry_at: null, detail_key: null },usage: { cycle_used_pct: 0, month_spend_cents: null, currency: null },// native_cli subscriptions surface the sanctioned CLI account; hub-held// experimental sources may stay null until a later adapter rev (schema).- account_label: draft.supply_channel === 'native_cli' ? '[email protected]' : null,+ account_label: flow.channel === 'native_cli' ? '[email protected]' : null,masked_credential: null,models: isOpenai? [{ id: 'gpt-5.6', display_name: 'GPT-5.6', provenance: 'discovered', discovered_at: new Date().toISOString() }]: [{ id: 'claude-opus-4-6', display_name: 'Opus 4.6', provenance: 'discovered', discovered_at: new Date().toISOString() }],- credential_ref: draft.supply_channel === 'hub' ? rid('cred') : null,+ credential_ref: flow.channel === 'hub' ? rid('cred') : null,+ });+ }++ /**+ * The terminal envelope every status/submit response carries (api.md, "OAuth+ * completion"): the flow, plus the creation it performed once it succeeded.+ * Looked up by `source_id` rather than remembered from the completing call, so+ * a later poll on an already-finished flow answers the same thing the server's+ * idempotent path does instead of pretending nothing was created.+ */+ private oauthResult(entry: MockFlow): OAuthResult {+ const flow = structuredClone(entry.flow);+ const source = flow.state === 'success' ? this.sources.find((s) => s.id === flow.source_id) : undefined;+ return {+ flow,+ created: source ? { source: structuredClone(source), adopted_by: this.adoptionOf(source.id) } : null,};- this.sources.push(source);- this.priority.order.push(source.id);- return delay(structuredClone(source), 300);}patchSource(id: string, patch: SourcePatch) {@@ -445,6 +709,17 @@ class MockStore {}}+// §4.3's runnability half: retry-ready, and never needs_action / error. A+// cooling source stays visible in the chain but is skipped by the turn. Derived+// from the page's own predicate rather than restated, so the fake server and the+// UI cannot drift into disagreeing about which statuses can serve a turn.+const isRunnable = (s: Source): boolean => !isUnhealthy(s.state);++// SourceStatus → the chain link's health vocabulary (the two healthy statuses+// collapse; the three blockers map one-to-one).+const chainHealth = (s: Source): AgentChainLink['health'] =>+ s.state.status === 'cooldown' ? 'cooldown' : s.state.status === 'needs_action' ? 'needs_action' : s.state.status === 'error' ? 'error' : 'healthy';+function vendorLabel(vendor: string): string {const table: Record<string, string> = {anthropic: 'Anthropic API Key',@@ -478,12 +753,14 @@ const mockStore = new MockStore();const mockApi: ModelsApi = {listSources: () => mockStore.listSources(),createApiKeySource: (draft) => mockStore.createApiKeySource(draft),- createOAuthSource: (draft) => mockStore.createOAuthSource(draft),patchSource: (id, patch) => mockStore.patchSource(id, patch),testSource: (id) => mockStore.testSource(id),deleteSource: (id, force) => mockStore.deleteSource(id, force),- putPriority: (order) => mockStore.putPriority(order),listAgents: () => mockStore.listAgents(),+ getAgentSources: (backend) => mockStore.getAgentSources(backend),+ putAgentSources: (backend, body) => mockStore.putAgentSources(backend, body),+ getAgentChain: (backend, model) => mockStore.getAgentChain(backend, model),+ probeAgent: (backend, model) => mockStore.probeAgent(backend, model),setAgentMode: (backend, mode) => mockStore.setAgentMode(backend, mode),putMappings: (backend, mappings) => mockStore.putMappings(backend, mappings),putMenu: (menu) => mockStore.putMenu(menu),@@ -491,7 +768,7 @@ const mockApi: ModelsApi = {deleteCustomModel: (sourceId, modelId) => mockStore.deleteCustomModel(sourceId, modelId),scanMigration: () => mockStore.scanMigration(),applyMigration: (itemIds) => mockStore.applyMigration(itemIds),- listEvents: (limit) => mockStore.listEvents(limit),+ listEvents: (limit, before) => mockStore.listEvents(limit, before),getRuntimeStatus: () => mockStore.getRuntimeStatus(),startOAuth: (vendor, channel, experimentalConsent) => mockStore.startOAuth(vendor, channel, experimentalConsent),getOAuthStatus: (flowId) => mockStore.getOAuthStatus(flowId),diff --git a/ui/src/components/settings/models/oauthResult.test.ts b/ui/src/components/settings/models/oauthResult.test.tsnew file mode 100644index 000000000..2502ccf8d--- /dev/null+++ b/ui/src/components/settings/models/oauthResult.test.ts@@ -0,0 +1,70 @@+// The OAuth terminal envelope (api.md → "OAuth completion").+//+// The regression these pin: the transport used to unwrap the response to `r.flow+// ?? r` and return the flow alone, so the `{source, adopted_by}` half the server+// puts beside it was discarded — and since the server materializes the Source+// inside the very call that first reports success (consuming the flow binding+// doing it), the dialog's follow-up POST /sources was then refused as+// `flow_not_found` on a connect that had in fact succeeded. Nothing in the mock+// caught it, because the mock had modelled completion and creation as separate.+import { describe, expect, it } from 'vitest';++import { oauthResult, type OAuthResultResponse } from './modelsApi';+import type { AdoptedBy, OAuthFlow, Source } from './types';++const flow = (over: Partial<OAuthFlow> = {}): OAuthFlow => ({+ flow_id: 'oaf_1',+ source_id: 'src_1',+ vendor: 'anthropic',+ channel: 'native_cli',+ state: 'success',+ presentation: { auth_url: null, device_code: null, expects: 'none', instructions_key: null },+ error_key: null,+ expires_at: null,+ ...over,+});++const source = { id: 'src_1', vendor: 'anthropic', kind: 'subscription' } as unknown as Source;+const adopted: AdoptedBy[] = [{ backend: 'claude', policy: 'follow', position: 1 }];++describe('oauthResult', () => {+ it('keeps the creation the terminal response reports', () => {+ const r = { flow: flow(), source, adopted_by: adopted } as OAuthResultResponse;+ expect(oauthResult(r)).toEqual({ flow: r.flow, created: { source, adopted_by: adopted } });+ });++ it('reads an absent adopted_by beside a source as nothing adopted it', () => {+ // Distinct from a response that reports no creation at all: here the source+ // exists, so 「没有 Agent 采用」 is a true statement and must be rendered.+ const { created } = oauthResult({ flow: flow(), source } as OAuthResultResponse);+ expect(created).toEqual({ source, adopted_by: [] });+ });++ it('reports no creation while the flow is still running', () => {+ expect(oauthResult({ flow: flow({ state: 'awaiting_action' }) } as OAuthResultResponse).created).toBeNull();+ });++ it('reports no creation for a terminal reauth flow', () => {+ // A reauth also terminates with a `source`, but its counterpart keys are+ // `recovered` / `interrupted_pairs` — no order changed, so there is no+ // adoption to report. Reading its payload as an adoption would state+ // something about this connect that the server never said.+ const r = { flow: flow({ intent: 'reauth' }), source } as OAuthResultResponse;+ expect(oauthResult(r).created).toBeNull();+ });++ it('treats a flow without `intent` as a create flow', () => {+ // The field postdates the first shipped payloads and the schema keeps it+ // optional, so absent must not mean "unknown, report nothing".+ expect(oauthResult({ flow: flow(), source } as OAuthResultResponse).created).not.toBeNull();+ });++ it('tolerates a flat terminal payload', () => {+ // Same tolerance every other write in this transport keeps: the flow may+ // arrive un-nested, and the create half still has to survive.+ const r = { ...flow(), source, adopted_by: adopted } as OAuthResultResponse;+ const result = oauthResult(r);+ expect(result.flow.flow_id).toBe('oaf_1');+ expect(result.created?.adopted_by).toEqual(adopted);+ });+});diff --git a/ui/src/components/settings/models/reorder.test.ts b/ui/src/components/settings/models/reorder.test.tsindex d2ec19949..d16b29a63 100644--- a/ui/src/components/settings/models/reorder.test.ts+++ b/ui/src/components/settings/models/reorder.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { movedOrder } from './reorder';+import { movedOrder, sameIds } from './reorder';const IDS = ['a', 'b', 'c', 'd'];@@ -40,3 +40,33 @@ describe('movedOrder', () => {expect(movedOrder(down, 2, -1)).toEqual(IDS);});});++describe('sameIds', () => {+ it('compares contents, not identity — the whole reason it exists', () => {+ expect(sameIds(IDS, [...IDS])).toBe(true);+ expect(sameIds(IDS, ['a', 'c', 'b', 'd'])).toBe(false);+ expect(sameIds(IDS, ['a', 'b', 'c'])).toBe(false);+ // Same set, different order IS a different order: this list is the spend order.+ expect(sameIds(['a', 'b'], ['b', 'a'])).toBe(false);+ expect(sameIds([], [])).toBe(true);+ });++ // The composition that decides whether a `follow` backend gets forked to+ // `custom`. `movedOrder` hands back a FRESH array at either boundary, so the+ // commit path has to compare contents; on `!==` alone every ArrowUp on row 1+ // would silently cost the user their recommended order.+ it('sees a boundary move as no change at all', () => {+ const up = movedOrder(IDS, 0, -1);+ expect(up).not.toBe(IDS);+ expect(sameIds(IDS, up)).toBe(true);+ expect(sameIds(IDS, movedOrder(IDS, IDS.length - 1, 1))).toBe(true);+ });++ it('sees a drag that lands back where it started as no change', () => {+ expect(sameIds(IDS, movedOrder(movedOrder(IDS, 1, 1), 2, -1))).toBe(true);+ });++ it('still sees a real move as a change', () => {+ expect(sameIds(IDS, movedOrder(IDS, 1, 1))).toBe(false);+ });+});diff --git a/ui/src/components/settings/models/reorder.ts b/ui/src/components/settings/models/reorder.tsindex ead9e78bf..5c6dd0969 100644--- a/ui/src/components/settings/models/reorder.ts+++ b/ui/src/components/settings/models/reorder.ts@@ -1,17 +1,18 @@/**- * Priority reordering for the 来源 list.+ * One-step reordering for a per-Agent source order (the 来源顺序 drawer).*- * Kept as a pure function so the one-step reorder behind the row menu's- * 上移一位 / 下移一位 is testable without a DOM: the list order IS the spend- * order, so an off-by-one here silently changes which account gets billed first.+ * Kept as a pure function so the keyboard/screen-reader path beside drag is+ * testable without a DOM: the order IS the spend order, so an off-by-one here+ * silently changes which account an Agent bills first.*//*** The id order after moving `index` by `delta` positions.** Returns the input order unchanged when the move would fall off either end, so- * callers can hand the result straight to the persist path without a second- * bounds check — a no-op move persists a no-op.+ * callers need no second bounds check — but they DO need `sameIds` before they+ * persist, because the returned list is a fresh array and reference equality can+ * never see that nothing moved.*/export function movedOrder(ids: readonly string[], index: number, delta: number): string[] {const target = index + delta;@@ -20,3 +21,15 @@ export function movedOrder(ids: readonly string[], index: number, delta: number)[next[index], next[target]] = [next[target], next[index]];return next;}++/**+ * Same ids in the same positions — the test that decides whether an edit happened.+ *+ * It lives beside `movedOrder` because it is the other half of one rule: an arrow+ * key at either end, and a drag that lands back where it started, both produce a+ * NEW array holding the old order. Whoever persists has to compare contents, and a+ * `follow` backend forks to `custom` on the first write, so getting this wrong+ * costs the user their recommendation for an input that did nothing.+ */+export const sameIds = (a: readonly string[], b: readonly string[]): boolean =>+ a.length === b.length && a.every((id, i) => id === b[i]);diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.tsnew file mode 100644index 000000000..861c75115--- /dev/null+++ b/ui/src/components/settings/models/serverCopy.test.ts@@ -0,0 +1,62 @@+// The open-vocabulary half of AC-19.+//+// contractLocaleKeys.test.ts can only cover keys a schema CLOSES (`enum` /+// `const`). The oauth flow's `instructions_key` / `error_key` and a migration+// item's `notes_key` are declared as free-form runtime keys, so no build-time+// check can know their membership and a new adapter rev is enough to send one no+// bundle carries. i18next then returns the key itself, which renders a machine+// string to a user as if it were a sentence — that is what this guards.+import { createInstance, type TFunction } from 'i18next';+import { describe, expect, it } from 'vitest';++import en from '../../../i18n/en.json';+import zh from '../../../i18n/zh.json';+import { serverText } from './serverCopy';++const t = (lng: 'en' | 'zh'): TFunction => {+ const i18n = createInstance();+ void i18n.init({+ lng,+ fallbackLng: 'en',+ resources: { en: { translation: en }, zh: { translation: zh } },+ interpolation: { escapeValue: false },+ });+ return i18n.t;+};++describe('serverText', () => {+ it.each(['zh', 'en'] as const)('renders a key the bundle carries in %s', (lng) => {+ // The keys the backend actually emits today (native_oauth._INSTRUCTIONS_KEYS,+ // migration._CUSTOM_ENDPOINT_NOTE) must come through unchanged.+ expect(serverText(t(lng), 'settings.models.oauth.pasteCode.hint', 'settings.models.oauth.error.generic')).toBe(+ t(lng)('settings.models.oauth.pasteCode.hint'),+ );+ expect(serverText(t(lng), 'settings.models.source.customEndpoint')).toBe(+ t(lng)('settings.models.source.customEndpoint'),+ );+ });++ it.each(['zh', 'en'] as const)('falls back to the generic copy for an unknown key in %s', (lng) => {+ const text = serverText(t(lng), 'models.oauth.some.future.adapter.key', 'settings.models.oauth.error.generic');+ expect(text).toBe(t(lng)('settings.models.oauth.error.generic'));+ // The point of the whole helper: never the key.+ expect(text).not.toContain('models.oauth.some.future');+ });++ it('renders nothing for optional copy whose key is unknown', () => {+ // A migration row's secondary line has no generic substitute — dropping the+ // line is honest, printing the key is not.+ expect(serverText(t('zh'), 'models.migration.some.future.note')).toBeNull();+ });++ it('renders nothing when there is no key at all', () => {+ expect(serverText(t('zh'), null)).toBeNull();+ expect(serverText(t('zh'), undefined)).toBeNull();+ });++ it('still falls back when the key is absent but a fallback is given', () => {+ expect(serverText(t('en'), null, 'settings.models.oauth.error.generic')).toBe(+ t('en')('settings.models.oauth.error.generic'),+ );+ });+});diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.tsnew file mode 100644index 000000000..f899e0f48--- /dev/null+++ b/ui/src/components/settings/models/serverCopy.ts@@ -0,0 +1,41 @@+// Rendering an i18n key the SERVER chose, safely.+//+// Two kinds of key reach this page from the backend. Closed vocabularies —+// `SourceState.detail_key`, `ProbeResult.error` — are declared member-by-member+// in the contract schemas, so contractLocaleKeys.test.ts can enumerate them and+// fail the build when a bundle is missing one. Open ones cannot be: the+// oauth-flow's `instructions_key` / `error_key` and a migration item's+// `notes_key` are described as free-form runtime-declared keys, so no test can+// know their membership ahead of time and any of them can be absent from a bundle+// at runtime — a new adapter rev is enough.+//+// i18next's default for a missing key is the key itself, so the honest failure+// mode without this helper is a machine string ("models.migration.keep_native.+// sanctioned") rendered to a user as if it were a sentence. This turns that into+// the generic copy the surrounding UI already has for the same situation.+//+// Not in format.ts on purpose: that module is deliberately i18n-free (its callers+// wrap what it returns), and this one has to take `t`.+import type { TFunction } from 'i18next';++/**+ * Translate a server-declared key, falling back to `fallbackKey` when the bundle+ * has no entry for it. Returns null when neither resolves — omit `fallbackKey`+ * for optional copy, where rendering nothing is the honest degradation.+ */+export const serverText = (+ t: TFunction,+ key: string | null | undefined,+ fallbackKey?: string,+): string | null => {+ if (key) {+ // `defaultValue: ''` rather than the fallback text itself: i18next returns+ // the default for a missing key, and an empty one lets us tell "missing" from+ // "translated to something" without string-comparing against the key.+ const translated = t(key, { defaultValue: '' }) as string;+ if (translated) return translated;+ }+ if (!fallbackKey) return null;+ const generic = t(fallbackKey, { defaultValue: '' }) as string;+ return generic || null;+};diff --git a/ui/src/components/settings/models/sufficiency.test.ts b/ui/src/components/settings/models/sufficiency.test.tsnew file mode 100644index 000000000..f37b3da9d--- /dev/null+++ b/ui/src/components/settings/models/sufficiency.test.ts@@ -0,0 +1,193 @@+// Tests for the one owner of 「will the next turn actually run?」.+//+// Written test-first, one block per consuming site, because the class this module+// closes was five sites each answering that question with a `.length` — and the+// review had named only two of them. The last block is the grep guard that makes a+// sixth site impossible to add quietly.+import { readFileSync, readdirSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import {+ SUPPLY_WARNINGS,+ adoptionVerdict,+ connectOutcome,+ isSupplyWarning,+ orderSufficiency,+} from './sufficiency';+import type { AdoptedBy, AgentSupply, Source, SourceState, SourceStatus } from './types';++const source = (id: string, status: SourceStatus): Source => ({+ id,+ kind: 'api_key',+ vendor: 'anthropic',+ display_name: id,+ protocol: 'anthropic',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status, ...(status === 'cooldown' ? { retry_at: '2030-01-01T00:00:00Z' } : {}) } as SourceState,+ models: [],+});++const hub = (order: string[], supply_status: AgentSupply['supply_status'] = null): AgentSupply => ({+ backend: 'claude',+ mode: 'hub',+ menu_kind: 'fixed',+ sources: { policy: 'follow', order },+ supply_status,+});++const adopted = (backend: AdoptedBy['backend'], position: number): AdoptedBy => ({+ backend,+ policy: 'follow',+ position,+});++describe('adoptionVerdict — the creation dialogs (AdoptionNote, AddApiKeyDialog, OAuthConnectDialog)', () => {+ it('reports an empty adopter list as adopted_none, which IS provable', () => {+ // The server sent the array and it is empty: nobody took the source. That is a+ // closed fact, not an absence of information.+ expect(adoptionVerdict([])).toEqual({ kind: 'adopted_none' });+ });++ it('refuses to call a non-empty adopter list covered while skipped_by is missing', () => {+ // The honesty rule. `_adopted_by` filters `policy == "follow"`, so a `custom`+ // backend that skipped the source is ABSENT — indistinguishable in this payload+ // from a backend that was never eligible. Non-empty proves someone took it; it+ // proves nothing about who did not.+ expect(adoptionVerdict([adopted('claude', 1)])).toEqual({ kind: 'indeterminate' });+ });++ it('has no verdict at all when the creation result never arrived', () => {+ expect(adoptionVerdict(null)).toEqual({ kind: 'indeterminate' });+ });++ // The two branches the server half unlocks. Reachable today only through the+ // parameter, so the wiring is proved before the field exists rather than after.+ it('is covered once the server states that nothing eligible was skipped', () => {+ expect(adoptionVerdict([adopted('claude', 1)], [])).toEqual({ kind: 'covered' });+ });++ it('names the skipped backends when the server states them', () => {+ const verdict = adoptionVerdict(+ [adopted('claude', 1)],+ [{ backend: 'codex', reason: 'custom-order-omission' }],+ );+ expect(verdict).toEqual({ kind: 'partly_skipped', backends: ['codex'] });+ });++ it('still reports adopted_none when everyone skipped', () => {+ // Nobody adopted it: the remedy is the same 「go add it somewhere」 line, and+ // splitting that into a second sentence would say less, not more.+ expect(adoptionVerdict([], [{ backend: 'codex', reason: 'custom-order-omission' }])).toEqual({+ kind: 'adopted_none',+ });+ });+});++describe('orderSufficiency — the drawer (SourceOrderDrawer) and the connect toasts', () => {+ it('separates 「nothing enabled」 from 「nothing works」, because the remedies differ', () => {+ expect(orderSufficiency([], [source('a', 'active')])).toEqual({ kind: 'adopted_none' });+ expect(orderSufficiency(['a'], [source('a', 'needs_action')])).toEqual({ kind: 'nothing_runnable' });+ });++ it('is covered when any enabled source can serve, not when the list is non-empty', () => {+ expect(orderSufficiency(['a', 'b'], [source('a', 'error'), source('b', 'standby')])).toEqual({+ kind: 'covered',+ });+ });++ it('counts a cooling source as unable to serve right now', () => {+ // `cooldown` heals itself, but the turn taken during it still fails, and this+ // verdict answers 「the NEXT turn」.+ expect(orderSufficiency(['a'], [source('a', 'cooldown')])).toEqual({ kind: 'nothing_runnable' });+ });++ it('will not claim nothing runs when an enabled id is missing from the inventory', () => {+ // The two reads can disagree; an id we cannot resolve is unknown, not broken.+ expect(orderSufficiency(['a', 'ghost'], [source('a', 'error')])).toEqual({ kind: 'indeterminate' });+ });++ it('is indeterminate where the source inventory is not loaded', () => {+ expect(orderSufficiency(['a'], null)).toEqual({ kind: 'indeterminate' });+ expect(orderSufficiency(null, [source('a', 'active')])).toEqual({ kind: 'indeterminate' });+ });+});++describe('connectOutcome — the two mode-switch toasts', () => {+ it('reports a switch that did not take', () => {+ expect(connectOutcome({ ...hub([]), mode: 'direct' }, [])).toBe('failed');+ });++ it('keeps the server word whenever the server graded the supply', () => {+ for (const status of ['degraded', 'waiting', 'interrupted'] as const) {+ expect(connectOutcome(hub(['a'], status), [source('a', 'active')])).toBe(status);+ }+ expect(connectOutcome(hub(['a'], 'ok'), [source('a', 'active')])).toBe('connected');+ });++ it('warns about an empty order before consulting the grade', () => {+ expect(connectOutcome(hub([], 'ok'), [])).toBe('noSources');+ });++ it('no longer reads a null grade as success', () => {+ // The finding. `supply_status: null` means the server had no model to resolve+ // (`_requested_model` returned nothing) — it is silence about the order, and the+ // old code answered it with the order's length.+ expect(connectOutcome(hub(['a']), [source('a', 'needs_action')])).toBe('nothingRunnable');+ expect(connectOutcome(hub(['a']), [source('a', 'active')])).toBe('connected');+ });++ it('says 「I did not check」 rather than 「fine」 where the inventory is absent', () => {+ // BackendSupplyModeCard holds no source list. Its toast states the mode change,+ // which is a fact it owns; it must not upgrade that into a supply claim.+ expect(connectOutcome(hub(['a']), null)).toBe('indeterminate');+ expect(isSupplyWarning('indeterminate')).toBe(false);+ });++ it('routes exactly the warning outcomes through the warning copy family', () => {+ expect([...SUPPLY_WARNINGS].sort()).toEqual(+ ['degraded', 'interrupted', 'noSources', 'nothingRunnable', 'waiting'].sort(),+ );+ expect(isSupplyWarning('connected')).toBe(false);+ expect(isSupplyWarning('failed')).toBe(false);+ });+});++describe('the class: no site answers sufficiency with an emptiness test', () => {+ const here = dirname(fileURLToPath(import.meta.url));+ const files = readdirSync(here, { recursive: true, encoding: 'utf8' })+ .filter((f) => /\.tsx?$/.test(f) && !/\.test\.tsx?$/.test(f) && f !== 'sufficiency.ts');++ /**+ * The identifiers that carry the question, used as a BOOLEAN. A count is fine+ * (`{ count: enabledIds.length }` renders a group header and claims nothing), so+ * the operator is what the rule keys on — which is why it needs no allowance list.+ */+ const PROXY = /\b(?:adopted_by|adoptedBy|order|enabledIds)\.length\s*(?:[=!<>]=|[<>]|\?|\)|&&|\|\|)/;++ it('sweeps a non-trivial file set', () => {+ // Without this the rule below passes over an empty list after any move.+ expect(files.length).toBeGreaterThan(15);+ expect(files).toContain('AdoptionNote.tsx');+ });++ it.each([+ 'AdoptionNote.tsx',+ 'AddApiKeyDialog.tsx',+ 'OAuthConnectDialog.tsx',+ 'SourceOrderDrawer.tsx',+ 'supply.ts',+ ])('%s asks the owner instead of keeping its own proxy', (name) => {+ // supply.ts is on the list because `connectOutcome` MOVED out of it: the module+ // that used to own the wrong answer must not grow a replacement.+ expect(readFileSync(join(here, name), 'utf8')).not.toMatch(PROXY);+ });++ it('holds for every other module on the page too', () => {+ const offenders = files.filter((f) => PROXY.test(readFileSync(join(here, f), 'utf8')));+ expect(offenders).toEqual([]);+ });+});diff --git a/ui/src/components/settings/models/sufficiency.ts b/ui/src/components/settings/models/sufficiency.tsnew file mode 100644index 000000000..47e212e4f--- /dev/null+++ b/ui/src/components/settings/models/sufficiency.ts@@ -0,0 +1,142 @@+// One owner for the question five surfaces were each answering on their own:+// 「will the next turn actually run?」+//+// The class this closes is an EMPTINESS test standing in for an ADEQUACY test. Five+// sites asked `collection.length === 0` and read a non-empty collection as success —+// AdoptionNote, both creation dialogs' auto-close timers, the order drawer's warning,+// and `connectOutcome`. Three different arrays, one question, five answers, and the+// review had named two of them. So the remedy is not five guards: it is one function+// that returns a CLOSED verdict, and no caller left holding a length.+//+// The honesty rule that shapes the union: what today's payload cannot prove is+// `indeterminate`, never optimistic. Two fields would make more of it provable —+// `skipped_by` beside `adopted_by` (the eligible-but-skipped complement, which+// `_adopted_by` filters out server-side) and process availability at backend grain+// (contracts v4 carries it only on `agent-chain`). Both are server-side and out of+// this lane. Until they land, the verdicts that depend on them stay indeterminate and+// the surfaces keyed on them stay quiet — which is the correct behaviour for a+// confirmation that would otherwise be able to lie. Their arrival is pure wiring:+// `adoptionVerdict` already takes the complement, and `orderSufficiency` already asks+// one predicate about each source.+import { isUnhealthy } from './supply';+import type { AdoptedBy, AgentBackend, AgentSupply, Source } from './types';++/**+ * The closed verdict. Not every grain can produce every member — each function+ * documents its own subset — but there is exactly one vocabulary.+ *+ * `adopted_none` is the empty-membership case at either grain: no backend adopted the+ * source, or no source is enabled for the backend. It is deliberately distinct from+ * `nothing_runnable`, because the remedy is 「add one」 rather than 「fix one」.+ */+export type Sufficiency =+ | { kind: 'covered' }+ | { kind: 'partly_skipped'; backends: AgentBackend[] }+ | { kind: 'nothing_runnable' }+ | { kind: 'adopted_none' }+ | { kind: 'indeterminate' };++/**+ * The eligible-but-skipped complement of `adopted_by`.+ *+ * Typed locally on purpose: `types.ts` mirrors the FROZEN contracts and never runs+ * ahead of them. When the field ships, this type moves there and the parameter below+ * starts being fed — no logic changes, and the tests that already cover the branch+ * stop being the only thing exercising it.+ */+export type SkippedBy = {+ backend: AgentBackend;+ /** v2's only cause: the backend keeps a `custom` order, which the server never+ * extends. An INELIGIBLE backend is not 「skipped」 — it was never a candidate. */+ reason: 'custom-order-omission';+};++/**+ * Did the new source actually reach everyone it should have?+ *+ * Returns `adopted_none` | `partly_skipped` | `covered` | `indeterminate`.+ */+export function adoptionVerdict(+ adoptedBy: readonly AdoptedBy[] | null | undefined,+ skippedBy?: readonly SkippedBy[] | null,+): Sufficiency {+ if (!adoptedBy) return { kind: 'indeterminate' };+ // Empty is a closed fact — the server sent the list and nobody is on it.+ if (adoptedBy.length === 0) return { kind: 'adopted_none' };+ // Non-empty proves someone took it and nothing about who did not.+ if (!skippedBy) return { kind: 'indeterminate' };+ if (skippedBy.length === 0) return { kind: 'covered' };+ return { kind: 'partly_skipped', backends: skippedBy.map((s) => s.backend) };+}++/**+ * Can this backend's enabled order serve the next turn?+ *+ * Returns `adopted_none` | `nothing_runnable` | `covered` | `indeterminate`. Takes the+ * ids rather than the agent so the drawer can ask about the order the user is CURRENTLY+ * editing, which is the order the warning is about.+ *+ * Known v4 caveat: `isUnhealthy` reads the source's own state, and a healthy+ * `native_cli` source can still be unrunnable at chain grain (the CLI process is not+ * installed on this machine). v4 publishes that fact only on `agent-chain`, whose grain+ * is (agent, model). So `covered` here means 「a source reports itself able to serve」,+ * which is the strongest claim this payload supports; the verdict tightens on its own+ * the day availability arrives at backend grain.+ */+export function orderSufficiency(+ orderIds: readonly string[] | null | undefined,+ sources: readonly Source[] | null | undefined,+): Sufficiency {+ if (!orderIds) return { kind: 'indeterminate' };+ if (orderIds.length === 0) return { kind: 'adopted_none' };+ if (!sources) return { kind: 'indeterminate' };++ const byId = new Map(sources.map((s) => [s.id, s]));+ const resolved = orderIds.map((id) => byId.get(id)).filter((s): s is Source => s !== undefined);+ if (resolved.some((s) => !isUnhealthy(s.state))) return { kind: 'covered' };+ // Every id we could resolve is down. If some could not be resolved, the two reads+ // disagree and an unknown source is not a broken one.+ return resolved.length === orderIds.length ? { kind: 'nothing_runnable' } : { kind: 'indeterminate' };+}++/** Outcomes that own a warning string under `settings.models.supply.*`. */+export const SUPPLY_WARNINGS = ['degraded', 'waiting', 'interrupted', 'noSources', 'nothingRunnable'] as const;+export type SupplyWarning = (typeof SUPPLY_WARNINGS)[number];++/**+ * What to tell the user right after they switch a backend to the Hub.+ *+ * `indeterminate` is not a warning and not a success claim — it is 「the switch took」+ * and nothing more, which is all a caller without the source inventory may say.+ */+export type ConnectOutcome = 'connected' | 'failed' | 'indeterminate' | SupplyWarning;++export const isSupplyWarning = (outcome: ConnectOutcome): outcome is SupplyWarning =>+ (SUPPLY_WARNINGS as readonly string[]).includes(outcome);++export function connectOutcome(agent: AgentSupply, sources: readonly Source[] | null | undefined): ConnectOutcome {+ // The PATCH echoed something other than hub: the switch did not take.+ if (agent.mode !== 'hub') return 'failed';++ const verdict = orderSufficiency(agent.sources?.order, sources);+ // Its own remedy, and it outranks any grade — an empty order has nothing to grade.+ if (verdict.kind === 'adopted_none') return 'noSources';++ switch (agent.supply_status) {+ case 'interrupted':+ case 'waiting':+ case 'degraded':+ return agent.supply_status;+ // The server resolved the selection against the order and found it fine. Trust it+ // over our own read of the inventory: it graded the model, we only see statuses.+ case 'ok':+ return 'connected';+ default:+ break;+ }++ // `supply_status: null` means the server had no model to resolve, not that the order+ // is fine. It is silence, so the order's own runnability is the only fact left.+ if (verdict.kind === 'nothing_runnable') return 'nothingRunnable';+ return verdict.kind === 'covered' ? 'connected' : 'indeterminate';+}diff --git a/ui/src/components/settings/models/supply.test.ts b/ui/src/components/settings/models/supply.test.tsnew file mode 100644index 000000000..e54724986--- /dev/null+++ b/ui/src/components/settings/models/supply.test.ts@@ -0,0 +1,356 @@+// The Models page's rules, tested where they live: as pure functions over the+// contract types. Each `it` names the frame or the acceptance criterion that+// decided the behaviour, because every one of these is a judgement someone can+// otherwise "simplify" back into a boolean.+import { describe, expect, it } from 'vitest';++import {+ attribution,+ chainChips,+ chainRoles,+ hasAttribution,+ isUnhealthy,+ needsAttention,+ pageStatus,+} from './supply';+import type { AgentSupply, RuntimeDependency, Source, SourceState } from './types';++const source = (id: string, state: SourceState, name = id): Source => ({+ id,+ kind: 'api_key',+ vendor: 'anthropic',+ display_name: name,+ protocol: 'anthropic',+ supply_channel: 'hub',+ billing: 'metered',+ state,+ models: [],+});++/** A subscription served by rewriting the CLI's own config — no gateway, so no+ * dependency on the engine (`model_hub.resolve()`'s native_cli branch). */+const nativeSource = (id: string, state: SourceState, name = id): Source => ({+ ...source(id, state, name),+ kind: 'subscription',+ supply_channel: 'native_cli',+});++const ACTIVE: SourceState = { status: 'active', retry_at: null, detail_key: null };+const STANDBY: SourceState = { status: 'standby', retry_at: null, detail_key: null };+const COOLING: SourceState = {+ status: 'cooldown',+ retry_at: '2026-07-30T09:00:00Z',+ detail_key: 'models.source.cooldown.timeout',+};+const EXHAUSTED: SourceState = {+ status: 'cooldown',+ retry_at: '2026-07-31T00:00:00Z',+ detail_key: 'models.source.cooldown.quota_exhausted',+};+const DEAD: SourceState = { status: 'needs_action', retry_at: null, detail_key: 'models.source.needs_action.oauth_expired' };++const hubAgent = (over: Partial<AgentSupply> = {}): AgentSupply => ({+ backend: 'claude',+ mode: 'hub',+ menu_kind: 'fixed',+ selected_by_agent: null,+ selected_model_id: 'claude-opus-4-6',+ current: { model_id: 'claude-opus-4-6', source_id: 'src_a', channel: 'hub' },+ sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility: [] },+ supply_status: 'ok',+ model_supply: [],+ named_agents: [],+ mappings: [],+ menu: null,+ builtin_models: [],+ standard_vendors: null,+ ...over,+});++const directAgent = (): AgentSupply =>+ hubAgent({+ backend: 'opencode',+ mode: 'direct',+ current: null,+ sources: null,+ supply_status: null,+ model_supply: null,+ });++const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({+ manifest: { name: 'cliproxyapi', version: '1.0.0', source_sha: 'sha', assets: [] },+ status: { installed_version: '1.0.0', verified: true, listening: null, health, last_check: null },+});++describe('isUnhealthy', () => {+ it('counts exactly the two serving statuses as healthy (§4.5)', () => {+ expect(isUnhealthy(ACTIVE)).toBe(false);+ expect(isUnhealthy(STANDBY)).toBe(false);+ expect(isUnhealthy(COOLING)).toBe(true);+ expect(isUnhealthy(DEAD)).toBe(true);+ expect(isUnhealthy({ status: 'error', retry_at: null, detail_key: 'models.source.error.unclassified' })).toBe(true);+ });+});++describe('needsAttention', () => {+ // V6 01 draws a timed-out relay with a GRAY sub-line; V6 04 draws an exhausted+ // subscription with a GOLD one. Gold means "a person has to do something".+ it('stays gray for weather and turns gold for money (V6 01 vs V6 04)', () => {+ expect(needsAttention(COOLING)).toBe(false);+ expect(needsAttention({ status: 'cooldown', retry_at: null, detail_key: 'models.source.cooldown.rate_limited' })).toBe(+ false,+ );+ expect(needsAttention(EXHAUSTED)).toBe(true);+ });++ it('is gold for every status that never heals unattended', () => {+ expect(needsAttention(DEAD)).toBe(true);+ expect(needsAttention({ status: 'error', retry_at: null, detail_key: 'models.source.error.unclassified' })).toBe(true);+ });++ it('leaves a healthy source alone', () => {+ expect(needsAttention(ACTIVE)).toBe(false);+ });+});++describe('chainChips', () => {+ const sources = [source('src_a', ACTIVE, 'ChatGPT Plus'), source('src_b', COOLING, 'relay.example')];++ it('numbers the chain in this backend’s own order and marks 当前', () => {+ const chips = chainChips(hubAgent(), sources);+ expect(chips.map((c) => [c.position, c.label, c.tone])).toEqual([+ [1, 'ChatGPT Plus', 'current'],+ [2, 'relay.example', 'neutral'],+ ]);+ });++ // V6 01: an unhealthy source BELOW 当前 is a warning about the next failover,+ // not a record of one, so it keeps full contrast and only takes the gold dot.+ it('does not dim an unhealthy source the resolver has not reached (V6 01)', () => {+ const chips = chainChips(hubAgent(), sources);+ expect(chips[1]).toMatchObject({ tone: 'neutral', unhealthy: true });+ });++ // V6 04: the same shape AFTER the failover — 当前 moved to position 2, so+ // position 1 is now a record of what was skipped.+ it('dims an unhealthy source the resolver has walked past (V6 04)', () => {+ const agent = hubAgent({+ current: { model_id: 'claude-opus-4-6', source_id: 'src_b', channel: 'hub' },+ });+ const chips = chainChips(agent, [source('src_a', EXHAUSTED, 'ChatGPT Plus'), source('src_b', ACTIVE, 'relay.example')]);+ expect(chips.map((c) => c.tone)).toEqual(['skipped', 'current']);+ });++ it('keeps an unresolvable id visible under its bare id', () => {+ const chips = chainChips(hubAgent(), [source('src_a', ACTIVE)]);+ expect(chips[1]).toMatchObject({ sourceId: 'src_b', label: 'src_b', unhealthy: false });+ });++ // AC-7: a Direct backend has no Hub order at all.+ it('draws nothing in Direct mode (AC-7)', () => {+ expect(chainChips(directAgent(), sources)).toEqual([]);+ });+});++describe('chainRoles', () => {+ const sources = [source('src_a', ACTIVE), source('src_b', COOLING)];++ it('enrolls every id a Hub chain lists', () => {+ const { enrolled, displaced } = chainRoles([hubAgent()], sources);+ expect([...enrolled].sort()).toEqual(['src_a', 'src_b']);+ expect([...displaced]).toEqual([]);+ });++ it('displaces only what a resolver has already fallen off', () => {+ const agent = hubAgent({ current: { model_id: 'm', source_id: 'src_b', channel: 'hub' } });+ const { displaced } = chainRoles([agent], [source('src_a', EXHAUSTED), source('src_b', ACTIVE)]);+ expect([...displaced]).toEqual(['src_a']);+ });++ it('ignores Direct-mode backends entirely', () => {+ const { enrolled } = chainRoles([directAgent()], sources);+ expect(enrolled.size).toBe(0);+ });+});++describe('attribution (AC-9)', () => {+ it('names the Agents whose own rollup says so, and no others', () => {+ const agent = hubAgent({+ named_agents: [+ { name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'interrupted' },+ { name: 'pm', effective_model_id: 'claude-sonnet-4-6', supply_status: 'waiting' },+ { name: 'reviewer', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' },+ ],+ });+ expect(attribution(agent)).toEqual({ interrupted: ['claude'], waiting: ['pm'], unassignedModels: [] });+ });++ // The other half of AC-9: a ticked model nobody runs is attributed to the MODEL+ // and to no Agent — the failure a per-backend rollup gets wrong.+ it('attributes an empty chain under an unassigned model to the model alone', () => {+ const agent = hubAgent({+ named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' }],+ model_supply: [+ { model_id: 'claude-opus-4-6', chain_length: 2 },+ { model_id: 'claude-haiku-4-5', chain_length: 0 },+ ],+ });+ expect(attribution(agent)).toEqual({+ interrupted: [],+ waiting: [],+ unassignedModels: ['claude-haiku-4-5'],+ });+ });++ it('never double-counts a model an Agent does run', () => {+ const agent = hubAgent({+ named_agents: [{ name: 'claude', effective_model_id: 'claude-haiku-4-5', supply_status: 'interrupted' }],+ model_supply: [{ model_id: 'claude-haiku-4-5', chain_length: 0 }],+ });+ expect(attribution(agent)).toEqual({ interrupted: ['claude'], waiting: [], unassignedModels: [] });+ });++ it('reports nothing for a Direct backend', () => {+ expect(hasAttribution(attribution(directAgent()))).toBe(false);+ });+});++describe('pageStatus', () => {+ it('reports the engine only when a Hub backend depends on it', () => {+ const sources = [source('src_a', ACTIVE)];+ expect(pageStatus(sources, [hubAgent()], runtime('down'))).toEqual({ tone: 'warn', kind: 'engineDown' });+ expect(pageStatus(sources, [directAgent()], runtime('down'))).toEqual({ tone: 'neutral', kind: 'none' });+ });++ // 「on Hub」 is not the same question as 「needs the engine」. A native_cli source is+ // launched by rewriting the CLI's own config — no gateway, and resolve() swallows+ // an engine-sync failure there on purpose — so this Agent keeps working and the+ // pill must not tell its owner otherwise.+ it('stays quiet with the engine down when the whole chain is served natively', () => {+ const sources = [nativeSource('src_a', ACTIVE), nativeSource('src_b', STANDBY)];+ expect(pageStatus(sources, [hubAgent()], runtime('down'))).toEqual({ tone: 'ok', kind: 'ok', hubCount: 1 });+ });++ it('reports the engine as soon as one enrolled source is served through it', () => {+ const sources = [nativeSource('src_a', ACTIVE), source('src_b', STANDBY)];+ expect(pageStatus(sources, [hubAgent()], runtime('down'))).toEqual({ tone: 'warn', kind: 'engineDown' });+ });++ it('ignores a hub-channel source no chain has enrolled', () => {+ const sources = [nativeSource('src_a', ACTIVE), nativeSource('src_b', ACTIVE), source('src_orphan', ACTIVE)];+ expect(pageStatus(sources, [hubAgent()], runtime('down'))).toEqual({ tone: 'ok', kind: 'ok', hubCount: 1 });+ });++ // An empty order routes nothing through the engine either — and it is the state+ // the row now reports as a coming failure, not as a Direct fallback.+ it('says nothing about the engine for a Hub backend with no enabled source', () => {+ const agent = hubAgent({ sources: { policy: 'custom', order: [], eligibility: [] }, current: null });+ expect(pageStatus([source('src_a', ACTIVE)], [agent], runtime('down'))).toEqual({+ tone: 'ok',+ kind: 'ok',+ hubCount: 1,+ });+ });++ it('puts an interrupted Agent above a waiting one', () => {+ const agents = [+ hubAgent({ supply_status: 'waiting' }),+ hubAgent({ backend: 'codex', supply_status: 'interrupted' }),+ ];+ expect(pageStatus([source('src_a', ACTIVE)], agents, runtime('ok'))).toEqual({+ tone: 'warn',+ kind: 'interrupted',+ count: 1,+ });+ });++ // ── The grain the pill counts at ─────────────────────────────────────+ // `supply_status` answers for ONE route; the attribution line answers per named+ // Agent, and the pill uses the same noun 「Agent」. So the pill has to count what+ // the line names, or the two contradict each other on one screen.++ it('counts interrupted named Agents, not the backends they sit on', () => {+ const agent = hubAgent({+ supply_status: 'ok',+ named_agents: [+ { name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'interrupted' },+ { name: 'pm', effective_model_id: 'claude-sonnet-4-6', supply_status: 'interrupted' },+ { name: 'reviewer', effective_model_id: 'claude-haiku-4-5', supply_status: 'ok' },+ ],+ });+ expect(pageStatus([source('src_a', ACTIVE)], [agent], runtime('ok'))).toEqual({+ tone: 'warn',+ kind: 'interrupted',+ count: 2,+ });+ });++ it('does not let the route-level rollup speak over the per-Agent projection', () => {+ // The finer projection wins in BOTH directions — a coarser 供给中断 cannot+ // headline a page whose every named Agent is fine.+ const agent = hubAgent({+ supply_status: 'interrupted',+ named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' }],+ });+ expect(pageStatus([source('src_a', ACTIVE)], [agent], runtime('ok'))).toEqual({+ tone: 'ok',+ kind: 'ok',+ hubCount: 1,+ });+ });++ it('keeps the warning for a Hub backend that publishes no named Agent', () => {+ // No enabled Agent on this backend, so there is no finer projection to read —+ // the row's own verdict is the finest thing displayed, and must still be heard.+ const agent = hubAgent({ supply_status: 'interrupted', named_agents: [] });+ expect(pageStatus([source('src_a', ACTIVE)], [agent], runtime('ok'))).toEqual({+ tone: 'warn',+ kind: 'interrupted',+ count: 1,+ });+ });++ // V6 01: a cooling relay nobody has fallen off still reads 一切正常. The source+ // row reports its own health; the pill speaks when the outage costs a turn.+ it('stays green while an unhealthy source is below every 当前 (V6 01)', () => {+ const sources = [source('src_a', ACTIVE), source('src_b', COOLING)];+ expect(pageStatus(sources, [hubAgent()], runtime('ok'))).toEqual({ tone: 'ok', kind: 'ok', hubCount: 1 });+ });++ // V6 04: the same cooling source, one failover later.+ it('reports the handled failover once a chain has fallen off the source (V6 04)', () => {+ const sources = [source('src_a', EXHAUSTED, 'ChatGPT Plus'), source('src_b', ACTIVE)];+ const agent = hubAgent({ current: { model_id: 'm', source_id: 'src_b', channel: 'hub' } });+ expect(pageStatus(sources, [agent], runtime('ok'))).toEqual({+ tone: 'warn',+ kind: 'cooldown',+ source: sources[0],+ others: 0,+ });+ });++ it('reports a dead source any chain lists, even at the tail', () => {+ const sources = [source('src_a', ACTIVE), source('src_b', DEAD, 'Anthropic API Key')];+ expect(pageStatus(sources, [hubAgent()], runtime('ok'))).toMatchObject({ kind: 'needsAction', others: 0 });+ });++ it('ignores a dead source no chain lists', () => {+ const sources = [source('src_a', ACTIVE), source('src_b', ACTIVE), source('src_orphan', DEAD)];+ expect(pageStatus(sources, [hubAgent()], runtime('ok'))).toEqual({ tone: 'ok', kind: 'ok', hubCount: 1 });+ });++ it('counts the rest of a bad batch into the same pill', () => {+ const agent = hubAgent({ sources: { policy: 'follow', order: ['src_a', 'src_b', 'src_c'], eligibility: [] } });+ const sources = [source('src_a', ACTIVE), source('src_b', DEAD), source('src_c', DEAD)];+ expect(pageStatus(sources, [agent], runtime('ok'))).toMatchObject({ kind: 'needsAction', others: 1 });+ });++ it('says nothing at all when no backend is on the Hub', () => {+ expect(pageStatus([source('src_a', DEAD)], [directAgent()], null)).toEqual({ tone: 'neutral', kind: 'none' });+ });+});++// `connectOutcome` and `isSupplyWarning` moved to `sufficiency.ts` (and their tests+// with them): deciding whether the next turn can run is one question, and this module+// answered it with `order.length` while four other sites answered it with a length of+// their own. What is left here is the per-source predicate that verdict consumes.diff --git a/ui/src/components/settings/models/supply.ts b/ui/src/components/settings/models/supply.tsnew file mode 100644index 000000000..ab72b28b3--- /dev/null+++ b/ui/src/components/settings/models/supply.ts@@ -0,0 +1,270 @@+// Rules behind the Models page — deliberately outside the components, because+// each one is a judgement the UI is not free to improvise: which source in a+// chain is 当前, which chip the resolver has already walked past, which Agents a+// supply failure is actually about (AC-9), and what the header pill is allowed to+// claim. Rules deserve unit tests, and this repo's vitest setup has no DOM, so+// they are plain functions over the contract types and nothing else.+import type {+ AgentSupply,+ ModelSupply,+ RuntimeDependency,+ Source,+ SourceState,+ SupplyStatus,+} from './types';++/**+ * Not serving normally. `active` and `standby` are the only two healthy statuses+ * (§4.5); `cooldown` heals itself, `needs_action` and `error` never do — but all+ * three mean "cannot take the next turn right now", which is the one question+ * every surface here asks.+ *+ * The single predicate behind the source row's state chip, its amber sub-line and+ * the chain's gold dot, so those three can never disagree about one source.+ */+export const isUnhealthy = (state: SourceState): boolean =>+ state.status !== 'active' && state.status !== 'standby';++/** The one cooldown reason that is about money rather than weather. */+const QUOTA_EXHAUSTED = 'models.source.cooldown.quota_exhausted';++/**+ * Worth reading, not just worth reporting — what earns the gold sub-line.+ *+ * `isUnhealthy` is too broad for that: V6 01 draws a timed-out relay with a GRAY+ * sub-line and V6 04 draws an exhausted subscription with a GOLD one, and the+ * difference is whether a human has anything to do about it. `needs_action` and+ * `error` wait on a person by definition; among the self-healing cooldowns only+ * 额度用完 does — it is out for the rest of the billing cycle, and topping up or+ * accepting metered spend is a decision. A rate limit or a network blip is weather:+ * the state chip already says 暂不可用, and colouring it too would make the one row+ * that needs reading look like the four that don't.+ */+export const needsAttention = (state: SourceState): boolean =>+ state.status === 'needs_action' || state.status === 'error' || state.detail_key === QUOTA_EXHAUSTED;++// What to say after putting a backend on the Hub used to live here as+// `connectOutcome`, deciding from `(agent.sources?.order ?? []).length === 0`. That+// is one of five sites that answered 「can the next turn run?」 with an emptiness+// test, so the decision moved to `sufficiency.ts`, which owns it for all five.+// Nothing here re-derives it; `isUnhealthy` above is the one predicate it consumes.++// ── The Agent row's supply chain (design.pen 「V6 01」 / 「V6 04」) ─────────+export type ChainTone = 'current' | 'skipped' | 'neutral';++export type ChainChip = {+ sourceId: string;+ /** The source's display name, or the bare id when it no longer resolves. */+ label: string;+ /** 1-based position in this backend's order. */+ position: number;+ tone: ChainTone;+ /** Draws the gold dot: this source cannot serve right now. */+ unhealthy: boolean;+};++/**+ * `sources.order` as the numbered chain the Agent row draws.+ *+ * The `skipped` rule is what lets one branch reproduce both frames: V6 01 leaves+ * a cooling relay at position 3 fully legible, while V6 04 dims position 1 after+ * the failover moved 当前 to position 2. So a chip dims only when it is unhealthy+ * AND the resolver has already walked past it — an unhealthy source *after* 当前+ * is a warning about the next failover, not a record of one, and greying it out+ * would claim something that has not happened.+ *+ * Returns [] in Direct mode: there is no Hub order to draw (AC-7).+ */+export function chainChips(agent: AgentSupply, sources: Source[]): ChainChip[] {+ const order = agent.sources?.order ?? [];+ const currentId = agent.current?.source_id ?? null;+ const currentIndex = currentId ? order.indexOf(currentId) : -1;+ return order.map((sourceId, i) => {+ const source = sources.find((s) => s.id === sourceId);+ const unhealthy = source ? isUnhealthy(source.state) : false;+ const tone: ChainTone =+ sourceId === currentId+ ? 'current'+ : unhealthy && currentIndex >= 0 && i < currentIndex+ ? 'skipped'+ : 'neutral';+ return { sourceId, label: source?.display_name ?? sourceId, position: i + 1, tone, unhealthy };+ });+}++// ── AC-9: who a supply problem is about ─────────────────────────────────+export type SupplyAttribution = {+ /** Named Agents whose effective model cannot be served at all. */+ interrupted: string[];+ /** Named Agents waiting for a cooling source to come back on its own. */+ waiting: string[];+ /** Selectable models with an empty chain that NO named Agent runs. */+ unassignedModels: string[];+};++const EMPTY_ATTRIBUTION: SupplyAttribution = { interrupted: [], waiting: [], unassignedModels: [] };++/**+ * Resolve a supply problem to the Agents it affects, from the server's per-Agent+ * projection — never by assuming every Agent on the backend is affected.+ *+ * That distinction IS AC-9: a source failing under a model the user ticked but+ * assigned to nobody must be attributed to the model **and no Agent**, while the+ * same failure under an Agent's effective model names exactly that Agent. Both+ * halves are read here, from `named_agents` (whose `supply_status` the resolver+ * computed) and `model_supply` (whose `chain_length: 0` is the honest 「ticked but+ * nothing supplies it」 state).+ *+ * A model an Agent does run is deliberately NOT reported as unassigned even when+ * its chain is empty — that Agent's own `supply_status` already carries it, and+ * saying both would double-count one failure.+ */+export function attribution(agent: AgentSupply): SupplyAttribution {+ const named = agent.named_agents ?? [];+ const modelSupply: ModelSupply[] = agent.model_supply ?? [];+ if (named.length === 0 && modelSupply.length === 0) return EMPTY_ATTRIBUTION;+ const withStatus = (status: SupplyStatus) =>+ named.filter((a) => a.supply_status === status).map((a) => a.name);+ const claimed = new Set(+ named.map((a) => a.effective_model_id).filter((id): id is string => typeof id === 'string'),+ );+ return {+ interrupted: withStatus('interrupted'),+ waiting: withStatus('waiting'),+ unassignedModels: modelSupply+ .filter((m) => m.chain_length === 0 && !claimed.has(m.model_id))+ .map((m) => m.model_id),+ };+}++/**+ * The supply verdict for every subject the page actually shows, at the FINEST grain+ * it shows one — the projection any page-level headline has to be derived from.+ *+ * `AgentSupply.supply_status` is a rollup for ONE route (「the current selection」 of+ * the Agent named by `selected_by_agent`), so counting backends by it answers a+ * different question than the page asks: a backend with three enabled Agents draws+ * 「claude、pm、codex 供给中断」 in its attribution line and would have had the header+ * say 「1 个 Agent 供给中断」 — a coarser count standing above a finer contradiction+ * the same screen displays, in the same noun.+ *+ * `named_agents` is that finer grain (AC-9: the ENABLED named Agents, each with its+ * own rollup), and `attribution()` already reads it. A backend that publishes none+ * falls back to its own rollup rather than to silence: the row still draws a supply+ * verdict of its own (「供给中断」 when no source is enabled), so dropping it here+ * would lose a warning the page is making — the fallback is per-subject too, never a+ * mix of grains for one subject.+ */+function displayedSupply(hubAgents: AgentSupply[]): (SupplyStatus | null)[] {+ return hubAgents.flatMap((agent) => {+ const named = agent.named_agents ?? [];+ return named.length > 0 ? named.map((a) => a.supply_status) : [agent.supply_status ?? null];+ });+}++export const hasAttribution = (a: SupplyAttribution): boolean =>+ a.interrupted.length > 0 || a.waiting.length > 0 || a.unassignedModels.length > 0;++// ── What a source outage is actually costing right now ──────────────────+export type ChainRoles = {+ /** Listed in at least one Hub Agent's order — an outage here will bite. */+ enrolled: Set<string>;+ /** A Hub resolver has already walked past it: the failover has happened. */+ displaced: Set<string>;+};++/**+ * Read the same chain the Agent rows draw, and answer the two questions the header+ * pill needs: is anything using this source, and has its outage already moved a+ * turn somewhere else.+ *+ * The pill cannot ask "is any source unhealthy" — V6 01 has a cooling relay at+ * position 3 and still reads 一切正常, because nothing was ever served from it.+ * The same shape becomes V6 04's 「已自动切换」 only once the cooling source is one+ * an Agent has fallen off. Position relative to 当前 is the whole difference, and+ * `chainChips` already computes it, so this reuses that judgement instead of+ * growing a second, driftable copy of it.+ */+export function chainRoles(agents: AgentSupply[], sources: Source[]): ChainRoles {+ const enrolled = new Set<string>();+ const displaced = new Set<string>();+ for (const agent of agents) {+ if (agent.mode !== 'hub') continue;+ for (const chip of chainChips(agent, sources)) {+ enrolled.add(chip.sourceId);+ if (chip.tone === 'skipped') displaced.add(chip.sourceId);+ }+ }+ return { enrolled, displaced };+}++// ── The page header's status pill ───────────────────────────────────────+/**+ * What the header pill says. A discriminated result rather than a translated+ * string: the ladder is a rule (worth testing), the copy is i18n (not this+ * module's business).+ */+export type PageStatus =+ | { tone: 'ok'; kind: 'ok'; hubCount: number }+ | { tone: 'neutral'; kind: 'none' }+ | { tone: 'warn'; kind: 'engineDown' }+ | { tone: 'warn'; kind: 'interrupted' | 'waiting'; count: number }+ | { tone: 'warn'; kind: 'needsAction' | 'cooldown'; source: Source; others: number };++/**+ * Worst-first, and every branch is a thing the user can act on:+ *+ * engine down nothing on Hub can run at all+ * interrupted an Agent has no source left and needs the user+ * waiting an Agent is stalled but a source will come back on its own+ * needs_action a source someone's chain lists is dead until re-auth / top-up+ * cooldown a source stepped aside; the chain covered for it ← V6 04+ * ok / none nothing to report+ *+ * `cooldown` deliberately outranks nothing: it is the only branch that reports a+ * problem the system already handled, which is exactly the V6 04 moment ("额度用完+ * · 已自动切换,恢复后切回") and the reason the pill cannot just be a boolean.+ *+ * Both source-level branches are gated on `chainRoles`, because an unhealthy source+ * is not by itself news — V6 01 draws a cooling relay AND 「一切正常 · 2 个 Agent+ * 已接入中枢」, since every Agent is still served from the head of its chain. The+ * source rows already report their own health; the pill speaks only when the outage+ * is costing someone a turn (`displaced`) or is waiting on a human (`needs_action`+ * under a chain that lists it).+ */+export function pageStatus(+ sources: Source[],+ agents: AgentSupply[],+ runtime: RuntimeDependency | null,+): PageStatus {+ const hubAgents = agents.filter((a) => a.mode === 'hub');+ const { enrolled, displaced } = chainRoles(agents, sources);+ // 「Hub mode」 is not the same question as 「needs the engine」, and only the second+ // one licenses this branch. A `native_cli` source is launched by rewriting the+ // CLI's own config — `model_hub.resolve()` builds that launch with no gateway and+ // swallows an engine-sync failure outright ("Native launch is independent") — so a+ // Hub Agent whose order enrolls only native sources keeps running with the engine+ // down, and telling its owner that nothing works would be false. The engine+ // becomes load-bearing exactly when someone's chain lists a `hub`-channel source.+ // (A Direct-only install has nothing enrolled at all, so this covers it too.)+ const needsEngine = sources.some((s) => s.supply_channel === 'hub' && enrolled.has(s.id));+ if (needsEngine && runtime?.status.health !== 'ok') return { tone: 'warn', kind: 'engineDown' };++ const subjects = displayedSupply(hubAgents);+ const rollup = (status: SupplyStatus) => subjects.filter((s) => s === status).length;+ const interrupted = rollup('interrupted');+ if (interrupted > 0) return { tone: 'warn', kind: 'interrupted', count: interrupted };+ const waiting = rollup('waiting');+ if (waiting > 0) return { tone: 'warn', kind: 'waiting', count: waiting };++ const dead = sources.filter(+ (s) => (s.state.status === 'needs_action' || s.state.status === 'error') && enrolled.has(s.id),+ );+ if (dead.length > 0) return { tone: 'warn', kind: 'needsAction', source: dead[0], others: dead.length - 1 };+ const cooling = sources.filter((s) => s.state.status === 'cooldown' && displaced.has(s.id));+ if (cooling.length > 0) return { tone: 'warn', kind: 'cooldown', source: cooling[0], others: cooling.length - 1 };++ return hubAgents.length === 0+ ? { tone: 'neutral', kind: 'none' }+ : { tone: 'ok', kind: 'ok', hubCount: hubAgents.length };+}diff --git a/ui/src/components/settings/models/supplyCopyRedline.test.ts b/ui/src/components/settings/models/supplyCopyRedline.test.tsnew file mode 100644index 000000000..f2b69391d--- /dev/null+++ b/ui/src/components/settings/models/supplyCopyRedline.test.ts@@ -0,0 +1,105 @@+// A redline over the page's COPY, not over one component.+//+// Round 1 fixed two strings that promised the Hub falls back to Direct when supply+// runs out. Round 2 found three more saying the same thing elsewhere, because the+// fix had been applied to the strings that were reported rather than to the class.+// `model_hub.resolve()` returns a Direct launch only when the backend's own mode is+// direct; past a switch to Hub an empty or blocked order raises+// `mapping_target_unavailable` and the turn FAILS. So any copy telling a Hub user+// that Direct will cover them is false, wherever it lives.+//+// The check is deliberately TOTAL rather than a list of known-bad keys: it walks+// every leaf under `settings.models` in both locales, and any string that pairs+// Direct with a fallback verb must be classified below with a reason. An+// unclassified match fails — which is the only way a rule catches copy that does+// not exist yet.+import { describe, expect, it } from 'vitest';++import en from '../../../i18n/en.json';+import zh from '../../../i18n/zh.json';+import { SUPPLY_WARNINGS } from './sufficiency';++const BUNDLES = { zh, en } as const;++const DIRECT = /直连|direct/i;+/** Verbs that turn a mention of Direct into a claim about falling back to it. */+const FALLBACK = /回退|切回|退回|改用|回到|继续用|fall ?back|revert|switch(?:es|ed)? back|stays? on/i;++/**+ * Leaves allowed to pair the two, each because it is NOT the false promise.+ *+ * Keys, not substrings: an allowance is granted to a sentence someone has read,+ * and rewriting that sentence into a promise should re-trip the check.+ */+const CLASSIFIED: Record<string, string> = {+ 'order.enabledEmpty': 'States the opposite — 「中枢不会替它回退到直连」 is the correction itself.',+ 'migration.nonDestructive':+ 'Describes a manual switch the user may make on the Backends page, not something the Hub does on their behalf.',+ 'consent.points.2':+ 'ToS advice: recommends the user choose Direct mode for subscriptions themselves. The subject is the user, not the Hub, and it is offered before enabling rather than after supply runs out.',+};++type Leaf = { key: string; text: string };++function leaves(bundle: unknown): Leaf[] {+ const out: Leaf[] = [];+ const walk = (node: unknown, path: string[]) => {+ if (typeof node === 'string') {+ out.push({ key: path.join('.'), text: node });+ return;+ }+ if (!node || typeof node !== 'object') return;+ for (const [k, v] of Object.entries(node as Record<string, unknown>)) walk(v, [...path, k]);+ };+ walk((bundle as any).settings?.models, []);+ return out;+}++const lookup = (bundle: unknown, key: string): unknown =>+ key.split('.').reduce<unknown>((node, part) => {+ if (!node || typeof node !== 'object') return undefined;+ return (node as Record<string, unknown>)[part];+ }, (bundle as any).settings?.models);++describe('Direct-fallback redline over settings.models copy', () => {+ it.each(['zh', 'en'] as const)('walks a non-trivial %s subtree', (lng) => {+ // Guards the walk itself: a renamed namespace would otherwise make every+ // assertion below pass over an empty list.+ const all = leaves(BUNDLES[lng]);+ expect(all.length).toBeGreaterThan(100);+ expect(all.map((l) => l.key)).toContain('supply.interrupted');+ });++ it.each(['zh', 'en'] as const)('classifies every Direct-fallback sentence in %s', (lng) => {+ const suspects = leaves(BUNDLES[lng]).filter((l) => DIRECT.test(l.text) && FALLBACK.test(l.text));+ const unclassified = suspects.filter((l) => !(l.key in CLASSIFIED));+ expect(unclassified.map((l) => `${l.key}: ${l.text}`)).toEqual([]);+ });++ // The family that replaced the false promise. Every non-ok outcome of a switch to+ // Hub owns exactly one string here, and none of them may mention Direct at all —+ // there is nothing true to say about Direct on any of these paths.+ //+ // Imported, never re-listed: a hand-kept copy of this list would have gone stale+ // the moment `nothingRunnable` joined it, and a coverage rule that misses the newest+ // member is exactly the drift it was written to catch.+ it.each(['zh', 'en'] as const)('gives every non-ok outcome one %s string that never names Direct', (lng) => {+ for (const outcome of SUPPLY_WARNINGS) {+ const text = lookup(BUNDLES[lng], `supply.${outcome}`);+ expect(typeof text, `supply.${outcome} missing in ${lng}`).toBe('string');+ expect(DIRECT.test(text as string), `supply.${outcome} names Direct in ${lng}`).toBe(false);+ }+ });++ // The three strings the class was fixed by DELETING. Re-adding any of them means+ // some surface has gone back to keeping its own paraphrase.+ it.each(['zh', 'en'] as const)('keeps the retired %s keys retired', (lng) => {+ for (const key of ['toast.connectedNoSupply', 'supplyMode.switchedHubNoSupply', 'supplyMode.hubNoSupply']) {+ expect(lookup(BUNDLES[lng], key), `${key} is back in ${lng}`).toBeUndefined();+ }+ });++ it('keeps zh and en in exact key correspondence under settings.models', () => {+ expect(leaves(zh).map((l) => l.key).sort()).toEqual(leaves(en).map((l) => l.key).sort());+ });+});diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex aa7ce0c3b..b31b62c85 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -2,10 +2,10 @@// (`avibe/docs/plans/model-hub-contracts/*`). Field names are exact// (case included); the UI consumes these types and never edits the schemas.//-// Contract version pinned to the frozen v1. If the orchestrator bumps a+// Contract version pinned to the frozen v3. If the orchestrator bumps a// contract, this file changes in lockstep — never ahead of it.-export const CONTRACT_VERSION = 1 as const;+export const CONTRACT_VERSION = 3 as const;// ── source.schema.json ──────────────────────────────────────────────────export type SourceKind = 'subscription' | 'api_key';@@ -15,15 +15,42 @@ export type SourceProtocol =| 'openai_chat'| 'openai_compatible';export type SupplyChannel = 'native_cli' | 'hub';-export type SourceStatus = 'active' | 'standby' | 'cooldown' | 'error';+/** v3 (§4.5): classified by whether the state heals itself. cooldown carries a+ * `retry_at` and clears on its own; needs_action never recovers unattended;+ * error is an unclassified failure and equally a blocker. */+export type SourceStatus = 'active' | 'standby' | 'cooldown' | 'needs_action' | 'error';export type ModelProvenance = 'discovered' | 'manual';+/** Optional cause of a self-healing cooldown. A closed vocabulary, not a+ * prefix: the key is rendered through i18n, never as raw upstream text. */+export type CooldownDetailKey =+ | 'models.source.cooldown.network'+ | 'models.source.cooldown.timeout'+ | 'models.source.cooldown.rate_limited'+ | 'models.source.cooldown.quota_exhausted'+ | 'models.source.cooldown.server_error';++/** Required on `needs_action`: the state's whole point is that the user must+ * act, which is unrenderable without naming the action. */+export type NeedsActionDetailKey =+ | 'models.source.needs_action.oauth_expired'+ | 'models.source.needs_action.balance_exhausted'+ | 'models.source.needs_action.credential_revoked'+ | 'models.source.needs_action.account_banned';++export type ErrorDetailKey = 'models.source.error.unclassified';++/** The complete set `state.detail_key` (and `ProbeResult.error`) can hold. */+export type SourceDetailKey = CooldownDetailKey | NeedsActionDetailKey | ErrorDetailKey;+export type SourceState = {status: SourceStatus;- /** ISO-8601; the cooldown retry ETA rendered in the row's mono sub-line. */+ /** ISO-8601; required on `cooldown`, null on every other status. Rendered as+ * the retry ETA in the row's mono sub-line. */retry_at?: string | null;- /** i18n key, never raw upstream error text. */- detail_key?: string | null;+ /** i18n key, never raw upstream error text. Optional on cooldown, required on+ * needs_action and error, null on the two healthy statuses. */+ detail_key?: SourceDetailKey | null;};export type SourceUsage = {@@ -31,6 +58,9 @@ export type SourceUsage = {month_spend_cents?: number | null;/** ISO 4217, e.g. USD / CNY. Absent means USD (see formatSpend). */currency?: string | null;+ /** v3, subscription sources only: when the current cycle is projected to run+ * out at the observed burn rate. null when unknown or not projectable. */+ projected_exhaust_at?: string | null;};export type SuppliedModel = {@@ -43,6 +73,11 @@ export type SuppliedModel = {export type Source = {id: string;+ /** v3, immutable once written: the `follow` policy recommends api_key sources+ * by creation time ascending, so the rule needs a persisted stamp (the+ * sources array itself is explicitly unordered). May be null on rows+ * persisted before the field existed; `id` ascending is the tie-breaker. */+ created_at?: string | null;kind: SourceKind;/** Standard vendor id (anthropic|openai|zhipuai|kimi|xai|…) or 'custom'. */vendor: string;@@ -68,12 +103,9 @@ export type Source = {credential_ref?: string | null;};-// ── priority.schema.json ────────────────────────────────────────────────-export type Priority = {- contract_version: typeof CONTRACT_VERSION;- /** source ids, position 0 = spend first; every non-deleted source once. */- order: string[];-};+// `priority.schema.json` does not exist in v3: there is no global source order,+// and no replacement for the removed `PUT /api/models/priority`. Order is a+// per-backend subset, carried by `AgentSupply.sources` below.// ── agent-supply.schema.json ────────────────────────────────────────────export type AgentBackend = 'claude' | 'codex' | 'opencode';@@ -99,12 +131,84 @@ export type AgentMenu = {checked: string[];};+/** Whether the per-backend order is server-recommended or user-owned. `follow`+ * recomputes on every read, so a newly eligible source joins automatically;+ * `custom` is a frozen subset the server never reorders and never extends. */+export type SourcePolicy = 'follow' | 'custom';++/** Why a source cannot serve this backend at all. A closed vocabulary — a new+ * cause ships its enum member and its locale copy in the same change. */+export type EligibilityReasonKey =+ | 'models.eligibility.subscription_wrong_client'+ | 'models.eligibility.opencode_api_key_only'+ | 'models.eligibility.consent_required';++/** Server-computed per (source, backend). The UI renders this and never+ * re-derives eligibility from source kind/vendor. */+export type SourceEligibility = {+ source_id: string;+ eligible: boolean;+ /** Required (and non-null) when `eligible` is false; null when it is true. */+ reason_key?: EligibilityReasonKey | null;+};++export type AgentSources = {+ policy: SourcePolicy;+ /** Enabled source ids for THIS backend, position 0 = tried first. A subset:+ * ids absent from it are not enabled here, not merely lower-priority. */+ order: string[];+ /** Every source the hub holds, eligible or not — the drawer's 不适用 section+ * reads its `reason_key` from here. */+ eligibility?: SourceEligibility[] | null;+};++/** Agent-level supply rollup (§4.5). `waiting` = every enabled source is+ * cooling and one will come back; `interrupted` = nothing can serve the+ * selection without the user acting. Both pin `current` to null, so a stale+ * 使用中 can never render. */+export type SupplyStatus = 'ok' | 'degraded' | 'waiting' | 'interrupted';++/** AC-9's per-Agent read projection: the ENABLED named Agents on this backend,+ * each with the model it effectively runs (explicit selection or the backend+ * default) and its own rollup. Empty for direct-mode backends. */+export type NamedAgentSupply = {+ name: string;+ effective_model_id: string | null;+ /** null exactly when `effective_model_id` is null — no model, no capability+ * to report. */+ supply_status: SupplyStatus | null;+};++/** How many sources can currently serve a selectable model. `chain_length: 0`+ * is the honest 「ticked but nothing supplies it」 state. */+export type ModelSupply = {+ model_id: string;+ chain_length: number;+};+export type AgentSupply = {backend: AgentBackend;mode: AgentMode;menu_kind: MenuKind;- /** What the next turn would use (composite pill). null when mode=direct. */+ /** The named Agent whose selection `selected_model_id` came from, or null when+ * the backend default supplies it. null whenever `selected_model_id` is. */+ selected_by_agent?: string | null;+ /** The model the next turn would ask for. null in direct mode and when no+ * selection resolves — an honest null, never a guessed default. */+ selected_model_id?: string | null;+ /** What the next turn would actually use (composite pill). null in exactly+ * three cases: mode=direct, supply_status=waiting, supply_status=interrupted. */current?: AgentCurrent | null;+ /** Per-backend enabled subset + order + policy. null when mode=direct. */+ sources?: AgentSources | null;+ /** Rollup over `sources.order` for the current selection. null in direct mode+ * and whenever `selected_model_id` is null. */+ supply_status?: SupplyStatus | null;+ /** Supply depth per selectable model. null when mode=direct. */+ model_supply?: ModelSupply[] | null;+ /** AC-9 attribution source. Always present; every entry's `supply_status` is+ * null in direct mode. */+ named_agents?: NamedAgentSupply[];mappings?: AgentMapping[];menu?: AgentMenu | null;/** v1.2 read-only projection: fixed-menu backends only — the backend's real@@ -145,7 +249,11 @@ export type ResolutionEventKind =| 'recover'| 'skip'| 'mapping_applied'- | 'channel_switch';+ | 'channel_switch'+ /** v3: a source stopped in a way that will never heal unattended. */+ | 'needs_action'+ /** v3: the chain emptied — both endpoints are null by contract. */+ | 'supply_interrupted';export type ResolutionReason =| 'quota_exhausted'| 'rate_limited'@@ -153,24 +261,93 @@ export type ResolutionReason =| 'network'| 'recovery'| 'manual'- | 'mapping';+ | 'mapping'+ // v3 — the five non-self-healing causes, a bijection with the needs_action /+ // error detail keys above.+ | 'credential_expired'+ | 'credential_revoked'+ | 'balance_exhausted'+ | 'account_banned'+ | 'unclassified_error'+ // v3 — supply exhaustion causes.+ | 'no_enabled_source'+ | 'no_eligible_source'+ | 'model_unsupported';export type BillingNote = null | 'entered_metered' | 'left_metered';+/** v3: `action_required` on needs_action / supply_interrupted, `info` on the six+ * traffic kinds. */+export type EventSeverity = 'info' | 'action_required';export type ResolutionEvent = {id: string;ts: string;agent: AgentBackend | 'system';kind: ResolutionEventKind;- model_id: string;+ /** v3: nullable — a supply interruption is about a backend, not a model. */+ model_id: string | null;+ /** v3: canonical `src_*` id or null. The feed derives 「已删除」 at render time+ * from this failing to resolve against live sources. */from_source?: string | null;to_source?: string | null;reason: ResolutionReason;/** drives the gold dot in the 最近切换 list. */billing_note?: BillingNote;+ severity?: EventSeverity | null;human_zh: string;human_en: string;};+// ── agent-chain.schema.json ─────────────────────────────────────────────+export type ChainHealth = 'healthy' | 'cooldown' | 'needs_action' | 'error';++export type AgentChainLink = {+ source_id: string;+ via_mapping: boolean;+ /** The id actually sent upstream. Non-null whenever `via_mapping` is true. */+ resolved_model_id: string | null;+ health: ChainHealth;+ /** false for cooldown / needs_action / error; true only for healthy. */+ runnable: boolean;+ /** Non-null only on `cooldown`. */+ retry_at: string | null;+};++/** GET /api/models/agents/<backend>/chain?model=<id> — hub mode only. Direct+ * mode answers with the `direct_mode` error instead of an empty chain, because+ * `chain: []` would be a false Hub-starvation alarm about a backend whose+ * native CLI runs the model fine (AC-7). */+export type AgentChain = {+ contract_version: typeof CONTRACT_VERSION;+ backend: AgentBackend;+ model_id: string;+ chain: AgentChainLink[];+ supply_state: 'ok' | 'waiting' | 'interrupted';+};++// ── probe-result.schema.json ────────────────────────────────────────────+/** POST /api/models/agents/<backend>/probe — hub mode only, same reason as the+ * chain route: there is no `src_*` identity to report in direct mode. */+export type ProbeResult = {+ contract_version: typeof CONTRACT_VERSION;+ backend: AgentBackend;+ reachable: boolean;+ source_id: string;+ model_id: string;+ latency_ms: number | null;+ via_mapping: boolean;+ /** Mirrors the `state.detail_key` vocabulary; null iff reachable. */+ error: SourceDetailKey | null;+};++/** api.md — returned by the source-creation routes: which backends adopted the+ * new source into their order, and where. `position` is ONE-based. A `custom`+ * backend is absent (the UI hints 「有新来源未启用」 instead). */+export type AdoptedBy = {+ backend: AgentBackend;+ policy: SourcePolicy;+ position: number;+};+// ── oauth-flow.schema.json ──────────────────────────────────────────────export type OAuthFlowState =| 'starting'@@ -192,6 +369,17 @@ export type OAuthPresentation = {export type OAuthFlow = {flow_id: string;+ /**+ * What the flow is FOR, and therefore what its terminal success response+ * carries: `create` → `{flow, source, adopted_by}`, `reauth` →+ * `{flow, source, recovered, interrupted_pairs}`.+ *+ * Read from the payload, never from which button the client pressed — a poll+ * that lands after a page reload has no memory of the button. Optional here+ * because the schema keeps it optional for payloads that predate it; a flow+ * without it is a `create` flow, which is the only kind this UI starts.+ */+ intent?: 'create' | 'reauth';/** Pending Source this flow binds to (deterministic association; hub-channel* flows always set it). The server derives the created source's id from it. */source_id?: string | null;@@ -245,11 +433,16 @@ export type ApiKeySourceCreate = {key: string;};-/** POST /api/models/sources — finalize a completed subscription OAuth flow into- * a persisted Source. `oauth_flow_ref` is the flow id; the server derives the- * source id from the flow binding and rejects credential/state fields, so the- * UI never sends them. `experimental_consent` is sent only for the consent-- * gated hub-held channel. */+/**+ * POST /api/models/sources with an `oauth_flow_ref` — the explicit-finalize arm+ * of the create route.+ *+ * NOT used by this UI, on purpose. A terminal `create` flow is already+ * materialized by the status/submit response that reports its success, and the+ * flow binding is consumed with it: posting here afterwards is rejected as+ * `flow_not_found`. The shape stays because the route does; the client's job is+ * to consume the terminal result, not to re-create from it.+ */export type OAuthSourceCreate = {kind: 'subscription';vendor: string;@@ -266,6 +459,11 @@ export type SourcePatch = {base_url?: string | null;};+/** PUT /api/models/agents/<backend>/sources — a TOTAL body: `follow` hands the+ * order back to the server, `custom` freezes exactly the ids sent. The route+ * rejects unknown keys, so `contract_version` is deliberately NOT part of it. */+export type AgentSourcesPut = { policy: 'follow' } | { policy: 'custom'; order: string[] };+/** POST /api/models/custom-models — appends a manual-provenance model entry to* a source's supply list (frame 08). */export type CustomModelCreate = {diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 09d336694..958f3e5ac 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -612,16 +612,22 @@"openSetup": "Open setup wizard","models": {"title": "Models",- "subtitle": "Connect a source once and every agent uses it; the list order is the spend order — Avibe switches on exhaustion and switches back on recovery.",+ "subtitle": "Connect a source once and every agent can draw on it; each agent decides which ones it uses and in what order, switching over on failure and back on recovery.","addSource": "Add source","loadError": "Failed to load: {{detail}}","statusPill": {- "ok": "All good · {{count}} agents connected",- "degraded": "Some sources need attention · {{count}} agents connected"+ "ok": "All good · {{count}} on the Hub",+ "none": "No agent is on the Hub yet",+ "engineDown": "Supply engine isn't ready · the Hub can't serve",+ "interrupted": "{{count}} with no supply · needs attention",+ "waiting": "{{count}} awaiting source recovery",+ "needsAction": "{{source}} — {{detail}}",+ "cooldown": "{{source}} — {{detail}} · switched over, will switch back",+ "andMore": "{{count}} more"},"sources": {"title": "Sources",- "subtitle": "One global list; drag to reorder — the order is the spend order",+ "subtitle": "One global account library; who comes first is set per agent below","empty": "No sources yet — use “Add source” to connect a subscription or API key."},"source": {@@ -631,10 +637,37 @@"customEndpoint": "Custom endpoint","retryIn": "retry in {{minutes}} min","reorder": "Reorder",- "oauthSignedOut": "CLI subscription is signed out",- "cooldown": {- "timeout": "Repeated timeouts"- }+ "oauthSignedOut": "CLI subscription is signed out"+ },+ "current": "Current",+ "order": {+ "title": "Source order · {{backend}}",+ "subtitle": "Used top to bottom; a failure switches to the next one and switches back once it recovers. This order only affects {{backend}}.",+ "subtitleShort": "Used top to bottom; failures switch over and back. Affects {{backend}} only.",+ "groupEnabled": "Enabled · {{count}}",+ "groupDisabled": "Not enabled · {{count}}",+ "groupIneligible": "Not applicable · {{count}}",+ "following": "Following recommended",+ "followingLong": "Following recommended · new sources join automatically",+ "restore": "Restore recommended order",+ "enable": "Enable",+ "enableAria": "Enable {{name}}",+ "disable": "Disable",+ "openMenu": "Model menu & mapping",+ "supplies": "Supplies all {{family}} models",+ "viaMapping": "usable by {{backend}} once rewritten in the model menu",+ "viaMappingShort": "usable by {{backend}} once mapped",+ "enabledEmpty": "{{backend}} has no source enabled, so its next turn fails with no supply — the Hub will not fall back to Direct for it. Add one from “Not enabled” below.",+ "ineligibleUnknown": "Cannot supply {{backend}}",+ "ineligibleClientUnknown": "{{vendor}} subscriptions only work in their own official client",+ "family": {+ "anthropic": "Claude",+ "openai": "GPT",+ "zhipuai": "GLM",+ "kimi": "Kimi",+ "xai": "Grok"+ },+ "enabledNoneRunnable": "None of {{backend}}’s enabled sources can serve right now, so the next turn fails with no supply. Fix one below, or enable another."},"billing": {"monthly": "Monthly",@@ -645,6 +678,7 @@"active": "In use","standby": "Standby","cooldown": "Cooling down",+ "needs_action": "Needs attention","error": "Unavailable"},"usage": {@@ -663,24 +697,37 @@"experimental": "Experimental","agents": {"title": "Agent",- "subtitle": "Which model each agent uses, and who supplies it",+ "subtitle": "Each agent picks its own sources and order; a failure moves to the next one","backendSettings": "Backend settings",- "modelMenu": "Model menu","connectHub": "Connect to Hub",- "menuComingSoon": "Model menus arrive in the next milestone",- "modelCount": "{{count}} models",- "multiSource": "Multiple sources",- "multiSourceCustom": "Multiple sources · {{count}} custom",- "hubNoSupply": "On Hub · no source available yet (using Direct)",- "directNote": "Still supplied by the CLI's own config — not connected to the Hub"+ "modelCount": "{{count}} model(s)",+ "hubNoSupply": "On Hub · no source enabled, the next turn will fail",+ "directNote": "Still supplied by the CLI's own config — not connected to the Hub",+ "sourceOrder": "Source order",+ "menuKind": {+ "fixed": "Fixed menu",+ "open": "Open menu"+ },+ "policy": {+ "follow": "Recommended",+ "custom": "Custom"+ },+ "attribution": {+ "interrupted": "No supply for {{names}}",+ "waiting": "Awaiting source recovery for {{names}}",+ "unassigned": "No source can supply {{models}}"+ }},"recent": {"title": "Recent switches","viewAll": "View all","collapse": "Collapse",+ "loadMore": "Load older entries",+ "loadingMore": "Loading…","today": "Today","yesterday": "Yesterday",- "empty": "No switches yet"+ "empty": "No switches yet",+ "deletedSource": "deleted"},"advanced": {"title": "Advanced",@@ -719,7 +766,7 @@"keyLabel": "API KEY","baseUrlLabel": "SERVICE URL (BASE URL)","baseUrlHint": "Official vendors are prefilled and editable; for a compatible service (relay, self-hosted gateway) enter the URL it gives you.",- "discovered": "Connected · discovered {{count}} models, added to the supply list",+ "discovered": "Connected · discovered {{count}} model(s), added to the supply list","failed": "Connection failed: {{detail}}","testing": "Connecting…","vendors": {@@ -756,8 +803,7 @@"awaitingPaste": "Waiting for authorization · times out in {{time}}","awaitingDevice": "Waiting to finish · detected automatically, nothing to paste","verifying": "Verifying…",- "success": "Connected",- "finalizing": "Creating the source…"+ "success": "Connected"},"error": {"start": "Couldn't start authorization, please retry",@@ -787,8 +833,20 @@"reorderFailed": "Couldn't save the new order","connected": "Connected to the Hub","connectFailed": "Couldn't connect, please retry",- "refreshFailed": "Couldn't refresh, please retry",- "connectedNoSupply": "Switched to Hub, but no source can supply yet — still on Direct"+ "refreshFailed": "Couldn't refresh, please retry"+ },+ "supply": {+ "degraded": "On the Hub · a source is down, already switched to the next one",+ "waiting": "On the Hub · every source is cooling down; turns fail until one recovers",+ "interrupted": "On the Hub · supply interrupted, the next turn will fail",+ "noSources": "On the Hub · no source enabled yet, the next turn will fail",+ "nothingRunnable": "On the Hub · no enabled source can serve right now, the next turn will fail"+ },+ "adoption": {+ "enabled": "Added to the source order of {{list}}",+ "entry": "{{name}} (#{{position}})",+ "none": "No agent has enabled it yet · add it to an agent's source order for it to be used",+ "partlySkipped": "Added to the source order of {{list}} · skipped for {{skipped}} (hand-picked order) — add it there to use it"},"menus": {"done": "Done",@@ -799,8 +857,8 @@"subtitle": "Fixed menu: {{backend}} only recognizes these built-in model IDs. Each ID can be redirected to another model — this affects {{backend}} only.","builtinCol": "Built-in model ID","supplyCol": "Actual supply",- "followNative": "Follow native · supply by priority",- "candidates": "By priority · {{sources}}",+ "followNative": "Follow native · supply by source order",+ "candidates": "Source order · {{sources}}","candidatesUnavailable": "No source can supply this model yet","warning": "Reasoning, cache and tool semantics aren't fully equivalent after remapping","resetRow": "Reset to default",@@ -855,7 +913,7 @@"title": "Hub mode","recommended": "Recommended · default","openModels": "Open Models page",- "description": "Model tokens are supplied from Settings → Models: sign-ins, API keys, priority and mappings all live there. {{backend}}'s native config is left untouched, and you can switch away anytime."+ "description": "Model tokens are supplied from Settings → Models: sign-ins, API keys, source order and mappings all live there. {{backend}}'s native config is left untouched, and you can switch away anytime."},"direct": {"title": "Direct mode",@@ -863,12 +921,11 @@"detected": "Existing direct config detected: {{detail}} — import it into the Hub in one click","import": "Import to Hub…"},- "switchedHubNoSupply": "Switched to Hub, but no source can supply yet — still on Direct",- "hubNoSupply": "Hub is selected, but no source can supply this backend yet, so it's still using Direct. Add or enable a source on the Models page to activate it."+ "fixHint": "Add or enable a source on the Models page to bring it back."},"migration": {"title": "Connect to the Model Hub",- "subtitle": "Move your existing sign-ins and API keys into the Models Hub in one pass — all three Agents share one set of sources and priority.",+ "subtitle": "Move your existing sign-ins and API keys into the Models Hub in one pass — each agent then picks its own sources and their order.","empty": "No native configuration detected to migrate.","scanFailed": "Couldn't scan native configs, please retry","applyFailed": "Import failed, please retry",@@ -914,20 +971,13 @@"deleteForceConfirm": "Force delete","deleted": "Source deleted","deleteFailed": "Couldn't delete, please retry",- "priorityLabel": "Priority {{position}}","renameHint": "Changes the display name only — the credential is untouched","rediscoverHint": "Re-fetch the models this source can supply",- "moveUp": "Move up one",- "moveUpHint": "Gets used earlier",- "moveUpHintAtTop": "Already first — can't move up",- "moveDown": "Move down one",- "moveDownHint": "Gets used later",- "moveDownHintAtBottom": "Already last — can't move down","deleteHint": "You'll be asked to confirm first"},"migrationBanner": {"title": "Native configs ready to import",- "body": "Found {{count}} native sign-in(s) / API key(s) you can move into the Hub — all three agents share one set of sources.",+ "body": "Found {{count}} native sign-in(s) / API key(s) you can move into the Hub — each agent then picks its own sources and their order.","import": "Import to Hub","dismiss": "Dismiss"}@@ -979,6 +1029,31 @@"optimizingRoute": "Optimizing...","optimizeStarted": "A second Connector is evaluating a better route"},+ "models": {+ "eligibility": {+ "subscription_wrong_client": "{{vendor}} subscriptions only work in {{backend}}",+ "opencode_api_key_only": "OpenCode can only be supplied by API-key sources",+ "consent_required": "Needs your consent for experimental hub supply first"+ },+ "source": {+ "cooldown": {+ "network": "Network unreachable",+ "timeout": "Repeated timeouts",+ "rate_limited": "Rate limited",+ "quota_exhausted": "Cycle quota used up",+ "server_error": "Upstream server error"+ },+ "needs_action": {+ "oauth_expired": "Sign-in expired — reauthorize it",+ "balance_exhausted": "Out of balance — top it up",+ "credential_revoked": "Credential revoked — enter a new one",+ "account_banned": "Account is restricted"+ },+ "error": {+ "unclassified": "Unknown error — temporarily unavailable"+ }+ }+ },"accessBlocked": {"title": "Can't open the control panel here","body": "Avibe is running, but it refused to open the control panel at this address.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 2d32efb2a..4e4a28655 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -612,16 +612,22 @@"openSetup": "打开设置向导","models": {"title": "模型",- "subtitle": "连一次来源,所有 Agent 统一供给;顺序即优先级,用完自动切换、恢复自动切回。",+ "subtitle": "来源连一次,全局共用;每个 Agent 自己决定用哪些、先用谁,失败自动切换、恢复自动切回。","addSource": "添加来源","loadError": "加载失败:{{detail}}","statusPill": {- "ok": "一切正常 · {{count}} 个 Agent 已接入",- "degraded": "部分来源需留意 · {{count}} 个 Agent 已接入"+ "ok": "一切正常 · {{count}} 个 Agent 已接入中枢",+ "none": "还没有 Agent 接入中枢",+ "engineDown": "供给引擎未就绪 · 中枢暂时无法供给",+ "interrupted": "{{count}} 个 Agent 供给中断 · 需要处理",+ "waiting": "{{count}} 个 Agent 正在等待来源恢复",+ "needsAction": "{{source}} {{detail}}",+ "cooldown": "{{source}} {{detail}} · 已自动切换,恢复后切回",+ "andMore": "另有 {{count}} 个来源"},"sources": {"title": "来源",- "subtitle": "全局一份;拖动调整顺序 —— 顺序就是花钱顺序",+ "subtitle": "全局一份的账号库;谁先谁后,在下方各 Agent 里调","empty": "还没有来源,点“添加来源”连接订阅或 API Key。"},"source": {@@ -631,10 +637,37 @@"customEndpoint": "自定义地址","retryIn": "{{minutes}} 分后重试","reorder": "拖动排序",- "oauthSignedOut": "CLI 订阅未登录",- "cooldown": {- "timeout": "连续超时"- }+ "oauthSignedOut": "CLI 订阅未登录"+ },+ "current": "当前",+ "order": {+ "title": "来源顺序 · {{backend}}",+ "subtitle": "从上到下依次使用;失败自动切到下一个,恢复后自动切回。这里的顺序只影响 {{backend}}。",+ "subtitleShort": "从上到下依次使用;失败自动切到下一个,恢复后自动切回。只影响 {{backend}}。",+ "groupEnabled": "启用 · {{count}} 个来源",+ "groupDisabled": "未启用 · {{count}}",+ "groupIneligible": "不适用 · {{count}}",+ "following": "跟随推荐中",+ "followingLong": "跟随推荐中 · 新来源自动加入",+ "restore": "恢复推荐顺序",+ "enable": "启用",+ "enableAria": "启用 {{name}}",+ "disable": "取消启用",+ "openMenu": "模型菜单与映射",+ "supplies": "供 {{family}} 全系",+ "viaMapping": "经模型菜单改写后可供 {{backend}} 使用",+ "viaMappingShort": "经映射后可供 {{backend}}",+ "enabledEmpty": "{{backend}} 没有启用任何来源,下一个回合会因为供给中断而失败——中枢不会替它回退到直连。从下面的「未启用」里加一个进来。",+ "ineligibleUnknown": "不能供 {{backend}} 使用",+ "ineligibleClientUnknown": "{{vendor}} 订阅只能供它自己的官方客户端使用",+ "family": {+ "anthropic": "Claude",+ "openai": "GPT",+ "zhipuai": "GLM",+ "kimi": "Kimi",+ "xai": "Grok"+ },+ "enabledNoneRunnable": "{{backend}} 已启用的来源当前都无法供给,下一个回合会因为没有供给而失败。修好下面的某一个,或者再启用一个。"},"billing": {"monthly": "包月",@@ -645,6 +678,7 @@"active": "使用中","standby": "备用","cooldown": "暂不可用",+ "needs_action": "需要处理","error": "不可用"},"usage": {@@ -663,24 +697,37 @@"experimental": "实验","agents": {"title": "Agent",- "subtitle": "每个 Agent 用什么模型、由谁供给",+ "subtitle": "各自选用来源、各自排序;失败自动切到下一个","backendSettings": "后端设置",- "modelMenu": "模型菜单","connectHub": "接入中枢",- "menuComingSoon": "模型菜单即将上线(随下一个里程碑发布)","modelCount": "{{count}} 个模型",- "multiSource": "多来源",- "multiSourceCustom": "多来源 · 含 {{count}} 个自定义",- "hubNoSupply": "已接入中枢 · 暂无可用来源(当前走直连)",- "directNote": "仍在用 CLI 原生配置供给,未接入中枢"+ "hubNoSupply": "已接入中枢 · 没有启用任何来源,下一个回合会失败",+ "directNote": "仍在用 CLI 原生配置供给,未接入中枢",+ "sourceOrder": "来源顺序",+ "menuKind": {+ "fixed": "菜单固定",+ "open": "菜单开放"+ },+ "policy": {+ "follow": "跟随推荐",+ "custom": "自定义"+ },+ "attribution": {+ "interrupted": "{{names}} 供给中断",+ "waiting": "{{names}} 正在等待来源恢复",+ "unassigned": "{{models}} 暂无来源可供给"+ }},"recent": {"title": "最近切换","viewAll": "查看全部","collapse": "收起",+ "loadMore": "加载更早的记录",+ "loadingMore": "加载中…","today": "今天","yesterday": "昨天",- "empty": "暂无切换记录"+ "empty": "暂无切换记录",+ "deletedSource": "已删除"},"advanced": {"title": "高级",@@ -756,8 +803,7 @@"awaitingPaste": "等待授权 · {{time}} 后超时","awaitingDevice": "等待完成 · 自动检测,无需回填","verifying": "验证中…",- "success": "连接成功",- "finalizing": "正在创建来源…"+ "success": "连接成功"},"error": {"start": "无法开始授权,请重试",@@ -787,8 +833,20 @@"reorderFailed": "顺序保存失败","connected": "已接入中枢","connectFailed": "接入失败,请重试",- "refreshFailed": "刷新失败,请重试",- "connectedNoSupply": "已切到中枢,但暂无可用来源,当前仍走直连"+ "refreshFailed": "刷新失败,请重试"+ },+ "supply": {+ "degraded": "已接入中枢 · 有来源不可用,已自动切到下一个",+ "waiting": "已接入中枢 · 来源都在冷却中,恢复前的回合会失败",+ "interrupted": "已接入中枢 · 供给中断,下一个回合会失败",+ "noSources": "已接入中枢 · 还没有启用任何来源,下一个回合会失败",+ "nothingRunnable": "已接入中枢 · 已启用的来源当前都无法供给,下一个回合会失败"+ },+ "adoption": {+ "enabled": "已自动加入 {{list}} 的来源顺序",+ "entry": "{{name}}(第 {{position}} 位)",+ "none": "还没有 Agent 启用它 · 到各 Agent 的「来源顺序」里加进来才会被使用",+ "partlySkipped": "已自动加入 {{list}} 的来源顺序 · {{skipped}} 使用自定义顺序,未加入——到那里手动加进来才会被使用"},"menus": {"done": "完成",@@ -799,8 +857,8 @@"subtitle": "菜单固定:{{backend}} 只认这些内置 model ID;每个 ID 可改写为其他模型供给,只影响 {{backend}}。","builtinCol": "内置 MODEL ID","supplyCol": "实际供给",- "followNative": "跟随原生 · 按优先级供给",- "candidates": "来源按优先级 · {{sources}}",+ "followNative": "跟随原生 · 按来源顺序供给",+ "candidates": "来源顺序 · {{sources}}","candidatesUnavailable": "暂无来源可供给此模型","warning": "改写后思维链、缓存与工具语义与原生不完全等价","resetRow": "恢复默认",@@ -855,7 +913,7 @@"title": "中枢模式 · Hub","recommended": "推荐 · 默认","openModels": "打开模型页",- "description": "模型 token 由「设置 → 模型」统一供给:登录、API Key、优先级、映射都在那里管理。不改动 {{backend}} 的原生配置,随时可切走。"+ "description": "模型 token 由「设置 → 模型」统一供给:登录、API Key、来源顺序、映射都在那里管理。不改动 {{backend}} 的原生配置,随时可切走。"},"direct": {"title": "直连模式 · Direct",@@ -863,12 +921,11 @@"detected": "检测到既有直连配置:{{detail}} —— 可一键搬进中枢","import": "导入中枢…"},- "switchedHubNoSupply": "已切到中枢,但暂无可用来源,当前仍走直连",- "hubNoSupply": "已选中枢,但还没有可供给本后端的来源,当前仍走直连。去「模型」页添加或启用来源后即生效。"+ "fixHint": "去「模型」页添加或启用来源即可恢复。"},"migration": {"title": "接入模型中枢",- "subtitle": "把现有的登录和 API Key 一次搬进「模型」中枢,三个 Agent 共用一份来源和优先级。",+ "subtitle": "把现有的登录和 API Key 一次搬进「模型」中枢;导入后每个 Agent 各自选用来源、各自排序。","empty": "没有检测到可迁移的原生配置。","scanFailed": "扫描原生配置失败,请重试","applyFailed": "导入失败,请重试",@@ -914,20 +971,13 @@"deleteForceConfirm": "强制删除","deleted": "已删除来源","deleteFailed": "删除失败,请重试",- "priorityLabel": "优先级 {{position}}","renameHint": "只改显示名,不动凭证","rediscoverHint": "重新拉取这个来源能供给的模型",- "moveUp": "上移一位",- "moveUpHint": "更早被使用",- "moveUpHintAtTop": "已在第 1 位,不能再上移",- "moveDown": "下移一位",- "moveDownHint": "更晚被使用",- "moveDownHintAtBottom": "已在最后一位,不能再下移","deleteHint": "删除前会再确认一次"},"migrationBanner": {"title": "发现可导入中枢的原生配置",- "body": "检测到 {{count}} 项原生登录 / API Key 可搬进中枢,三个 Agent 共用一份来源和优先级。",+ "body": "检测到 {{count}} 项原生登录 / API Key 可搬进中枢;导入后每个 Agent 各自选用来源、各自排序。","import": "导入中枢","dismiss": "忽略"}@@ -979,6 +1029,31 @@"optimizingRoute": "优化中...","optimizeStarted": "第二条 Connector 正在评估更优线路"},+ "models": {+ "eligibility": {+ "subscription_wrong_client": "{{vendor}} 订阅仅可供 {{backend}} 使用",+ "opencode_api_key_only": "OpenCode 只能由 API Key 来源供给",+ "consent_required": "需要先同意实验性中枢供给"+ },+ "source": {+ "cooldown": {+ "network": "网络不通",+ "timeout": "连续超时",+ "rate_limited": "触发限流",+ "quota_exhausted": "本周期额度用完",+ "server_error": "上游服务异常"+ },+ "needs_action": {+ "oauth_expired": "登录已过期,需要重新授权",+ "balance_exhausted": "余额不足,需要充值",+ "credential_revoked": "凭据已失效,需要重新填写",+ "account_banned": "账号被限制使用"+ },+ "error": {+ "unclassified": "未知错误,暂时不可用"+ }+ }+ },"accessBlocked": {"title": "无法在此地址打开控制台","body": "Avibe 正在运行,但拒绝在当前地址打开控制台。",