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(models): rebuild Models page around model supply (#1120)
Call Whiteb846d4f40b52
diff --git a/ui/src/components/settings/models/AdoptionNote.test.tsx b/ui/src/components/settings/models/AdoptionNote.test.tsxindex 04b2b1336..a4b8a4a32 100644--- a/ui/src/components/settings/models/AdoptionNote.test.tsx+++ b/ui/src/components/settings/models/AdoptionNote.test.tsx@@ -80,7 +80,7 @@ describe('AdoptionNote', () => {const body = text(html);expect(body).toContain('Claude Code');expect(body).toContain('Codex');- expect(body).toContain('自定义顺序');+ expect(body).toContain('已改为手动');});it('names them even when nobody adopted it at all', () => {@@ -90,7 +90,7 @@ describe('AdoptionNote', () => {// half must NOT appear: there is no list to name.const body = text(render([], [{ backend: 'codex', reason: 'custom_order' }]));expect(body).toContain('Codex');- expect(body).toContain('自定义顺序');+ expect(body).toContain('已改为手动');expect(body).not.toContain('已自动加入');});diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex 985ac2a0e..b12ea5124 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -1,7 +1,3 @@-// 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';@@ -10,25 +6,20 @@ import { describe, expect, it, vi } from 'vitest';import en from '../../../i18n/en.json';import zh from '../../../i18n/zh.json';+import { ToastProvider } from '@/context/ToastContext';import { AgentCard } from './AgentCard';-import type { AgentSupply, Source, SourceState } from './types';+import { modelChainKey, type ModelChainIndex } from './modelRows';+import type { AgentChain, AgentSupply, Source } 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 i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'zh',+ fallbackLng: 'en',+ resources: { en: { translation: en }, zh: { translation: zh } },+ interpolation: { escapeValue: false },+});-const source = (id: string, name: string, state: SourceState = ACTIVE): Source => ({+const source = (id: string, name: string): Source => ({id,kind: 'api_key',vendor: 'anthropic',@@ -36,153 +27,284 @@ const source = (id: string, name: string, state: SourceState = ACTIVE): Source =protocol: 'anthropic',supply_channel: 'hub',billing: 'metered',- state,- models: [],+ state: { status: 'active', retry_at: null, detail_key: null },+ models: [{ id: 'claude-opus-4-6', provenance: 'discovered' }],});-const hubAgent = (over: Partial<AgentSupply> = {}): AgentSupply => ({+const agent = (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: [] },+ sources: { policy: 'follow', order: ['src_a'], eligibility: [] },supply_status: 'ok',- model_supply: [],+ model_supply: [{ model_id: 'claude-opus-4-6', chain_length: 1 }],named_agents: [],mappings: [],menu: null,- builtin_models: ['claude-opus-4-6'],+ builtin_models: ['claude-opus-4-6', 'claude-sonnet-4-6'],standard_vendors: null,...over,});-const SOURCES = [source('src_a', 'Claude Pro 订阅'), source('src_b', 'Anthropic API Key')];+const chain = (modelId: string, over: Partial<AgentChain> = {}): AgentChain => ({+ contract_version: 4,+ backend: 'claude',+ model_id: modelId,+ supply_state: 'ok',+ chain: [{+ source_id: 'src_a',+ channel: 'hub',+ via_mapping: false,+ resolved_model_id: null,+ health: 'healthy',+ runnable: true,+ reason: null,+ retry_at: null,+ }],+ ...over,+});-const render = (agents: AgentSupply[], sources: Source[] = SOURCES, lng: 'en' | 'zh' = 'zh') =>- renderToStaticMarkup(- <MemoryRouter>- <I18nextProvider i18n={instance(lng)}>+const chains = (...rows: AgentChain[]): ModelChainIndex => Object.fromEntries(+ rows.map((row) => [modelChainKey(row.backend, row.model_id), { kind: 'ready', chain: row }]),+);++const render = (+ agents: AgentSupply[],+ reads: ModelChainIndex,+ issuesOnly = false,+ sourceRows: Source[] = [source('src_a', 'Anthropic API Key'), source('src_b', 'OpenAI API Key')],+ pendingBackends: ReadonlySet<string> = new Set(),+) => renderToStaticMarkup(+ <MemoryRouter>+ <I18nextProvider i18n={i18n}>+ <ToastProvider><AgentCardagents={agents}- sources={sources}+ sources={sourceRows}+ chains={reads}+ runtime={null}+ issuesOnly={issuesOnly}+ pendingBackends={pendingBackends}onConnectHub={vi.fn()}onOpenOrder={vi.fn()}+ onOpenModels={vi.fn()}+ onSetRoute={vi.fn()}+ onAddModel={vi.fn()}+ onRepair={vi.fn()}+ onRetest={vi.fn()}+ retestingSourceId={null}+ onProbeSettled={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);- });+ </ToastProvider>+ </I18nextProvider>+ </MemoryRouter>,+);- 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,+describe('AgentCard model list', () => {+ it('shows every model, the current marker, and the actual serving source', () => {+ const html = render(+ [agent()],+ chains(chain('claude-opus-4-6'), chain('claude-sonnet-4-6')),);+ expect(html).toContain('claude-opus-4-6');+ expect(html).toContain('claude-sonnet-4-6');+ expect(html).toContain(zh.settings.models.current);+ expect(html).toContain('当前由 Anthropic API Key 供给');});- 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);+ it('explains an automatic switch on the current model row', () => {+ const failedOver = chain('claude-opus-4-6', {+ chain: [+ {+ source_id: 'src_a',+ channel: 'hub',+ via_mapping: false,+ resolved_model_id: null,+ health: 'needs_action',+ runnable: false,+ reason: null,+ retry_at: null,+ },+ {+ source_id: 'src_b',+ channel: 'hub',+ via_mapping: true,+ resolved_model_id: 'gpt-5.5',+ health: 'healthy',+ runnable: true,+ reason: null,+ retry_at: null,+ },+ ],+ });+ const html = render([agent()], chains(failedOver, chain('claude-sonnet-4-6')));+ expect(html).toContain('当前已自动换到 OpenAI API Key');});- // 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/);+ it('renders an honest row-zero state when no model is selected', () => {+ const html = render([agent({ selected_model_id: null, current: null })], chains(chain('claude-opus-4-6')));+ expect(html).toContain(zh.settings.models.emptySelection.title);+ expect(html).toContain(zh.settings.models.emptySelection.action);});-});-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('gives an interrupted model its route door', () => {+ const broken = chain('claude-opus-4-6', { chain: [], supply_state: 'interrupted' });+ const html = render([agent()], chains(broken, chain('claude-sonnet-4-6')));+ expect(html).toContain(zh.settings.models.modelStatus.needsAction);+ expect(html).toContain(zh.settings.models.routes.manual);});- it('offers 接入中枢 instead of the order editor', () => {- const html = render([direct]);- expect(html).toContain(COPY.connectHub);- expect(html).not.toContain(COPY.sourceOrder);+ it('gives a blocked non-credential source its retest remedy on the model row', () => {+ const blockedSource = {+ ...source('src_a', 'Anthropic API Key'),+ state: { status: 'error' as const, detail_key: 'models.source.error.unclassified' as const },+ };+ const blocked = chain('claude-opus-4-6', {+ supply_state: 'interrupted',+ chain: [{+ source_id: 'src_a',+ channel: 'hub',+ via_mapping: false,+ resolved_model_id: null,+ health: 'needs_action',+ runnable: false,+ reason: null,+ retry_at: null,+ }],+ });+ const html = render([agent()], chains(blocked, chain('claude-sonnet-4-6')), false, [blockedSource]);+ expect(html).toContain(zh.settings.models.repair.retest);+ expect(html).not.toContain(zh.settings.models.routes.manual);});- 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);+ it('routes a native CLI process blocker to backend settings instead of inventory actions', () => {+ const nativeSource = {+ ...source('src_a', 'Claude subscription'),+ kind: 'subscription' as const,+ supply_channel: 'native_cli' as const,+ billing: 'monthly' as const,+ };+ const blocked = chain('claude-opus-4-6', {+ supply_state: 'interrupted',+ chain: [{+ source_id: 'src_a',+ channel: 'native_cli',+ via_mapping: false,+ resolved_model_id: null,+ health: 'healthy',+ runnable: false,+ reason: 'native_cli_unavailable',+ retry_at: null,+ }],+ });+ const html = render([agent()], chains(blocked, chain('claude-sonnet-4-6')), false, [nativeSource]);+ expect(html).toContain(zh.models.probe.native_cli_unavailable);+ expect(html).toContain('href="/admin/settings/backends/claude"');+ expect(html).not.toContain(zh.settings.models.routes.manual);+ expect(html).not.toContain(zh.settings.models.sources.addModel);});-});-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' },+ it('routes an off-order OpenCode supplier to source order instead of manual inventory', () => {+ const enabled = {+ ...source('src_enabled', 'Enabled source'),+ models: [{ id: 'another-model', provenance: 'discovered' as const }],+ };+ const outside = source('src_outside', 'Disabled supplier');+ const open = agent({+ backend: 'opencode',+ menu_kind: 'open',+ selected_model_id: 'anthropic/claude-opus-4-6',+ current: null,+ sources: {+ policy: 'custom',+ order: ['src_enabled'],+ eligibility: [+ { source_id: 'src_enabled', eligible: true },+ { source_id: 'src_outside', eligible: true },],- }),- ]);- expect(html).toContain('claude 供给中断');- expect(html).toContain('pm 正在等待来源恢复');- expect(html).not.toContain('reviewer');+ },+ model_supply: [{ model_id: 'anthropic/claude-opus-4-6', chain_length: 0 }],+ mappings: [],+ menu: { view: 'featured', checked: ['anthropic/claude-opus-4-6'] },+ builtin_models: null,+ standard_vendors: ['anthropic'],+ });+ const interrupted = chain('anthropic/claude-opus-4-6', { backend: 'opencode', supply_state: 'interrupted', chain: [] });+ const html = render([open], chains(interrupted), false, [enabled, outside]);+ expect(html.match(new RegExp(zh.settings.models.agents.sourceOrder, 'g'))).toHaveLength(2);+ expect(html).not.toContain(zh.settings.models.sources.addModel);});- 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 },- ],+ it('disables every OpenCode model-menu entry while the agent write is pending', () => {+ const open = agent({ backend: 'opencode', menu_kind: 'open', builtin_models: null });+ const pending = new Set(['opencode']);+ const footer = render([open], {}, false, undefined, pending);+ expect(footer).toMatch(/<button[^>]*disabled=""[^>]*>(?:(?!<\/button>)[\s\S])*?管理型号<\/button>/);++ const rowZero = render([+ agent({+ backend: 'opencode',+ menu_kind: 'open',+ selected_model_id: null,+ current: null,+ model_supply: [],+ mappings: [],+ menu: { view: 'featured', checked: [] },+ builtin_models: null,}),- ]);- expect(html).toContain('claude-haiku-4-5 暂无来源可供给');- expect(html).not.toContain('供给中断');+ ], {}, false, undefined, pending);+ expect(rowZero).toMatch(/<button[^>]*disabled=""[^>]*>(?:(?!<\/button>)[\s\S])*?选择型号<\/button>/);});- // 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' },- ],+ it('filters to affected rows without leaving healthy siblings behind', () => {+ const html = render(+ [agent()],+ chains(chain('claude-opus-4-6', { chain: [], supply_state: 'interrupted' }), chain('claude-sonnet-4-6')),+ true,+ );+ expect(html).toContain('claude-opus-4-6');+ expect(html).not.toContain('claude-sonnet-4-6');+ });++ it('keeps a cooling model in the affected view without offering manual repair', () => {+ const waiting = chain('claude-opus-4-6', {+ supply_state: 'waiting',+ chain: [{+ source_id: 'src_a',+ channel: 'hub',+ via_mapping: false,+ resolved_model_id: null,+ health: 'cooldown',+ runnable: false,+ reason: null,+ retry_at: '2026-07-31T04:00:00Z',+ }],+ });+ const html = render([agent({ builtin_models: ['claude-opus-4-6'] })], chains(waiting), true);+ expect(html).toContain('claude-opus-4-6');+ expect(html).toContain(zh.settings.models.modelStatus.cooldown);+ expect(html).toContain('data-model-issue="true"');+ expect(html).not.toContain(zh.settings.models.routes.manual);+ });++ it('gives a chain read failure a retry door', () => {+ const html = render([agent()], {+ [modelChainKey('claude', 'claude-opus-4-6')]: { kind: 'error' },+ [modelChainKey('claude', 'claude-sonnet-4-6')]: { kind: 'ready', chain: chain('claude-sonnet-4-6') },});- expect(render([agent], SOURCES, 'zh')).toContain('claude、pm');- expect(render([agent], SOURCES, 'en')).toContain('claude, pm');+ expect(html).toContain(zh.settings.models.modelStatus.needsAction);+ expect(html).toContain(zh.settings.models.modelStatus.retry);});- 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('暂无来源可供给');+ it('keeps Direct honest and offers the managed-mode action instead of order editing', () => {+ const html = render([agent({ mode: 'direct', sources: null, current: null })], {});+ expect(html).toContain(zh.settings.models.modelStatus.direct);+ expect(html).toContain(zh.settings.models.agents.enableManaged);+ expect(html).not.toContain(zh.settings.models.agents.sourceOrder);+ expect(html).not.toContain(zh.settings.models.routes.expand);});});diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsxindex 5ecf014ea..89c985bca 100644--- a/ui/src/components/settings/models/AgentCard.tsx+++ b/ui/src/components/settings/models/AgentCard.tsx@@ -1,343 +1,702 @@-// 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 { ArrowDownUp, ArrowRight, ChevronRight, Download, TriangleAlert, Zap } from 'lucide-react';+import {+ ArrowDownUp,+ ChevronDown,+ ChevronRight,+ CircleAlert,+ Loader2,+ Plus,+ Settings2,+ TriangleAlert,+ Zap,+} from 'lucide-react';import { useTranslation } from 'react-i18next';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';+import { SegmentedRadio } from '@/components/ui/segmented';import { cn } from '@/lib/utils';-import { ModeChip } from './chips';+import { apiFailure, modelsApi } from './modelsApi';+import {+ dryRunOutcome,+ probeArrival,+ repairAction,+ REPAIR_LABEL_KEY,+ type DryRunOutcome,+ type RepairKind,+} from './repair';+import { serverText } from './serverCopy';+import { ModelRoutePicker } from './ModelRoutePicker';+import { useAnnounceEnrollment } from './menus/enrollment';+import {+ agentNeedsModelSelection,+ listedModelIds,+ modelChainKey,+ modelHasOffOrderSupplier,+ modelNeedsAttention,+ type ModelChainIndex,+ type ModelChainRead,+} from './modelRows';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';+import type { RaisedRepair } from './SourceRowMenu';+import type { AgentBackend, AgentChainLink, AgentSupply, RuntimeDependency, 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 }) => {+type ModelTone = 'ok' | 'cooldown' | 'attention' | 'neutral';++const TONE_DOT: Record<ModelTone, string> = {+ ok: 'bg-mint',+ cooldown: 'bg-muted',+ attention: 'bg-destructive',+ neutral: 'bg-muted/60',+};++const sourceName = (sources: Source[], sourceId: string): string =>+ sources.find((source) => source.id === sourceId)?.display_name ?? sourceId;++const runnableHead = (read: ModelChainRead | undefined): AgentChainLink | null =>+ read?.kind === 'ready' ? read.chain.chain.find((link) => link.runnable) ?? null : null;++const blockedRepair = (+ read: ModelChainRead | undefined,+ sources: Source[],+): { source: Source; kind: RepairKind } | null => {+ if (read?.kind !== 'ready') return null;+ for (const link of read.chain.chain) {+ const source = sources.find((candidate) => candidate.id === link.source_id);+ if (!source) continue;+ const kind = repairAction(source);+ if (kind) return { source, kind };+ }+ return null;+};++const isRaisedRepair = (kind: RepairKind): kind is RaisedRepair => kind !== 'retest';++const ModelProbe: React.FC<{+ agent: AgentSupply;+ modelId: string;+ sources: Source[];+ disabled?: boolean;+ onSettled: () => void;+}> = ({ agent, modelId, sources, disabled, onSettled }) => {const { t } = useTranslation();+ const [running, setRunning] = React.useState(false);+ const [outcome, setOutcome] = React.useState<DryRunOutcome | null>(null);+ const [errorReason, setErrorReason] = React.useState<{ key: string | null } | null>(null);+ const seq = React.useRef(0);++ React.useEffect(() => {+ seq.current += 1;+ setRunning(false);+ setOutcome(null);+ setErrorReason(null);+ }, [agent.backend, modelId, agent.sources?.policy, agent.sources?.order, agent.mappings]);++ const run = async () => {+ if (agent.mode !== 'hub' || running || disabled) return;+ const mine = ++seq.current;+ setRunning(true);+ setOutcome(null);+ setErrorReason(null);+ try {+ const probe = await modelsApi.probeAgent(agent.backend, modelId);+ const arrival = probeArrival({ kind: 'result', probe }, seq.current === mine);+ if (arrival.report) setOutcome(dryRunOutcome(probe, sources));+ if (arrival.reread) onSettled();+ } catch (error) {+ const failure = apiFailure(error);+ const arrival = probeArrival(+ {+ kind: 'thrown',+ code: failure?.code ?? null,+ serverNamed: failure?.serverNamed ?? false,+ },+ seq.current === mine,+ );+ if (arrival.report) setErrorReason({ key: failure?.detail ?? null });+ if (arrival.reread) onSettled();+ } finally {+ if (seq.current === mine) setRunning(false);+ }+ };++ const result = outcome+ ? outcome.kind === 'ok'+ ? outcome.channel === 'native_cli'+ ? t('settings.models.probe.nativeReady', { source: outcome.sourceName }) as string+ : t('settings.models.probe.hubOk', {+ source: outcome.sourceName,+ ms: outcome.latencyMs,+ }) as string+ : t('settings.models.probe.failed', {+ source: outcome.sourceName,+ detail: serverText(t, outcome.detailKey, 'settings.models.probe.unknown'),+ }) as string+ : errorReason+ ? serverText(t, errorReason.key, 'settings.models.probe.error')+ : null;+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>+ <div className="flex flex-col items-start gap-2 sm:items-end">+ <Button+ variant="outline"+ size="sm"+ className="h-9"+ onClick={() => void run()}+ disabled={agent.mode !== 'hub' || disabled || running}+ >+ {running ? <Loader2 className="animate-spin" /> : <Zap />}+ {t(running ? 'settings.models.probe.running' : 'settings.models.probe.action')}+ </Button>+ {result && (+ <p className={cn('max-w-sm text-[11.5px] leading-relaxed', outcome?.kind === 'ok' ? 'text-mint' : 'text-gold')}>+ {result}+ </p>+ )}+ </div>);};-/**- * 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 RoutePanel: React.FC<{+ agent: AgentSupply;+ modelId: string;+ sources: Source[];+ read: ModelChainRead | undefined;+ pending: boolean;+ onSetRoute: (backend: AgentBackend, modelId: string, targetModelId: string | null) => void;+ onAddModel: () => void;+ onProbeSettled: () => void;+}> = ({ agent, modelId, sources, read, pending, onSetRoute, onAddModel, onProbeSettled }) => {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;+ const stored = agent.mappings?.find((mapping) => mapping.builtin_id === modelId && mapping.enabled);+ const storedTarget = stored?.target_model_id ?? null;+ const [choice, setChoice] = React.useState<'global' | 'manual'>(stored ? 'manual' : 'global');+ React.useEffect(() => setChoice(storedTarget ? 'manual' : 'global'), [storedTarget]);+ const backendName = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend }) as string;++ const head = runnableHead(read);+ const actualSource = head ? sourceName(sources, head.source_id) : null;+ const actualTarget = head?.resolved_model_id && head.resolved_model_id !== modelId ? head.resolved_model_id : 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>- );-};+ <div className="grid gap-4 border-t border-border bg-foreground/[0.015] px-4 py-4 sm:grid-cols-[minmax(0,1fr)_auto] sm:px-5">+ <div className="min-w-0 space-y-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <span className="text-[12px] font-semibold text-foreground">{t('settings.models.routes.title')}</span>+ {actualSource && (+ <span className="truncate text-[11.5px] text-muted">+ {t('settings.models.routes.liveSource', {+ source: actualSource,+ model: actualTarget ?? modelId,+ })}+ </span>+ )}+ </div>++ {agent.menu_kind === 'fixed' ? (+ <>+ <SegmentedRadio+ value={choice}+ onChange={(next) => {+ if (next === 'global' && stored) onSetRoute(agent.backend, modelId, null);+ else setChoice(next);+ }}+ options={[+ { id: 'global', label: t('settings.models.routes.global', { backend: backendName }) as string },+ { id: 'manual', label: t('settings.models.routes.manual') as string },+ ]}+ ariaLabel={t('settings.models.routes.title') as string}+ disabled={pending}+ />+ {choice === 'global' ? (+ <p className="text-[11.5px] leading-relaxed text-muted">+ {stored+ ? t('settings.models.routes.globalPending', { backend: backendName })+ : actualSource+ ? t('settings.models.routes.globalActual', { backend: backendName, source: actualSource })+ : t('settings.models.routes.globalUnavailable', { backend: backendName })}+ </p>+ ) : (+ <div className="space-y-2">+ <ModelRoutePicker+ agent={agent}+ sources={sources}+ value={stored?.target_model_id ?? ''}+ servedBy={actualSource}+ disabled={pending}+ onChange={(targetModelId) => onSetRoute(agent.backend, modelId, targetModelId)}+ onAddModel={onAddModel}+ />+ <p className="flex items-start gap-1.5 text-[11px] leading-relaxed text-gold">+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0" />+ {t('settings.models.routes.compatibility')}+ </p>+ </div>+ )}+ </>+ ) : (+ <p className="rounded-lg border border-border bg-background px-3 py-2.5 text-[11.5px] leading-relaxed text-muted">+ {t('settings.models.routes.openMenuGlobal', {+ backend: backendName,+ source: actualSource ?? t('settings.models.routes.none'),+ })}+ </p>+ )}+ </div>-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]',+ <ModelProbe+ agent={agent}+ modelId={modelId}+ sources={sources}+ disabled={pending}+ onSettled={onProbeSettled}+ />+ </div>+ );};-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.+const ModelRow: React.FC<{+ agent: AgentSupply;+ modelId: string;+ sources: Source[];+ read: ModelChainRead | undefined;+ runtime: RuntimeDependency | null;+ pending: boolean;+ onSetRoute: (backend: AgentBackend, modelId: string, targetModelId: string | null) => void;+ onAddModel: () => void;+ onOpenOrder: () => void;+ onRepair: (source: Source, kind: RaisedRepair) => void;+ onRetest: (source: Source) => void;+ retestingSourceId: string | null;+ onProbeSettled: () => void;+}> = ({+ agent,+ modelId,+ sources,+ read,+ runtime,+ pending,+ onSetRoute,+ onAddModel,+ onOpenOrder,+ onRepair,+ onRetest,+ retestingSourceId,+ onProbeSettled,+}) => {+ const { t } = useTranslation();+ const [expanded, setExpanded] = React.useState(false);+ const configurable = agent.mode === 'hub';+ const current = agent.selected_model_id === modelId;+ const head = runnableHead(read);+ const headIndex = read?.kind === 'ready' && head ? read.chain.chain.indexOf(head) : -1;+ const runtimeBlocked = head?.channel === 'hub' && Boolean(runtime && runtime.status.health !== 'ok');+ const needsAttention = modelNeedsAttention(agent, modelId, read, runtime);+ const recoversAutomatically = read?.kind === 'ready' && read.chain.supply_state === 'waiting';+ const needsAction = needsAttention && !recoversAutomatically;+ const nativeProcessBlock = read?.kind === 'ready' && read.chain.supply_state === 'interrupted'+ ? read.chain.chain.find((link) => link.reason === 'native_cli_unavailable') ?? null+ : null;+ const needsOrderEnrollment = agent.menu_kind === 'open'+ && read?.kind === 'ready'+ && read.chain.supply_state === 'interrupted'+ && modelHasOffOrderSupplier(agent, sources, modelId);+ const repair = blockedRepair(read, sources);+ const raisedRepair = repair && isRaisedRepair(repair.kind)+ ? { source: repair.source, kind: repair.kind }+ : null;+ const structuralEmpty =+ read?.kind === 'ready'+ ? read.chain.chain.length === 0+ : agent.model_supply?.find((model) => model.model_id === modelId)?.chain_length === 0;- Muted dot = the same skip for a reason nobody can act on from this page: the- source is healthy and on the route, this process just cannot sign the- backend's CLI in with it. A second HUE on the one dot, not a second dot — a- position is stepped over for one reason at a time, and 10px of chip has no- room to argue. Which is also why neither dot carries its own label: the gold- one is named by the source row's state chip and the muted one by- `order.nativeUnavailable` in the order drawer, the two places the user goes- to do something about it. */}- {(chip.unhealthy || chip.unavailable) && (- <span- className={cn('size-1 shrink-0 rounded-full sm:size-[5px]', chip.unhealthy ? 'bg-gold' : 'bg-muted')}- aria-hidden- />- )}- </span>-);+ let tone: ModelTone = 'neutral';+ let status = t('settings.models.modelStatus.checking') as string;+ let detail = '';+ if (agent.mode === 'direct') {+ status = t('settings.models.modelStatus.direct') as string;+ } else if (read?.kind === 'ready' && read.chain.supply_state === 'waiting') {+ tone = 'cooldown';+ status = t('settings.models.modelStatus.cooldown') as string;+ const waiting = read.chain.chain[0];+ if (waiting) detail = sourceName(sources, waiting.source_id);+ } else if (runtimeBlocked) {+ tone = 'attention';+ status = t('settings.models.modelStatus.needsAction') as string;+ detail = t('settings.models.modelStatus.runtime') as string;+ } else if (nativeProcessBlock) {+ tone = 'attention';+ status = t('settings.models.modelStatus.needsAction') as string;+ detail = t('models.probe.native_cli_unavailable') as string;+ } else if (needsAction) {+ tone = 'attention';+ status = t('settings.models.modelStatus.needsAction') as string;+ detail = read?.kind === 'error'+ ? t('settings.models.modelStatus.unknown') as string+ : structuralEmpty+ ? t('settings.models.modelStatus.noSource') as string+ : t('settings.models.modelStatus.blocked') as string;+ } else if (head) {+ tone = 'ok';+ status = t('settings.models.modelStatus.ok') as string;+ const serving = sourceName(sources, head.source_id);+ detail = t(+ current+ ? headIndex > 0+ ? 'settings.models.modelStatus.currentSwitched'+ : 'settings.models.modelStatus.currentSource'+ : 'settings.models.modelStatus.source',+ { source: serving },+ ) as string;+ } else if (read?.kind === 'error') {+ status = t('settings.models.modelStatus.unknown') as string;+ }-/** 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>-);+ const action = needsAction ? (+ read?.kind === 'error' ? (+ <Button variant="outline" size="xs" className="h-7 shrink-0" onClick={onProbeSettled}>+ {t('settings.models.modelStatus.retry')}+ </Button>+ ) : runtimeBlocked ? (+ <Button asChild variant="outline" size="xs" className="h-7 shrink-0">+ <Link to="/admin/settings/dependencies">{t('settings.models.modelStatus.runtimeAction')}</Link>+ </Button>+ ) : nativeProcessBlock ? (+ <Button asChild variant="outline" size="xs" className="h-7 shrink-0">+ <Link to={`/admin/settings/backends/${agent.backend}`}>{t('settings.models.modelStatus.runtimeAction')}</Link>+ </Button>+ ) : repair?.kind === 'retest' ? (+ <Button+ variant="outline"+ size="xs"+ className="h-7 shrink-0"+ onClick={() => onRetest(repair.source)}+ disabled={retestingSourceId !== null}+ >+ {retestingSourceId === repair.source.id && <Loader2 className="animate-spin" />}+ {t(REPAIR_LABEL_KEY.retest)}+ </Button>+ ) : raisedRepair ? (+ <Button+ variant="outline"+ size="xs"+ className="h-7 shrink-0"+ onClick={() => onRepair(raisedRepair.source, raisedRepair.kind)}+ >+ {t(REPAIR_LABEL_KEY[raisedRepair.kind])}+ </Button>+ ) : needsOrderEnrollment ? (+ <Button variant="outline" size="xs" className="h-7 shrink-0" onClick={onOpenOrder} disabled={pending}>+ <ArrowDownUp />+ {t('settings.models.agents.sourceOrder')}+ </Button>+ ) : agent.menu_kind === 'open' ? (+ <Button variant="outline" size="xs" className="h-7 shrink-0" onClick={onAddModel}>+ <Plus />+ {t('settings.models.sources.addModel')}+ </Button>+ ) : (+ <Button variant="outline" size="xs" className="h-7 shrink-0" onClick={() => setExpanded(true)}>+ {t('settings.models.routes.manual')}+ </Button>+ )+ ) : null;-/** 跟随推荐 (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,+ <div className={cn('border-b border-border last:border-b-0', current && 'bg-mint-soft/35')} data-model-issue={needsAttention || undefined}>+ <div className="group grid min-w-0 grid-cols-[minmax(0,1fr)] items-center gap-3 px-4 py-3 sm:grid-cols-[minmax(180px,0.9fr)_minmax(260px,1.4fr)_auto] sm:px-5">+ <button+ type="button"+ onClick={() => configurable && setExpanded((value) => !value)}+ className="min-w-0 text-left"+ >+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate font-mono text-[12.5px] font-semibold text-foreground">{modelId}</span>+ {current && (+ <Badge variant="success" className="shrink-0 px-1.5 py-0 text-[9.5px]">+ {t('settings.models.current')}+ </Badge>+ )}+ </span>+ </button>++ <button+ type="button"+ onClick={() => configurable && setExpanded((value) => !value)}+ className="col-start-1 row-start-2 flex min-w-0 items-center gap-2 text-left sm:col-start-2 sm:row-start-1"+ >+ <span className={cn('size-2 shrink-0 rounded-full', TONE_DOT[tone])} aria-hidden />+ <span className={cn('shrink-0 text-[11.5px] font-semibold', tone === 'attention' ? 'text-destructive' : tone === 'ok' ? 'text-mint' : 'text-muted')}>+ {status}+ </span>+ {detail && <span className="min-w-0 truncate text-[11.5px] text-muted">· {detail}</span>}+ </button>++ <div className="col-start-1 row-start-3 flex min-w-0 items-center justify-end gap-1.5 sm:col-start-3 sm:row-start-1">+ {action}+ {configurable && (+ <button+ type="button"+ aria-label={t('settings.models.routes.expand') as string}+ onClick={() => setExpanded((value) => !value)}+ className={cn(+ 'hidden size-8 items-center justify-center rounded-md text-muted transition hover:bg-surface-2 hover:text-foreground sm:flex',+ expanded ? 'opacity-100' : 'opacity-60 sm:opacity-0 sm:group-hover:opacity-100 sm:focus-visible:opacity-100',+ )}+ >+ {expanded ? <ChevronDown className="size-4" /> : <ChevronRight className="size-4" />}+ </button>+ )}+ </div>+ </div>+ {configurable && expanded && (+ <RoutePanel+ agent={agent}+ modelId={modelId}+ sources={sources}+ read={read}+ pending={pending}+ onSetRoute={onSetRoute}+ onAddModel={onAddModel}+ onProbeSettled={onProbeSettled}+ />)}- >- {t(`settings.models.agents.policy.${follow ? 'follow' : 'custom'}`)}- </Badge>+ </div>);};-/**- * 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 EmptySelectionRow: React.FC<{+ agent: AgentSupply;+ pending: boolean;+ onOpenModels: (agent: AgentSupply) => void;+}> = ({+ agent,+ pending,+ onOpenModels,+}) => {+ const { t } = useTranslation();+ return (+ <div className="flex flex-col gap-3 border-b border-destructive/25 bg-destructive/[0.035] px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5" data-model-issue>+ <span className="flex min-w-0 items-start gap-2.5">+ <CircleAlert className="mt-0.5 size-4 shrink-0 text-destructive" />+ <span>+ <span className="block text-[12.5px] font-semibold text-foreground">{t('settings.models.emptySelection.title')}</span>+ <span className="mt-0.5 block text-[11.5px] text-muted">{t('settings.models.emptySelection.body')}</span>+ </span>+ </span>+ {agent.menu_kind === 'open' ? (+ <Button+ variant="outline"+ size="sm"+ className="h-9 shrink-0"+ onClick={() => onOpenModels(agent)}+ disabled={pending}+ >+ {t('settings.models.emptySelection.action')}+ </Button>+ ) : (+ <Button asChild variant="outline" size="sm" className="h-9 shrink-0">+ <Link to="/agents">{t('settings.models.emptySelection.action')}</Link>+ </Button>+ )}+ </div>+ );};-const AgentRow: React.FC<{+const AgentModelCard: React.FC<{agent: AgentSupply;sources: Source[];+ chains: ModelChainIndex;+ runtime: RuntimeDependency | null;+ issuesOnly: boolean;+ pending: boolean;+ connecting: boolean;onConnectHub: (agent: AgentSupply) => void;onOpenOrder: (agent: AgentSupply) => void;- connecting: boolean;-}> = ({ agent, sources, onConnectHub, onOpenOrder, connecting }) => {+ onOpenModels: (agent: AgentSupply) => void;+ onSetRoute: (+ backend: AgentBackend,+ modelId: string,+ targetModelId: string | null,+ onCommitted: (before: AgentSupply, after: AgentSupply) => void,+ ) => void;+ onAddModel: (backend: AgentBackend) => void;+ onRepair: (source: Source, kind: RaisedRepair) => void;+ onRetest: (source: Source) => void;+ retestingSourceId: string | null;+ onProbeSettled: () => void;+}> = (props) => {const { t } = useTranslation();+ const { agent, sources, chains, runtime, issuesOnly } = props;+ const announceEnrollment = useAnnounceEnrollment(agent.backend, sources);const { Icon, accent } = backendVisual(agent.backend);- const hub = agent.mode === 'hub';- const chips = chainChips(agent, sources);-- 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>- );+ const allModels = listedModelIds(agent);+ const models = issuesOnly+ ? allModels.filter((modelId) => modelNeedsAttention(agent, modelId, chains[modelChainKey(agent.backend, modelId)], runtime))+ : allModels;+ const emptySelection = agentNeedsModelSelection(agent);+ if (issuesOnly && !emptySelection && models.length === 0) return null;return (- // 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.- //- // 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>-- <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>- <MenuKindBadge agent={agent} />- </span>-- <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>-- {/* 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>+ <section className="overflow-hidden rounded-xl border border-border bg-background">+ <div className="flex flex-col gap-3 border-b border-border px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5">+ <div className="flex min-w-0 items-center gap-3">+ <span className={cn('flex size-9 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>+ <Icon className={cn('size-[18px]', ACCENT_ICON[accent])} />+ </span>+ <span className="min-w-0">+ <span className="flex items-center gap-2">+ <h2 className="truncate text-[14px] font-bold text-foreground">+ {t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}+ </h2>+ {agent.mode === 'direct' && (+ <Badge variant="secondary" className="px-2 py-0 text-[10px]">+ {t('settings.models.modelStatus.direct')}+ </Badge>)}</span>- <AttributionLine agent={agent} />- </>- ) : (- <span className="text-[11.5px] leading-relaxed text-muted sm:hidden">- {t('settings.models.agents.directNote')}+ <span className="mt-0.5 block text-[11.5px] text-muted">+ {t('settings.models.agents.modelListCount', { count: allModels.length })}+ </span></span>+ </div>++ {agent.mode === 'hub' ? (+ <Button+ variant="secondary"+ size="sm"+ className="h-9 shrink-0"+ onClick={() => props.onOpenOrder(agent)}+ disabled={props.pending}+ >+ <ArrowDownUp />+ {t('settings.models.agents.sourceOrder')}+ </Button>+ ) : (+ <Button+ variant="secondary"+ size="sm"+ className="h-9 shrink-0"+ onClick={() => props.onConnectHub(agent)}+ disabled={props.connecting}+ >+ <Settings2 />+ {t('settings.models.agents.enableManaged')}+ </Button>)}- </span>+ </div>- <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}- </span>- </div>+ {emptySelection && (+ <EmptySelectionRow agent={agent} pending={props.pending} onOpenModels={props.onOpenModels} />+ )}++ {models.length === 0 && !emptySelection ? (+ <div className="flex flex-col items-center gap-3 px-4 py-10 text-center sm:px-5">+ <p className="text-[12.5px] text-muted">{t('settings.models.agents.emptyModels')}</p>+ {agent.menu_kind === 'open' ? (+ <Button+ variant="outline"+ size="sm"+ className="h-9"+ onClick={() => props.onOpenModels(agent)}+ disabled={props.pending}+ >+ <Plus />+ {t('settings.models.emptySelection.action')}+ </Button>+ ) : (+ <Button asChild variant="outline" size="sm" className="h-9">+ <Link to="/agents">+ <Plus />+ {t('settings.models.emptySelection.action')}+ </Link>+ </Button>+ )}+ </div>+ ) : (+ models.map((modelId) => (+ <ModelRow+ key={modelId}+ agent={agent}+ modelId={modelId}+ sources={sources}+ read={chains[modelChainKey(agent.backend, modelId)]}+ runtime={runtime}+ pending={props.pending}+ onSetRoute={(backend, modelId, targetModelId) =>+ props.onSetRoute(backend, modelId, targetModelId, announceEnrollment)+ }+ onAddModel={() => props.onAddModel(agent.backend)}+ onOpenOrder={() => props.onOpenOrder(agent)}+ onRepair={props.onRepair}+ onRetest={props.onRetest}+ retestingSourceId={props.retestingSourceId}+ onProbeSettled={props.onProbeSettled}+ />+ ))+ )}++ {agent.menu_kind === 'open' && !issuesOnly && (+ <button+ type="button"+ onClick={() => props.onOpenModels(agent)}+ disabled={props.pending}+ className="flex min-h-11 w-full items-center justify-center gap-2 border-t border-border px-4 py-2.5 text-[12px] font-semibold text-muted transition hover:bg-surface-2 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent disabled:hover:text-muted"+ >+ <Settings2 className="size-3.5" />+ {t('settings.models.agents.manageModels')}+ </button>+ )}+ </section>);};export const AgentCard: React.FC<{agents: AgentSupply[];sources: Source[];+ chains: ModelChainIndex;+ runtime: RuntimeDependency | null;+ issuesOnly: boolean;+ pendingBackends: ReadonlySet<string>;onConnectHub: (agent: AgentSupply) => void;onOpenOrder: (agent: AgentSupply) => void;+ onOpenModels: (agent: AgentSupply) => void;+ onSetRoute: (+ backend: AgentBackend,+ modelId: string,+ targetModelId: string | null,+ onCommitted: (before: AgentSupply, after: AgentSupply) => void,+ ) => void;+ onAddModel: (backend: AgentBackend) => void;+ onRepair: (source: Source, kind: RaisedRepair) => void;+ onRetest: (source: Source) => void;+ retestingSourceId: string | null;+ onProbeSettled: () => void;connectingBackend: string | null;-}> = ({ agents, sources, onConnectHub, onOpenOrder, connectingBackend }) => {+}> = ({ agents, ...props }) => {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-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 className="flex flex-col gap-4">+ {agents.map((agent) => (+ <AgentModelCard+ key={agent.backend}+ agent={agent}+ {...props}+ pending={props.pendingBackends.has(agent.backend)}+ connecting={props.connectingBackend === agent.backend}+ />+ ))}+ {props.issuesOnly && !agents.some((agent) => {+ if (agentNeedsModelSelection(agent)) return true;+ return listedModelIds(agent).some((modelId) =>+ modelNeedsAttention(agent, modelId, props.chains[modelChainKey(agent.backend, modelId)], props.runtime),+ );+ }) && (+ <div className="rounded-xl border border-border bg-background px-4 py-10 text-center text-[12.5px] text-muted">+ {t('settings.models.status.noIssues')}</div>- <Link- to="/admin/settings/backends"- 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" />- </Link>- </div>- <div className="flex flex-col">- {agents.map((agent) => (- <AgentRow- key={agent.backend}- agent={agent}- sources={sources}- onConnectHub={onConnectHub}- onOpenOrder={onOpenOrder}- connecting={connectingBackend === agent.backend}- />- ))}- </div>- </section>+ )}+ </div>);};diff --git a/ui/src/components/settings/models/ModelRoutePicker.tsx b/ui/src/components/settings/models/ModelRoutePicker.tsxnew file mode 100644index 000000000..1f3e944cf--- /dev/null+++ b/ui/src/components/settings/models/ModelRoutePicker.tsx@@ -0,0 +1,167 @@+import * as React from 'react';+import { Check, ChevronDown, Plus, Search } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Badge } from '@/components/ui/badge';+import { Input } from '@/components/ui/input';+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';+import { cn } from '@/lib/utils';+import { modelSupplierCounts, orderedRouteSources } from './modelRows';+import type { AgentSupply, Source } from './types';++type RouteTarget = {+ source: Source;+ modelId: string;+ displayName: string | null;+ manual: boolean;+};++export const ModelRoutePicker: React.FC<{+ agent: AgentSupply;+ sources: Source[];+ value: string;+ servedBy?: string | null;+ disabled?: boolean;+ onChange: (modelId: string) => void;+ onAddModel: () => void;+}> = ({ agent, sources, value, servedBy, disabled, onChange, onAddModel }) => {+ const { t } = useTranslation();+ const backendName = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend }) as string;+ const [open, setOpen] = React.useState(false);+ const [query, setQuery] = React.useState('');+ const routeSources = React.useMemo(() => orderedRouteSources(agent, sources), [agent, sources]);+ const groups = React.useMemo(() => {+ const needle = query.trim().toLocaleLowerCase();+ return routeSources+ .map((source) => ({+ source,+ targets: source.models+ .map(+ (model): RouteTarget => ({+ source,+ modelId: model.id,+ displayName: model.display_name ?? null,+ manual: model.provenance === 'manual',+ }),+ )+ .filter((target) => {+ if (!needle) return true;+ return [source.display_name, target.modelId, target.displayName ?? '']+ .some((part) => part.toLocaleLowerCase().includes(needle));+ }),+ }))+ .filter((group) => group.targets.length > 0);+ }, [query, routeSources]);++ const selectedSources = React.useMemo(+ () => routeSources.filter((source) => source.models.some((model) => model.id === value)),+ [routeSources, value],+ );+ const supplierCountByModel = React.useMemo(() => modelSupplierCounts(routeSources), [routeSources]);+ const selectedLabel = selectedSources.length === 0+ ? value+ : servedBy+ ? `${value} · ${servedBy}`+ : selectedSources.length === 1+ ? `${value} · ${selectedSources[0].display_name}`+ : t('settings.models.routes.multipleSources', { model: value, count: selectedSources.length }) as string;++ return (+ <Popover+ open={open}+ onOpenChange={(next) => {+ if (disabled) return;+ setOpen(next);+ if (!next) setQuery('');+ }}+ >+ <PopoverTrigger asChild>+ <button+ type="button"+ disabled={disabled}+ className="flex min-h-11 w-full items-center gap-2 rounded-lg border border-border bg-background px-3 text-left text-[12.5px] transition-colors hover:border-border-strong disabled:opacity-60"+ >+ <span className={cn('min-w-0 flex-1 truncate', value ? 'font-medium text-foreground' : 'text-muted')}>+ {value ? selectedLabel : t('settings.models.routes.chooseTarget')}+ </span>+ <ChevronDown className="size-4 shrink-0 text-muted" />+ </button>+ </PopoverTrigger>+ <PopoverContent+ align="start"+ sideOffset={6}+ className="flex max-h-[420px] w-[min(420px,var(--radix-popover-trigger-width))] flex-col overflow-hidden p-0"+ >+ <div className="relative border-b border-border p-2.5">+ <Search className="pointer-events-none absolute left-5 top-1/2 size-3.5 -translate-y-1/2 text-muted" />+ <Input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t('settings.models.routes.searchPlaceholder') as string}+ className="h-9 pl-8 text-[12.5px]"+ autoFocus+ />+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto p-1.5">+ {groups.length === 0 ? (+ <p className="px-3 py-8 text-center text-[12.5px] text-muted">{t('settings.models.routes.empty')}</p>+ ) : (+ groups.map(({ source, targets }) => (+ <div key={source.id} className="pb-2 last:pb-0">+ <div className="sticky top-0 z-[1] flex items-center justify-between gap-2 bg-popover px-2.5 py-2">+ <span className="truncate text-[11px] font-bold text-foreground">{source.display_name}</span>+ <span className="shrink-0 text-[10.5px] text-muted">{t('settings.models.routes.availableCount', { count: targets.length })}</span>+ </div>+ {targets.map((target) => (+ <button+ key={`${source.id}:${target.modelId}`}+ type="button"+ onClick={() => {+ onChange(target.modelId);+ setOpen(false);+ }}+ className={cn(+ 'flex min-h-11 w-full items-center gap-2 rounded-md px-2.5 py-2 text-left transition-colors hover:bg-surface-2',+ value === target.modelId && 'bg-mint-soft/60',+ )}+ >+ <span className="min-w-0 flex-1">+ <span className="block break-all font-mono text-[12.5px] font-medium text-foreground">+ {target.modelId}+ </span>+ {target.displayName && (+ <span className="block truncate text-[11px] text-muted">{target.displayName}</span>+ )}+ {(supplierCountByModel.get(target.modelId) ?? 0) > 1 && (+ <span className="block text-[10.5px] text-muted">+ {t('settings.models.routes.orderDecidesSource', { backend: backendName })}+ </span>+ )}+ </span>+ {target.manual && (+ <Badge variant="secondary" className="shrink-0 px-1.5 py-0 text-[9.5px]">+ {t('settings.models.routes.manualBadge')}+ </Badge>+ )}+ {value === target.modelId && <Check className="size-4 shrink-0 text-mint" />}+ </button>+ ))}+ </div>+ ))+ )}+ </div>+ <button+ type="button"+ onClick={() => {+ setOpen(false);+ onAddModel();+ }}+ className="flex min-h-11 items-center gap-2 border-t border-border px-3.5 py-2.5 text-left text-[12.5px] font-semibold text-mint transition-colors hover:bg-surface-2"+ >+ <Plus className="size-4" />+ {t('settings.models.routes.addManual')}+ </button>+ </PopoverContent>+ </Popover>+ );+};diff --git a/ui/src/components/settings/models/RecentSwitchesCard.test.tsx b/ui/src/components/settings/models/RecentSwitchesCard.test.tsxindex eedf8841b..effaed8b0 100644--- a/ui/src/components/settings/models/RecentSwitchesCard.test.tsx+++ b/ui/src/components/settings/models/RecentSwitchesCard.test.tsx@@ -8,7 +8,8 @@ import { describe, expect, it } from 'vitest';import en from '../../../i18n/en.json';import zh from '../../../i18n/zh.json';-import { RecentSwitchesCard, eventAccent } from './RecentSwitchesCard';+import { eventAccent } from './eventFeed';+import { RecentSwitchesCard } from './RecentSwitchesCard';import type { ResolutionEvent, Source } from './types';const instance = (lng: 'en' | 'zh') => {@@ -48,10 +49,15 @@ const event = (over: Partial<ResolutionEvent> = {}): ResolutionEvent => ({...over,});-const render = (events: ResolutionEvent[], sources: Source[], lng: 'en' | 'zh' = 'zh') =>+const render = (+ events: ResolutionEvent[],+ sources: Source[],+ lng: 'en' | 'zh' = 'zh',+ hasMore = false,+) =>renderToStaticMarkup(<I18nextProvider i18n={instance(lng)}>- <RecentSwitchesCard events={events} sources={sources} />+ <RecentSwitchesCard events={events} sources={sources} hasMore={hasMore} /></I18nextProvider>,);@@ -96,6 +102,21 @@ describe('RecentSwitchesCard (AC-18)', () => {const four = [...three, event({ id: 'evt_4' })];expect(render(four, [source('src_live01')])).toContain(zh.settings.models.recent.viewAll);});++ it('keeps route configuration out of the user event feed', () => {+ const configured = event({ kind: 'mapping_applied', human_zh: '内部路由配置已变更' });+ const html = render([configured, event({ id: 'evt_2', human_zh: '已自动换到 openai' })], [source('src_live01')]);+ expect(html).not.toContain(configured.human_zh);+ expect(html).toContain('已自动换到 openai');+ });++ it('keeps a paging door open when the fetched page contains only route configuration', () => {+ const configured = event({ kind: 'mapping_applied', human_zh: '内部路由配置已变更' });+ const html = render([configured], [source('src_live01')], 'zh', true);+ expect(html).not.toContain(configured.human_zh);+ expect(html).not.toContain(zh.settings.models.recent.empty);+ expect(html).toContain(zh.settings.models.recent.loadMore);+ });});// The contract puts `severity` in the payload as 「Feed and Models-page presentationdiff --git a/ui/src/components/settings/models/RecentSwitchesCard.tsx b/ui/src/components/settings/models/RecentSwitchesCard.tsxindex 7b60773fc..4be63a266 100644--- a/ui/src/components/settings/models/RecentSwitchesCard.tsx+++ b/ui/src/components/settings/models/RecentSwitchesCard.tsx@@ -16,36 +16,14 @@ import { useTranslation } from 'react-i18next';import { Badge } from '@/components/ui/badge';import { Dot } from './chips';-import type { Accent } from './vendorMeta';+import { eventAccent } from './eventFeed';import type { ResolutionEvent, Source } from './types';const COLLAPSED = 3;-/**- * 需处理 — 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';- return 'cyan';-}+/** Route configuration is visible on the model row; it is not a user event. */+const visibleResolutionEvents = (events: ResolutionEvent[]): ResolutionEvent[] =>+ events.filter((event) => event.kind !== 'mapping_applied');function useEventTime() {const { t } = useTranslation();@@ -73,7 +51,7 @@ export const RecentSwitchesCard: React.FC<{hasMore?: boolean;loadingMore?: boolean;/** Fetch the next older page. Required for 查看全部 to mean 全部. */- onLoadMore?: () => void;+ onLoadMore?: () => void | Promise<void>;}> = ({ events, sources, hasMore = false, loadingMore = false, onLoadMore }) => {const { t, i18n } = useTranslation();const [expanded, setExpanded] = React.useState(false);@@ -83,10 +61,26 @@ export const RecentSwitchesCard: React.FC<{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 visibleEvents = visibleResolutionEvents(events);+ const shown = expanded ? visibleEvents : visibleEvents.slice(0, COLLAPSED);+ const rawTailId = events.at(-1)?.id ?? '';+ const backfilledTailRef = React.useRef<string | null>(null);++ // The API pages the raw journal, while this card deliberately omits route+ // configuration rows. Walk past mapping-only pages until the collapsed feed+ // has three user events (or the server says there are no older rows). The raw+ // tail is the generation key: it advances after every useful page and keeps a+ // failed/overlapping response from becoming an automatic retry loop.+ React.useEffect(() => {+ if (visibleEvents.length >= COLLAPSED || !hasMore || loadingMore || !onLoadMore) return;+ if (backfilledTailRef.current === rawTailId) return;+ backfilledTailRef.current = rawTailId;+ void onLoadMore();+ }, [hasMore, loadingMore, onLoadMore, rawTailId, visibleEvents.length]);+// 查看全部 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 canExpand = visibleEvents.length > COLLAPSED || hasMore;const expand = () => {setExpanded(true);if (hasMore && !loadingMore) onLoadMore?.();@@ -107,7 +101,18 @@ export const RecentSwitchesCard: React.FC<{)}</div>{shown.length === 0 ? (- <div className="px-4 py-8 text-center sm:px-5 text-[13px] text-muted">{t('settings.models.recent.empty')}</div>+ <div className="flex flex-col items-center gap-2 px-4 py-8 text-center text-[13px] text-muted sm:px-5">+ <span>{hasMore ? t('settings.models.recent.loadingMore') : t('settings.models.recent.empty')}</span>+ {hasMore && !loadingMore && (+ <button+ type="button"+ onClick={() => void onLoadMore?.()}+ className="min-h-8 font-medium text-mint transition-colors hover:text-mint/80"+ >+ {t('settings.models.recent.loadMore')}+ </button>+ )}+ </div>) : (<div className="flex flex-col">{/* Phones stack the timestamp above the sentence (design.pen M01 m01Ev):@@ -140,7 +145,7 @@ export const RecentSwitchesCard: React.FC<{{expanded && hasMore && (<buttontype="button"- onClick={() => onLoadMore?.()}+ onClick={() => void 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]">diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex 4ac4e8bf9..f2f1ce32f 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -1,16 +1,12 @@-// 设置 · 模型 — 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).+// Model-centric settings surface. The page reads model chains from the server,+// hosts shared source repair journeys, and serializes Agent writes by backend.import * as React from 'react';-import { CheckCircle2, Info, TriangleAlert } from 'lucide-react';+import { CheckCircle2, ListFilter, TriangleAlert } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';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';@@ -20,7 +16,7 @@ import { AdvancedRow } from './AdvancedRow';import { AddApiKeyDialog } from './AddApiKeyDialog';import { OAuthConnectDialog } from './OAuthConnectDialog';import { RepairJourney, type RepairTarget } from './RepairJourney';-import { agentsWithEcho, createLatestAsyncAuthority, createPendingWrites } from './asyncLifetime';+import { agentsWithEcho, createLatestAsyncAuthority, createPendingWrites, mapWithConcurrency } from './asyncLifetime';import {emptyFeed,feedAfterHeadRead,@@ -28,57 +24,64 @@ import {feedTailCursor,type EventFeed,} from './eventFeed';-import { MappingDrawer } from './menus/MappingDrawer';+import { AddCustomModelDialog } from './menus/AddCustomModelDialog';import { OpenCodeMenuDrawer } from './menus/OpenCodeMenuDrawer';import { modelsApi } from './modelsApi';import { connectOutcome, isSupplyWarning } from './sufficiency';-import { pageStatus, type PageStatus } from './supply';+import {+ manualModelSources,+ modelChainKey,+ modelChainRequests,+ modelIssueCount,+ routableMappings,+ type ModelChainIndex,+} from './modelRows';import type { AgentBackend, AgentSupply, ResolutionEvent, RuntimeDependency, Source } from './types';-/**- * 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 ModelStatusButton: React.FC<{ issueCount: number; active: boolean; onClick: () => void }> = ({+ issueCount,+ active,+ onClick,+}) => {const { t } = useTranslation();- 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;+ const healthy = issueCount === 0;+ const Icon = healthy ? CheckCircle2 : TriangleAlert;return (- <Badge variant={variant} className="gap-1.5 rounded-full px-3 py-1.5 text-[12px]">+ <Button+ variant={healthy ? 'secondary' : 'outline'}+ size="sm"+ className={healthy ? 'h-9 text-mint' : 'h-9 border-destructive/35 text-destructive'}+ onClick={onClick}+ aria-pressed={active}+ ><Icon className="size-3.5" />- {text}- </Badge>+ {healthy ? t('settings.models.status.allHealthy') : t('settings.models.status.needsAction', { count: issueCount })}+ {!healthy && <ListFilter className="size-3.5" />}+ </Button>+ );+};++const CHAIN_READ_CONCURRENCY = 6;++const readModelChains = async (agents: AgentSupply[]): Promise<ModelChainIndex> => {+ const reads = await mapWithConcurrency(+ modelChainRequests(agents),+ CHAIN_READ_CONCURRENCY,+ async ({ backend, modelId }) => {+ const key = modelChainKey(backend, modelId);+ try {+ return [key, { kind: 'ready' as const, chain: await modelsApi.getAgentChain(backend, modelId) }] as const;+ } catch {+ return [key, { kind: 'error' as const }] as const;+ }+ },);+ return Object.fromEntries(reads);+};++const readModelSurface = async (): Promise<[Source[], AgentSupply[], ModelChainIndex]> => {+ const [sources, agents] = await Promise.all([modelsApi.listSources(), modelsApi.listAgents()]);+ return [sources, agents, await readModelChains(agents)];};// 最近切换 is a cursor feed, not a fixed window: `/events` pages with `before`,@@ -92,6 +95,7 @@ export const SettingsModelsPage: React.FC = () => {const [sources, setSources] = React.useState<Source[]>([]);const [agents, setAgents] = React.useState<AgentSupply[]>([]);+ const [chains, setChains] = React.useState<ModelChainIndex>({});// Rows and end-of-feed as ONE value: every read moves both, and the transition// that moved only the rows is what made 加载更早 lie. `EventFeed` owns the rules.const [feed, setFeed] = React.useState<EventFeed>(emptyFeed);@@ -100,6 +104,9 @@ export const SettingsModelsPage: React.FC = () => {const [loading, setLoading] = React.useState(true);const [loadError, setLoadError] = React.useState<string | null>(null);const [connecting, setConnecting] = React.useState<string | null>(null);+ const [retestingSourceId, setRetestingSourceId] = React.useState<string | null>(null);+ const [issuesOnly, setIssuesOnly] = React.useState(false);+ const agentSectionRef = React.useRef<HTMLDivElement>(null);const [apiKeyOpen, setApiKeyOpen] = React.useState(false);const [oauthVendor, setOauthVendor] = React.useState<string | null>(null);@@ -112,6 +119,10 @@ export const SettingsModelsPage: React.FC = () => {// freshest agent.const [menuBackend, setMenuBackend] = React.useState<AgentBackend | null>(null);const [orderBackend, setOrderBackend] = React.useState<AgentBackend | null>(null);+ const [customModelRequest, setCustomModelRequest] = React.useState<{+ sourceId?: string;+ backend?: AgentBackend;+ } | null>(null);// Which backends have a 来源顺序 write outstanding. Held HERE and not in the// drawer that issues it, because the drawer does not outlive its own write:@@ -119,8 +130,12 @@ export const SettingsModelsPage: React.FC = () => {// read-back are in flight, and closing unmounts the drawer, so a flag inside it// is re-created reading 「idle」 by the reopen — which is exactly when the// hand-off below must still be shut. See `createPendingWrites`.- const [orderWrites, setOrderWrites] = React.useState<ReadonlySet<string>>(() => new Set());- const [orderWriteRegistry] = React.useState(() => createPendingWrites(setOrderWrites));+ const [agentWrites, setAgentWrites] = React.useState<ReadonlySet<string>>(() => new Set());+ const [agentWriteRegistry] = React.useState(() => createPendingWrites(setAgentWrites));+ const agentsRef = React.useRef(agents);+ React.useEffect(() => {+ agentsRef.current = agents;+ }, [agents]);// Guards event-handler async writes (refresh / connect) from landing after// the page unmounts — the whole class of stale-async writes the review flagged.@@ -151,11 +166,13 @@ export const SettingsModelsPage: React.FC = () => {// this refresh's job. A feed left one write behind is not wrong, only not newer,// and the next mutation or reload catches it up.const [refreshAuthority] = React.useState(() =>- createLatestAsyncAuthority<[Source[], AgentSupply[], ResolutionEvent[] | null]>(- ([nextSources, nextAgents, headEvents]) => {+ createLatestAsyncAuthority<[Source[], AgentSupply[], ResolutionEvent[] | null, ModelChainIndex]>(+ ([nextSources, nextAgents, headEvents, nextChains]) => {if (!aliveRef.current) return;setSources(nextSources);setAgents(nextAgents);+ agentsRef.current = nextAgents;+ setChains(nextChains);// Merged, not replaced: 加载更早 pages tail-ward, and a head re-read must// not silently drop the rows it never asked for. See `feedAfterHeadRead`// for the one case merging is wrong, and for what that costs 加载更早.@@ -167,16 +184,13 @@ export const SettingsModelsPage: React.FC = () => {React.useEffect(() => {let cancelled = false;setLoading(true);- Promise.all([- modelsApi.listSources(),- modelsApi.listAgents(),- modelsApi.listEvents(EVENT_PAGE),- modelsApi.getRuntimeStatus(),- ])- .then(([s, a, e, r]) => {+ Promise.all([readModelSurface(), modelsApi.listEvents(EVENT_PAGE), modelsApi.getRuntimeStatus()])+ .then(([[s, a, nextChains], e, r]) => {if (cancelled) return;setSources(s);setAgents(a);+ agentsRef.current = a;+ setChains(nextChains);// The first page is a tail read as much as a head one: it reaches the end// of the feed exactly when it comes back short, and its cursor is `null`// because it asked for the top. Applied to `prev` rather than to@@ -197,13 +211,13 @@ export const SettingsModelsPage: React.FC = () => {const refreshSourcesAgents = React.useCallback(async () => {try {- await refreshAuthority.run(() =>- Promise.all([- modelsApi.listSources(),- modelsApi.listAgents(),+ await refreshAuthority.run(async () => {+ const [[nextSources, nextAgents, nextChains], headEvents] = await Promise.all([+ readModelSurface(),modelsApi.listEvents(EVENT_PAGE).catch(() => null),- ]),- );+ ]);+ return [nextSources, nextAgents, headEvents, nextChains];+ });} 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.@@ -225,12 +239,46 @@ export const SettingsModelsPage: React.FC = () => {*/const agentSaved = React.useCallback((echoed: AgentSupply) => {- setAgents((prev) => agentsWithEcho(prev, echoed));+ setAgents((prev) => {+ const next = agentsWithEcho(prev, echoed);+ agentsRef.current = next;+ return next;+ });return refreshSourcesAgents();},[refreshSourcesAgents],);+ const setModelRoute = React.useCallback(+ (+ backend: AgentBackend,+ modelId: string,+ targetModelId: string | null,+ onCommitted: (before: AgentSupply, after: AgentSupply) => void,+ ) => {+ void agentWriteRegistry.track(backend, async () => {+ const current = agentsRef.current.find((agent) => agent.backend === backend);+ if (!current || current.menu_kind !== 'fixed') return;+ const byModel = new Map(+ routableMappings(current, sources).map((mapping) => [mapping.builtin_id, mapping]),+ );+ if (targetModelId) {+ byModel.set(modelId, { builtin_id: modelId, target_model_id: targetModelId, enabled: true });+ } else {+ byModel.delete(modelId);+ }+ try {+ const echoed = await modelsApi.putMappings(backend, [...byModel.values()].filter((mapping) => mapping.enabled));+ onCommitted(current, echoed);+ await agentSaved(echoed);+ } catch {+ showToast(t('settings.models.menus.saveFailed') as string, 'error');+ }+ });+ },+ [agentSaved, agentWriteRegistry, showToast, sources, t],+ );+const loadOlderEvents = React.useCallback(async () => {const oldest = feedTailCursor(feed);if (!oldest) return;@@ -254,6 +302,16 @@ export const SettingsModelsPage: React.FC = () => {}}, [feed, showToast, t]);+ const openCustomModel = React.useCallback((sourceId?: string, backend?: AgentBackend) => {+ const writableSources = manualModelSources(sources);+ if (writableSources.length === 0) {+ setApiKeyOpen(true);+ return;+ }+ const requested = writableSources.find((source) => source.id === sourceId);+ setCustomModelRequest({ sourceId: requested?.id, backend });+ }, [sources]);+const connectHub = async (agent: AgentSupply) => {setConnecting(agent.backend);try {@@ -279,21 +337,59 @@ export const SettingsModelsPage: React.FC = () => {}};+ const retestSource = async (source: Source) => {+ if (retestingSourceId !== null) return;+ setRetestingSourceId(source.id);+ try {+ const count = await modelsApi.testSource(source.id);+ if (!aliveRef.current) return;+ await refreshSourcesAgents();+ if (aliveRef.current) {+ showToast(t('settings.models.sourceActions.rediscovered', { count }) as string, 'success');+ }+ } catch {+ if (!aliveRef.current) return;+ await refreshSourcesAgents();+ if (aliveRef.current) {+ showToast(t('settings.models.sourceActions.rediscoverFailed') as string, 'error');+ }+ } finally {+ if (aliveRef.current) setRetestingSourceId(null);+ }+ };+// Resolve an open drawer's agent from live state so edits see fresh data.- const menuAgent = agents.find((a) => a.backend === menuBackend) ?? null;+ const menuAgent = agents.find(+ (agent) => agent.backend === menuBackend && !agentWrites.has(agent.backend),+ ) ?? 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 status = pageStatus(sources, agents, runtime);+ const issueCount = modelIssueCount(agents, chains, runtime);+ const standardVendors = new Set(agents.flatMap((agent) => agent.standard_vendors ?? []));++ React.useEffect(() => {+ if (issueCount === 0) setIssuesOnly(false);+ }, [issueCount]);++ const focusIssues = () => {+ if (issueCount > 0) setIssuesOnly((value) => !value);+ else setIssuesOnly(false);+ requestAnimationFrame(() => agentSectionRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }));+ };return (<SettingsPageShellactiveTab="models"title={t('settings.models.title')}subtitle={t('settings.models.subtitle')}- actions={!loading && !loadError ? <StatusPill status={status} /> : undefined}+ actions={+ !loading && !loadError ? (+ <ModelStatusButton issueCount={issueCount} active={issuesOnly} onClick={focusIssues} />+ ) : undefined+ }>{loading ? (<div className="text-[13px] text-muted">{t('common.loading')}</div>@@ -305,6 +401,28 @@ export const SettingsModelsPage: React.FC = () => {) : (<div className="flex flex-col gap-5"><MigrationBanner onApplied={() => void refreshSourcesAgents()} />+ <div ref={agentSectionRef} className="scroll-mt-6">+ <AgentCard+ agents={agents}+ sources={sources}+ chains={chains}+ runtime={runtime}+ issuesOnly={issuesOnly}+ pendingBackends={agentWrites}+ onConnectHub={(agent) => void connectHub(agent)}+ onOpenOrder={(agent) => setOrderBackend(agent.backend)}+ onOpenModels={(agent) => {+ if (!agentWrites.has(agent.backend)) setMenuBackend(agent.backend);+ }}+ onSetRoute={setModelRoute}+ onAddModel={(backend) => openCustomModel(undefined, backend)}+ onRepair={(source, kind) => setRepairTarget({ source, kind })}+ onRetest={(source) => void retestSource(source)}+ retestingSourceId={retestingSourceId}+ onProbeSettled={() => void refreshSourcesAgents()}+ connectingBackend={connecting}+ />+ </div><SourcesCardsources={sources}onConnectClaude={() => setOauthVendor('anthropic')}@@ -312,20 +430,14 @@ export const SettingsModelsPage: React.FC = () => {onAddApiKey={() => setApiKeyOpen(true)}onSourceChanged={() => void refreshSourcesAgents()}onRepair={(source, kind) => setRepairTarget({ source, kind })}- />- <AgentCard- agents={agents}- sources={sources}- onConnectHub={connectHub}- onOpenOrder={(agent) => setOrderBackend(agent.backend)}- connectingBackend={connecting}+ onAddModel={(source) => openCustomModel(source.id)}/><RecentSwitchesCardevents={feed.events}sources={sources}hasMore={!feed.exhausted}loadingMore={loadingEvents}- onLoadMore={() => void loadOlderEvents()}+ onLoadMore={loadOlderEvents}/><AdvancedRow /></div>@@ -356,25 +468,10 @@ export const SettingsModelsPage: React.FC = () => {// makes the baseline it hands over CORRECT is the echo `agentSaved` takes// — the re-read is allowed to fail here without leaving one behind.onSaved={agentSaved}- // 试跑's own re-read. It is not this drawer's write, so there is no echo- // to take — the probe moves source state and answers with a probe result.- onReread={() => void refreshSourcesAgents()}orderWrite={{- pending: orderWrites.has(orderAgent.backend),- track: (work) => orderWriteRegistry.track(orderAgent.backend, work),+ pending: agentWrites.has(orderAgent.backend),+ track: (work) => agentWriteRegistry.track(orderAgent.backend, work),}}- // 模型菜单与映射 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- }/>)}@@ -388,16 +485,17 @@ export const SettingsModelsPage: React.FC = () => {// A custom model is a SOURCE write: it echoes the source, not the Agent.onRefresh={() => void refreshSourcesAgents()}/>- ) : menuAgent && (menuAgent.backend === 'claude' || menuAgent.backend === 'codex') ? (- <MappingDrawer- open- backend={menuAgent.backend}- agent={menuAgent}- sources={sources}- onClose={() => setMenuBackend(null)}- onSaved={(echoed) => void agentSaved(echoed)}- />) : null}++ <AddCustomModelDialog+ open={customModelRequest !== null}+ sources={sources}+ standardVendors={standardVendors}+ initialSourceId={customModelRequest?.sourceId}+ showOpenCodeIdentifier={customModelRequest?.backend === 'opencode'}+ onClose={() => setCustomModelRequest(null)}+ onSaved={() => void refreshSourcesAgents()}+ /></SettingsPageShell>);};diff --git a/ui/src/components/settings/models/SourceOrderDrawer.tsx b/ui/src/components/settings/models/SourceOrderDrawer.tsxindex d7aef6a28..14027c965 100644--- a/ui/src/components/settings/models/SourceOrderDrawer.tsx+++ b/ui/src/components/settings/models/SourceOrderDrawer.tsx@@ -1,173 +1,122 @@-// 来源顺序 · <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 type { TFunction } from 'i18next';import { Reorder, useDragControls } from 'framer-motion';-import {- CheckCircle2,- ChevronRight,- CirclePlus,- GripVertical,- List,- Loader2,- TriangleAlert,- WandSparkles,- X,- Zap,-} from 'lucide-react';+import { CirclePlus, GripVertical, X } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';+import { useToast } from '@/context/ToastContext';import { cn } from '@/lib/utils';import { useIsMobile } from '@/lib/useIsMobile';-import { useToast } from '@/context/ToastContext';import { initialSeedState, savedSourcesKey, seedStep, type PendingWrite } from './asyncLifetime';-import { CurrentChip, StateChip } from './chips';import { eligibilityOf } from './eligibility';-import { DRY_RUN_ENABLED } from './featureFlags';-import { cooldownEtaMinutes } from './format';import { MenuDrawer } from './menus/MenuDrawer';-import { apiFailure, modelsApi } from './modelsApi';-import {- dryRunChainKey,- dryRunOutcome,- dryRunPlan,- dryRunRowView,- probeArrival,- type DryRunOutcome,-} from './repair';+import { modelsApi } from './modelsApi';import { movedOrder, sameIds } from './reorder';-import { serverText } from './serverCopy';-import { orderSufficiency } from './sufficiency';-import { healthyButUnrunnable, isUnhealthy, needsAttention } from './supply';import { ACCENT_ICON, ACCENT_TILE, backendVisual, sourceVisual } from './vendorMeta';-import type { AgentBackend, AgentSourcesPut, AgentSupply, Source, SourcePolicy } from './types';+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]';+ '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: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],- )}- >+ <span className={cn('flex size-[30px] shrink-0 items-center justify-center rounded-[9px] sm:size-[34px]', 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>+const Identity: React.FC<{ source: Source; detail?: string }> = ({ source, detail }) => (+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="truncate text-[13px] font-semibold text-foreground sm:text-[13.5px]">{source.display_name}</span>+ {(source.account_label || source.masked_credential || detail) && (+ <span className="truncate font-mono text-[10px] text-muted sm:text-[11px]">+ {[source.account_label ?? source.masked_credential, detail].filter(Boolean).join(' · ')}+ </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')}>+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', first ? 'pt-0.5' : 'pt-2')}><span className="text-[10px] font-bold tracking-[1px] text-muted">{label}</span>{children}</div>);-// ── Drawer ──────────────────────────────────────────────────────────────+const EnabledRow: React.FC<{+ source: Source;+ index: number;+ busy: boolean;+ onCommit: () => void;+ onMove: (delta: -1 | 1) => void;+ onRemove: () => void;+}> = ({ source, index, 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 border-border bg-background')}+ >+ <button+ type="button"+ aria-label={t('settings.models.source.reorder') as string}+ aria-keyshortcuts="ArrowUp ArrowDown"+ disabled={busy}+ onPointerDown={(event) => controls.start(event)}+ onKeyDown={(event) => {+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;+ event.preventDefault();+ onMove(event.key === 'ArrowUp' ? -1 : 1);+ }}+ className="relative flex size-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted/60 active:cursor-grabbing disabled:cursor-default disabled:opacity-50"+ >+ <GripVertical className="size-4" />+ <span className="absolute -inset-3 sm:hidden" aria-hidden />+ </button>+ <span className={NUMBER}>{index + 1}</span>+ <SourceTile source={source} />+ <Identity source={source} />+ <button+ type="button"+ aria-label={t('settings.models.order.disable') as string}+ onClick={onRemove}+ disabled={busy}+ className="relative flex size-7 shrink-0 items-center justify-center rounded-md text-muted transition 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 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;- /** Hands the page the Agent row this write echoed, and re-reads what else the- * order moved (● 当前 elsewhere, the source rows, the feed). Returning that- * read's promise lets the pending mark span it — see `persist`. */onSaved: (echoed: AgentSupply) => void | Promise<void>;- /** Re-reads the rows behind the drawer, claiming nothing about them. Separate- * from `onSaved` because only a write can hand over an echo: 试跑 is a probe- * that moves source state (a cooldown, a 需处理) and echoes no Agent, so a read- * is genuinely all there is to do about it. */- onReread: () => void;- /** This backend's slot in the page's pending-write registry. Held by the page- * because every close path stays live during a write and closing unmounts this- * drawer — see `createPendingWrites` in asyncLifetime.ts. */orderWrite: PendingWrite;- /** 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, onReread, orderWrite, onOpenMenu }) => {+}> = ({ open, agent, agents, sources, onClose, onSaved, orderWrite }) => {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 { Icon, accent } = backendVisual(agent.backend);const [policy, setPolicy] = React.useState<SourcePolicy>(agent.sources?.policy ?? 'follow');const [order, setOrder] = React.useState<string[]>(agent.sources?.order ?? []);- // Deliberately not this component's state: the user can close this drawer —- // which unmounts it — and reopen it while the write is still outstanding.const saving = orderWrite.pending;- /** 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);@@ -180,181 +129,39 @@ export const SourceOrderDrawer: React.FC<{// 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, agent);- const rest = sources.filter((s) => !order.includes(s.id));- const disabledSources = rest.filter((s) => eligibilityOf(agent, s.id).eligible);+ const backendName = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend }) as string;+ const byId = React.useMemo(() => new Map(sources.map((source) => [source.id, source])), [sources]);+ const enabledSources = order.map((sourceId) => byId.get(sourceId)).filter((source): source is Source => Boolean(source));+ const enabledIds = enabledSources.map((source) => source.id);+ const rest = sources.filter((source) => !order.includes(source.id));+ const disabledSources = rest.filter((source) => eligibilityOf(agent, source.id).eligible);const ineligible = rest.map((source) => ({ source, ...eligibilityOf(agent, source.id) }))- .filter((e) => !e.eligible);+ .filter((entry) => !entry.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- *- * 启用 and 未启用 share one retraction: a healthy source this machine cannot- * launch the Agent's process against says so instead of naming what it supplies- * — see `healthyButUnrunnable`.- *- * 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 backendLabel = (backend: string) =>+ t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;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(' · ');-- /**- * The second segment answers 「why is this row not the one serving」, and there- * are two independent answers competing for it. Health first — a cooling or- * broken source is the one the user can act on, and its state chip has already- * raised the question this segment answers. A HEALTHY source that this machine- * cannot launch gets the segment instead, and it must not be spent on 供 … 全系- * there: a model count is a promise, and this is the row that cannot keep it.- *- * Only a per-Agent surface may say it at all (it is per (source, backend)), and- * only in muted grey: `needsAttention` is false for a healthy source, so the- * line stays the same colour as the chain strip's dim dot rather than borrowing- * the gold that means 「and it needs you」.- */- const nativeUnavailable = () =>- t('settings.models.order.nativeUnavailable', { backend: backendName }) as string;-- 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)- ? ''- : healthyButUnrunnable(agent, source)- ? nativeUnavailable()- : supplies(source),- ]);-- /**- * The 未启用 row says what turning this source on would get — so it owes the- * same retraction the 启用 row owes, and owes it EARLIER. Availability is per- * (source, backend) and has nothing to do with where the source sits in the- * order, so a row that only admits it once enabled has told the user one step- * after the step it was about; `chainChips` already promises that 「the- * all-sources drawer keeps the ungated fact」, and this is half of that drawer.- *- * It replaces the whole line rather than joining it, in both branches: 供 … 全系- * is the promise being retracted, and 经模型菜单改写后可供 X 使用 is the same- * promise routed through a rewrite — neither survives a process that cannot be- * launched, and the sub-line is two segments wide.- */- const disabledSubline = (source: Source): string => {- if (healthyButUnrunnable(agent, source)) return join([identity(source), nativeUnavailable()]);- // 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);+ const ineligibleDetail = (source: Source, reasonKey: string | null): string => {+ if (!reasonKey) return t('settings.models.order.ineligibleUnknown', { backend: backendName }) as string;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);+ const owners = agents.filter(+ (candidate) => candidate.backend !== agent.backend && eligibilityOf(candidate, source.id).eligible,+ );+ return owners.length === 1+ ? t(reasonKey, { vendor: vendorLabel(source), backend: backendLabel(owners[0].backend) }) as string+ : t('settings.models.order.ineligibleClientUnknown', { vendor: vendorLabel(source) }) as string;}- // The server's own i18n key (contract v3's closed vocabulary), rendered as-is.- return t(reasonKey, { vendor }) as string;+ return t(reasonKey, { vendor: vendorLabel(source) }) 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 made in quick succession resolve later-edit-wins, which every PUT- * carrying the whole list rather than a delta makes possible and `orderWrite`'s- * per-backend queue makes true: sent together they would settle in whichever- * order they reached the server's lock, and the discarded one is a whole list.- *- * Runs to completion even if the drawer closes mid-flight, and deliberately so.- * Everything this does on the way out belongs to something that outlives the- * drawer — the pending mark to the page, `onSaved()` to the page whose ● 当前 the- * write just moved, the failure toast to 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.)- *- * Which is also why `orderWrite.track` and not a local flag. The drawer is not- * alive for the whole of its own write: 完成, the X, Escape and the overlay all- * stay live while this runs, and closing UNMOUNTS this component. A flag in here- * would then be re-created reading 「idle」 by the reopen, over a write still- * outstanding, and the gate below would be off for exactly the user who closed- * and reopened. The page holds it instead — see `createPendingWrites`.- */const persist = (body: AgentSourcesPut, next: { policy: SourcePolicy; order: string[] }) =>- // Marked pending for the whole hand-back and not merely until the PUT returns,- // because the mark is what keeps 模型菜单与映射 shut while this runs, and the- // drawer it hands off to reads its enrollment baseline out of the page's Agent- // list. What the mark cannot do is make that baseline right: `onSaved` finishes- // whether the page's re-read landed, failed or was superseded. So the baseline- // travels with the hand-back — the echo below IS the server's post-write row —- // and the mark only has to cover the window in which the write is in flight.orderWrite.track(async () => {const previous = saved.current;setPolicy(next.policy);setOrder(next.order);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,@@ -363,9 +170,6 @@ export const SourceOrderDrawer: React.FC<{saved.current = adopted;setPolicy(adopted.policy);setOrder(adopted.order);- // A failed re-read belongs to the page that made it and is not this write's- // to roll back: the server accepted the order either way. Which is why the- // echo goes over with it rather than being left for that read to rediscover.await Promise.resolve(onSaved(echoed)).catch(() => {});} catch {saved.current = previous;@@ -375,26 +179,14 @@ export const SourceOrderDrawer: React.FC<{}});- // 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 });+ const restoreDefault = () => void persist({ policy: 'follow' }, { policy: 'follow', order });return (<MenuDrawer@@ -403,108 +195,46 @@ export const SourceOrderDrawer: React.FC<{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- }+ 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.-- Disabled while an order write is unsettled, for the same reason as- the two 恢复推荐顺序 buttons and one more: the hand-off closes this- drawer and opens one whose enrollment notice is a diff against the- page's copy of this order. Leaving on the way out of an edit the page- has not read back is how that diff acquires someone else's append. */}- {onOpenMenu && (- <Button- variant="outline"- size="sm"- className="hidden sm:inline-flex"- onClick={onOpenMenu}- disabled={saving}- >- <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>- </>+ <Button variant="brand" size="sm" className="h-10" onClick={onClose}>+ {t('settings.models.menus.done')}+ </Button>}>- <div className="flex flex-col gap-2 sm:gap-2.5">+ <div className="flex flex-col 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>+ {policy === 'custom' && (+ <span className="text-[11.5px] font-medium text-muted">+ {t('settings.models.order.customized')}+ <span aria-hidden> · </span>+ <button+ type="button"+ onClick={restoreDefault}+ disabled={saving}+ className="font-semibold text-mint hover:text-mint/80 disabled:opacity-50"+ >+ {t('settings.models.order.restore')}+ </button>+ </span>)}</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">+ {enabledSources.length === 0 ? (+ <p className="rounded-xl border border-border bg-foreground/[0.02] px-3.5 py-3 text-[12px] text-muted">{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>- )}+ <Reorder.Group axis="y" values={enabledIds} onReorder={setOrder} className="flex list-none flex-col gap-2.5">{enabledSources.map((source, index) => (<EnabledRowkey={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))}+ onRemove={() => commitOrder(enabledIds.filter((sourceId) => sourceId !== source.id))}/>))}</Reorder.Group>@@ -513,26 +243,23 @@ export const SourceOrderDrawer: React.FC<{{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>- ))}+ <div className="flex flex-col gap-2.5 rounded-xl border border-dashed border-border p-2">+ {disabledSources.map((source) => (+ <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-transparent bg-background text-left transition hover:border-border-strong disabled:opacity-50')}+ >+ <CirclePlus className="size-[17px] shrink-0 text-mint" />+ <SourceTile source={source} />+ <Identity source={source} />+ <span className="shrink-0 text-[11.5px] font-semibold text-foreground">{t('settings.models.order.enable')}</span>+ </button>+ ))}+ </div></>)}@@ -540,294 +267,16 @@ export const SourceOrderDrawer: React.FC<{<><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]')}>+ <div key={source.id} className={cn(ROW, 'border-border opacity-55')}><SourceTile source={source} />- <Identity name={source.display_name} subline={ineligibleSubline(source, reasonKey)} />+ <Identity source={source} detail={ineligibleDetail(source, reasonKey)} /></div>))}</>)}-- {DRY_RUN_ENABLED && (- <DryRunRow- agent={agent}- sources={sources}- chainKey={dryRunChainKey(agent, policy, order, sources)}- saving={saving}- reread={onReread}- />- )}-- {/* 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}- disabled={saving}- >- <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>);};-/** 「<name> 没跑通」, with the server's reason when it gave one. */-const failedLine = (t: TFunction, name: string, detail: string | null): string =>- detail- ? (t('settings.models.dryRun.failed', { name, detail }) as string)- : (t('settings.models.dryRun.failedUnknown', { name }) as string);--/**- * 试跑 — one real turn through this Agent's chain, and its answer.- *- * Full-width at every breakpoint, at the end of the list. No V6 or M02 frame- * draws it, so it takes the geometry of the phone's 模型菜单与映射 row rather than- * inventing one, and it is a row instead of a third footer button because the- * answer belongs UNDER the question: 「这条链现在能不能跑通」 is about the list- * above it, and a footer control would report on it from the wrong end of the- * sheet, with nowhere to put the result line.- *- * It reports the head the SERVER picked, never one this drawer chose: the probe- * takes no model, the reply names the source it reached, and a null latency is a- * head the Hub does not carry the request for (a native CLI login) — which is- * `可用` without a number, not a zero.- */-const DryRunRow: React.FC<{- agent: AgentSupply;- sources: Source[];- /** Everything the USER selects the probed turn with — order, policy, and the- * model surface, from `dryRunChainKey`. Deliberately not the head the server- * computes from it; see that owner and the reset effect below. */- chainKey: string;- /** The drawer's order PUT is in flight. A probe started now would answer for the- * chain the server still holds, filed under the one the user already sees —- * `dryRunRowView` owns that rule. */- saving: boolean;- /** Re-read sources + agents, the drawer's own `onReread`: a failing 试跑 is a- * write, so the page it sits on is stale until this runs — and `probeArrival`- * owns the part that is easy to get wrong, that this is owed even for an answer- * the row will not draw. A read and not an echo: the probe writes SOURCE state- * and hands back no Agent row to take. */- reread: () => void;-}> = ({ agent, sources, chainKey, saving, reread }) => {- const { t } = useTranslation();- const plan = dryRunPlan(agent);- const [running, setRunning] = React.useState(false);- const [outcome, setOutcome] = React.useState<DryRunOutcome | null>(null);- // The REASON, not the sentence built from it: a stored sentence keeps the- // language it was built in, and a language switch re-renders this row without- // re-running the probe. Wrapped rather than a bare `string | null`, because a- // thrown failure may carry no key at all and `null` has to keep meaning 「nothing- // ran yet」 — `{ key: null }` is the third state, 「it failed and nobody named- // why」, whose sentence is the generic line below.- const [errorReason, setErrorReason] = React.useState<{ key: string | null } | null>(null);- const seq = React.useRef(0);-- // A result describes ONE chain, and editing the chain stops it being about- // anything — so it goes, rather than sitting there under a list it no longer- // answers for.- //- // Keyed on the chain the USER edits, not on `agent.current`, because the head- // is where the two diverge: a failing 试跑 cools its own head down, so the- // re-read below moves `agent.current` almost every time the report is a- // failure. Keyed on the head, the refresh would erase the sentence the click- // produced — and the line names its source, so after a self-inflicted move it- // is the EXPLANATION for the new head rather than a claim about it.- React.useEffect(() => {- seq.current += 1;- setRunning(false);- setOutcome(null);- setErrorReason(null);- }, [chainKey]);-- const run = async (backend: AgentBackend) => {- const mine = ++seq.current;- setRunning(true);- setOutcome(null);- setErrorReason(null);- try {- const probe = await modelsApi.probeAgent(backend);- // `seq` guards the REPORT, not the refetch. An edit to the chain while this- // was in flight makes the answer moot, but not the cooldown it wrote — and- // that edit's own refetch went out before this returned, so it cannot have- // seen it. `probeArrival` owns the split; the verdict is stored first, then- // the page behind this sheet is corrected.- const arrival = probeArrival({ kind: 'result', probe }, seq.current === mine);- if (arrival.report) setOutcome(dryRunOutcome(probe, sources));- if (arrival.reread) reread();- } catch (err) {- const failure = apiFailure(err);- // `serverNamed` is the error's to state, not this site's to infer from- // 「is it one of ours?」: a response that would not parse is one of ours and- // names nothing, and that is the case the reread below exists for. The code- // rides along for the opposite case — a refusal that named itself and, in- // naming itself, disproved the head this button was drawn from.- const arrival = probeArrival(- {- kind: 'thrown',- serverNamed: failure?.serverNamed ?? false,- code: failure?.code ?? null,- },- seq.current === mine,- );- // The server's own reason when it named one (`probe_no_candidate` carries a- // detail key), and the absence of one when it didn't. Which sentence either- // becomes is the render's call — the same degradation the rest of the page- // gives a server-chosen key, applied with the `t` that is current when it is- // READ rather than the one that happened to be in scope when it arrived.- if (arrival.report) setErrorReason({ key: failure?.detail ?? null });- // Either because the probe may have run and written with the answer lost on- // the way back, or because the refusal that came back contradicts the chain- // this row is drawn from — `probeArrival` keeps those two apart.- if (arrival.reread) reread();- } finally {- if (seq.current === mine) setRunning(false);- }- };-- const ok = outcome?.kind === 'ok';- const line = !outcome- ? errorReason && serverText(t, errorReason.key, 'settings.models.dryRun.error')- : outcome.kind === 'ok'- ? outcome.latencyMs !== null- ? (t('settings.models.dryRun.ok', { name: outcome.sourceName, ms: outcome.latencyMs }) as string)- : (t('settings.models.dryRun.okNoLatency', { name: outcome.sourceName }) as string)- : // The detail is the server's key; with none, the name alone is the honest- // sentence rather than a machine code appended to it.- failedLine(t, outcome.sourceName, serverText(t, outcome.detailKey));-- // What this row IS right now, which the plan alone cannot say: no head means no- // control (Direct mode, or waiting/interrupted — the page states that one level- // up with the remedy attached, so a disabled 试跑 would only repeat it), and yet- // this very row is how a chain LOSES its head, because a failing probe cools its- // own head down. The answer therefore outlives the chain it was about; only the- // control goes with it. `saving` is in there for the mirror-image reason — see- // `dryRunRowView`.- const { backend, enabled, report } = dryRunRowView(plan, { line, saving, running });- if (backend === null && !report) return null;-- return (- <div className="mt-1 flex flex-col gap-2">- {backend !== null && (- <Button- variant="outline"- className="h-[46px] w-full justify-between rounded-xl px-4 text-[13px] font-semibold"- onClick={() => void run(backend)}- disabled={!enabled}- >- <span className="flex items-center gap-2">- {running ? <Loader2 className="size-4 animate-spin" /> : <Zap className="size-4" />}- {t(running ? 'settings.models.dryRun.running' : 'settings.models.dryRun.action')}- </span>- </Button>- )}- {report && (- <p- className={cn(- 'flex items-start gap-1.5 px-1 text-[12px] leading-relaxed',- ok ? 'text-mint' : 'text-gold',- )}- >- {ok ? (- <CheckCircle2 className="mt-[2px] size-3.5 shrink-0" />- ) : (- <TriangleAlert className="mt-[2px] size-3.5 shrink-0" />- )}- {line}- </p>- )}- </div>- );-};--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.test.tsx b/ui/src/components/settings/models/SourceRow.test.tsxnew file mode 100644index 000000000..abd0566d0--- /dev/null+++ b/ui/src/components/settings/models/SourceRow.test.tsx@@ -0,0 +1,54 @@+import { createInstance } from 'i18next';+import { renderToStaticMarkup } from 'react-dom/server';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { describe, expect, it, vi } from 'vitest';++import { ToastProvider } from '@/context/ToastContext';+import en from '../../../i18n/en.json';+import zh from '../../../i18n/zh.json';+import { SourceRow } from './SourceRow';+import type { Source } from './types';++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'zh',+ fallbackLng: 'en',+ resources: { en: { translation: en }, zh: { translation: zh } },+ interpolation: { escapeValue: false },+});++const source = (kind: Source['kind']): Source => ({+ id: `src_${kind}`,+ kind,+ vendor: 'anthropic',+ display_name: kind,+ protocol: 'anthropic',+ supply_channel: kind === 'subscription' ? 'native_cli' : 'hub',+ billing: kind === 'subscription' ? 'monthly' : 'metered',+ state: { status: 'active', retry_at: null, detail_key: null },+ models: [],+});++const render = (row: Source) => renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <ToastProvider>+ <SourceRow source={row} onChanged={vi.fn()} onRepair={vi.fn()} onAddModel={vi.fn()} />+ </ToastProvider>+ </I18nextProvider>,+);++describe('SourceRow empty inventory', () => {+ it('sends subscriptions to sign-in instead of an unavailable manual-model action', () => {+ const html = render(source('subscription'));+ expect(html).toContain(zh.settings.models.sources.modelsEmptySubscription);+ expect(html).toContain(zh.settings.models.sourceActions.reauth);+ expect(html).not.toContain(zh.settings.models.sources.modelsEmpty);+ expect(html).not.toContain(zh.settings.models.sources.addModel);+ });++ it('keeps manual model creation available for API-key sources', () => {+ const html = render(source('api_key'));+ expect(html).toContain(zh.settings.models.sources.modelsEmpty);+ expect(html).toContain(zh.settings.models.sources.addModel);+ });+});diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsxindex da5480553..b3643e462 100644--- a/ui/src/components/settings/models/SourceRow.tsx+++ b/ui/src/components/settings/models/SourceRow.tsx@@ -15,8 +15,11 @@// 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 { LogIn, Plus } 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 { BillingChip, ExperimentalChip, StateChip } from './chips';import { SupplyTooltip } from './SupplyTooltip';@@ -121,7 +124,10 @@ export const SourceRow: React.FC<{onChanged: () => void;/** Open a repair journey the page hosts — see SourceRowMenu's `onRepair`. */onRepair?: (source: Source, kind: RaisedRepair) => void;-}> = ({ source, onChanged, onRepair }) => {+ /** Open the shared manual-model action with this source preselected. */+ onAddModel: (source: Source) => void;+}> = ({ source, onChanged, onRepair, onAddModel }) => {+ const { t } = useTranslation();const { Icon, accent } = sourceVisual(source);const subline = useSubline(source);const isExperimental = source.kind === 'subscription' && source.supply_channel === 'hub';@@ -132,7 +138,8 @@ 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.5 sm:px-5 sm:py-3">+ <div className="group border-b border-border last:border-b-0">+ <div className="flex flex-wrap items-center gap-x-2.5 gap-y-2.5 px-4 py-3 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.5"><SupplyTooltip models={source.models} className="flex min-w-0 flex-1 items-center gap-2.5 sm:gap-3.5">@@ -173,7 +180,7 @@ export const SourceRow: React.FC<{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} className="sm:ml-1.5" />+ <BillingChip billing={source.billing} className="sm:ml-1.5" /><StateCell source={source} /></div>@@ -184,6 +191,59 @@ export const SourceRow: React.FC<{<div className="order-2 flex shrink-0 items-center gap-1.5 sm:order-3"><SourceRowMenu source={source} onChanged={onChanged} onRepair={onRepair} /></div>+ </div>++ <div className="flex flex-col gap-2 border-t border-border/70 bg-foreground/[0.012] px-4 py-3 sm:px-5">+ <div className="flex items-center justify-between gap-3">+ <span className="text-[11px] font-semibold text-muted">+ {t('settings.models.sources.modelCount', { count: source.models.length })}+ </span>+ {source.kind === 'api_key' && (+ <button+ type="button"+ onClick={() => onAddModel(source)}+ className="inline-flex min-h-8 shrink-0 items-center gap-1 text-[11.5px] font-semibold text-mint transition-colors hover:text-mint/80"+ >+ <Plus className="size-3.5" />+ {t('settings.models.sources.addModel')}+ </button>+ )}+ </div>+ {source.models.length === 0 ? (+ <div className="flex flex-wrap items-center justify-between gap-2">+ <p className="text-[11.5px] text-muted">+ {t(+ source.kind === 'subscription'+ ? 'settings.models.sources.modelsEmptySubscription'+ : 'settings.models.sources.modelsEmpty',+ )}+ </p>+ {source.kind === 'subscription' && onRepair && (+ <Button variant="outline" size="xs" className="h-7 shrink-0" onClick={() => onRepair(source, 'reauth')}>+ <LogIn />+ {t('settings.models.sourceActions.reauth')}+ </Button>+ )}+ </div>+ ) : (+ <div className="flex max-h-28 flex-wrap gap-1.5 overflow-y-auto pr-1">+ {source.models.map((model) => (+ <span+ key={model.id}+ title={model.display_name || model.id}+ className="inline-flex max-w-full items-center gap-1.5 rounded-md border border-border bg-background px-2 py-1"+ >+ <span className="truncate font-mono text-[10.5px] text-foreground">{model.id}</span>+ {model.provenance === 'manual' && (+ <Badge variant="secondary" className="shrink-0 px-1 py-0 text-[8.5px]">+ {t('settings.models.routes.manualBadge')}+ </Badge>+ )}+ </span>+ ))}+ </div>+ )}+ </div></div>);};diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsxindex b9c1eee0f..51bbf80a6 100644--- a/ui/src/components/settings/models/SourcesCard.tsx+++ b/ui/src/components/settings/models/SourcesCard.tsx@@ -1,12 +1,5 @@-// 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.+// Demoted account-management section. Each source keeps its repair journeys and+// exposes the server-provided model inventory plus the shared manual-model action.//// Mobile header (design.pen M01 m01SrcHead): the title block and 添加来源 stack// instead of competing for one line, with 添加来源 as a full-width primary@@ -29,7 +22,8 @@ export const SourcesCard: React.FC<{onSourceChanged: () => void;/** Open a repair journey the page hosts — see SourceRowMenu's `onRepair`. */onRepair?: (source: Source, kind: RaisedRepair) => void;-}> = ({ sources, onConnectClaude, onConnectChatGPT, onAddApiKey, onSourceChanged, onRepair }) => {+ onAddModel: (source: Source) => void;+}> = ({ sources, onConnectClaude, onConnectChatGPT, onAddApiKey, onSourceChanged, onRepair, onAddModel }) => {const { t } = useTranslation();return (@@ -52,7 +46,13 @@ export const SourcesCard: React.FC<{) : (<div className="flex flex-col">{sources.map((source) => (- <SourceRow key={source.id} source={source} onChanged={onSourceChanged} onRepair={onRepair} />+ <SourceRow+ key={source.id}+ source={source}+ onChanged={onSourceChanged}+ onRepair={onRepair}+ onAddModel={onAddModel}+ />))}</div>)}diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.tsindex 436ecd3ee..857ae95e6 100644--- a/ui/src/components/settings/models/asyncLifetime.test.ts+++ b/ui/src/components/settings/models/asyncLifetime.test.ts@@ -72,6 +72,7 @@ import {flowStep,initialSeedState,isDone,+ mapWithConcurrency,pollFailureSettles,releaseFlow,savedMappingsKey,@@ -145,6 +146,27 @@ describe('latest async authority', () => {});});+describe('bounded async map', () => {+ it('caps concurrent work and preserves input order', async () => {+ const gates = Array.from({ length: 12 }, () => deferred<number>());+ let active = 0;+ let maxActive = 0;++ const run = mapWithConcurrency(gates, 3, async (gate, index) => {+ active += 1;+ maxActive = Math.max(maxActive, active);+ const value = await gate.promise;+ active -= 1;+ return `${index}:${value}`;+ });++ expect(active).toBe(3);+ gates.forEach((gate, index) => gate.resolve(index * 2));+ await expect(run).resolves.toEqual(gates.map((_, index) => `${index}:${index * 2}`));+ expect(maxActive).toBe(3);+ });+});+describe('agentsWithEcho — what speaks for a row when no read does', () => {const claude = agent({ backend: 'claude', sources: { policy: 'custom', order: ['src_a'] } });const codex = agent({ backend: 'codex', sources: { policy: 'follow', order: ['src_b'] } });@@ -184,13 +206,16 @@ describe('agentsWithEcho — what speaks for a row when no read does', () => {it('is how every Agent write on the page reports itself', () => {const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');- expect(page).toMatch(/setAgents\(\(prev\) => agentsWithEcho\(prev, echoed\)\)/);+ expect(page).toMatch(/const next = agentsWithEcho\(prev, echoed\)/);// The mode PATCH echoes the same row the drawers' writes do.expect(page).toMatch(/await agentSaved\(echoed\)/);const handlers = [...page.matchAll(/onSaved=\{([^}]*)\}/g)].map((m) => m[1]);- expect(handlers.length).toBeGreaterThanOrEqual(3);- expect(handlers.filter((h) => !h.includes('agentSaved'))).toEqual([]);+ expect(handlers.length).toBeGreaterThanOrEqual(2);+ expect(handlers.filter((h) => h.includes('agentSaved')).length).toBeGreaterThanOrEqual(2);+ // The shared manual-model dialog is a source write and intentionally has no+ // Agent echo; it refreshes the model surface instead.+ expect(page).toMatch(/<AddCustomModelDialog[\s\S]*?onSaved=\{\(\) => void refreshSourcesAgents\(\)\}/);});});@@ -381,9 +406,13 @@ describe('createPendingWrites — a write that outlives the drawer that issued iexpect(drawer).toMatch(/orderWrite\.track\(async \(\) => \{/);expect(drawer).toMatch(/await Promise\.resolve\(onSaved\(echoed\)\)\.catch\(\(\) => \{\}\);/);- expect(page).toMatch(/createPendingWrites\(setOrderWrites\)/);- expect(page).toMatch(/pending: orderWrites\.has\(orderAgent\.backend\)/);- expect(page).toMatch(/track: \(work\) => orderWriteRegistry\.track\(orderAgent\.backend, work\)/);+ expect(page).toMatch(/createPendingWrites\(setAgentWrites\)/);+ expect(page).toMatch(/pending: agentWrites\.has\(orderAgent\.backend\)/);+ expect(page).toMatch(/track: \(work\) => agentWriteRegistry\.track\(orderAgent\.backend, work\)/);+ // Every OpenCode menu door disables at the card, and the page repeats the+ // guard at the ownership boundary so a stale click cannot bypass it.+ expect(page).toMatch(/agent\.backend === menuBackend && !agentWrites\.has\(agent\.backend\)/);+ expect(page).toMatch(/if \(!agentWrites\.has\(agent\.backend\)\) setMenuBackend\(agent\.backend\)/);});});diff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.tsindex ca611ceef..e4736e6c6 100644--- a/ui/src/components/settings/models/asyncLifetime.ts+++ b/ui/src/components/settings/models/asyncLifetime.ts@@ -28,6 +28,29 @@ export const createLatestAsyncAuthority = <T>(land: (value: T) => void) => {};};+/** Maps a potentially large read set without allowing it to fan out unbounded. */+export async function mapWithConcurrency<T, R>(+ items: readonly T[],+ limit: number,+ read: (item: T, index: number) => Promise<R>,+): Promise<R[]> {+ if (!Number.isFinite(limit) || limit < 1) throw new RangeError('limit must be at least 1');+ const results = new Array<R>(items.length);+ let nextIndex = 0;++ const worker = async () => {+ while (nextIndex < items.length) {+ const index = nextIndex;+ nextIndex += 1;+ results[index] = await read(items[index], index);+ }+ };++ const workerCount = Math.min(Math.floor(limit), items.length);+ await Promise.all(Array.from({ length: workerCount }, worker));+ return results;+}+// ── What speaks for a row when no read does ────────────────────────────────/*** Takes a write's echoed Agent row into the page's list.diff --git a/ui/src/components/settings/models/chips.tsx b/ui/src/components/settings/models/chips.tsxindex 222fcfd5b..763ae72c8 100644--- a/ui/src/components/settings/models/chips.tsx+++ b/ui/src/components/settings/models/chips.tsx@@ -9,7 +9,6 @@ import { Badge } from '@/components/ui/badge';import { cn } from '@/lib/utils';import { useTranslation } from 'react-i18next';-import { currencySymbol } from './format';import { ACCENT_DOT, type Accent } from './vendorMeta';import type { AgentMode, SourceState } from './types';@@ -29,19 +28,12 @@ const CHIP_MOBILE = 'rounded-full py-1';const BILLING_CHIP = cn(CHIP_MOBILE, 'font-medium sm:w-[58px] sm:justify-center');/**- * 包月 / 按量 $ — content-width on phones, fixed-width column on sm+.- *- * The metered symbol tracks the source's REPORTED currency (USD when absent).- * A static `$` contradicted the usage cell for a source that genuinely reports- * CNY/EUR — it would read `按量 $` beside `¥12.4`. The symbol still comes from- * 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).+ * Billing type — content-width on phones, fixed-width column on sm+.*/export const BillingChip: React.FC<{billing: 'monthly' | 'metered';- currency?: string | null;className?: string;-}> = ({ billing, currency, className }) => {+}> = ({ billing, className }) => {const { t } = useTranslation();if (billing === 'monthly') {return (@@ -50,12 +42,9 @@ export const BillingChip: React.FC<{</Badge>);}- const symbol = currencySymbol(currency);return (<Badge variant="warning" className={cn(BILLING_CHIP, className)}>- {symbol- ? t('settings.models.billing.meteredWithSymbol', { symbol })- : t('settings.models.billing.metered')}+ {t('settings.models.billing.metered')}</Badge>);};@@ -117,7 +106,7 @@ export const CurrentChip: React.FC = () => {};/**- * 中枢 Hub / 直连 Direct — a fixed 104px column on desktop so the pills line up+ * Managed / 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@@ -150,4 +139,3 @@ export const ExperimentalChip: React.FC = () => {</Badge>);};-diff --git a/ui/src/components/settings/models/eventFeed.test.ts b/ui/src/components/settings/models/eventFeed.test.tsindex 9ba5fbe90..d65d2be0a 100644--- a/ui/src/components/settings/models/eventFeed.test.ts+++ b/ui/src/components/settings/models/eventFeed.test.ts@@ -213,7 +213,7 @@ describe('the page reads the feed through this owner', () => {// the same Promise.all, one failing leg left repaired sources and the ● 当前// the user just moved on screen as they were before the mutation.expect(page).toMatch(/modelsApi\.listEvents\(EVENT_PAGE\)\.catch\(\(\) => null\)/);- expect(page).toMatch(/createLatestAsyncAuthority<\[Source\[\], AgentSupply\[\], ResolutionEvent\[\] \| null\]>/);+ expect(page).toMatch(/createLatestAsyncAuthority<\[Source\[\], AgentSupply\[\], ResolutionEvent\[\] \| null, ModelChainIndex\]>/);// Sources and agents are NOT tolerated the same way — they are what this// refresh is for, and the caller's toast is what reports them failing.expect(page).not.toMatch(/modelsApi\.list(Sources|Agents)\(\)\.catch/);diff --git a/ui/src/components/settings/models/eventFeed.ts b/ui/src/components/settings/models/eventFeed.tsindex 3a8d50d17..ab4ebb054 100644--- a/ui/src/components/settings/models/eventFeed.ts+++ b/ui/src/components/settings/models/eventFeed.ts@@ -2,6 +2,19 @@// pages from the TAIL, so both directions are merges into one accumulated list// and neither may throw the other's rows away.import type { ResolutionEvent } from './types';+import type { Accent } from './vendorMeta';++const isActionRequired = (event: ResolutionEvent): boolean =>+ event.severity === 'action_required' ||+ (event.severity == null && (event.kind === 'needs_action' || event.kind === 'supply_interrupted'));++/** Presentation grade for a server-authored event; never rewords its historical copy. */+export const eventAccent = (event: ResolutionEvent): Accent => {+ if (isActionRequired(event) || event.billing_note === 'entered_metered') return 'gold';+ if (event.kind === 'recover' || event.reason === 'recovery') return 'mint';+ if (event.kind === 'cooldown' || event.kind === 'skip') return 'muted';+ return 'cyan';+};/*** 最近切换 as the page knows it: the rows, and whether its far end has been seen.diff --git a/ui/src/components/settings/models/featureFlags.ts b/ui/src/components/settings/models/featureFlags.tsindex 1c95cd7e2..85c0c5514 100644--- a/ui/src/components/settings/models/featureFlags.ts+++ b/ui/src/components/settings/models/featureFlags.ts@@ -21,24 +21,6 @@ export const modelHubEnabledFromConfig = (config: unknown): boolean => {*/export const MODELS_API_MODE: 'mock' | 'live' = 'live';-/**- * 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;--/**- * Offers 试跑 in the 来源顺序 drawer — one real turn through the chain.- *- * ON: `POST /api/models/agents/<backend>/probe` landed with the- * provenance/channel-aware-probe lane, which is the merge this flip was waiting- * for — the same way MODEL_MENUS_ENABLED above waited for the drawers it opens.- * The route answers per channel: hub attempts the request upstream and times it,- * native_cli re-verifies the CLI's readiness and times nothing.- */-export const DRY_RUN_ENABLED = true;-/*** Offers the consent-gated hub-held subscription option (`subscription_hub_* experimental`, spec §4.1/§7) inside the connect-subscription dialog. OFF bydiff --git a/ui/src/components/settings/models/menus/AddCustomModelDialog.test.ts b/ui/src/components/settings/models/menus/AddCustomModelDialog.test.tsnew file mode 100644index 000000000..4b567dd1c--- /dev/null+++ b/ui/src/components/settings/models/menus/AddCustomModelDialog.test.ts@@ -0,0 +1,28 @@+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import { manualModelIdentifier } from './identifiers';++const here = dirname(fileURLToPath(import.meta.url));++describe('manual model identifier context', () => {+ const standardVendors = new Set(['anthropic', 'openai']);++ it('keeps raw upstream IDs outside OpenCode and prefixes OpenCode identifiers only', () => {+ expect(manualModelIdentifier(' claude-special ', 'anthropic', standardVendors, false)).toBe('claude-special');+ expect(manualModelIdentifier(' claude-special ', 'anthropic', standardVendors, true)).toBe('anthropic/claude-special');+ });++ it('shows the generated preview only for OpenCode callers', () => {+ const dialog = readFileSync(join(here, 'AddCustomModelDialog.tsx'), 'utf8');+ const drawer = readFileSync(join(here, 'OpenCodeMenuDrawer.tsx'), 'utf8');+ const page = readFileSync(join(here, '..', 'SettingsModelsPage.tsx'), 'utf8');++ expect(dialog).toMatch(/\{showOpenCodeIdentifier && \(\s*<div/);+ expect(drawer).toMatch(/<AddCustomModelDialog[\s\S]*?showOpenCodeIdentifier/);+ expect(page).toMatch(/showOpenCodeIdentifier=\{customModelRequest\?\.backend === 'opencode'\}/);+ });+});diff --git a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsxindex 697a775e8..7bf852f09 100644--- a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx+++ b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx@@ -1,8 +1,7 @@// 添加自定义模型 (frame 08). Supplements a source's supply list with a model the-// auto-discovery missed, so it appears in the OpenCode menu. Source + model id-// (+ optional display name) → a LIVE identifier preview built with the vendor-id-// rule (`custom/` fallback). Persists via POST /custom-models; also used to edit-// an existing custom entry (same upsert endpoint).+// auto-discovery missed. OpenCode callers show its provider-prefixed identifier;+// fixed-backend and source-list callers keep the upstream's raw model id. Persists+// via POST /custom-models; also used to edit an existing custom entry.import * as React from 'react';import { ChevronDown, Copy, Plus, Trash2 } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -22,9 +21,10 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popoverimport { cn } from '@/lib/utils';import { useToast } from '@/context/ToastContext';import { modelsApi } from '../modelsApi';+import { manualModelSources } from '../modelRows';import { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, sourceVisual } from '../vendorMeta';import type { Source } from '../types';-import { buildIdentifier, type StandardVendors } from './identifiers';+import { manualModelIdentifier, type StandardVendors } from './identifiers';const FieldLabel: React.FC<{ mono?: boolean; children: React.ReactNode }> = ({ mono, children }) => (<span@@ -112,13 +112,27 @@ export const AddCustomModelDialog: React.FC<{/** Server-populated standard OpenCode vendor prefixes (agent-supply v1.2),* so the live identifier preview byte-matches the backend. */standardVendors: StandardVendors;+ /** Optional source door that opened the shared action. */+ initialSourceId?: string | null;+ /** OpenCode uses provider-prefixed identifiers; every other caller uses the raw upstream id. */+ showOpenCodeIdentifier?: boolean;/** When set, prefill for editing an existing custom entry. */edit?: { sourceId: string; modelId: string; displayName: string | null } | null;onClose: () => void;onSaved: (identifier: string) => void;/** Fired after a custom model is removed (edit mode only). */onDeleted?: (identifier: string) => void;-}> = ({ open, sources, standardVendors, edit, onClose, onSaved, onDeleted }) => {+}> = ({+ open,+ sources,+ standardVendors,+ initialSourceId,+ showOpenCodeIdentifier = false,+ edit,+ onClose,+ onSaved,+ onDeleted,+}) => {const { t } = useTranslation();const { showToast } = useToast();@@ -127,13 +141,16 @@ export const AddCustomModelDialog: React.FC<{const [displayName, setDisplayName] = React.useState('');const [saving, setSaving] = React.useState(false);const [deleteOpen, setDeleteOpen] = React.useState(false);+ const writableSources = React.useMemo(() => manualModelSources(sources), [sources]);- // Seed on open: edit prefill, else the first source that can carry custom- // models (an api_key source), else the first source.+ // Seed on open: existing invalid legacy rows remain selectable in edit mode+ // so they can be deleted, but create mode only accepts credential-backed+ // inventories. A subscription inventory is read-only by contract.React.useEffect(() => {if (!open) return;const editing = edit ? sources.find((s) => s.id === edit.sourceId) ?? null : null;- const preferred = editing ?? sources.find((s) => s.kind === 'api_key') ?? sources[0] ?? null;+ const requested = initialSourceId ? writableSources.find((s) => s.id === initialSourceId) ?? null : null;+ const preferred = editing ?? requested ?? writableSources[0] ?? null;setSource(preferred);setModelId(edit?.modelId ?? '');setDisplayName(edit?.displayName ?? '');@@ -142,7 +159,12 @@ export const AddCustomModelDialog: React.FC<{}, [open]);const trimmedId = modelId.trim();- const identifier = source && trimmedId ? buildIdentifier(source.vendor, trimmedId, standardVendors) : '';+ const identifier = manualModelIdentifier(+ trimmedId,+ source?.vendor ?? null,+ standardVendors,+ showOpenCodeIdentifier,+ );const copyIdentifier = () => {if (!identifier || !navigator.clipboard?.writeText) {@@ -156,7 +178,7 @@ export const AddCustomModelDialog: React.FC<{};const submit = async () => {- if (!source || !trimmedId || saving) return;+ if (!source || source.kind !== 'api_key' || !trimmedId || saving) return;setSaving(true);try {await modelsApi.addCustomModel({ source_id: source.id, model_id: trimmedId, display_name: displayName.trim() || null });@@ -203,7 +225,7 @@ export const AddCustomModelDialog: React.FC<{<div className="flex flex-col gap-2"><FieldLabel>{t('settings.models.menus.custom.sourceLabel')}</FieldLabel>- <SourceSelect sources={sources} value={source} onChange={setSource} disabled={Boolean(edit)} />+ <SourceSelect sources={writableSources} value={source} onChange={setSource} disabled={Boolean(edit)} /></div><div className="flex flex-col gap-2">@@ -230,26 +252,28 @@ export const AddCustomModelDialog: React.FC<{/></div>- <div className="flex flex-col gap-2 rounded-xl border border-violet/30 bg-violet-soft/40 px-4 py-3.5">- <div className="flex items-center justify-between gap-2">- <span className="font-mono text-[11px] font-semibold uppercase tracking-wide text-violet">- {t('settings.models.menus.custom.previewLabel')}+ {showOpenCodeIdentifier && (+ <div className="flex flex-col gap-2 rounded-xl border border-violet/30 bg-violet-soft/40 px-4 py-3.5">+ <div className="flex items-center justify-between gap-2">+ <span className="font-mono text-[11px] font-semibold uppercase tracking-wide text-violet">+ {t('settings.models.menus.custom.previewLabel')}+ </span>+ <button+ type="button"+ aria-label={t('common.copy') as string}+ onClick={copyIdentifier}+ disabled={!identifier}+ className="flex size-10 items-center justify-center rounded-md text-muted transition-colors hover:text-foreground disabled:opacity-40 sm:size-6"+ >+ <Copy className="size-4" />+ </button>+ </div>+ <span className="font-mono text-[16px] font-semibold text-foreground">+ {identifier || t('settings.models.menus.custom.previewEmpty')}</span>- <button- type="button"- aria-label={t('common.copy') as string}- onClick={copyIdentifier}- disabled={!identifier}- className="flex size-10 items-center justify-center rounded-md text-muted transition-colors hover:text-foreground disabled:opacity-40 sm:size-6"- >- <Copy className="size-4" />- </button>+ <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.menus.custom.previewHint')}</p></div>- <span className="font-mono text-[16px] font-semibold text-foreground">- {identifier || t('settings.models.menus.custom.previewEmpty')}- </span>- <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.menus.custom.previewHint')}</p>- </div>+ )}<DialogFooter className={cn('gap-2', edit ? 'sm:justify-between' : 'sm:justify-end')}>{edit && (@@ -268,7 +292,13 @@ export const AddCustomModelDialog: React.FC<{<Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={saving}>{t('common.cancel')}</Button>- <Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={() => void submit()} disabled={!source || !trimmedId || saving}>+ <Button+ variant="brand"+ size="sm"+ className="h-10 sm:h-9"+ onClick={() => void submit()}+ disabled={!source || source.kind !== 'api_key' || !trimmedId || saving}+ ><Plus className="size-4" />{t(edit ? 'common.save' : 'settings.models.menus.custom.add')}</Button>diff --git a/ui/src/components/settings/models/menus/MappingDrawer.tsx b/ui/src/components/settings/models/menus/MappingDrawer.tsxdeleted file mode 100644index 38251632f..000000000--- a/ui/src/components/settings/models/menus/MappingDrawer.tsx+++ /dev/null@@ -1,322 +0,0 @@-// 模型菜单 · Claude Code / Codex — the fixed-menu mapping drawer (frame 04).-// Left column: the backend's built-in model ids (mono, not editable). Right-// column: the supply each id resolves to — 跟随原生 · 按优先级供给 by default, or-// an override to another model (violet, with a per-row reset and a persistent-// capability warning). Per-agent scope; commits via PUT .../mappings on 完成.-import * as React from 'react';-import { ArrowRight, CheckCircle2, ChevronDown, Info, RotateCcw } from 'lucide-react';-import { useTranslation } from 'react-i18next';--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 { eligibleSources } from '../eligibility';-import { buildTargetModels, type TargetModel } from './identifiers';-import { SupplyDots } from './supplyBits';-import { useAnnounceEnrollment } from './enrollment';-import { useCompactSourceLabel } from './sourceLabel';--// Fixed-menu backends expose their built-in model catalog via agent.builtin_models-// (real ids from vibe/backend_model_catalog.py, agent-supply v1.2). The contract-// stores only OVERRIDES in agent.mappings (absent entry = 跟随原生), so the row list-// comes from this server-populated catalog — the UI never hardcodes it.-const resolveBuiltinIds = (agent: AgentSupply): string[] => agent.builtin_models ?? [];--const seedDraft = (agent: AgentSupply): AgentMapping[] => {- const byId = new Map((agent.mappings ?? []).map((m) => [m.builtin_id, m]));- const ids = resolveBuiltinIds(agent);- // Preserve any stored builtin id we don't know about, appended after the- // canonical list, so a backend that adds ids stays visible.- const extra = (agent.mappings ?? []).map((m) => m.builtin_id).filter((id) => !ids.includes(id));- return [...ids, ...extra].map(- (builtin_id) => byId.get(builtin_id) ?? { builtin_id, target_model_id: '', enabled: false },- );-};--const sameDraft = (a: AgentMapping[], b: AgentMapping[]): boolean =>- a.length === b.length &&- a.every((m, i) => m.builtin_id === b[i].builtin_id && m.enabled === b[i].enabled && m.target_model_id === b[i].target_model_id);--const BuiltinChip: React.FC<{ id: string }> = ({ id }) => (- <span className="shrink-0 whitespace-nowrap rounded-lg border border-border bg-surface-2 px-3 py-2 font-mono text-[13px] font-medium text-foreground">- {id}- </span>-);--const SupplySelector: React.FC<{- mapping: AgentMapping;- targets: TargetModel[];- onFollowNative: () => void;- onOverride: (targetId: string) => void;-}> = ({ mapping, targets, onFollowNative, onOverride }) => {- const { t } = useTranslation();- const compactLabel = useCompactSourceLabel();- const [open, setOpen] = React.useState(false);- const override = mapping.enabled && Boolean(mapping.target_model_id);- const target = targets.find((x) => x.id === mapping.target_model_id);- const candidateLabel = target- ? (t('settings.models.menus.mapping.candidates', {- sources: target.sources.map(compactLabel).join(' / '),- }) as string)- : (t('settings.models.menus.mapping.candidatesUnavailable') as string);-- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <button- type="button"- className={cn(- 'flex h-11 w-full items-center gap-2.5 rounded-lg border px-3.5 text-left text-[13px] transition-colors',- override- ? 'border-violet/40 bg-violet-soft/60 hover:border-violet/60'- : 'border-border bg-background hover:border-border-strong',- )}- >- {override ? (- <>- <span className="shrink-0 font-mono font-semibold text-violet">{mapping.target_model_id}</span>- {target && <SupplyDots accents={target.accents} className="flex shrink-0 items-center gap-1" />}- <span className="truncate text-muted">{candidateLabel}</span>- </>- ) : (- <>- <CheckCircle2 className="size-4 shrink-0 text-mint" />- <span className="truncate text-foreground">{t('settings.models.menus.mapping.followNative')}</span>- </>- )}- <ChevronDown className="ml-auto size-4 shrink-0 text-muted" />- </button>- </PopoverTrigger>- <PopoverContent- align="start"- sideOffset={6}- className="max-h-[320px] w-[var(--radix-popover-trigger-width)] overflow-y-auto p-1.5"- >- <button- type="button"- onClick={() => {- onFollowNative();- setOpen(false);- }}- className="flex min-h-11 w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] hover:bg-surface-2 sm:min-h-0"- >- <CheckCircle2 className={cn('size-4 shrink-0', override ? 'text-muted/40' : 'text-mint')} />- <span className="text-foreground">{t('settings.models.menus.mapping.followNative')}</span>- </button>- <div className="my-1 h-px bg-border" />- {targets.map((tg) => {- const active = override && tg.id === mapping.target_model_id;- return (- <button- key={tg.id}- type="button"- onClick={() => {- onOverride(tg.id);- setOpen(false);- }}- className={cn(- 'flex min-h-11 w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left hover:bg-surface-2 sm:min-h-0',- active && 'bg-violet-soft/60',- )}- >- {/* Same rule as the OpenCode rows: wrap a long id, never hide its- suffix — picking the wrong override target is unrecoverable. */}- <span className="min-w-0 break-all font-mono text-[13px] font-medium text-foreground">{tg.id}</span>- {tg.displayName && <span className="truncate text-[12px] text-muted">{tg.displayName}</span>}- <SupplyDots accents={tg.accents} className="ml-auto flex shrink-0 items-center gap-1" />- </button>- );- })}- </PopoverContent>- </Popover>- );-};--export const MappingDrawer: React.FC<{- open: boolean;- backend: Extract<AgentBackend, 'claude' | 'codex'>;- agent: AgentSupply;- sources: Source[];- onClose: () => void;- /** Hands the page the Agent row this write echoed — see `agentsWithEcho`. */- onSaved: (echoed: AgentSupply) => void;-}> = ({ open, backend, agent, sources, onClose, onSaved }) => {- const { t } = useTranslation();- const { showToast } = useToast();- const { Icon, accent } = backendVisual(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]);- // Accepting an override may also enroll its supplier into this backend's source- // order (api.md → "Mapping and menu enrollment"). Read off the echo at commit.- const announceEnrollment = useAnnounceEnrollment(backend, sources);-- const [draft, setDraft] = React.useState<AgentMapping[]>(() => seedDraft(agent));- const initialRef = React.useRef<AgentMapping[]>(draft);- const [saving, setSaving] = React.useState(false);-- // 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- // draft so the heal makes the drawer dirty and Done PERSISTS the cleaned- // mappings; a no-op close still heals the stored config.- const targetIds = new Set(targets.map((tg) => tg.id));- const healed = raw.map((m) =>- m.enabled && !targetIds.has(m.target_model_id) ? { ...m, enabled: false, target_model_id: '' } : m,- );- setDraft(healed);- initialRef.current = raw;- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [open, authoritative]);-- const backendName = t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;-- const setMapping = (builtinId: string, next: Partial<AgentMapping>) =>- setDraft((prev) => prev.map((m) => (m.builtin_id === builtinId ? { ...m, ...next } : m)));-- const resetAll = () => setDraft((prev) => prev.map((m) => ({ ...m, enabled: false, target_model_id: '' })));-- const commitAndClose = async () => {- if (saving) return;- if (sameDraft(draft, initialRef.current)) {- onClose();- return;- }- setSaving(true);- try {- // Contract: absent entry = 跟随原生 (identity). Send only enabled overrides- // — disabled rows carry an empty target_model_id that from_payload rejects.- // Self-heal: drop an override whose target is no longer available (its- // supplier source was deleted); it reverts to 跟随原生 instead of being- // resubmitted and rejected as mapping_target_unavailable.- const targetIds = new Set(targets.map((tg) => tg.id));- const echoed = await modelsApi.putMappings(- backend,- draft.filter((m) => m.enabled && targetIds.has(m.target_model_id)),- );- announceEnrollment(agent, echoed);- onSaved(echoed);- onClose();- } catch {- showToast(t('settings.models.menus.saveFailed') as string, 'error');- } finally {- setSaving(false);- }- };-- const anyOverride = draft.some((m) => m.enabled);-- return (- <MenuDrawer- open={open}- onClose={() => void commitAndClose()}- Icon={Icon}- accent={accent}- title={t('settings.models.menus.mapping.title', { backend: backendName }) as string}- subtitle={t('settings.models.menus.mapping.subtitle', { backend: backendName }) as string}- footer={- <>- <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={resetAll} disabled={!anyOverride || saving}>- <RotateCcw className="size-3.5" />- {t('settings.models.menus.resetAll')}- </Button>- <Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={() => void commitAndClose()} disabled={saving}>- {t('settings.models.menus.done')}- </Button>- </>- }- >- {/* Column headers only make sense while the two columns sit side by side;- on phones each row stacks, so the labels would mislabel the layout. */}- <div className="hidden items-center gap-3 px-1 pb-2.5 sm:flex">- <span className="w-[172px] shrink-0 font-mono text-[11px] font-medium uppercase tracking-wide text-muted">- {t('settings.models.menus.mapping.builtinCol')}- </span>- <span className="font-mono text-[11px] font-medium uppercase tracking-wide text-muted">- {t('settings.models.menus.mapping.supplyCol')}- </span>- </div>-- <div className="flex flex-col gap-2.5">- {draft.map((mapping) => {- const override = mapping.enabled && Boolean(mapping.target_model_id);- return (- <div key={mapping.builtin_id} className="flex items-start gap-2.5">- <div- className={cn(- 'flex flex-1 flex-col gap-2 rounded-xl border p-2.5',- override ? 'border-violet/40 bg-violet-soft/40' : 'border-border',- )}- >- {/* Phones stack builtin-id over supply (the 172px id column plus- the selector pushed the selector's chevron and the row reset- off-screen, so a mapping could not be changed at all); the- arrow rotates to keep reading as "maps to". */}- <div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center sm:gap-2.5">- <div className="min-w-0 sm:w-[172px] sm:shrink-0">- <BuiltinChip id={mapping.builtin_id} />- </div>- <ArrowRight- className={cn(- 'size-4 shrink-0 rotate-90 self-center sm:rotate-0 sm:self-auto',- override ? 'text-violet' : 'text-muted/60',- )}- />- <div className="min-w-0 flex-1">- <SupplySelector- mapping={mapping}- targets={targets}- onFollowNative={() => setMapping(mapping.builtin_id, { enabled: false, target_model_id: '' })}- onOverride={(targetId) => setMapping(mapping.builtin_id, { enabled: true, target_model_id: targetId })}- />- </div>- </div>- {override && (- <p className="flex items-start gap-1.5 text-[12px] text-gold sm:items-center sm:pl-[208px]">- <Info className="mt-0.5 size-3.5 shrink-0 sm:mt-0" />- {t('settings.models.menus.mapping.warning')}- </p>- )}- </div>- <button- type="button"- aria-label={t('settings.models.menus.mapping.resetRow') as string}- onClick={() => setMapping(mapping.builtin_id, { enabled: false, target_model_id: '' })}- disabled={!override}- className={cn(- 'mt-0.5 flex size-11 shrink-0 items-center justify-center rounded-lg border border-border text-muted transition-colors',- override ? 'hover:border-border-strong hover:text-foreground' : 'opacity-0',- )}- >- <RotateCcw className="size-4" />- </button>- </div>- );- })}- </div>-- <p className="mt-4 flex items-start gap-1.5 px-1 text-[12px] leading-relaxed text-muted">- <Info className="mt-0.5 size-3.5 shrink-0" />- {t('settings.models.menus.mapping.footnote', { backend: backendName })}- </p>- </MenuDrawer>- );-};diff --git a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsxindex 39f77aeef..3ceca84be 100644--- a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx+++ b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx@@ -271,6 +271,7 @@ export const OpenCodeMenuDrawer: React.FC<{open={customOpen}sources={eligibleSources}standardVendors={standardVendors}+ showOpenCodeIdentifieredit={editTarget}onClose={() => setCustomOpen(false)}onSaved={(identifier) => {diff --git a/ui/src/components/settings/models/menus/identifiers.ts b/ui/src/components/settings/models/menus/identifiers.tsindex 732f6e999..cd9ff019c 100644--- a/ui/src/components/settings/models/menus/identifiers.ts+++ b/ui/src/components/settings/models/menus/identifiers.ts@@ -34,6 +34,20 @@ export function buildIdentifier(sourceVendor: string, modelId: string, standardVreturn `${inferProvider(sourceVendor, standardVendors)}/${modelId}`;}+/** Identifier shown/returned by the shared manual-model action for its invoking surface. */+export function manualModelIdentifier(+ modelId: string,+ sourceVendor: string | null,+ standardVendors: StandardVendors,+ showOpenCodeIdentifier: boolean,+): string {+ const trimmed = modelId.trim();+ if (!trimmed) return '';+ return showOpenCodeIdentifier && sourceVendor+ ? buildIdentifier(sourceVendor, trimmed, standardVendors)+ : trimmed;+}+// `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 wasdiff --git a/ui/src/components/settings/models/modelRows.test.ts b/ui/src/components/settings/models/modelRows.test.tsnew file mode 100644index 000000000..722fb6e40--- /dev/null+++ b/ui/src/components/settings/models/modelRows.test.ts@@ -0,0 +1,197 @@+import { describe, expect, it } from 'vitest';++import {+ agentNeedsModelSelection,+ listedModelIds,+ manualModelSources,+ modelChainKey,+ modelChainRequests,+ modelHasOffOrderSupplier,+ modelIssueCount,+ modelNeedsAttention,+ modelSupplierCounts,+ orderedRouteSources,+ routableMappings,+ type ModelChainRead,+} from './modelRows';+import type { AgentSupply, RuntimeDependency, Source } from './types';++const agent = (over: Partial<AgentSupply> = {}): AgentSupply => ({+ backend: 'claude',+ mode: 'hub',+ menu_kind: 'fixed',+ selected_by_agent: null,+ selected_model_id: 'current-model',+ current: null,+ sources: { policy: 'follow', order: [], eligibility: [] },+ supply_status: 'ok',+ model_supply: [{ model_id: 'supply-model', chain_length: 1 }],+ named_agents: [],+ mappings: [{ builtin_id: 'mapped-model', target_model_id: 'target-model', enabled: true }],+ menu: null,+ builtin_models: ['builtin-model', 'current-model'],+ standard_vendors: null,+ ...over,+});++const read = (over: Partial<Extract<ModelChainRead, { kind: 'ready' }>['chain']> = {}): ModelChainRead => ({+ kind: 'ready',+ chain: {+ contract_version: 4,+ backend: 'claude',+ model_id: 'builtin-model',+ supply_state: 'ok',+ chain: [{+ source_id: 'src_a',+ channel: 'hub',+ via_mapping: false,+ resolved_model_id: null,+ health: 'healthy',+ runnable: true,+ reason: null,+ retry_at: null,+ }],+ ...over,+ },+});++const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({+ manifest: { name: 'cliproxyapi', version: '1', source_sha: 'a', assets: [] },+ status: { health, verified: health === 'ok' },+});++const source = (id: string): Source => ({+ id,+ kind: 'api_key',+ vendor: 'custom',+ display_name: id,+ protocol: 'openai_compatible',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active' },+ models: [],+});++describe('model row projection', () => {+ it('keeps every server-published model surface without duplicates', () => {+ expect(listedModelIds(agent())).toEqual(['builtin-model', 'current-model', 'supply-model', 'mapped-model']);+ });++ it('does not expose fixed-menu mappings as OpenCode model rows', () => {+ const open = agent({+ backend: 'opencode',+ menu_kind: 'open',+ selected_model_id: 'checked-model',+ menu: { view: 'featured', checked: ['checked-model'] },+ builtin_models: null,+ model_supply: [],+ mappings: [{ builtin_id: 'stale-fixed-model', target_model_id: 'target-model', enabled: true }],+ });+ expect(listedModelIds(open)).toEqual(['checked-model']);+ });++ it('deduplicates chain reads by backend and model', () => {+ expect(modelChainRequests([agent(), agent()])).toEqual([+ { backend: 'claude', modelId: 'builtin-model' },+ { backend: 'claude', modelId: 'current-model' },+ { backend: 'claude', modelId: 'supply-model' },+ { backend: 'claude', modelId: 'mapped-model' },+ ]);+ });++ it('keeps every eligible source in the route picker, including sources outside this agent order', () => {+ const ordered = orderedRouteSources(+ agent({+ sources: {+ policy: 'follow',+ order: ['src_b'],+ eligibility: [+ { source_id: 'src_a', eligible: true },+ { source_id: 'src_b', eligible: true },+ { source_id: 'src_c', eligible: false },+ ],+ },+ }),+ [source('src_a'), source('src_b'), source('src_c')],+ );+ expect(ordered.map((item) => item.id)).toEqual(['src_b', 'src_a']);+ });++ it('distinguishes an off-order supplier from a missing inventory entry', () => {+ const outside = { ...source('src_outside'), models: [{ id: 'existing-model', provenance: 'discovered' as const }] };+ const a = agent({+ menu_kind: 'open',+ standard_vendors: ['custom'],+ sources: {+ policy: 'custom',+ order: [],+ eligibility: [{ source_id: 'src_outside', eligible: true }],+ },+ });+ expect(modelHasOffOrderSupplier(a, [outside], 'custom/existing-model')).toBe(true);+ expect(modelHasOffOrderSupplier(a, [outside], 'custom/missing-model')).toBe(false);+ });++ it('drops unavailable sibling routes before a per-row save', () => {+ const available = { ...source('src_available'), models: [{ id: 'live-target', provenance: 'discovered' as const }] };+ const a = agent({+ sources: {+ policy: 'custom',+ order: ['src_available'],+ eligibility: [{ source_id: 'src_available', eligible: true }],+ },+ mappings: [+ { builtin_id: 'live-row', target_model_id: 'live-target', enabled: true },+ { builtin_id: 'stale-row', target_model_id: 'removed-target', enabled: true },+ ],+ });+ expect(routableMappings(a, [available])).toEqual([+ { builtin_id: 'live-row', target_model_id: 'live-target', enabled: true },+ ]);+ });++ it('only offers API-key inventories for manual models', () => {+ const subscription = { ...source('src_subscription'), kind: 'subscription' as const };+ expect(manualModelSources([subscription, source('src_key')]).map((item) => item.id)).toEqual(['src_key']);+ });++ it('counts duplicate suppliers from the full inventory', () => {+ const first = { ...source('src_a'), models: [{ id: 'shared-model', provenance: 'discovered' as const }] };+ const second = { ...source('src_b'), models: [{ id: 'shared-model', provenance: 'manual' as const }] };+ expect(modelSupplierCounts([first, second]).get('shared-model')).toBe(2);+ });++ it('counts an interrupted model and the honest row-zero state independently', () => {+ const row = read({ supply_state: 'interrupted', chain: [] });+ const a = agent({ selected_model_id: null, builtin_models: ['builtin-model'], model_supply: [] });+ expect(agentNeedsModelSelection(a)).toBe(true);+ expect(modelIssueCount([a], { [modelChainKey('claude', 'builtin-model')]: row })).toBe(2);+ });++ it('attributes runtime failure only to a model whose current head uses the managed channel', () => {+ expect(modelNeedsAttention(agent(), 'builtin-model', read(), runtime('down'))).toBe(true);+ const native = read({ chain: [{+ source_id: 'src_native',+ channel: 'native_cli',+ via_mapping: false,+ resolved_model_id: null,+ health: 'healthy',+ runnable: true,+ reason: null,+ retry_at: null,+ }] });+ expect(modelNeedsAttention(agent(), 'builtin-model', native, runtime('down'))).toBe(false);+ });++ it('keeps an automatic cooldown in the non-healthy rollup', () => {+ const waiting = read({ supply_state: 'waiting' });+ expect(modelNeedsAttention(agent(), 'builtin-model', waiting)).toBe(true);+ expect(modelIssueCount([agent({ builtin_models: ['builtin-model'], model_supply: [] })], {+ [modelChainKey('claude', 'builtin-model')]: waiting,+ })).toBe(1);+ });++ it('does not claim health when the live chain could not be read', () => {+ expect(modelNeedsAttention(agent(), 'builtin-model', { kind: 'error' })).toBe(true);+ });+});diff --git a/ui/src/components/settings/models/modelRows.ts b/ui/src/components/settings/models/modelRows.tsnew file mode 100644index 000000000..42aab441e--- /dev/null+++ b/ui/src/components/settings/models/modelRows.ts@@ -0,0 +1,128 @@+import { eligibleSources } from './eligibility';+import { buildIdentifier } from './menus/identifiers';+import type { AgentBackend, AgentChain, AgentMapping, AgentSupply, RuntimeDependency, Source } from './types';++export type ModelChainRead =+ | { kind: 'ready'; chain: AgentChain }+ | { kind: 'error' };++export type ModelChainIndex = Record<string, ModelChainRead>;++export type ModelChainRequest = {+ backend: AgentBackend;+ modelId: string;+};++export const modelChainKey = (backend: AgentBackend, modelId: string): string =>+ `${backend}\u0000${modelId}`;++/** Manual inventory is a credential-backed capability; subscriptions are read-only. */+export function manualModelSources(sources: Source[]): Source[] {+ return sources.filter((source) => source.kind === 'api_key');+}++/** Count suppliers from the complete route inventory, never a searched subset. */+export function modelSupplierCounts(sources: Source[]): ReadonlyMap<string, number> {+ const counts = new Map<string, number>();+ for (const source of sources) {+ for (const modelId of new Set(source.models.map((model) => model.id))) {+ counts.set(modelId, (counts.get(modelId) ?? 0) + 1);+ }+ }+ return counts;+}++/** Every server-eligible source is a route-target inventory; the order only ranks groups. */+export function orderedRouteSources(agent: AgentSupply, sources: Source[]): Source[] {+ const eligible = eligibleSources(sources, agent);+ const byId = new Map(eligible.map((source) => [source.id, source]));+ const ordered = (agent.sources?.order ?? [])+ .map((sourceId) => byId.get(sourceId))+ .filter((source): source is Source => Boolean(source));+ const seen = new Set(ordered.map((source) => source.id));+ return [...ordered, ...eligible.filter((source) => !seen.has(source.id))];+}++/** Whether the model already exists on an eligible supplier omitted from this Agent's order. */+export function modelHasOffOrderSupplier(agent: AgentSupply, sources: Source[], modelId: string): boolean {+ const enabled = new Set(agent.sources?.order ?? []);+ const standardVendors = new Set(agent.standard_vendors ?? []);+ return eligibleSources(sources, agent).some(+ (source) => !enabled.has(source.id) && source.models.some((model) => (+ agent.menu_kind === 'open'+ ? buildIdentifier(source.vendor, model.id, standardVendors) === modelId+ : model.id === modelId+ )),+ );+}++/** Enabled fixed-menu routes whose target still exists in an eligible source inventory. */+export function routableMappings(agent: AgentSupply, sources: Source[]): AgentMapping[] {+ const targets = new Set(+ orderedRouteSources(agent, sources).flatMap((source) => source.models.map((model) => model.id)),+ );+ return (agent.mappings ?? []).filter((mapping) => mapping.enabled && targets.has(mapping.target_model_id));+}++/** The model list the server says this backend exposes. */+export function listedModelIds(agent: AgentSupply): string[] {+ const primary = agent.menu_kind === 'fixed' ? agent.builtin_models ?? [] : agent.menu?.checked ?? [];+ const extras = [+ ...(agent.selected_model_id ? [agent.selected_model_id] : []),+ ...(agent.model_supply ?? []).map((model) => model.model_id),+ ...(agent.menu_kind === 'fixed' ? (agent.mappings ?? []).map((mapping) => mapping.builtin_id) : []),+ ];+ const seen = new Set<string>();+ return [...primary, ...extras].filter((modelId) => {+ if (!modelId || seen.has(modelId)) return false;+ seen.add(modelId);+ return true;+ });+}++/** One chain read per backend/model pair, even if a duplicated Agent row reaches the page. */+export function modelChainRequests(agents: AgentSupply[]): ModelChainRequest[] {+ const requests = new Map<string, ModelChainRequest>();+ for (const agent of agents) {+ if (agent.mode !== 'hub') continue;+ for (const modelId of listedModelIds(agent)) {+ const key = modelChainKey(agent.backend, modelId);+ if (!requests.has(key)) requests.set(key, { backend: agent.backend, modelId });+ }+ }+ return [...requests.values()];+}++/** Whether a row belongs in the non-healthy rollup, including automatic cooldowns. */+export function modelNeedsAttention(+ agent: AgentSupply,+ modelId: string,+ read: ModelChainRead | undefined,+ runtime?: RuntimeDependency | null,+): boolean {+ if (agent.mode !== 'hub') return false;+ if (read?.kind === 'error') return true;+ if (read?.kind === 'ready') {+ const head = read.chain.chain.find((link) => link.runnable);+ if (head?.channel === 'hub' && runtime && runtime.status.health !== 'ok') return true;+ return read.chain.supply_state !== 'ok';+ }+ return agent.model_supply?.find((model) => model.model_id === modelId)?.chain_length === 0;+}++export function agentNeedsModelSelection(agent: AgentSupply): boolean {+ return agent.mode === 'hub' && !agent.selected_model_id;+}++export function modelIssueCount(+ agents: AgentSupply[],+ chains: ModelChainIndex,+ runtime?: RuntimeDependency | null,+): number {+ return agents.reduce((count, agent) => {+ const modelIssues = listedModelIds(agent).filter((modelId) =>+ modelNeedsAttention(agent, modelId, chains[modelChainKey(agent.backend, modelId)], runtime),+ ).length;+ return count + modelIssues + (agentNeedsModelSelection(agent) ? 1 : 0);+ }, 0);+}diff --git a/ui/src/components/settings/models/repair.test.ts b/ui/src/components/settings/models/repair.test.tsindex 73b79ee4b..a83fd546f 100644--- a/ui/src/components/settings/models/repair.test.ts+++ b/ui/src/components/settings/models/repair.test.ts@@ -160,6 +160,18 @@ describe('repairAction — the one tap a stopped row offers (SourceRowMenu)', ()});});+describe('model-row repair routing', () => {+ it('routes retest through the server recovery endpoint and refreshes the shared rows', () => {+ const here = dirname(fileURLToPath(import.meta.url));+ const card = readFileSync(join(here, 'AgentCard.tsx'), 'utf8');+ const page = readFileSync(join(here, 'SettingsModelsPage.tsx'), 'utf8');++ expect(card).toMatch(/repair\?\.kind === 'retest'[\s\S]*?onRetest\(repair\.source\)/);+ expect(page).toMatch(/const retestSource = async \(source: Source\)[\s\S]*?modelsApi\.testSource\(source\.id\)/);+ expect(page).toMatch(/onRetest=\{\(source\) => void retestSource\(source\)\}/);+ });+});+const gap = (backend: SupplyGap['backend'], model_id: string): SupplyGap => ({ backend, model_id });describe('repairOutcome — 「did that fix it?」 (OAuthConnectDialog, ReplaceKeyDialog)', () => {@@ -577,7 +589,7 @@ describe('dryRunChainKey — which edits make a 试跑 report stop being about a});});-describe('dryRunOutcome — what the probe came back with (SourceOrderDrawer)', () => {+describe('dryRunOutcome — what the per-model probe came back with', () => {it('names the source the server actually started from', () => {// Not the first row in the order: the point of a dry run is which source the// chain resolved to, which can differ from what the list suggests.@@ -585,6 +597,7 @@ describe('dryRunOutcome — what the probe came back with (SourceOrderDrawer)',kind: 'ok',sourceName: 'Key B',latencyMs: 412,+ channel: 'hub',});});@@ -595,6 +608,7 @@ describe('dryRunOutcome — what the probe came back with (SourceOrderDrawer)',kind: 'ok',sourceName: 'src_gone',latencyMs: 412,+ channel: 'hub',});});@@ -609,6 +623,7 @@ describe('dryRunOutcome — what the probe came back with (SourceOrderDrawer)',kind: 'ok',sourceName: 'Key A',latencyMs: null,+ channel: 'native_cli',});});@@ -623,7 +638,7 @@ describe('dryRunOutcome — what the probe came back with (SourceOrderDrawer)',probe({ channel: 'native_cli', reachable: false, latency_ms: null, error: 'models.probe.native_cli_unavailable' }),[source()],),- ).toEqual({ kind: 'failed', sourceName: 'Key A', detailKey: 'models.probe.native_cli_unavailable' });+ ).toEqual({ kind: 'failed', sourceName: 'Key A', detailKey: 'models.probe.native_cli_unavailable', channel: 'native_cli' });});it('carries the server’s reason through on a failure', () => {@@ -631,7 +646,7 @@ describe('dryRunOutcome — what the probe came back with (SourceOrderDrawer)',dryRunOutcome(probe({ reachable: false, latency_ms: null, error: 'models.source.needs_action.credential_revoked' }), [source(),]),- ).toEqual({ kind: 'failed', sourceName: 'Key A', detailKey: 'models.source.needs_action.credential_revoked' });+ ).toEqual({ kind: 'failed', sourceName: 'Key A', detailKey: 'models.source.needs_action.credential_revoked', channel: 'hub' });});it('still reports a failure when the server named no reason', () => {@@ -642,6 +657,7 @@ describe('dryRunOutcome — what the probe came back with (SourceOrderDrawer)',kind: 'failed',sourceName: 'Key A',detailKey: null,+ channel: 'hub',});});});@@ -748,15 +764,15 @@ describe('probeArrival — an answer nobody wants can still be one the page owes);});- it('is how the drawer reads its own probe, at both arrivals', () => {+ it('is how each model row reads its own probe, at both arrivals', () => {// The regression this replaces was a `return` on the staleness guard ABOVE the// refetch, so the shape matters as much as the rule: no early exit may sit// between a probe arriving and the page being corrected.- const drawer = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'SourceOrderDrawer.tsx'), 'utf8');+ const drawer = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'AgentCard.tsx'), 'utf8');expect(drawer).not.toMatch(/if \(seq\.current !== mine\) return;/);expect((drawer.match(/probeArrival\(/g) ?? []).length).toBe(2);- expect(drawer).toMatch(/if \(arrival\.reread\) reread\(\);/);+ expect(drawer).toMatch(/if \(arrival\.reread\) onSettled\(\);/);// And takes `serverNamed` from the error rather than inferring it from 「is it// one of ours?」 — `bad_response` is one of ours and names nothing, so that// inference skipped the reread in the one case it was added for.@@ -764,6 +780,9 @@ describe('probeArrival — an answer nobody wants can still be one the page owesexpect(drawer).not.toMatch(/serverNamed: failure !== null/);// The code rides along so the second reason can be asked at all.expect(drawer).toMatch(/code: failure\?\.code \?\? null/);+ // Invalidating the request generation invalidates its busy state too; an old+ // finally block is no longer allowed to own the current button.+ expect(drawer).toMatch(/seq\.current \+= 1;\s+setRunning\(false\);/);});});@@ -976,9 +995,8 @@ describe('the class: no component decides a repair for itself', () => {it('leaves the chain key to its owner', () => {const offenders = files.filter((f) => INLINE_CHAIN_KEY.test(read(f)));expect(offenders).toEqual([]);- expect(read('SourceOrderDrawer.tsx')).toMatch(- /chainKey=\{dryRunChainKey\(agent, policy, order, sources\)\}/,- );+ expect(read('AgentCard.tsx')).toMatch(/modelsApi\.probeAgent\(agent\.backend, modelId\)/);+ expect(read('SourceOrderDrawer.tsx')).not.toMatch(/probeAgent|dryRunChainKey/);});/**@@ -994,11 +1012,11 @@ describe('the class: no component decides a repair for itself', () => {});it('keeps the dry-run failure as a reason, three states and all', () => {- const src = read('SourceOrderDrawer.tsx');+ const src = read('AgentCard.tsx');// `{ key: null }` is not the same as `null`: 「it failed and nobody named why」// has a sentence (the generic line), 「nothing ran yet」 has none.expect(src).toMatch(/useState<\{ key: string \| null \} \| null>\(null\)/);expect(src).toMatch(/setErrorReason\(\{ key: failure\?\.detail \?\? null \}\)/);- expect(src).toMatch(/errorReason && serverText\(t, errorReason\.key, 'settings\.models\.dryRun\.error'\)/);+ expect(src).toMatch(/serverText\(t, errorReason\.key, 'settings\.models\.probe\.error'\)/);});});diff --git a/ui/src/components/settings/models/repair.ts b/ui/src/components/settings/models/repair.tsindex e0e2066de..cd5dec363 100644--- a/ui/src/components/settings/models/repair.ts+++ b/ui/src/components/settings/models/repair.ts@@ -18,6 +18,7 @@ import type {SourcePolicy,SourceRepaired,SourceState,+ SupplyChannel,SupplyGap,} from './types';@@ -439,17 +440,17 @@ export const dryRunChainKey = (* wall-clock expiry it cannot prove.*/export type DryRunOutcome =- | { kind: 'ok'; sourceName: string; latencyMs: number | null }+ | { kind: 'ok'; sourceName: string; latencyMs: number | null; channel: SupplyChannel }/** v4 widened the key set past `state.detail_key`: the native branch reports* process unavailability, the case the paragraph above is about, and no* source-state key can express it. */- | { kind: 'failed'; sourceName: string; detailKey: ProbeErrorKey | null };+ | { kind: 'failed'; sourceName: string; detailKey: ProbeErrorKey | null; channel: SupplyChannel };export function dryRunOutcome(probe: ProbeResult, sources: Source[]): DryRunOutcome {const sourceName = nameOf(sources, probe.source_id);return probe.reachable- ? { kind: 'ok', sourceName, latencyMs: probe.latency_ms }- : { kind: 'failed', sourceName, detailKey: probe.error };+ ? { kind: 'ok', sourceName, latencyMs: probe.latency_ms, channel: probe.channel }+ : { kind: 'failed', sourceName, detailKey: probe.error, channel: probe.channel };}/**diff --git a/ui/src/components/settings/models/supply.test.ts b/ui/src/components/settings/models/supply.test.tsindex 91b678284..ac47d27dc 100644--- a/ui/src/components/settings/models/supply.test.ts+++ b/ui/src/components/settings/models/supply.test.ts@@ -288,19 +288,14 @@ describe('healthyButUnrunnable', () => {expect(healthyButUnrunnable(offOrder, nativeSource('src_c', ACTIVE))).toBe(true);});- it('is what BOTH of the order drawer’s source lines ask', () => {- // Round 4. The retraction was in the 启用 line only, so a row admitted it one- // step after the step it was about: availability is per (source, backend) and- // has nothing to do with where the source sits in the order.+ it('is absent from the ordering-only drawer', () => {+ // Supply truth moved to model rows. The drawer no longer makes availability+ // claims and therefore has no reason to derive process or model state.const drawer = readFileSync(join(__dirname, 'SourceOrderDrawer.tsx'), 'utf8');- expect([...drawer.matchAll(/healthyButUnrunnable\(agent, source\)/g)].length).toBe(2);- // The 未启用 branch REPLACES the line rather than joining it: both 供 … 全系 and- // its rewritten form are the promise being retracted, and the line is two- // segments wide.- expect(drawer).toMatch(/if \(healthyButUnrunnable\(agent, source\)\) return join\(\[identity\(source\), nativeUnavailable\(\)\]\);/);- // And nothing reaches around the shared predicate to the raw reader.+ expect(drawer).not.toMatch(/healthyButUnrunnable/);expect(drawer).not.toMatch(/processAvailabilityOf/);+ expect(drawer).not.toMatch(/viaMapping|via_mapping|builtin_models|models\.some/);});});diff --git a/ui/src/components/settings/models/supplyCopyRedline.test.ts b/ui/src/components/settings/models/supplyCopyRedline.test.tsindex f2b69391d..191d18236 100644--- a/ui/src/components/settings/models/supplyCopyRedline.test.ts+++ b/ui/src/components/settings/models/supplyCopyRedline.test.ts@@ -41,6 +41,13 @@ const CLASSIFIED: Record<string, string> = {type Leaf = { key: string; text: string };+const modelsRoot = (bundle: unknown): unknown => {+ if (!bundle || typeof bundle !== 'object') return undefined;+ const settings = (bundle as Record<string, unknown>).settings;+ if (!settings || typeof settings !== 'object') return undefined;+ return (settings as Record<string, unknown>).models;+};+function leaves(bundle: unknown): Leaf[] {const out: Leaf[] = [];const walk = (node: unknown, path: string[]) => {@@ -51,7 +58,7 @@ function leaves(bundle: unknown): Leaf[] {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, []);+ walk(modelsRoot(bundle), []);return out;}@@ -59,7 +66,7 @@ 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);+ }, modelsRoot(bundle));describe('Direct-fallback redline over settings.models copy', () => {it.each(['zh', 'en'] as const)('walks a non-trivial %s subtree', (lng) => {@@ -102,4 +109,19 @@ describe('Direct-fallback redline over settings.models copy', () => {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());});++ it.each(['zh', 'en'] as const)('names the per-Agent source order in %s route copy', (lng) => {+ const routeCopy = leaves(BUNDLES[lng]).filter((leaf) => leaf.key.startsWith('routes.'));+ expect(routeCopy.map((leaf) => leaf.text).join('\n')).not.toMatch(/全局顺序|global (?:source )?order/i);+ for (const key of [+ 'routes.global',+ 'routes.globalPending',+ 'routes.globalActual',+ 'routes.globalUnavailable',+ 'routes.orderDecidesSource',+ 'routes.openMenuGlobal',+ ]) {+ expect(lookup(BUNDLES[lng], key), `${key} does not name its backend in ${lng}`).toContain('{{backend}}');+ }+ });});diff --git a/ui/src/components/settings/models/vocabulary.test.ts b/ui/src/components/settings/models/vocabulary.test.tsnew file mode 100644index 000000000..87dd383b6--- /dev/null+++ b/ui/src/components/settings/models/vocabulary.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';++import zh from '../../../i18n/zh.json';++const leaves = (node: unknown): string[] =>+ typeof node === 'string'+ ? [node]+ : node && typeof node === 'object'+ ? Object.values(node as Record<string, unknown>).flatMap(leaves)+ : [];++describe('Models page vocabulary', () => {+ it('contains none of the retired user-facing terms', () => {+ const copy = leaves(zh.settings.models).join('\n');+ expect(copy).not.toMatch(/菜单固定|跟随推荐|中枢 Hub|按量\s*\$|映射|供给引擎|自定义顺序/);+ expect(zh.settings.models.order.customized).toBe('已改为手动');+ expect(zh.settings.models.order.restore).toBe('恢复默认');+ });+});diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 564d3c997..e854f77f7 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -612,9 +612,14 @@"openSetup": "Open setup wizard","models": {"title": "Models",- "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.",+ "subtitle": "See whether each agent model can run now and which source serves it; set a route for one model when needed.","addSource": "Add source","loadError": "Failed to load: {{detail}}",+ "status": {+ "allHealthy": "All healthy",+ "needsAction": "{{count}} model(s) need attention",+ "noIssues": "No models need attention"+ },"statusPill": {"ok": "All good · {{count}} on the Hub","none": "No agent is on the Hub yet",@@ -627,8 +632,12 @@},"sources": {"title": "Sources",- "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."+ "subtitle": "Manage shared accounts and model inventories; source order is set on each agent card",+ "empty": "No sources yet — use “Add source” to connect a subscription or API key.",+ "modelCount": "{{count}} model(s)",+ "addModel": "Add model",+ "modelsEmpty": "No supplied models yet. Add one manually.",+ "modelsEmptySubscription": "No supplied models were discovered."},"source": {"nativeSupply": "Native supply",@@ -647,40 +656,25 @@"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",+ "customized": "Changed manually",+ "restore": "Restore default","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.",+ "enabledEmpty": "{{backend}} has no source enabled, so its next turn will fail. Enable one from the list 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.",- "nativeUnavailable": "{{backend}} CLI sign-in unavailable here"+ "ineligibleClientUnknown": "{{vendor}} subscriptions only work in their own official client"},"billing": {"monthly": "Monthly",- "metered": "Metered",- "meteredWithSymbol": "Metered {{symbol}}"+ "metered": "Metered"},"state": {- "active": "In use",- "standby": "Standby",- "cooldown": "Cooling down",+ "active": "Healthy",+ "standby": "Healthy",+ "cooldown": "Cooling down (auto-recovers)","needs_action": "Needs attention",- "error": "Unavailable"+ "error": "Needs attention"},"usage": {"monthSpend": "{{amount}} this month"@@ -705,6 +699,10 @@"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",+ "modelListCount": "{{count}} model(s)",+ "enableManaged": "Manage centrally",+ "emptyModels": "This agent has no models yet.",+ "manageModels": "Manage models","menuKind": {"fixed": "Fixed menu","open": "Open menu"@@ -719,6 +717,57 @@"unassigned": "No source can supply {{models}}"}},+ "modelStatus": {+ "ok": "Healthy",+ "cooldown": "Cooling down (auto-recovers)",+ "needsAction": "Needs attention",+ "checking": "Checking",+ "direct": "Direct",+ "noSource": "No available source",+ "blocked": "Current source unavailable",+ "currentSwitched": "Currently switched to {{source}}",+ "currentSource": "Currently served by {{source}}",+ "source": "Served by {{source}}",+ "unknown": "Unable to confirm",+ "retry": "Retry",+ "runtime": "Model service is not ready",+ "runtimeAction": "Resolve"+ },+ "emptySelection": {+ "title": "No model selected",+ "body": "This agent has no current model and needs one before its next run.",+ "action": "Choose model"+ },+ "routes": {+ "title": "Supply method",+ "global": "Follow {{backend}}'s source order",+ "manual": "Set route",+ "liveSource": "Currently served by {{source}} · {{model}}",+ "globalPending": "Restoring {{backend}}'s source order…",+ "globalActual": "{{backend}}'s source order currently resolves to {{source}}.",+ "globalUnavailable": "No source in {{backend}}'s source order can serve right now.",+ "chooseTarget": "Choose target model",+ "searchPlaceholder": "Search sources or models",+ "empty": "No matching models",+ "availableCount": "{{count}} available",+ "manualBadge": "Manual",+ "addManual": "Enter a model manually",+ "multipleSources": "{{model}} · sources available: {{count}}",+ "orderDecidesSource": "Actual source follows {{backend}}'s source order",+ "compatibility": "Reasoning, cache, and tool semantics may differ from the original model.",+ "openMenuGlobal": "Open models use {{backend}}'s source order; {{source}} currently serves this one.",+ "none": "no source",+ "expand": "Expand supply method"+ },+ "probe": {+ "action": "Try it",+ "running": "Testing",+ "nativeReady": "{{source}} is ready and can run directly.",+ "hubOk": "{{source}} responded successfully · {{ms}} ms",+ "failed": "{{source}} failed: {{detail}}",+ "unknown": "Source did not pass the test",+ "error": "Test failed, please retry"+ },"recent": {"title": "Recent switches","viewAll": "View all",@@ -891,8 +940,8 @@}},"custom": {- "title": "Add a custom model",- "subtitle": "Register a model that discovery missed and add it to the OpenCode menu.",+ "title": "Add model manually",+ "subtitle": "Register a model missing from this source so it can be selected or used as a route target.","sourceLabel": "Source (able to supply this model)","modelIdLabel": "Model ID","modelIdPlaceholder": "glm-5.2-air",@@ -901,7 +950,7 @@"previewLabel": "OpenCode identifier · generated","previewEmpty": "Enter a model ID to preview","previewHint": "The provider segment is chosen automatically: a recognized vendor uses its standard ID (identical to native OpenCode), otherwise it falls under custom/. Adding or removing sources and switching modes never change the identifier.",- "add": "Add to menu",+ "add": "Add model","failed": "Couldn't add the model, please retry","delete": "Remove model","deleteConfirmTitle": "Remove custom model?",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 8c7617815..1e5e03b2f 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -612,13 +612,18 @@"openSetup": "打开设置向导","models": {"title": "模型",- "subtitle": "来源连一次,全局共用;每个 Agent 自己决定用哪些、先用谁,失败自动切换、恢复自动切回。",+ "subtitle": "按 Agent 查看每个型号现在能否运行、由谁供给;需要时可为单个型号指定路由。","addSource": "添加来源","loadError": "加载失败:{{detail}}",+ "status": {+ "allHealthy": "全部正常",+ "needsAction": "{{count}} 个模型需要处理",+ "noIssues": "没有需要处理的模型"+ },"statusPill": {"ok": "一切正常 · {{count}} 个 Agent 已接入中枢","none": "还没有 Agent 接入中枢",- "engineDown": "供给引擎未就绪 · 中枢暂时无法供给",+ "engineDown": "模型服务未就绪 · 暂时无法供给","interrupted": "{{count}} 个 Agent 供给中断 · 需要处理","waiting": "{{count}} 个 Agent 正在等待来源恢复","needsAction": "{{source}} {{detail}}",@@ -627,8 +632,12 @@},"sources": {"title": "来源",- "subtitle": "全局一份的账号库;谁先谁后,在下方各 Agent 里调",- "empty": "还没有来源,点“添加来源”连接订阅或 API Key。"+ "subtitle": "管理全局共用的账号和型号清单;来源顺序在各 Agent 卡片中调整",+ "empty": "还没有来源,点“添加来源”连接订阅或 API Key。",+ "modelCount": "{{count}} 个型号",+ "addModel": "添加型号",+ "modelsEmpty": "还没有可供给的型号,请手动添加。",+ "modelsEmptySubscription": "还没有发现可供给的型号。"},"source": {"nativeSupply": "原生供给",@@ -647,40 +656,25 @@"groupEnabled": "启用 · {{count}} 个来源","groupDisabled": "未启用 · {{count}}","groupIneligible": "不适用 · {{count}}",- "following": "跟随推荐中",- "followingLong": "跟随推荐中 · 新来源自动加入",- "restore": "恢复推荐顺序",+ "customized": "已改为手动",+ "restore": "恢复默认","enable": "启用","enableAria": "启用 {{name}}","disable": "取消启用",- "openMenu": "模型菜单与映射",- "supplies": "供 {{family}} 全系",- "viaMapping": "经模型菜单改写后可供 {{backend}} 使用",- "viaMappingShort": "经映射后可供 {{backend}}",- "enabledEmpty": "{{backend}} 没有启用任何来源,下一个回合会因为供给中断而失败——中枢不会替它回退到直连。从下面的「未启用」里加一个进来。",+ "enabledEmpty": "{{backend}} 没有启用任何来源,下一个回合会失败。请从下方启用一个来源。","ineligibleUnknown": "不能供 {{backend}} 使用",- "ineligibleClientUnknown": "{{vendor}} 订阅只能供它自己的官方客户端使用",- "family": {- "anthropic": "Claude",- "openai": "GPT",- "zhipuai": "GLM",- "kimi": "Kimi",- "xai": "Grok"- },- "enabledNoneRunnable": "{{backend}} 已启用的来源当前都无法供给,下一个回合会因为没有供给而失败。修好下面的某一个,或者再启用一个。",- "nativeUnavailable": "本机无法使用 {{backend}} CLI 登录"+ "ineligibleClientUnknown": "{{vendor}} 订阅只能供它自己的官方客户端使用"},"billing": {"monthly": "包月",- "metered": "按量",- "meteredWithSymbol": "按量 {{symbol}}"+ "metered": "按量"},"state": {- "active": "使用中",- "standby": "备用",- "cooldown": "暂不可用",+ "active": "正常",+ "standby": "正常",+ "cooldown": "冷却中(自动恢复)","needs_action": "需要处理",- "error": "不可用"+ "error": "需要处理"},"usage": {"monthSpend": "本月 {{amount}}"@@ -689,7 +683,7 @@"label": "供应:"},"mode": {- "hub": "中枢 Hub",+ "hub": "统一管理","direct": "直连 Direct"},"errors": {@@ -705,12 +699,16 @@"hubNoSupply": "已接入中枢 · 没有启用任何来源,下一个回合会失败","directNote": "仍在用 CLI 原生配置供给,未接入中枢","sourceOrder": "来源顺序",+ "modelListCount": "{{count}} 个型号",+ "enableManaged": "统一管理",+ "emptyModels": "这个 Agent 还没有型号。",+ "manageModels": "管理型号","menuKind": {- "fixed": "菜单固定",+ "fixed": "内置型号","open": "菜单开放"},"policy": {- "follow": "跟随推荐",+ "follow": "默认顺序","custom": "自定义"},"attribution": {@@ -719,6 +717,57 @@"unassigned": "{{models}} 暂无来源可供给"}},+ "modelStatus": {+ "ok": "正常",+ "cooldown": "冷却中(自动恢复)",+ "needsAction": "需要处理",+ "checking": "正在确认",+ "direct": "直连",+ "noSource": "没有可用来源",+ "blocked": "当前来源不可用",+ "currentSwitched": "当前已自动换到 {{source}}",+ "currentSource": "当前由 {{source}} 供给",+ "source": "由 {{source}} 供给",+ "unknown": "暂时无法确认",+ "retry": "重试",+ "runtime": "模型服务未就绪",+ "runtimeAction": "去处理"+ },+ "emptySelection": {+ "title": "尚未选择型号",+ "body": "这个 Agent 现在没有当前型号,下一次运行前需要选择。",+ "action": "选择型号"+ },+ "routes": {+ "title": "供给方式",+ "global": "跟随 {{backend}} 来源顺序",+ "manual": "指定路由",+ "liveSource": "当前由 {{source}} 供给 · {{model}}",+ "globalPending": "正在恢复 {{backend}} 来源顺序…",+ "globalActual": "按 {{backend}} 来源顺序,当前会由 {{source}} 供给。",+ "globalUnavailable": "{{backend}} 来源顺序里暂时没有可用来源。",+ "chooseTarget": "选择目标型号",+ "searchPlaceholder": "搜索来源或型号",+ "empty": "没有匹配的型号",+ "availableCount": "{{count}} 个",+ "manualBadge": "手动",+ "addManual": "手动输入型号",+ "multipleSources": "{{model}} · {{count}} 个来源可供给",+ "orderDecidesSource": "实际来源由 {{backend}} 来源顺序决定",+ "compatibility": "目标型号的思维链、缓存和工具语义可能与原型号不同。",+ "openMenuGlobal": "开放型号按 {{backend}} 来源顺序供给,当前由 {{source}} 负责。",+ "none": "暂无来源",+ "expand": "展开供给方式"+ },+ "probe": {+ "action": "试一下",+ "running": "正在测试",+ "nativeReady": "{{source}} 已就绪,可直接运行。",+ "hubOk": "{{source}} 返回正常 · {{ms}} ms",+ "failed": "{{source}} 未通过:{{detail}}",+ "unknown": "来源未通过测试",+ "error": "测试失败,请重试"+ },"recent": {"title": "最近切换","viewAll": "查看全部",@@ -853,8 +902,8 @@"enabled": "已自动加入 {{list}} 的来源顺序","entry": "{{name}}(第 {{position}} 位)","none": "还没有 Agent 启用它 · 到各 Agent 的「来源顺序」里加进来才会被使用",- "noneSkipped": "还没有 Agent 启用它 · {{skipped}} 使用自定义顺序,未加入——到那里手动加进来才会被使用",- "partlySkipped": "已自动加入 {{list}} 的来源顺序 · {{skipped}} 使用自定义顺序,未加入——到那里手动加进来才会被使用"+ "noneSkipped": "还没有 Agent 启用它 · {{skipped}} 已改为手动,未加入——到那里手动加进来才会被使用",+ "partlySkipped": "已自动加入 {{list}} 的来源顺序 · {{skipped}} 已改为手动,未加入——到那里手动加进来才会被使用"},"menus": {"done": "完成",@@ -863,7 +912,7 @@"enrolled": "已自动把「{{sources}}」加入 {{backend}} 的来源顺序,你选的模型才有来源可用","mapping": {"title": "{{backend}} · 模型菜单",- "subtitle": "菜单固定:{{backend}} 只认这些内置 model ID;每个 ID 可改写为其他模型供给,只影响 {{backend}}。",+ "subtitle": "{{backend}} 只认这些内置 model ID;每个 ID 可指定其他型号供给,只影响 {{backend}}。","builtinCol": "内置 MODEL ID","supplyCol": "实际供给","followNative": "跟随原生 · 按来源顺序供给",@@ -891,8 +940,8 @@}},"custom": {- "title": "添加自定义模型",- "subtitle": "补登来源清单里没有的模型,加入 OpenCode 菜单。",+ "title": "手动添加型号",+ "subtitle": "补登这个来源清单里没有的型号,可用于型号选择和指定路由。","sourceLabel": "来源(它能供应这个模型)","modelIdLabel": "模型 ID","modelIdPlaceholder": "glm-5.2-air",@@ -901,28 +950,28 @@"previewLabel": "OPENCODE 标识 · 自动生成","previewEmpty": "填入模型 ID 后预览","previewHint": "provider 段自动选:可识别厂商用标准 ID(与 OpenCode 原生一致),识别不了归 custom/;来源增减、模式切换都不影响标识。",- "add": "添加到菜单",+ "add": "添加型号","failed": "添加失败,请重试","delete": "删除模型","deleteConfirmTitle": "移除自定义模型?","deleteConfirmBody": "将从「{{source}}」的清单移除 {{model}}。","deleted": "已移除自定义模型","deleteFailed": "移除失败,请重试",- "deleteInUse": "该模型仍被某个 Agent 选用,请先在其菜单/映射里取消后再删除。"+ "deleteInUse": "该模型仍被某个 Agent 选用,请先在其菜单或指定路由里取消后再删除。"}},"supplyMode": {"title": "供给方式",- "currentHub": "当前:中枢 Hub",+ "currentHub": "当前:统一管理","currentDirect": "当前:直连 Direct",- "switchedHub": "已切换到中枢 Hub",+ "switchedHub": "已切换到统一管理","switchedDirect": "已切换到直连 Direct","switchFailed": "切换失败,请重试","hub": {"title": "中枢模式 · Hub","recommended": "推荐 · 默认","openModels": "打开模型页",- "description": "模型 token 由「设置 → 模型」统一供给:登录、API Key、来源顺序、映射都在那里管理。不改动 {{backend}} 的原生配置,随时可切走。"+ "description": "模型 token 由「设置 → 模型」统一供给:登录、API Key、来源顺序、指定路由都在那里管理。不改动 {{backend}} 的原生配置,随时可切走。"},"direct": {"title": "直连模式 · Direct",