Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): build Sources and Gateway UI (#1339)
Call White51d00a2e64b6
diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.jsonindex a0fa59a40..b8cd2708b 100644--- a/docs/plans/model-hub-contracts/mirror-registry.json+++ b/docs/plans/model-hub-contracts/mirror-registry.json@@ -547,15 +547,8 @@},"consumers": [{- "kind": "json_object_keys",- "file": "ui/src/i18n/en.json",- "path": "/settings/models/install/fail",- "prefix": "settings.models.install.fail."- },- {- "kind": "json_object_keys",- "file": "ui/src/i18n/zh.json",- "path": "/settings/models/install/fail",+ "kind": "marker",+ "file": "ui/src/components/settings/models/types.ts","prefix": "settings.models.install.fail."}]diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex d388fad61..647662c1a 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -58,13 +58,23 @@ def test_protocol_vocabulary_matches_authority_and_rejects_removed_alias():assert SOURCE_PROTOCOLS == protocolstype_source = (UI_MODEL_CONSUMERS / "types.ts").read_text(encoding="utf-8")+ tuple_match = re.search(+ r"export const SOURCE_PROTOCOLS\s*=\s*\[(.*?)\]\s*as const",+ type_source,+ re.DOTALL,+ )+ assert tuple_match is not None+ ui_protocols = tuple(re.findall(r"'([^']+)'", tuple_match.group(1)))+ assert frozenset(ui_protocols) == frozenset(protocols)+ assert len(ui_protocols) == len(set(ui_protocols))+type_match = re.search(r"export type SourceProtocol\s*=\s*(.*?);",type_source,re.DOTALL,)assert type_match is not None- assert tuple(re.findall(r"'([^']+)'", type_match.group(1))) == protocols+ assert re.sub(r"\s+", "", type_match.group(1)) == "(typeofSOURCE_PROTOCOLS)[number]"retired_alias = "openai" + "_compatible"for filename in (diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.jsonindex c9d861644..4397a372e 100644--- a/ui/eslint-baseline.json+++ b/ui/eslint-baseline.json@@ -35,9 +35,6 @@"src/components/settings/SettingsServicePage.tsx": {"@typescript-eslint/no-explicit-any": 4},- "src/components/settings/models/modelsApi.ts": {- "@typescript-eslint/no-explicit-any": 1- },"src/components/settings/providers/ClaudeProviderConfig.tsx": {"@typescript-eslint/no-explicit-any": 1},@@ -170,15 +167,6 @@"src/components/settings/SettingsBackendsPage.tsx": {"react-hooks/exhaustive-deps": 1},- "src/components/settings/models/SourceOrderDrawer.tsx": {- "react-hooks/exhaustive-deps": 1- },- "src/components/settings/models/menus/AddCustomModelDialog.tsx": {- "react-hooks/exhaustive-deps": 1- },- "src/components/settings/models/menus/OpenCodeMenuDrawer.tsx": {- "react-hooks/exhaustive-deps": 1- },"src/components/settings/providers/OpencodeProviderConfig.tsx": {"react-hooks/exhaustive-deps": 1},diff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsxnew file mode 100644index 000000000..bf367fa30--- /dev/null+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx@@ -0,0 +1,321 @@+// @vitest-environment jsdom+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import { AddApiKeyDialog } from './AddApiKeyDialog';+import { createSourceCollectionReadAuthority } from './collectionReadAuthority';+import { modelsApi } from './modelsApi';+import { CONTRACT_VERSION, SOURCE_DISPLAY_NAME_MAX_LENGTH, SOURCE_PROTOCOLS, type Source, type SourceObservation } from './types';++const observed = (patch: Partial<SourceObservation> = {}): SourceObservation => ({+ contract_version: CONTRACT_VERSION,+ outcome: 'observed',+ reachable: true,+ authenticated: 'authenticated',+ protocol: 'openai_chat',+ discovery: 'succeeded',+ models: ['model-a', 'model-b'],+ ...patch,+});++const source: Source = {+ id: 'src_new',+ last_discovered_at: null,+ kind: 'api_key',+ vendor: 'custom',+ display_name: 'Relay',+ protocol: 'openai_chat',+ base_url: 'https://relay.example/v1',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'standby', retry_at: null, detail_key: null },+ models: [],+};++const deferred = <T,>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+};++const renderDialog = (onClose = vi.fn(), onAdded = vi.fn()) => {+ render(+ <I18nextProvider i18n={i18n}>+ <AddApiKeyDialog open sourceReads={createSourceCollectionReadAuthority(modelsApi)} onClose={onClose} onAdded={onAdded} />+ </I18nextProvider>,+ );+ return { onClose, onAdded };+};++const fillCredentials = async () => {+ const user = userEvent.setup();+ await user.type(screen.getByRole('textbox', { name: /^Base URL$/i }), 'https://relay.example/v1');+ await user.type(screen.getByLabelText(/^API key$/i), 'secret-key');+ return user;+};++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('AddApiKeyDialog', () => {+ it('pulls models without persisting and drops the report when credentials change', async () => {+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(observed());+ const create = vi.spyOn(modelsApi, 'createApiKeySource');+ renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /Fetch models|拉取型号/i }));+ expect(await screen.findByText(/Fetched 2 models|拉到 2 个型号/i)).toBeTruthy();+ expect(create).not.toHaveBeenCalled();++ await user.type(screen.getByRole('textbox', { name: /^Base URL$/i }), '/changed');+ expect(screen.queryByText(/Fetched 2 models|拉到 2 个型号/i)).toBeNull();+ });++ it('uses the interface choice only as the next complete probe order', async () => {+ const observe = vi.spyOn(modelsApi, 'observeApiKeySource')+ .mockResolvedValueOnce(observed({+ outcome: 'ambiguous',+ authenticated: 'unknown',+ protocol: null,+ discovery: 'not_attempted',+ models: [],+ }))+ .mockResolvedValueOnce(observed({ protocol: 'openai_responses' }));+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValueOnce({+ source,+ added_to: [],+ adopted_by: [],+ });+ const { onAdded } = renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ const retry = await screen.findByRole('button', { name: /^Retry$|^重试$/i });+ expect((retry as HTMLButtonElement).disabled).toBe(true);+ await user.click(screen.getByRole('button', { name: 'OpenAI Responses' }));+ await user.click(retry);++ await waitFor(() => expect(create).toHaveBeenCalledOnce());+ const secondObservation = observe.mock.calls[1][0];+ expect(secondObservation.protocol_order?.[0]).toBe('openai_responses');+ expect(new Set(secondObservation.protocol_order)).toEqual(new Set(SOURCE_PROTOCOLS));+ expect(create.mock.calls[0][0]).not.toHaveProperty('protocol');+ expect(create.mock.calls[0][0].protocol_order?.[0]).toBe('openai_responses');+ expect(onAdded).toHaveBeenCalledWith({ source, added_to: [], adopted_by: [] });+ });++ it('retries the complete observation from inventory failure and persists only through Add anyway', async () => {+ const inventory = observed({ discovery: 'failed', models: [] });+ const observe = vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValue(inventory);+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValue({+ source,+ added_to: [],+ adopted_by: [],+ });+ renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await screen.findByRole('button', { name: /Add anyway|仍要添加/i });+ await user.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));+ await waitFor(() => expect(observe).toHaveBeenCalledTimes(2));+ expect(create).not.toHaveBeenCalled();+ expect(screen.queryByText(/The list could not be read|清单没能读出来/i)).toBeNull();++ await user.click(await screen.findByRole('button', { name: /Add anyway|仍要添加/i }));+ await waitFor(() => expect(create).toHaveBeenCalledOnce());+ expect(create.mock.calls[0][0]).not.toHaveProperty('protocol');+ expect(create.mock.calls[0][0].protocol_order?.[0]).toBe('openai_chat');+ });++ it('adopts the new observation result when inventory retry moves to interface undetermined', async () => {+ const inventory = observed({ discovery: 'failed', models: [] });+ const ambiguous = observed({+ outcome: 'ambiguous',+ authenticated: 'unknown',+ protocol: null,+ discovery: 'not_attempted',+ models: [],+ });+ const observe = vi.spyOn(modelsApi, 'observeApiKeySource')+ .mockResolvedValueOnce(inventory)+ .mockResolvedValueOnce(ambiguous);+ renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await screen.findByRole('button', { name: /Add anyway|仍要添加/i });+ await user.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));++ await waitFor(() => expect(observe).toHaveBeenCalledTimes(2));+ expect(await screen.findByText(/cannot tell which interface|无法判断是哪种接口/i)).toBeTruthy();+ expect(screen.queryByRole('button', { name: /Add anyway|仍要添加/i })).toBeNull();+ });++ it('aborts an in-flight pull and returns to the form without dismissing', async () => {+ let wasAborted = false;+ vi.spyOn(modelsApi, 'observeApiKeySource').mockImplementation((_draft, signal) => new Promise((_resolve, reject) => {+ signal?.addEventListener('abort', () => {+ wasAborted = true;+ reject(new DOMException('aborted', 'AbortError'));+ }, { once: true });+ }));+ const { onClose } = renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /Fetch models|拉取型号/i }));+ await user.click(screen.getAllByRole('button', { name: /^Cancel$|^取消$/i }).at(-1)!);++ expect(wasAborted).toBe(true);+ expect(onClose).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: /Fetch models|拉取型号/i })).toBeTruthy();+ });++ it('reconciles a lost source-create response by nonce without posting twice', async () => {+ let nonce: string | undefined;+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(observed());+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockImplementationOnce(async (draft) => {+ nonce = draft.client_nonce;+ throw new TypeError('response lost');+ });+ const list = vi.spyOn(modelsApi, 'listSources').mockImplementation(async () => [{+ ...source,+ client_nonce: nonce,+ adopted_by: [],+ }]);+ const { onAdded } = renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));++ await waitFor(() => expect(onAdded).toHaveBeenCalledOnce());+ expect(list).toHaveBeenCalledOnce();+ expect(create).toHaveBeenCalledOnce();+ expect(nonce).toMatch(/^scn_[a-z0-9]{16,64}$/);+ });++ it('retries source creation only after the nonce is confirmed absent', async () => {+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(observed());+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockRejectedValueOnce(new TypeError('response lost'))+ .mockResolvedValueOnce({ source, added_to: [], adopted_by: [] });+ const list = vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([]);+ renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));++ await waitFor(() => expect(create).toHaveBeenCalledTimes(2));+ expect(list).toHaveBeenCalledOnce();+ expect(create.mock.calls[1][0].client_nonce).toBe(create.mock.calls[0][0].client_nonce);+ });++ it('cannot create or navigate after cancelling a pending lost-response reconciliation', async () => {+ const pendingInventory = deferred<Source[]>();+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(observed());+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockRejectedValueOnce(new TypeError('response lost'));+ vi.spyOn(modelsApi, 'listSources').mockReturnValueOnce(pendingInventory.promise);+ const { onAdded, onClose } = renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));+ await user.click(screen.getAllByRole('button', { name: /^Cancel$|^取消$/i }).at(-1)!);+ pendingInventory.resolve([]);+ await pendingInventory.promise;++ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());+ expect(create).toHaveBeenCalledOnce();+ expect(onAdded).not.toHaveBeenCalled();+ });++ it('cannot replay a reconciled Source after the dialog attempt is cancelled', async () => {+ const pendingInventory = deferred<Source[]>();+ let nonce: string | undefined;+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(observed());+ vi.spyOn(modelsApi, 'createApiKeySource').mockImplementationOnce(async (draft) => {+ nonce = draft.client_nonce;+ throw new TypeError('response lost');+ });+ vi.spyOn(modelsApi, 'listSources').mockReturnValueOnce(pendingInventory.promise);+ const { onAdded } = renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));+ await user.click(screen.getAllByRole('button', { name: /^Cancel$|^取消$/i }).at(-1)!);+ pendingInventory.resolve([{ ...source, client_nonce: nonce }]);+ await pendingInventory.promise;++ expect(onAdded).not.toHaveBeenCalled();+ });++ it('rejects a trimmed blank or overlong display name before observation', async () => {+ const observe = vi.spyOn(modelsApi, 'observeApiKeySource');+ renderDialog();+ const user = await fillCredentials();+ const name = screen.getByRole('textbox', { name: /^Name|^名称/i });+ const add = screen.getByRole('button', { name: /^Add$|^添加$/i }) as HTMLButtonElement;++ await user.type(name, ' ');+ expect(add.disabled).toBe(true);+ await user.clear(name);+ await user.type(name, 'x'.repeat(SOURCE_DISPLAY_NAME_MAX_LENGTH + 1));+ expect(add.disabled).toBe(true);+ await user.click(add);+ expect(observe).not.toHaveBeenCalled();+ });++ it('counts supplementary display-name characters as JSON Schema code points', async () => {+ renderDialog();+ const user = await fillCredentials();+ const name = screen.getByRole('textbox', { name: /^Name|^名称/i });+ const add = screen.getByRole('button', { name: /^Add$|^添加$/i }) as HTMLButtonElement;++ await user.type(name, '😀'.repeat(SOURCE_DISPLAY_NAME_MAX_LENGTH));+ expect(add.disabled).toBe(false);+ await user.type(name, '😀');+ expect(add.disabled).toBe(true);+ });++ it('keeps a server-named create validation failure editable and out of save reconciliation', async () => {+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {+ if (String(input) === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });+ return Response.json({ ok: false, error: 'invalid_source', detail: 'modelHub.errors.discovery_failed' }, { status: 422 });+ }));+ let validationError: unknown;+ try {+ await modelsApi.createApiKeySource({ kind: 'api_key', vendor: 'custom', base_url: 'https://relay.example/v1', key: 'secret-key' });+ } catch (error) {+ validationError = error;+ }+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(observed());+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockRejectedValue(validationError);+ const list = vi.spyOn(modelsApi, 'listSources');+ renderDialog();+ const user = await fillCredentials();+ const name = screen.getByRole('textbox', { name: /^Name|^名称/i });+ await user.type(name, 'Relay');++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));++ expect(await screen.findByText(i18n.t('settings.models.addKey.fail.unclassified'))).toBeTruthy();+ expect(screen.queryByText('modelHub.errors.discovery_failed')).toBeNull();+ expect((name as HTMLInputElement).disabled).toBe(false);+ expect(screen.queryByText(/not confirmed saved|确认.*保存/i)).toBeNull();+ expect(list).not.toHaveBeenCalled();+ await user.clear(name);+ await user.type(name, 'Fixed relay');+ expect(screen.getByRole('button', { name: /^Add$|^添加$/i })).toBeTruthy();+ expect(create).toHaveBeenCalledOnce();+ });+});diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsxindex 94120ab6b..f66bda052 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx@@ -1,223 +1,455 @@-// 添加 API Key dialog (frame 06r): the only form dialog for adding a source.-// Vendor picker prefills the official base URL (editable for compatible /-// relay endpoints); the primary button is test-and-add — it validates the key,-// discovers models, and reports the count before the dialog dismisses.import * as React from 'react';-import { CheckCircle2, Globe, KeyRound, Plus, TriangleAlert } from 'lucide-react';+import * as DialogPrimitive from '@radix-ui/react-dialog';+import {+ CheckCircle2,+ CircleX,+ Eye,+ EyeOff,+ Info,+ LoaderCircle,+ PlugZap,+ TriangleAlert,+ X,+} from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';import { Input } from '@/components/ui/input';-import { Select } from '@/components/ui/select';-import { modelsApi, type Adoption } from './modelsApi';-import { AdoptionNote } from './AdoptionNote';+import { cn } from '@/lib/utils';import { Field } from './dialogFields';-import { adoptionVerdict } from './sufficiency';-import { DEFAULT_VENDOR, VENDOR_OPTIONS } from './vendorMeta';-import type { Source } from './types';-import { errorMessage } from '@/lib/errorMessage';+import {+ classifyObservation,+ isAbortError,+ PROTOCOL_COPY_KEYS,+ protocolOrderWithHint,+ type AddApiKeyFailure,+ type AddApiKeyOrigin,+} from './addApiKeyState';+import type { CollectionReadAuthority } from './collectionReadAuthority';+import { apiFailure, modelsApi, type SourceCreated } from './modelsApi';+import { createContinuationSettlement, createSourceCreatedDelivery, type ContinuationTicket } from './mutationSettlement';+import { reconcileUnknownWrite } from './reconcileUnknownWrite';+import { serverText } from './serverCopy';+import {+ SOURCE_DISPLAY_NAME_MAX_LENGTH,+ SOURCE_PROTOCOLS,+ type ApiKeySourceCreate,+ type Source,+ type SourceObservation,+ type SourceProtocol,+} from './types';+import { optionalTrimmedTextWithin } from './validation';-/** Nothing created yet. `skipped_by: null` rather than `[]` for the reason the- * reader defaults it that way: 「nobody was left out」 is a claim, and no- * creation has made it. */-const NO_ADOPTION: Adoption = { adopted_by: [], skipped_by: null };+type Phase =+ | { kind: 'form'; report: SourceObservation | null }+ | { kind: 'working'; origin: AddApiKeyOrigin; stage: 'observe' | 'persist' }+ | { kind: 'failure'; origin: AddApiKeyOrigin; cause: AddApiKeyFailure }+ | { kind: 'undetermined'; origin: AddApiKeyOrigin; observation: SourceObservation; hint: SourceProtocol | null }+ | { kind: 'inventory'; origin: AddApiKeyOrigin; observation: SourceObservation }+ | { kind: 'persist_failure'; messageKey: string | null; protocolOrder: SourceProtocol[] | undefined }+ | { kind: 'save_unconfirmed'; protocolOrder: SourceProtocol[] | undefined };++const INITIAL_PHASE: Phase = { kind: 'form', report: null };++const sourceClientNonce = (): string => {+ const uuid = globalThis.crypto.randomUUID?.();+ if (uuid) return `scn_${uuid.replaceAll('-', '').toLowerCase()}`;+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));+ return `scn_${Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('')}`;+};-type Phase = 'edit' | 'submitting' | 'done' | 'error';+const failureCopy = (cause: AddApiKeyFailure): string => {+ switch (cause) {+ case 'auth': return 'settings.models.addKey.fail.auth';+ case 'network': return 'settings.models.addKey.fail.network';+ case 'engineDown': return 'settings.models.addKey.fail.engineDown';+ case 'unclassified': return 'settings.models.addKey.fail.unclassified';+ }+};export const AddApiKeyDialog: React.FC<{open: boolean;onClose: () => void;- onAdded: (source: Source) => void;-}> = ({ open, onClose, onAdded }) => {+ onAdded: (created: SourceCreated) => void;+ sourceReads: CollectionReadAuthority<Source[]>;+}> = ({ open, onClose, onAdded, sourceReads }) => {const { t } = useTranslation();- const [vendor, setVendor] = React.useState(DEFAULT_VENDOR.value);- const [apiKey, setApiKey] = React.useState('');+ const [displayName, setDisplayName] = React.useState('');const [baseUrl, setBaseUrl] = React.useState('');- const [phase, setPhase] = React.useState<Phase>('edit');- const [discovered, setDiscovered] = React.useState(0);- // One state for both halves of the tail: the note and the auto-close timer each- // read both, and two states could hold one half of an older response.- const [adoption, setAdoption] = React.useState<Adoption>(NO_ADOPTION);- const [error, setError] = React.useState<string | null>(null);- const closeTimer = React.useRef<number | null>(null);- // Bumped on every open/close so a test-and-add resolving after the dialog was- // closed or reopened is dropped instead of clobbering the new state.- const submitSeq = React.useRef(0);-- // Reset the form each time the dialog opens; clear any pending auto-close.+ const [apiKey, setApiKey] = React.useState('');+ const [revealed, setRevealed] = React.useState(false);+ const [phase, setPhase] = React.useState<Phase>(INITIAL_PHASE);+ const [continuation] = React.useState(createContinuationSettlement);+ const [createdDelivery] = React.useState(createSourceCreatedDelivery);+ const clientNonce = React.useRef(sourceClientNonce());+ const observationAbort = React.useRef<AbortController | null>(null);React.useEffect(() => {- submitSeq.current += 1;+ createdDelivery.update(onAdded, onClose);+ }, [createdDelivery, onAdded, onClose]);++ React.useEffect(() => {+ continuation.invalidate();+ observationAbort.current?.abort();+ observationAbort.current = null;if (open) {- setVendor(DEFAULT_VENDOR.value);+ clientNonce.current = sourceClientNonce();+ setDisplayName('');+ setBaseUrl('');setApiKey('');- setBaseUrl(DEFAULT_VENDOR.base_url ?? '');- setPhase('edit');- setDiscovered(0);- setAdoption(NO_ADOPTION);- setError(null);+ setRevealed(false);+ setPhase(INITIAL_PHASE);}- return () => {- if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);- };- }, [open]);-- const onVendorChange = (value: string) => {- setVendor(value);- const meta = VENDOR_OPTIONS.find((v) => v.value === value);- // Official vendors prefill their base URL (editable); 自定义 clears it.- setBaseUrl(meta?.base_url ?? '');- };+ }, [continuation, open]);++ const draft = React.useCallback((protocolOrder?: SourceProtocol[]): ApiKeySourceCreate => ({+ kind: 'api_key',+ vendor: 'custom',+ ...(displayName.trim() ? { display_name: displayName.trim() } : {}),+ base_url: baseUrl.trim(),+ key: apiKey.trim(),+ client_nonce: clientNonce.current,+ ...(protocolOrder ? { protocol_order: protocolOrder } : {}),+ }), [apiKey, baseUrl, displayName]);- const submit = async () => {- if (!apiKey.trim()) return;- const seq = submitSeq.current;- setPhase('submitting');- setError(null);+ const persist = React.useCallback(async (seq: ContinuationTicket, protocolOrder?: SourceProtocol[]) => {+ if (continuation.settle(seq, () => setPhase({ kind: 'working', origin: 'add', stage: 'persist' })) === 'stale') return;try {- const { source, adopted_by, skipped_by } = await modelsApi.createApiKeySource({- kind: 'api_key',- vendor,- base_url: baseUrl.trim() || null,+ const created = await modelsApi.createApiKeySource(draft(protocolOrder));+ createdDelivery.settle(continuation, seq, created);+ } catch (error) {+ const failure = apiFailure(error);+ const definitiveClientFailure = failure?.serverNamed+ && failure.responseStatus !== undefined+ && failure.responseStatus >= 400+ && failure.responseStatus < 500+ && failure.responseStatus !== 409;+ continuation.settle(seq, () => setPhase(definitiveClientFailure+ ? { kind: 'persist_failure', messageKey: failure.detail ?? failure.code ?? null, protocolOrder }+ : { kind: 'save_unconfirmed', protocolOrder }));+ }+ }, [continuation, createdDelivery, draft]);++ const observe = React.useCallback(async (+ origin: AddApiKeyOrigin,+ protocolOrder?: SourceProtocol[],+ ) => {+ const seq = continuation.begin();+ observationAbort.current?.abort();+ const controller = new AbortController();+ observationAbort.current = controller;+ setPhase({ kind: 'working', origin, stage: 'observe' });+ try {+ const observation = await modelsApi.observeApiKeySource({+ vendor: 'custom',+ base_url: baseUrl.trim(),key: apiKey.trim(),+ ...(protocolOrder ? { protocol_order: protocolOrder } : {}),+ }, controller.signal);+ const verdict = classifyObservation(observation);+ let persistNext = false;+ const landed = continuation.settle(seq, () => {+ observationAbort.current = null;+ if (verdict.kind === 'ready') {+ if (origin === 'pull') setPhase({ kind: 'form', report: observation });+ else persistNext = true;+ } else if (verdict.kind === 'undetermined') {+ setPhase({ kind: 'undetermined', origin, observation, hint: null });+ } else if (verdict.kind === 'inventory') {+ setPhase({ kind: 'inventory', origin, observation });+ } else {+ setPhase({ kind: 'failure', origin, cause: verdict.cause });+ }+ });+ if (landed === 'landed' && persistNext) await persist(seq, protocolOrder);+ } catch (error) {+ if (isAbortError(error)) return;+ continuation.settle(seq, () => {+ observationAbort.current = null;+ setPhase({+ kind: 'failure',+ origin,+ cause: apiFailure(error)?.code === 'engine_down' ? 'engineDown' : 'unclassified',+ });});- if (submitSeq.current !== seq) return; // dialog closed/reopened mid-request- setDiscovered(source.models.length);- setAdoption({ adopted_by, skipped_by });- setPhase('done');- onAdded(source);- // Auto-dismiss only when the note is pure confirmation. 「还没有 Agent- // 启用它」 is an instruction, and 1.5s is not long enough to read one — a- // dialog that closes itself over that sentence is how the user ends up- // believing a working key is in service.- //- // `covered` and nothing weaker: a non-empty adopter list does not rule out a- // `custom` backend that skipped the key, and that sentence is an instruction- // too. `skipped_by` is what makes `covered` reachable at all — a server that- // omits it leaves the verdict `indeterminate`, and the dialog waits, which is- // the same answer this site gave before the field existed.- if (adoptionVerdict(adopted_by, skipped_by).kind === 'covered')- closeTimer.current = window.setTimeout(onClose, 1500);- } catch (e) {- if (submitSeq.current !== seq) return;- // The engine reports a machine-readable `code`; fall back to the message- // and then to a generic key so the copy lookup always has something.- const rawCode = (e as { code?: unknown } | null | undefined)?.code;- const code = (typeof rawCode === 'string' ? rawCode : undefined) || errorMessage(e) || 'discovery_failed';- setError(code === 'engine_down' ? (t('settings.models.errors.engineDown') as string) : code);- setPhase('error');}+ }, [apiKey, baseUrl, continuation, persist]);++ const cancel = React.useCallback(() => {+ if (phase.kind === 'working' && phase.stage === 'persist') return;+ continuation.invalidate();+ observationAbort.current?.abort();+ observationAbort.current = null;+ if ('origin' in phase && phase.origin === 'pull') {+ setPhase(INITIAL_PHASE);+ return;+ }+ createdDelivery.close();+ }, [continuation, createdDelivery, phase]);++ const retry = async () => {+ if (phase.kind === 'undetermined') {+ if (!phase.hint) return;+ await observe(phase.origin, protocolOrderWithHint(phase.hint));+ return;+ }+ if (phase.kind === 'inventory') {+ const order = phase.observation.protocol+ ? protocolOrderWithHint(phase.observation.protocol)+ : undefined;+ // 2026-08-11 ruling: retry repeats the complete observation. There is no+ // inventory-only credential lifetime or server capability.+ await observe(phase.origin, order);+ return;+ }+ if (phase.kind === 'save_unconfirmed') {+ const seq = continuation.begin();+ const reconciliation = await reconcileUnknownWrite(+ () => sourceReads.readValue(),+ (sources) => sources.find((source) => source.client_nonce === clientNonce.current),+ );+ if (reconciliation.kind === 'committed') {+ createdDelivery.settle(continuation, seq, {+ source: reconciliation.value,+ added_to: [],+ adopted_by: reconciliation.value.adopted_by ?? [],+ });+ return;+ }+ if (reconciliation.kind === 'absent') {+ await persist(seq, phase.protocolOrder);+ }+ return;+ }+ if (phase.kind === 'persist_failure') {+ await persist(continuation.begin(), phase.protocolOrder);+ return;+ }+ if (phase.kind === 'failure') await observe(phase.origin);+ };++ const addAnyway = async () => {+ if (phase.kind !== 'inventory' || phase.origin !== 'add' || !phase.observation.protocol) return;+ const seq = continuation.begin();+ await persist(seq, protocolOrderWithHint(phase.observation.protocol));+ };++ const editEndpoint = (value: string) => {+ setBaseUrl(value);+ if (phase.kind === 'form' && phase.report) setPhase(INITIAL_PHASE);+ };+ const editKey = (value: string) => {+ setApiKey(value);+ if (phase.kind === 'form' && phase.report) setPhase(INITIAL_PHASE);+ };+ const editDisplayName = (value: string) => {+ setDisplayName(value);+ if (phase.kind === 'persist_failure') setPhase(INITIAL_PHASE);};+ const isWorking = phase.kind === 'working';+ const formLocked = isWorking || phase.kind === 'save_unconfirmed';+ const canCancel = !(phase.kind === 'working' && phase.stage === 'persist');+ const displayNameValid = optionalTrimmedTextWithin(displayName, SOURCE_DISPLAY_NAME_MAX_LENGTH);+ const canObserve = Boolean(baseUrl.trim() && apiKey.trim()) && !formLocked;+ const canSubmit = canObserve && displayNameValid;+ const showForm = phase.kind !== 'undetermined' && phase.kind !== 'inventory';return (- // Block close (Esc / overlay / X) while the test-and-add request is in- // flight — the source is provisioned server-side, so closing mid-request- // would leave a created source the UI never reflected.- <Dialog open={open} onOpenChange={(v) => !v && phase !== 'submitting' && onClose()}>- <DialogContent className="max-w-[560px] gap-5">- <DialogHeader>- <DialogTitle className="text-[18px] font-bold">{t('settings.models.addKey.title')}</DialogTitle>- <DialogDescription>{t('settings.models.addKey.subtitle')}</DialogDescription>- </DialogHeader>-- <Field label={t('settings.models.addKey.vendorLabel')} hint={t('settings.models.addKey.vendorHint')}>- {(id) => (- <Select- id={id}- value={vendor}- onChange={(e) => onVendorChange(e.target.value)}- className="h-11 text-[14px]"+ <DialogPrimitive.Root open={open} onOpenChange={(next) => !next && canCancel && cancel()}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay className="model-hub-add-key-overlay fixed inset-0 z-50" />+ <DialogPrimitive.Content+ className="model-hub-add-key-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col gap-0 overflow-y-auto border border-border-strong bg-surface p-0 shadow-xl outline-none"+ onEscapeKeyDown={(event) => { if (!canCancel) event.preventDefault(); }}+ onPointerDownOutside={(event) => { if (!canCancel) event.preventDefault(); }}+ >+ <header className="model-hub-add-key-head flex flex-col border-b border-border px-5 py-4">+ <div className="flex items-center justify-between gap-3">+ <DialogPrimitive.Title className="model-hub-add-key-title font-bold text-foreground">+ {t('settings.models.addKey.title')}+ </DialogPrimitive.Title>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="model-hub-ink-white-59 size-[27px]"+ aria-label={t('settings.models.addKey.cancel')}+ disabled={!canCancel}+ onClick={cancel}>- {VENDOR_OPTIONS.map((v) => (- <option key={v.value} value={v.value}>- {t(v.labelKey)}- </option>- ))}- </Select>- )}- </Field>-- <Field label={t('settings.models.addKey.keyLabel')} mono icon={KeyRound}>- {(id) => (- <Input- id={id}- type="password"- autoComplete="off"- spellCheck={false}- placeholder={t('settings.models.field.apiKeyPlaceholder')}- value={apiKey}- onChange={(e) => setApiKey(e.target.value)}- className="h-11 pl-9 font-mono text-[14px]"- disabled={phase === 'submitting' || phase === 'done'}- />- )}- </Field>+ <X className="size-[15px]" />+ </Button>+ </div>+ <DialogPrimitive.Description className="model-hub-add-key-subtitle model-hub-ink-muted-b3 font-mono">+ {t('settings.models.addKey.subtitle')}+ </DialogPrimitive.Description>+ </header>- <Field- label={t('settings.models.addKey.baseUrlLabel')}- mono- icon={Globe}- hint={t('settings.models.addKey.baseUrlHint')}- >- {(id) => (- <Input- id={id}- type="text"- autoComplete="off"- spellCheck={false}- placeholder={t('settings.models.field.baseUrlPlaceholder')}- value={baseUrl}- onChange={(e) => setBaseUrl(e.target.value)}- className="h-11 pl-9 font-mono text-[14px]"- disabled={phase === 'submitting' || phase === 'done'}- />- )}- </Field>+ {showForm && (+ <div className="model-hub-add-key-body flex flex-col">+ <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={t('settings.models.addKey.field.name')}>+ {(id) => <Input id={id} value={displayName} disabled={formLocked} aria-invalid={!displayNameValid} onChange={(event) => editDisplayName(event.target.value)} className="model-hub-add-key-input" />}+ </Field>+ <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" hintClassName="model-hub-add-key-hint" label={t('settings.models.addKey.field.baseUrl')} hint={t('settings.models.addKey.field.baseUrl.hint')}>+ {(id) => <Input id={id} value={baseUrl} disabled={formLocked} autoComplete="url" spellCheck={false} onChange={(event) => editEndpoint(event.target.value)} className="model-hub-add-key-input font-mono" />}+ </Field>+ <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={t('settings.models.addKey.field.apiKey')}>+ {(id) => <span className="model-hub-add-key-secret relative flex items-center"><Input id={id} value={apiKey} type={revealed ? 'text' : 'password'} disabled={formLocked} autoComplete="off" spellCheck={false} onChange={(event) => editKey(event.target.value)} className="model-hub-add-key-input w-full pr-10 font-mono" /><Button type="button" variant="ghost" size="icon" className="model-hub-ink-white-59 absolute right-1 size-7" aria-label={t(`settings.models.addKey.field.apiKey.${revealed ? 'conceal' : 'reveal'}`)} disabled={formLocked} onClick={() => setRevealed((value) => !value)}>{revealed ? <EyeOff className="size-3.5" /> : <Eye className="size-3.5" />}</Button></span>}+ </Field>++ {!isWorking && (+ <div className="model-hub-add-key-test-row flex items-center justify-between gap-4">+ <Button+ type="button"+ variant="outline"+ className="model-hub-add-key-secondary"+ disabled={!canObserve}+ onClick={() => void observe('pull')}+ >+ <PlugZap className="size-3" />+ {t('settings.models.addKey.test')}+ </Button>+ <span className="model-hub-add-key-hint">{t('settings.models.addKey.test.hint')}</span>+ </div>+ )}++ {phase.kind === 'form' && phase.report && (+ <div className="model-hub-add-key-strip model-hub-add-key-strip--success">+ <CheckCircle2 className="model-hub-ink-mint size-3.5 shrink-0" />+ <span>{phase.report.models.length === 0+ ? t('settings.models.addKey.pull.empty')+ : t('settings.models.addKey.pull.result', { count: phase.report.models.length })}</span>+ </div>+ )}+ {phase.kind === 'working' && (+ <div className="model-hub-add-key-strip model-hub-add-key-strip--working">+ <LoaderCircle className="model-hub-ink-mint size-3.5 shrink-0 animate-spin" />+ <div className="flex min-w-0 flex-col gap-[3px]">+ <span className="model-hub-add-key-strip-title text-foreground">{t('settings.models.addKey.adding')}</span>+ <span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.adding.detail')}</span>+ </div>+ </div>+ )}+ {phase.kind === 'failure' && (+ <div className="model-hub-add-key-strip model-hub-add-key-strip--error">+ <CircleX className="model-hub-add-key-error-ink size-3.5 shrink-0" />+ <div className="flex min-w-0 flex-col gap-[3px]">+ <span className="model-hub-add-key-error-ink model-hub-add-key-strip-title">{t(failureCopy(phase.cause))}</span>+ {phase.cause === 'auth' && <span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.fail.auth.detail')}</span>}+ {phase.cause !== 'engineDown' && <span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.fail.subtitle')}</span>}+ </div>+ </div>+ )}+ {phase.kind === 'save_unconfirmed' && (+ <div className="model-hub-add-key-strip model-hub-add-key-strip--error">+ <CircleX className="model-hub-add-key-error-ink size-3.5 shrink-0" />+ <span className="model-hub-add-key-error-ink model-hub-add-key-strip-title">{t('settings.models.addKey.fail.save')}</span>+ </div>+ )}+ {phase.kind === 'persist_failure' && (+ <div className="model-hub-add-key-strip model-hub-add-key-strip--error">+ <CircleX className="model-hub-add-key-error-ink size-3.5 shrink-0" />+ <span className="model-hub-add-key-error-ink model-hub-add-key-strip-title">+ {serverText(t, phase.messageKey, 'settings.models.addKey.fail.unclassified')+ ?? t('settings.models.addKey.fail.unclassified')}+ </span>+ </div>+ )}+ </div>+ )}- {phase === 'done' && (- <div className="flex flex-col gap-2">- <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">- <CheckCircle2 className="size-4 shrink-0" />- <span>{t('settings.models.addKey.discovered', { count: discovered })}</span>+ {phase.kind === 'undetermined' && (+ <div className="model-hub-add-key-outcome flex flex-col">+ <div className="model-hub-add-key-outcome-wrap">+ <div className="model-hub-add-key-strip model-hub-add-key-strip--advisory">+ <Info className="model-hub-ink-gold size-3.5 shrink-0" />+ <div className="flex min-w-0 flex-col gap-[3px]">+ <span className="model-hub-add-key-strip-title model-hub-ink-gold">{t('settings.models.addKey.undetermined.title')}</span>+ <span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.undetermined.detail')}</span>+ </div>+ </div>+ </div>+ <div className="model-hub-add-key-protocol-field flex flex-col">+ <div className="flex items-center gap-1.5">+ <span className="model-hub-add-key-label">{t('settings.models.addKey.undetermined.label')}</span>+ <Info className="model-hub-ink-white-59 size-[13px]" aria-hidden />+ </div>+ <div className="model-hub-add-key-segments flex max-w-full flex-wrap">+ {SOURCE_PROTOCOLS.map((protocol) => (+ <button+ key={protocol}+ type="button"+ aria-pressed={phase.hint === protocol}+ className={cn('model-hub-add-key-segment', phase.hint === protocol && 'is-selected')}+ onClick={() => setPhase({ ...phase, hint: protocol })}+ >+ {t(PROTOCOL_COPY_KEYS[protocol])}+ </button>+ ))}+ </div>+ <span className="model-hub-add-key-hint">{t('settings.models.addKey.undetermined.hint')}</span></div>- <AdoptionNote adoptedBy={adoption.adopted_by} skippedBy={adoption.skipped_by} /></div>)}- {phase === 'error' && (- <div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive">- <TriangleAlert className="mt-0.5 size-4 shrink-0" />- <span>{t('settings.models.addKey.failed', { detail: error })}</span>++ {phase.kind === 'inventory' && (+ <div className="model-hub-add-key-outcome-wrap">+ <div className="model-hub-add-key-strip model-hub-add-key-strip--advisory model-hub-add-key-strip--inventory">+ <TriangleAlert className="model-hub-ink-gold size-3.5 shrink-0" />+ <span className="model-hub-add-key-strip-title model-hub-ink-gold">{t('settings.models.addKey.inventory.title')}</span>+ </div></div>)}- <DialogFooter>- <div className="flex items-center gap-2">- {/* 关闭, not 取消, once the source exists: after a successful add this- is the way out of a dialog that no longer auto-dismisses, and- 「取消」 on a committed credential reads as an undo. */}- <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={phase === 'submitting'}>- {t(phase === 'done' ? 'common.close' : 'common.cancel')}+ <footer className="model-hub-add-key-foot model-hub-fill-white-05 flex flex-row items-center justify-end border-t border-border">+ <Button+ type="button"+ variant="outline"+ className="model-hub-add-key-action"+ disabled={!canCancel}+ onClick={cancel}+ >+ {t('settings.models.addKey.cancel')}+ </Button>+ {phase.kind === 'inventory' && phase.origin === 'add' && (+ <Button type="button" variant="outline" className="model-hub-add-key-action" onClick={() => void addAnyway()}>+ {t('settings.models.addKey.addAnyway')}</Button>+ )}+ {phase.kind === 'form' && (<Button+ type="button"variant="brand"- size="sm"- className="h-10 sm:h-9"- onClick={() => void submit()}- disabled={phase === 'submitting' || phase === 'done' || !apiKey.trim()}+ className="model-hub-add-key-action"+ disabled={!canSubmit}+ onClick={() => void observe('add')}>- <Plus className="size-4" />- {phase === 'submitting' ? t('settings.models.addKey.testing') : t('settings.models.addSource')}+ {t('settings.models.addKey.submit')}</Button>- </div>- </DialogFooter>- </DialogContent>- </Dialog>+ )}+ {phase.kind === 'working' && (+ <Button type="button" variant="brand" className="model-hub-add-key-action" disabled>+ <LoaderCircle className="size-3 animate-spin" />+ {t('settings.models.addKey.adding')}+ </Button>+ )}+ {(phase.kind === 'failure' || phase.kind === 'persist_failure' || phase.kind === 'save_unconfirmed' || phase.kind === 'inventory' || phase.kind === 'undetermined') && (+ <Button+ type="button"+ variant="brand"+ className={cn(+ 'model-hub-add-key-action',+ (phase.kind === 'inventory' || phase.kind === 'save_unconfirmed' || (phase.kind === 'undetermined' && !phase.hint))+ && 'model-hub-add-key-action--dim',+ )}+ disabled={phase.kind === 'undetermined' && !phase.hint}+ onClick={() => void retry()}+ >+ {t('settings.models.addKey.retry')}+ </Button>+ )}+ </footer>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>);};diff --git a/ui/src/components/settings/models/AddSourceMenu.tsx b/ui/src/components/settings/models/AddSourceMenu.tsxdeleted file mode 100644index 4a619c062..000000000--- a/ui/src/components/settings/models/AddSourceMenu.tsx+++ /dev/null@@ -1,193 +0,0 @@-// 添加来源 (frame 07): connect a Claude / ChatGPT subscription (→ OAuth connect-// dialog) or add an API Key (→ form dialog). No type-chooser dialog on desktop;-// the menu IS the chooser.-//-// On phones it becomes a bottom sheet, and the flat three-entry list becomes the-// design's two-step chooser (design.pen M04 m04Sheet 0): 订阅账号 / API Key first,-// vendor second. Three vendor-specific rows read as three unrelated products on a-// small screen, where the actual decision the user is making is "subscription or-// key". Desktop keeps the flat list — frame 07 has the room for it, and the wide-// menu loses nothing by skipping a step.-import * as React from 'react';-import { ChevronLeft, ChevronRight, ExternalLink, KeyRound, Plus, Sparkles } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { Badge } from '@/components/ui/badge';-import { Button } from '@/components/ui/button';-import { ResponsiveMenu } from '@/components/ui/responsive-menu';-import { cn } from '@/lib/utils';-import { useIsMobile } from '@/lib/useIsMobile';-import { ACCENT_ICON, ACCENT_TILE } from './vendorMeta';--const MenuItem: React.FC<{- Icon: React.ComponentType<{ size?: number; className?: string }>;- accentTile: string;- accentIcon: string;- title: string;- subtitle: string;- badge?: string;- Trailing: React.ComponentType<{ className?: string }>;- onClick: () => void;- /** Roomier type + wrapping subtitle for the touch sheet. */- large?: boolean;-}> = ({ Icon, accentTile, accentIcon, title, subtitle, badge, Trailing, onClick, large }) => (- <button- type="button"- onClick={onClick}- className={cn(- 'flex w-full items-center gap-3 border-b border-border px-4 py-3 text-left transition-colors last:border-b-0 hover:bg-surface-2',- large && 'items-start gap-3.5 py-4',- )}- >- <span className={cn('flex shrink-0 items-center justify-center rounded-[10px]', large ? 'size-11' : 'size-10', accentTile)}>- <Icon size={large ? 22 : 20} className={accentIcon} />- </span>- <span className="flex min-w-0 flex-1 flex-col gap-0.5">- <span className="flex items-center gap-2">- <span className={cn('font-semibold text-foreground', large ? 'text-[15px]' : 'text-[14px]')}>{title}</span>- {badge && (- <Badge variant="success" className="shrink-0 px-2 py-0.5 text-[10px]">- {badge}- </Badge>- )}- </span>- <span className={cn('text-[12px] text-muted', large ? 'leading-relaxed' : 'truncate')}>{subtitle}</span>- </span>- <Trailing className={cn('size-4 shrink-0 text-muted', large && 'mt-1')} />- </button>-);--export const AddSourceMenu: React.FC<{- onConnectClaude: () => void;- onConnectChatGPT: () => void;- onAddApiKey: () => void;-}> = ({ onConnectClaude, onConnectChatGPT, onAddApiKey }) => {- const { t } = useTranslation();- const isMobile = useIsMobile();- const [open, setOpen] = React.useState(false);- // Mobile only: which step of the chooser is showing.- const [step, setStep] = React.useState<'type' | 'vendor'>('type');-- // The chooser always opens on the first step. Resetting on the OPEN edge, not- // the close edge, is deliberate: closing happens through several paths (picking- // an entry, Escape, tapping the overlay, a future programmatic close) and any- // one of them that skips the reset leaves the next open on the vendor list.- // Opening only ever happens through the trigger, so this single place cannot be- // bypassed. (Codex P2, 2026-07-25: `pick` closed via a helper that set `open`- // directly and skipped the close-edge reset.)- const onOpenChange = (next: boolean) => {- setOpen(next);- if (next) setStep('type');- };-- const pick = (fn: () => void) => () => {- setOpen(false);- fn();- };-- const claude = {- Icon: Sparkles,- accentTile: ACCENT_TILE.mint,- accentIcon: ACCENT_ICON.mint,- title: t('settings.models.addMenu.claude.title') as string,- subtitle: t('settings.models.addMenu.claude.subtitle') as string,- Trailing: ExternalLink,- onClick: pick(onConnectClaude),- };- const chatgpt = {- Icon: Sparkles,- accentTile: ACCENT_TILE.gold,- accentIcon: ACCENT_ICON.gold,- title: t('settings.models.addMenu.chatgpt.title') as string,- subtitle: t('settings.models.addMenu.chatgpt.subtitle') as string,- Trailing: ExternalLink,- onClick: pick(onConnectChatGPT),- };- const apiKey = {- Icon: KeyRound,- accentTile: ACCENT_TILE.violet,- accentIcon: ACCENT_ICON.violet,- title: t('settings.models.addMenu.apiKey.title') as string,- subtitle: t('settings.models.addMenu.apiKey.subtitle') as string,- Trailing: ChevronRight,- onClick: pick(onAddApiKey),- };-- const vendorStep = step === 'vendor';-- return (- <ResponsiveMenu- open={open}- onOpenChange={onOpenChange}- align="end"- sideOffset={8}- // Never wider than the phone viewport (the fixed 360px overflowed a 360px- // device once collision padding was applied).- className="w-[min(360px,calc(100vw-1.5rem))] overflow-hidden p-0 sm:w-[360px]"- sheetTitle={- vendorStep- ? (t('settings.models.addMenu.vendorTitle') as string)- : (t('settings.models.addMenu.sheetTitle') as string)- }- sheetDescription={- vendorStep- ? (t('settings.models.addMenu.vendorSubtitle') as string)- : (t('settings.models.addMenu.sheetSubtitle') as string)- }- sheetHeader={- vendorStep ? (- <div className="px-4 pb-2">- <button- type="button"- onClick={() => setStep('type')}- className="inline-flex min-h-10 items-center gap-1 text-[13px] font-medium text-mint transition-colors hover:text-mint/80"- >- <ChevronLeft className="size-4" />- {t('common.back')}- </button>- </div>- ) : undefined- }- trigger={- <Button- variant="outline"- size="sm"- // Full-width primary-looking button on phones (design.pen M01 m01AddBtn:- // mint-soft fill, 1.5px mint stroke); the quieter inline button on sm+.- className="h-11 w-full rounded-[11px] border-[1.5px] border-mint/70 bg-mint-soft text-mint hover:bg-mint-soft/80 sm:h-9 sm:w-auto sm:rounded-md sm:border sm:border-mint/40 sm:bg-mint-soft/50 sm:hover:bg-mint-soft"- >- <Plus className="size-4" />- {t('settings.models.addSource')}- </Button>- }- >- {!isMobile ? (- <>- <MenuItem {...claude} />- <MenuItem {...chatgpt} />- <MenuItem {...apiKey} />- </>- ) : vendorStep ? (- <>- <MenuItem {...claude} large />- <MenuItem {...chatgpt} large />- </>- ) : (- <>- <MenuItem- Icon={Sparkles}- accentTile={ACCENT_TILE.mint}- accentIcon={ACCENT_ICON.mint}- title={t('settings.models.addMenu.subscription.title') as string}- subtitle={t('settings.models.addMenu.subscription.subtitle') as string}- badge={t('settings.models.addMenu.subscription.recommended') as string}- Trailing={ChevronRight}- onClick={() => setStep('vendor')}- large- />- <MenuItem {...apiKey} subtitle={t('settings.models.addMenu.apiKeySheetSubtitle') as string} large />- </>- )}- </ResponsiveMenu>- );-};diff --git a/ui/src/components/settings/models/AdoptionNote.test.tsx b/ui/src/components/settings/models/AdoptionNote.test.tsxindex a4b8a4a32..57dfa040d 100644--- a/ui/src/components/settings/models/AdoptionNote.test.tsx+++ b/ui/src/components/settings/models/AdoptionNote.test.tsx@@ -1,103 +1,27 @@-// The empty array is the case worth a test: `adopted_by: []` means the source is-// live and serving nothing, and a note that renders blank there is the same defect-// the note was added to fix. It cannot be reached from the mock store (every-// `follow` backend adopts an eligible source), so it is pinned here instead.-import { createInstance } from 'i18next';+import * as React from 'react';import { renderToStaticMarkup } from 'react-dom/server';-import { I18nextProvider, initReactI18next } from 'react-i18next';-import { describe, expect, it } from 'vitest';+import { beforeEach, describe, expect, it } from 'vitest';+import { I18nextProvider } from 'react-i18next';-import en from '../../../i18n/en.json';-import zh from '../../../i18n/zh.json';+import i18n from '@/i18n';import { AdoptionNote } from './AdoptionNote';-import type { AdoptedBy, SkippedBy } from './types';-const instance = (lng: 'en' | 'zh') => {- const i18n = createInstance();- void i18n.use(initReactI18next).init({- lng,- fallbackLng: 'en',- resources: { en: { translation: en }, zh: { translation: zh } },- interpolation: { escapeValue: false },- });- return i18n;-};--const render = (adoptedBy: AdoptedBy[] | null, skippedBy?: SkippedBy[], lng: 'en' | 'zh' = 'zh') =>- renderToStaticMarkup(- <I18nextProvider i18n={instance(lng)}>- <AdoptionNote adoptedBy={adoptedBy} skippedBy={skippedBy} />- </I18nextProvider>,- );+beforeEach(async () => { await i18n.changeLanguage('en'); });-const text = (html: string) => html.replace(/<[^>]+>/g, '');--const entry = (backend: string, position: number): AdoptedBy => ({- backend,- policy: 'follow',- position,-});+const render = (addedTo: React.ComponentProps<typeof AdoptionNote>['addedTo']) => renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <AdoptionNote addedTo={addedTo} adoptedBy={addedTo?.map(({ backend, menu_model }) => ({ backend, menu_model })) ?? null} />+ </I18nextProvider>,+);describe('AdoptionNote', () => {- it.each(['zh', 'en'] as const)('says nobody enabled it yet in %s', (lng) => {- const html = render([], undefined, lng);- // Not blank, and not a raw key — an unresolved i18n key would still render- // non-empty text, so assert the sentence is real.- expect(html).not.toContain('adoption.none');- expect(html.replace(/<[^>]+>/g, '').trim().length).toBeGreaterThan(8);- });-- it('lists adopters by position, not by response order', () => {- const html = render([entry('codex', 3), entry('claude', 1)]);- const text = html.replace(/<[^>]+>/g, '');- expect(text.indexOf('Claude Code')).toBeLessThan(text.indexOf('Codex'));- expect(text).toContain('第 1 位');- expect(text).toContain('第 3 位');- // The page separator, so a joined list reads like the rest of the page.- expect(text).toContain(' · ');- });-- it('falls back to the raw backend id for an unknown backend', () => {- // A backend shipped by the server before the UI has a label for it must still- // be nameable — dropping it would understate who took the source.- expect(render([entry('futurecli', 2)])).toContain('futurecli');- });-- // 「谁没有」 is the answer this note exists for, and `adopted_by` alone cannot give- // it: `_adopted_by` filters `policy == "follow"`, so a `custom` backend that- // skipped the source is absent for the same reason an ineligible one is. That is- // what `skipped_by` is for — and a response that omits it is still a response that- // did not answer, so the note keeps saying only what it can prove.- it('claims nothing about who skipped it while the server does not say', () => {- const html = render([entry('claude', 1)]);- expect(text(html)).toContain('Claude Code');- expect(html).not.toContain('adoption.');- expect(text(html)).not.toContain('自定义顺序');- });-- it('names the skipped backends once the server sends them', () => {- const html = render([entry('claude', 1)], [{ backend: 'codex', reason: 'custom_order' }]);- const body = text(html);- expect(body).toContain('Claude Code');- expect(body).toContain('Codex');- expect(body).toContain('已改为手动');- });-- it('names them even when nobody adopted it at all', () => {- // `adopted_by: []` with a non-empty complement — every eligible backend keeps a- // hand-picked order. The generic 「还没有 Agent 启用它」 is true here but throws- // away the one thing the payload knows: which orders to go edit. And the adopted- // 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).not.toContain('已自动加入');+ it('renders exact add-time Route locations', () => {+ const html = render([{ backend: 'claude', menu_model: 'claude-opus-4-6', source_id: 'src_a', model_id: 'claude-opus-4-6', position: 2 }]);+ expect(html).toContain('Claude Code');+ expect(html).toContain('claude-opus-4-6');});- it('says nothing at all when the creation reported no adoption result', () => {- // OAuthConnectDialog's unreported-creation path. An absent result is not an empty- // one: 「没有 Agent 启用它」 would be a claim, and this is ignorance. The component- // owns that distinction so its callers stop guarding it on the way in.- expect(render(null)).toBe('');+ it('states that an unmatched source remains available for explicit routing', () => {+ expect(render([])).toContain('route');});});diff --git a/ui/src/components/settings/models/AdoptionNote.tsx b/ui/src/components/settings/models/AdoptionNote.tsxindex db105058c..4c84480e9 100644--- a/ui/src/components/settings/models/AdoptionNote.tsx+++ b/ui/src/components/settings/models/AdoptionNote.tsx@@ -1,80 +1,29 @@-// The 「so what now?」 line of both creation dialogs (api.md → `adopted_by`).-//-// A new credential is not automatically usable: only `follow` backends take it in,-// and only where their eligibility admits it. So the two answers a user needs-// before the dialog closes are 「哪些 Agent 已经用上了,排第几」 and 「谁没有」 —-// and the second one is the whole reason this exists, because a `custom` backend is-// simply ABSENT from the array. Reading nothing there as 「fine, nothing to say」 is-// how a connected key silently never serves a turn.-//-// Shared rather than written twice: an API key and a subscription differ in how they-// are added and in nothing at all afterwards, and the previous per-dialog success-// copy is exactly where the two drifted into saying different things.-//-// Which of those two answers can be given is `adoptionVerdict`'s call, not this-// component's: 「who did not」 is only answerable from the server's own-// eligible-but-skipped complement, and a response that omits it still gets the-// sentence the note can prove rather than a guess at the missing half.import * as React from 'react';import { useTranslation } from 'react-i18next';-import { adoptionVerdict } from './sufficiency';-import type { AdoptedBy, SkippedBy } from './types';+import type { AddedTo, AdoptedBy } from './types';-export const AdoptionNote: React.FC<{ adoptedBy: AdoptedBy[] | null; skippedBy?: SkippedBy[] | null }> = ({- adoptedBy,- skippedBy,-}) => {+export const AdoptionNote: React.FC<{+ addedTo: AddedTo[] | null;+ adoptedBy: AdoptedBy[] | null;+}> = ({ addedTo, adoptedBy }) => {const { t } = useTranslation();- // No result at all — a creation that reported nothing about adoption. Not the same- // as an empty result, and the only case with nothing true to say.- if (!adoptedBy) return null;- const verdict = adoptionVerdict(adoptedBy, skippedBy);+ if (!addedTo || !adoptedBy) return null;+ if (addedTo.length === 0) {+ return <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.adoption.none')}</p>;+ }const backendName = (backend: string) =>t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;-- if (verdict.kind === 'adopted_none' || verdict.kind === 'skipped_all') {- // Not an error — the source exists and is healthy. It is a pointer to the one- // action that makes it serve traffic, on the page the user is already on. And- // it points AT the orders whenever the server named them: 「nobody took it」 and- // 「these hand-picked orders left it out」 want the same edit in two very- // different amounts of hunting.- return (- <p className="text-[12px] leading-relaxed text-muted">- {verdict.kind === 'skipped_all'- ? t('settings.models.adoption.noneSkipped', {- skipped: verdict.backends.map(backendName).join(' · '),- })- : t('settings.models.adoption.none')}- </p>- );- }-- // Position order, not response order: 「第 1 位」 before 「第 3 位」 reads as a- // ranking, which is what it is.- const list = [...adoptedBy]- .sort((a, b) => a.position - b.position)- .map((a) =>- t('settings.models.adoption.entry', {- name: backendName(a.backend),- position: a.position,- }),- )- // ' · ' is this page's separator everywhere else (source sub-lines, the- // supply tooltip, the agent card's amber line) — locale-neutral on purpose.- .join(' · ');-+ const locations = addedTo.map((entry) =>+ t('settings.models.adoption.route', {+ backend: backendName(entry.backend),+ model: entry.menu_model,+ position: entry.position,+ }),+ );return (<p className="text-[12px] leading-relaxed text-muted">- {verdict.kind === 'partly_skipped'- ? t('settings.models.adoption.partlySkipped', {- list,- skipped: verdict.backends.map(backendName).join(' · '),- })- : // `covered` and `indeterminate` render the same sentence, and it is the- // sentence that is TRUE of both: these backends took it. Only the omission- // needs the server half, so only the omission waits for it.- t('settings.models.adoption.enabled', { list })}+ {t('settings.models.adoption.enabled', { list: locations.join(' · ') })}</p>);};diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex 98f614137..24bca80e8 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -1,310 +1,138 @@-import { createInstance } from 'i18next';-import { renderToStaticMarkup } from 'react-dom/server';-import { I18nextProvider, initReactI18next } from 'react-i18next';-import { MemoryRouter } from 'react-router-dom';-import { describe, expect, it, vi } from 'vitest';--import en from '../../../i18n/en.json';-import zh from '../../../i18n/zh.json';-import { ToastProvider } from '@/context/ToastProvider';-import { AgentCard } from './AgentCard';-import { modelChainKey, type ModelChainIndex } from './modelRows';-import type { AgentChain, AgentSupply, 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 },-});+// @vitest-environment jsdom+import type { ComponentProps } from 'react';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { cleanup } from '@testing-library/react';++import i18n from '@/i18n';+import { AgentCard as RuntimeAgentCard } from './AgentCard';+import { modelChainKey, NOMINAL_MODEL_BASELINE } from './modelRows';+import { readyRegion } from './regionRead';+import { freshRuntimeProjection } from './runtimeLifecycle';+import type { AgentSupply, RuntimeDependency, Source } from './types';++const runtime: RuntimeDependency = {+ contract_version: 5,+ manifest: { name: 'cliproxyapi', version: '1.0.0', source_sha: 'fixture', assets: [] },+ status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },+};+const AgentCard = (props: Omit<ComponentProps<typeof RuntimeAgentCard>, 'runtime'>) =>+ <RuntimeAgentCard {...props} runtime={freshRuntimeProjection(readyRegion(runtime))} />;const source = (id: string, name: string): Source => ({- id,- kind: 'api_key',- vendor: 'anthropic',- display_name: name,- protocol: 'anthropic',- supply_channel: 'hub',- billing: 'metered',- state: { status: 'active', retry_at: null, detail_key: null },- last_discovered_at: null,- models: [{ id: 'claude-opus-4-6', provenance: 'discovered' }],-});--const agent = (over: Partial<AgentSupply> = {}): AgentSupply => ({- backend: 'claude',- mode: 'hub',- menu_kind: 'fixed',- selected_by_agent: null,- selected_model_id: 'claude-opus-4-6',- sources: { policy: 'follow', order: ['src_a'], eligibility: [] },- supply_status: 'ok',- model_supply: [{ model_id: 'claude-opus-4-6', chain_length: 1 }],- named_agents: [],- mappings: [],- menu: null,- builtin_models: ['claude-opus-4-6', 'claude-sonnet-4-6'],- standard_vendors: null,- ...over,-});--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,+ id, last_discovered_at: null, kind: 'api_key', vendor: 'anthropic', display_name: name,+ protocol: 'anthropic', supply_channel: 'hub', billing: 'metered', state: { status: 'active', retry_at: null, detail_key: null },+ models: [{ id: 'claude-opus-4-6', origin: 'discovered', reasoning_efforts: [] }],});--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>- <AgentCard- agents={agents}- 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}- />- </ToastProvider>- </I18nextProvider>- </MemoryRouter>,-);--describe('AgentCard model list', () => {- it('shows every model and the actual serving source without a current badge', () => {- 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('当前由 Anthropic API Key 供给');- expect(html).not.toContain('>当前</');+const hubAgent: AgentSupply = {+ backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed', selected_model_id: 'claude-opus-4-6', selected_model_explicit: true,+ sources: { order: ['src_a', 'src_b'], eligibility: [{ source_id: 'src_a', eligible: true }, { source_id: 'src_b', eligible: true }] },+ routes: { 'claude-opus-4-6': { hops: [{ source_id: 'src_a', model_id: 'claude-opus-4-6' }, { source_id: 'src_b', model_id: 'claude-opus-4-6' }] } },+ supply_status: 'degraded', model_supply: [{ model_id: 'claude-opus-4-6', chain_length: 2, has_runnable_hop: true }], named_agents: [], builtin_models: ['claude-opus-4-6'], menu: null,+};++afterEach(cleanup);++describe('AgentCard', () => {+ it('derives takeover from the exact current hop', () => {+ const key = modelChainKey('claude', 'claude-opus-4-6');+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 5, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ expect(screen.getByText(/Backup/)).toBeTruthy();+ expect(screen.getByText(/takeover/i)).toBeTruthy();});- 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');+ it('does not call a later current hop takeover unless the head is unavailable for cooldown', () => {+ const key = modelChainKey('claude', 'claude-opus-4-6');+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 5, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ expect(screen.getByText(/Backup/)).toBeTruthy();+ expect(screen.queryByText(/takeover/i)).toBeNull();});- it('does not turn an absent selection into a Models-page state', () => {- const html = render([agent({ selected_model_id: null })], chains(chain('claude-opus-4-6')));- expect(html).toContain('claude-opus-4-6');- expect(html).not.toContain('尚未选择型号');- expect(html).not.toContain('href="/agents"');- });+ it('hides current and takeover projections while the runtime is stopped', () => {+ const key = modelChainKey('claude', 'claude-opus-4-6');+ const stopped = { ...runtime, status: { ...runtime.status, health: 'down' as const } };+ render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 5, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);- 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);+ expect(screen.queryByText(/Backup/)).toBeNull();+ expect(screen.queryByText(/takeover/i)).toBeNull();+ expect(screen.getAllByText('—').length).toBeGreaterThanOrEqual(2);});- 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('offers only gateway enablement and ignores stale chain data in direct mode', () => {+ const key = modelChainKey('claude', 'claude-opus-4-6');+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[{ ...hubAgent, mode: 'direct', sources: null, routes: null, supply_status: null, model_supply: null }]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 5, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ expect(screen.queryByText(/Source order/i)).toBeNull();+ expect(screen.queryByRole('button', { name: /route chain/i })).toBeNull();+ expect(screen.queryByText(/Backup/)).toBeNull();+ expect(screen.queryByText(/takeover/i)).toBeNull();});- 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);+ it('renders the AgentSupply collapse projection and rereads chains on expand and collapse', async () => {+ const onProbeSettled = vi.fn();+ const models = Array.from({ length: NOMINAL_MODEL_BASELINE + 2 }, (_, index) => `model-${index + 1}`);+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[{+ ...hubAgent,+ builtin_models: models,+ model_supply: models.map((modelId) => ({ model_id: modelId, chain_length: 1, has_runnable_hop: true })),+ routes: {},+ }]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={onProbeSettled} /></I18nextProvider>);++ expect(screen.queryByText(models.at(-1) as string)).toBeNull();+ await userEvent.click(screen.getByRole('button', { name: /more model/i }));+ expect(screen.getByText(models.at(-1) as string)).toBeTruthy();+ expect(onProbeSettled).toHaveBeenCalledOnce();+ await userEvent.click(screen.getByRole('button', { name: /more model/i }));+ expect(screen.queryByText(models.at(-1) as string)).toBeNull();+ expect(onProbeSettled).toHaveBeenCalledTimes(2);+ expect(onProbeSettled).toHaveBeenNthCalledWith(1, expect.objectContaining({ backend: 'claude' }));+ expect(onProbeSettled).toHaveBeenNthCalledWith(2, expect.objectContaining({ backend: 'claude' }));});- 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',- sources: {- policy: 'custom',- order: ['src_enabled'],- eligibility: [- { source_id: 'src_enabled', eligible: true },- { source_id: 'src_outside', eligible: true },- ],- },- 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('keeps a nonempty paused route visible beyond the nominal collapsed rows', () => {+ const models = Array.from({ length: NOMINAL_MODEL_BASELINE + 2 }, (_, index) => `model-${index + 1}`);+ const pausedModel = models.at(-1) as string;+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[{+ ...hubAgent,+ builtin_models: models,+ routes: {},+ model_supply: models.map((modelId) => ({+ model_id: modelId,+ chain_length: 1,+ has_runnable_hop: modelId !== pausedModel,+ })),+ }]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);++ expect(screen.getByText(pausedModel)).toBeTruthy();+ expect(screen.getByText(/^Supply paused$|^供给已暂停$/i)).toBeTruthy();});- 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>/);+ it('keeps a chain reread reachable when a short group is unresolved', async () => {+ const onProbeSettled = vi.fn();+ const key = modelChainKey('claude', 'claude-opus-4-6');+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[]} chains={{ [key]: { kind: 'unread', retryable: true } }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={onProbeSettled} /></I18nextProvider>);- const emptyMenu = render([- agent({- backend: 'opencode',- menu_kind: 'open',- selected_model_id: null,- model_supply: [],- mappings: [],- menu: { view: 'featured', checked: [] },- builtin_models: null,- }),- ], {}, false, undefined, pending);- expect(emptyMenu).toContain(zh.settings.models.agents.emptyModels);- expect(emptyMenu).toMatch(/<button[^>]*disabled=""[^>]*>(?:(?!<\/button>)[\s\S])*?管理型号<\/button>/);+ await userEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));+ expect(onProbeSettled).toHaveBeenCalledOnce();+ expect(onProbeSettled).toHaveBeenCalledWith(expect.objectContaining({ backend: 'claude' }));});- 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('opens Frame 02 with the exact backend and model context', async () => {+ const onOpenRoute = vi.fn();+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={onOpenRoute} onProbeSettled={vi.fn()} /></I18nextProvider>);- 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);- });+ await userEvent.click(screen.getByRole('button', { name: /Open claude-opus-4-6 route chain/i }));- 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(html).toContain(zh.settings.models.modelStatus.needsAction);- expect(html).toContain(zh.settings.models.modelStatus.retry);+ expect(onOpenRoute).toHaveBeenCalledWith(hubAgent, 'claude-opus-4-6');});- it('keeps Direct honest and offers the managed-mode action instead of order editing', () => {- const html = render([agent({ mode: 'direct', sources: 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);+ it('replaces the gateway status slot and action with an in-place retry after leaving fails', async () => {+ const onSwitchDirect = vi.fn();+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set(['claude'])} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={onSwitchDirect} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);++ expect(screen.getByText(/did not go through/i)).toBeTruthy();+ await userEvent.click(screen.getByRole('button', { name: /retry/i }));+ expect(onSwitchDirect).toHaveBeenCalledWith(hubAgent);});});diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsxindex 10e39fe7a..aae585c00 100644--- a/ui/src/components/settings/models/AgentCard.tsx+++ b/ui/src/components/settings/models/AgentCard.tsx@@ -1,258 +1,36 @@import * as React from 'react';-import { Link } from 'react-router-dom';-import {- ArrowDownUp,- ChevronDown,- ChevronRight,- Loader2,- Plus,- Settings2,- TriangleAlert,- Zap,-} from 'lucide-react';+import { ChevronDown, ChevronRight, ChevronUp, RefreshCw } 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 { 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 {- listedModelIds,- modelChainKey,- modelHasOffOrderSupplier,- modelNeedsAttention,- runtimeHealthNeedsAttention,- type ModelChainIndex,- type ModelChainRead,-} from './modelRows';+import { ModelHubInfoHint } from './ModelHubInfoHint';+import { collapsedModelRows, listedModelIds, modelChainKey, modelSupplyState, type ModelChainIndex, type ModelChainRead } from './modelRows';+import { foldRegionRead } from './regionRead';+import { agentHasLiveChainProjection, type FreshRuntimeProjection } from './runtimeLifecycle';+import { currentChainLink, isTakeoverChain } from './takeover';import { ACCENT_ICON, ACCENT_TILE, backendVisual } from './vendorMeta';-import type { RaisedRepair } from './SourceRowMenu';-import type { AgentBackend, AgentChainLink, AgentSupply, RuntimeDependency, Source } from './types';--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;+import type { AgentSupply, Source } from './types';++const sourceName = (sources: Source[], id: string): string => sources.find((source) => source.id === id)?.display_name ?? id;+const currentLink = (read: ModelChainRead | undefined) => {+ const chain = read ? foldRegionRead(read, {+ loading: () => null,+ ready: (value) => value,+ unread: () => null,+ degraded: () => null,+ }) : null;+ return chain ? currentChainLink(chain) : 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 (- <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>- );-};--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 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 (- <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>-- <ModelProbe- agent={agent}- modelId={modelId}- sources={sources}- disabled={pending}- onSettled={onProbeSettled}- />- </div>- );+const isTakeoverRead = (read: ModelChainRead | undefined): boolean => {+ const chain = read ? foldRegionRead(read, {+ loading: () => null,+ ready: (value) => value,+ unread: () => null,+ degraded: () => null,+ }) : null;+ return chain ? isTakeoverChain(chain) : false;};const ModelRow: React.FC<{@@ -260,373 +38,131 @@ const ModelRow: React.FC<{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,-}) => {+ onOpenRoute: (agent: AgentSupply, modelId: string) => void;+}> = ({ agent, modelId, sources, read, onOpenRoute }) => {const { t } = useTranslation();- const [expanded, setExpanded] = React.useState(false);- const configurable = agent.mode === 'hub';- const selected = 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 && runtimeHealthNeedsAttention(runtime.status.health));- 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;-- 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(- selected- ? 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;- }-- 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;-+ const current = currentLink(read);+ const takeover = isTakeoverRead(read);+ const supplyState = modelSupplyState(agent, modelId);+ const resolved = read?.kind === 'ready' && current !== null;+ const mode = resolved+ ? current.channel === 'native_cli'+ ? t('settings.models.legend.native') as string+ : t('settings.models.gateway.group.mode.gateway') as string+ : '—';+ const currentCopy = supplyState === 'paused'+ ? t('settings.models.legend.unavailable') as string+ : resolved+ ? t(takeover ? 'settings.models.gateway.row.currentTakeover' : 'settings.models.gateway.row.current', { source: sourceName(sources, current.source_id) }) as string+ : '—';return (- <div className={cn('border-b border-border last:border-b-0', selected && '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="truncate font-mono text-[12.5px] font-semibold text-foreground">{modelId}</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}- />- )}- </div>+ <button+ type="button"+ onClick={() => onOpenRoute(agent, modelId)}+ aria-label={t('settings.models.routeDialog.open', { model: modelId }) as string}+ className="model-hub-model-row flex h-9 w-full min-w-0 items-center gap-2.5 overflow-hidden rounded-lg border border-border px-3 text-left"+ >+ <span className="flex min-w-0 flex-1 items-center justify-between gap-2.5">+ <span className="flex min-w-0 flex-1 items-center gap-[7px]"><span className="min-w-0 flex-1 truncate font-mono text-[12px] font-medium text-foreground" title={modelId}>{modelId}</span><span className="model-hub-model-mode-chip shrink-0 rounded-full border border-border px-2 py-[3px] text-[10.5px] font-semibold text-muted">{mode}</span></span>+ <span className={cn('model-hub-model-current min-w-0 flex-1 truncate text-[10.5px]', supplyState === 'paused' ? 'model-hub-ink-gold' : takeover && 'model-hub-model-current--takeover')} title={currentCopy}>{currentCopy}</span>+ </span>+ <ChevronRight className="model-hub-overview-chevron size-[15px] shrink-0" aria-hidden="true" />+ </button>);};const AgentModelCard: React.FC<{agent: AgentSupply;+ runtime: FreshRuntimeProjection | null;sources: Source[];chains: ModelChainIndex;- runtime: RuntimeDependency | null;- issuesOnly: boolean;pending: boolean;connecting: boolean;+ switchFailed: boolean;onConnectHub: (agent: AgentSupply) => void;+ onSwitchDirect: (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;-}> = (props) => {+ onOpenRoute: (agent: AgentSupply, modelId: string) => void;+ onProbeSettled: (agent: AgentSupply) => void;+}> = ({ agent, runtime, sources, chains, pending, connecting, switchFailed, onConnectHub, onSwitchDirect, onOpenOrder, onOpenRoute, onProbeSettled }) => {const { t } = useTranslation();- const { agent, sources, chains, runtime, issuesOnly } = props;- const announceEnrollment = useAnnounceEnrollment(agent.backend, sources);const { Icon, accent } = backendVisual(agent.backend);+ const [expanded, setExpanded] = React.useState(false);const allModels = listedModelIds(agent);- const models = issuesOnly- ? allModels.filter((modelId) => modelNeedsAttention(agent, modelId, chains[modelChainKey(agent.backend, modelId)], runtime))- : allModels;- if (issuesOnly && models.length === 0) return null;-+ const chainProjectionLive = agentHasLiveChainProjection(runtime, agent);+ const collapsed = collapsedModelRows(agent, expanded);+ const collapsedAtRest = collapsedModelRows(agent);+ const models = collapsed.visible;+ const canCollapse = collapsedAtRest.hidden.length > 0;+ const needsChainRepair = chainProjectionLive+ && allModels.some((modelId) => {+ const read = chains[modelChainKey(agent.backend, modelId)];+ return read?.kind === 'unread' || (read?.kind === 'degraded' && read.cause === 'read_failed');+ });+ const hasTakeover = chainProjectionLive+ && allModels.some((modelId) => isTakeoverRead(chains[modelChainKey(agent.backend, modelId)]));+ const modeWord = t(`settings.models.gateway.group.mode.${agent.mode === 'hub' ? 'gateway' : 'direct'}`) as string;+ const health = agent.supply_status ?? 'noSelection';+ const subtitle = agent.mode === 'direct'+ ? t('settings.models.gateway.group.subtitle.direct', { mode: modeWord }) as string+ : t('settings.models.gateway.group.subtitle.gateway', { mode: modeWord, health: t(`settings.models.gateway.group.status.${health}`) }) as string;+ const toggleCollapsed = () => {+ setExpanded((value) => !value);+ onProbeSettled(agent);+ };+ const retryChains = () => onProbeSettled(agent);+ const noUsableSource = agent.mode === 'hub'+ && Boolean(agent.model_supply?.length)+ && agent.model_supply?.every((entry) => !entry.has_runnable_hop);+ const statusClass = switchFailed || health === 'interrupted'+ ? 'text-destructive'+ : hasTakeover || health === 'degraded' || health === 'waiting'+ ? 'model-hub-ink-gold'+ : 'text-muted';+ const statusDot = switchFailed || health === 'interrupted'+ ? 'bg-destructive'+ : hasTakeover || health === 'degraded' || health === 'waiting'+ ? 'bg-gold'+ : health === 'ok' && agent.mode === 'hub'+ ? 'bg-mint'+ : 'bg-muted';return (- <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>- )}+ <section className="overflow-hidden rounded-xl border border-border bg-background" data-agent-backend={agent.backend}>+ <div className="flex min-h-[66px] flex-col justify-center gap-[7px] border-b border-border px-3.5 py-3 sm:h-[66px] sm:py-0">+ <div className="flex min-w-0 flex-col items-stretch gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">+ <div className="flex min-w-0 items-center gap-[9px]">+ <span className={cn('flex size-[30px] shrink-0 items-center justify-center rounded-[9px]', ACCENT_TILE[accent])}><Icon className={cn('size-[15px]', ACCENT_ICON[accent])} /></span>+ <span className="flex min-w-0 items-center gap-[7px]">+ <h2 className="truncate text-[14px] font-bold text-foreground">{t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}</h2>+ <Badge variant="secondary" className={cn('px-2 py-[3px] text-[10.5px] font-semibold', hasTakeover && 'model-hub-takeover-chip')}>+ {hasTakeover ? t('settings.models.takeover.chip') : t('settings.models.gateway.modelCount', { count: allModels.length })}+ </Badge></span>- <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' ? <div className="flex shrink-0 flex-wrap gap-2"><Button variant="secondary" size="sm" className="h-auto rounded-lg px-3 py-[9px] text-[11.5px] font-bold" onClick={() => onOpenOrder(agent)} disabled={pending}>{t('settings.models.gateway.sourceOrder')}</Button><Button variant="outline" size="sm" className="h-auto rounded-lg px-3 py-[9px] text-[11.5px] font-bold" onClick={() => onSwitchDirect(agent)} disabled={pending}>{t(switchFailed ? 'settings.models.gateway.retry' : 'settings.models.gateway.switchToDirect')}</Button></div> : <Button variant="secondary" size="sm" className="h-auto shrink-0 self-start rounded-lg px-3 py-[9px] text-[11.5px] font-bold sm:self-auto" onClick={() => onConnectHub(agent)} disabled={connecting}>{t('settings.models.gateway.switchToGateway')}</Button>}</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 className={cn('flex items-center gap-1.5 text-[11px] font-semibold sm:ml-[42px]', statusClass)}>+ <span className={cn('size-[5px] shrink-0 rounded-full', statusDot)} />+ {switchFailed ? t('settings.models.gateway.fail.switchToDirect') : subtitle}+ <ModelHubInfoHint label={switchFailed ? t('settings.models.gateway.fail.switchToDirect') : subtitle} content={switchFailed ? t('settings.models.gateway.fail.switchToDirect') : subtitle} className="model-hub-overview-info size-[13px]" />+ </span></div>-- {models.length === 0 ? (- <div className="px-4 py-10 text-center sm:px-5">- <p className="text-[12.5px] text-muted">{t('settings.models.agents.emptyModels')}</p>- </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>- )}+ {agent.mode === 'hub' && (models.length === 0 ? <div className="px-4 py-10 text-center sm:px-5"><p className="text-[12.5px] text-muted">{t('settings.models.gateway.group.emptyModels')}</p></div> : <div className="space-y-2 p-2">{noUsableSource && <p className="px-3 py-1 text-[11px] font-semibold text-muted">{t('settings.models.gateway.supply.none')}</p>}{models.map((modelId) => <ModelRow key={modelId} agent={agent} modelId={modelId} sources={sources} read={chainProjectionLive ? chains[modelChainKey(agent.backend, modelId)] : undefined} onOpenRoute={onOpenRoute} />)}{canCollapse ? <button type="button" onClick={toggleCollapsed} className="model-hub-model-collapse flex h-6 w-full items-center gap-1.5 hover:text-foreground">{expanded ? <ChevronUp /> : <ChevronDown />}{expanded ? t('settings.models.gateway.collapse', { count: collapsedAtRest.hidden.length }) : t('settings.models.gateway.collapse', { count: collapsed.hidden.length })}</button> : needsChainRepair ? <button type="button" onClick={retryChains} className="model-hub-model-collapse flex h-6 w-full items-center gap-1.5 hover:text-foreground"><RefreshCw />{t('settings.models.gateway.retry')}</button> : null}</div>)}</section>);};export const AgentCard: React.FC<{agents: AgentSupply[];+ runtime: FreshRuntimeProjection | null;sources: Source[];chains: ModelChainIndex;- runtime: RuntimeDependency | null;- issuesOnly: boolean;pendingBackends: ReadonlySet<string>;+ switchFailures: ReadonlySet<string>;onConnectHub: (agent: AgentSupply) => void;+ onSwitchDirect: (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;+ onOpenRoute: (agent: AgentSupply, modelId: string) => void;+ onProbeSettled: (agent: AgentSupply) => void;connectingBackend: string | null;-}> = ({ agents, ...props }) => {- const { t } = useTranslation();- return (- <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) => {- 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>- )}- </div>- );-};+}> = ({ agents, pendingBackends, switchFailures, connectingBackend, ...props }) => <div className="flex flex-col gap-4">{agents.map((agent) => <AgentModelCard key={agent.backend} agent={agent} {...props} pending={pendingBackends.has(agent.backend)} switchFailed={switchFailures.has(agent.backend)} connecting={connectingBackend === agent.backend} />)}</div>;diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.tsxindex ae8672a6a..90b19054b 100644--- a/ui/src/components/settings/models/BackendSupplyModeCard.tsx+++ b/ui/src/components/settings/models/BackendSupplyModeCard.tsx@@ -12,6 +12,7 @@ import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Card, CardContent } from '@/components/ui/card';import { cn } from '@/lib/utils';+import { createAgentCollectionReadAuthority } from './collectionReadAuthority';import { useToast } from '@/context/ToastContext';import { modelsApi } from './modelsApi';import { MigrationDialog } from './MigrationDialog';@@ -82,6 +83,7 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bacconst [detected, setDetected] = React.useState<MigrationItem[]>([]);const [switching, setSwitching] = React.useState<AgentMode | null>(null);const [migrateOpen, setMigrateOpen] = React.useState(false);+ const [agentReads] = React.useState(() => createAgentCollectionReadAuthority(modelsApi));const aliveRef = React.useRef(true);React.useEffect(() => {aliveRef.current = true;@@ -92,12 +94,12 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bacconst load = React.useCallback(async () => {try {- const agents = await modelsApi.listAgents();+ const agents = await agentReads.readValue();if (aliveRef.current) setAgent(agents.find((a) => a.backend === backend) ?? null);} catch {/* card simply stays hidden if the hub is unreachable */}- }, [backend]);+ }, [agentReads, backend]);const scan = React.useCallback(async () => {try {@@ -179,7 +181,7 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac<Linkto="/admin/settings/models"onClick={(e) => e.stopPropagation()}- className="inline-flex shrink-0 items-center gap-1 text-[13px] font-medium text-mint transition-colors hover:text-mint/80"+ className="model-hub-action-mint inline-flex shrink-0 items-center gap-1 text-[13px] font-medium transition-colors">{t('settings.models.supplyMode.hub.openModels')}<ArrowRight className="size-3.5" />@@ -194,7 +196,7 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bacno instructions. */}{mode === 'hub' && isSupplyWarning(hubOutcome) && (<div className="flex items-start gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-2.5 text-[12px] leading-relaxed text-foreground">- <Info className="mt-0.5 size-3.5 shrink-0 text-gold" />+ <Info className="model-hub-ink-gold mt-0.5 size-3.5 shrink-0" /><span>{t(`settings.models.supply.${hubOutcome}`)}{(hubOutcome === 'noSources' || hubOutcome === 'interrupted') &&@@ -216,7 +218,7 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac{mode === 'direct' && detectItem && (<div className="flex items-center justify-between gap-3 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-2.5"><span className="flex min-w-0 items-center gap-2 text-[12px] leading-relaxed text-foreground">- <Info className="size-3.5 shrink-0 text-gold" />+ <Info className="model-hub-ink-gold size-3.5 shrink-0" /><span className="truncate">{t('settings.models.supplyMode.direct.detected', { detail: detectItem.masked_detail })}</span>diff --git a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx b/ui/src/components/settings/models/EnableGatewayDialog.test.tsxnew file mode 100644index 000000000..cc89f493a--- /dev/null+++ b/ui/src/components/settings/models/EnableGatewayDialog.test.tsx@@ -0,0 +1,115 @@+// @vitest-environment jsdom+import { cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import { createAgentCollectionReadAuthority } from './collectionReadAuthority';+import { EnableGatewayDialog } from './EnableGatewayDialog';+import { modelsApi } from './modelsApi';+import { failRegionRead, readyRegion, unreadRegion, type RegionRead } from './regionRead';+import type { AgentSupply, RuntimeDependency } from './types';++const direct: AgentSupply = {+ backend: 'claude',+ cli_present: true,+ mode: 'direct',+ menu_kind: 'fixed',+ sources: { order: [], eligibility: [] },+};++const runtime = (+ health: RuntimeDependency['status']['health'],+ withAsset = false,+ hostPlatform?: string,+): RuntimeDependency => ({+ contract_version: 5,+ // #1326 runtime-dependency shape; host evidence is consumed only when present.+ ...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),+ manifest: {+ name: 'cliproxyapi',+ version: '1',+ source_sha: 'a'.repeat(40),+ assets: withAsset ? [{+ platform: 'darwin-arm64',+ url: 'https://example.invalid/runtime',+ size_bytes: 1,+ sha256: '0'.repeat(64),+ }] : [],+ },+ status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },+});++const renderDialog = (runtimeValue: RegionRead<RuntimeDependency>, props: Partial<React.ComponentProps<typeof EnableGatewayDialog>> = {}) => render(+ <I18nextProvider i18n={i18n}>+ <EnableGatewayDialog+ agent={direct}+ runtime={runtimeValue}+ agentReads={createAgentCollectionReadAuthority(modelsApi)}+ onClose={vi.fn()}+ onAdopted={vi.fn()}+ onRuntime={vi.fn()}+ trackWrite={async (work) => work()}+ {...props}+ />+ </I18nextProvider>,+);++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe('EnableGatewayDialog', () => {+ it('names the dependency and changes the primary when runtime is missing', () => {+ renderDialog(readyRegion(runtime('not_installed', true)));++ expect(screen.getByText(/cliproxyapi/)).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Install and switch' })).toBeTruthy();+ });++ it('shares the server-host installability predicate with the runtime pill', () => {+ renderDialog(readyRegion(runtime('not_installed', true, 'linux-amd64')));++ expect(screen.queryByRole('button', { name: 'Install and switch' })).toBeNull();+ expect((screen.getByRole('button', { name: 'Switch to gateway' }) as HTMLButtonElement).disabled).toBe(true);+ });++ it('keeps the dialog open with cause-neutral failure copy and a retryable primary', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([direct]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime('ok'));+ vi.spyOn(modelsApi, 'setAgentMode').mockRejectedValue(new TypeError('offline'));+ const onClose = vi.fn();+ renderDialog(readyRegion(runtime('ok')), { onClose });++ await user.click(screen.getByRole('button', { name: 'Switch to gateway' }));++ expect(await screen.findByText('The switch to the gateway did not go through')).toBeTruthy();+ expect(screen.getByText(/PATCH \/api\/models\/agents\/claude\/mode · The gateway could not be reached/)).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Switch to gateway' })).toBeTruthy();+ expect(onClose).not.toHaveBeenCalled();+ });++ it('keeps adoption disabled while runtime status is unread', async () => {+ const user = userEvent.setup();+ const setMode = vi.spyOn(modelsApi, 'setAgentMode');+ renderDialog(unreadRegion<RuntimeDependency>());++ const confirm = screen.getByRole('button', { name: 'Switch to gateway' }) as HTMLButtonElement;+ expect(confirm.disabled).toBe(true);+ expect(screen.getByText('Gateway status unavailable')).toBeTruthy();++ await user.click(confirm);+ expect(setMode).not.toHaveBeenCalled();+ });++ it('does not use a retained runtime value to choose an adoption action', () => {+ renderDialog(failRegionRead(readyRegion(runtime('not_installed', true))));++ expect(screen.queryByRole('button', { name: 'Install and switch' })).toBeNull();+ expect((screen.getByRole('button', { name: 'Switch to gateway' }) as HTMLButtonElement).disabled).toBe(true);+ expect(screen.getByText('Gateway status unavailable')).toBeTruthy();+ });+});diff --git a/ui/src/components/settings/models/EnableGatewayDialog.tsx b/ui/src/components/settings/models/EnableGatewayDialog.tsxnew file mode 100644index 000000000..feeb9b41a--- /dev/null+++ b/ui/src/components/settings/models/EnableGatewayDialog.tsx@@ -0,0 +1,168 @@+import * as React from 'react';+import * as DialogPrimitive from '@radix-ui/react-dialog';+import { Check, CircleX, LoaderCircle, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import type { CollectionReadAuthority } from './collectionReadAuthority';+import { resumeGatewayAdoption, type GatewayAdoptionFailure } from './gatewayAdoption';+import { modelsApi } from './modelsApi';+import { foldRegionRead, readyRegion, type RegionRead } from './regionRead';+import { runtimeHasInstallAsset } from './runtimeLifecycle';+import type { AgentSupply, RuntimeDependency } from './types';+import { BACKEND_ADOPTION_VENDOR_KEY } from './vendorMeta';++const Bullet: React.FC<{ children: React.ReactNode }> = ({ children }) => (+ <p className="model-hub-adopt-bullet">+ <Check aria-hidden />+ <span>{children}</span>+ </p>+);++export const EnableGatewayDialog: React.FC<{+ agent: AgentSupply;+ runtime: RegionRead<RuntimeDependency>;+ agentReads: CollectionReadAuthority<AgentSupply[]>;+ onClose: () => void;+ onAdopted: (agent: AgentSupply) => void | Promise<void>;+ onRuntime: (runtime: RuntimeDependency) => void;+ trackWrite: (work: () => Promise<void>) => Promise<void>;+}> = ({ agent, runtime, agentReads, onClose, onAdopted, onRuntime, trackWrite }) => {+ const { t } = useTranslation();+ const [busy, setBusy] = React.useState(false);+ const [runtimeView, setRuntimeView] = React.useState(runtime);+ const [failure, setFailure] = React.useState<GatewayAdoptionFailure | null>(null);+ const backend = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend });+ const vendor = t(`settings.models.adopt.vendor.${BACKEND_ADOPTION_VENDOR_KEY[agent.backend]}`);+ const runtimeDecision = foldRegionRead<RuntimeDependency, { kind: 'ready'; runtime: RuntimeDependency } | { kind: 'unavailable' }>(runtimeView, {+ loading: () => ({ kind: 'unavailable' }),+ ready: (value) => ({ kind: 'ready', runtime: value }),+ unread: () => ({ kind: 'unavailable' }),+ degraded: () => ({ kind: 'unavailable' }),+ });+ const runtimeValue = runtimeDecision.kind === 'ready' ? runtimeDecision.runtime : null;+ const runtimeUnavailable = runtimeValue === null;+ const needsInstall = runtimeValue?.status.health === 'not_installed';+ const missing = Boolean(needsInstall && runtimeValue && runtimeHasInstallAsset(runtimeValue));+ const installUnsupported = Boolean(needsInstall && !missing);+ const effectKeys = agent.backend === 'opencode'+ ? ['1.opencode', '2.opencode', '3', '4'] as const+ : ['1', '2', '3', '4'] as const;++ React.useEffect(() => {+ if (!busy) setRuntimeView(runtime);+ }, [busy, runtime]);++ const commit = () => {+ if (busy || runtimeUnavailable || installUnsupported) return;+ setBusy(true);+ setFailure(null);+ void trackWrite(async () => {+ try {+ const result = await resumeGatewayAdoption(modelsApi, agentReads, agent.backend);+ if (result.runtime) {+ setRuntimeView(readyRegion(result.runtime));+ onRuntime(result.runtime);+ }+ if (!result.ok) {+ setFailure(result.failure);+ return;+ }+ await Promise.resolve(onAdopted(result.agent)).catch(() => {});+ onClose();+ } finally {+ setBusy(false);+ }+ });+ };++ const reason = failure ? t(`settings.models.adopt.fail.reason.${failure.reason}`) : '';+ const failureDetail = failure?.step === 'install'+ ? t('settings.models.install.fail.detail')+ : failure?.request && failure.responseStatus+ ? t('settings.models.adopt.fail.detail', {+ request: failure.request,+ status: failure.responseStatus,+ reason,+ })+ : failure+ ? [failure.request, failure.responseStatus, reason].filter((slot) => slot !== undefined && slot !== '').join(' · ')+ : '';++ return (+ <DialogPrimitive.Root open onOpenChange={(open) => !open && !busy && onClose()}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay className="model-hub-adopt-overlay fixed inset-0 z-50" />+ <DialogPrimitive.Content+ className="model-hub-adopt-dialog fixed left-1/2 top-1/2 z-50 flex -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden bg-surface outline-none"+ onEscapeKeyDown={(event) => { if (busy) event.preventDefault(); }}+ onPointerDownOutside={(event) => { if (busy) event.preventDefault(); }}+ >+ <header className="model-hub-adopt-head">+ <div className="flex items-center justify-between gap-3">+ <DialogPrimitive.Title className="model-hub-adopt-title text-foreground">+ {t('settings.models.adopt.title', { backend })}+ </DialogPrimitive.Title>+ <DialogPrimitive.Close asChild>+ <Button type="button" variant="ghost" size="icon" className="model-hub-adopt-close" disabled={busy} aria-label={t('settings.models.adopt.cancel')}>+ <X />+ </Button>+ </DialogPrimitive.Close>+ </div>+ <DialogPrimitive.Description className="model-hub-adopt-subtitle">+ {t('settings.models.adopt.subtitle', { backend })}+ </DialogPrimitive.Description>+ </header>++ <div className="model-hub-adopt-body">+ {failure && (+ <div className="model-hub-adopt-failure" role="alert">+ <CircleX aria-hidden />+ <span className="min-w-0">+ <strong>{t('settings.models.adopt.fail.title')}</strong>+ <span>{failureDetail}</span>+ </span>+ </div>+ )}+ {runtimeUnavailable && !failure && (+ <div className="model-hub-adopt-failure" role="status">+ <CircleX aria-hidden />+ <span className="min-w-0"><strong>{t('settings.models.shell.unread')}</strong></span>+ </div>+ )}+ <section className="model-hub-adopt-section">+ <h3>{t('settings.models.adopt.section.effects')}</h3>+ {missing && (+ <Bullet>{t('settings.models.adopt.effects.install', {+ component: runtimeValue?.manifest.name,+ duration: t('settings.models.install.duration'),+ })}</Bullet>+ )}+ {effectKeys.map((key) => (+ <Bullet key={key}>{t(`settings.models.adopt.effects.${key}`, { backend, vendor })}</Bullet>+ ))}+ </section>+ <section className="model-hub-adopt-section">+ <h3>{t('settings.models.adopt.section.undo')}</h3>+ {(['1', '2', '3'] as const).map((key) => (+ <Bullet key={key}>{t(`settings.models.adopt.undo.${key}`, { backend })}</Bullet>+ ))}+ </section>+ </div>++ <footer className="model-hub-adopt-foot">+ <Button type="button" variant="outline" className="model-hub-adopt-action" onClick={onClose} disabled={busy}>+ {t('settings.models.adopt.cancel')}+ </Button>+ <Button type="button" variant="brand" className="model-hub-adopt-action" onClick={commit} disabled={busy || runtimeUnavailable || installUnsupported}>+ {busy && <LoaderCircle className="animate-spin" />}+ {missing ? t('settings.models.adopt.confirm.install') : t('settings.models.adopt.confirm')}+ </Button>+ </footer>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>+ );+};++export default EnableGatewayDialog;diff --git a/ui/src/components/settings/models/ExperimentalConsentDialog.tsx b/ui/src/components/settings/models/ExperimentalConsentDialog.tsxdeleted file mode 100644index 4b2fef971..000000000--- a/ui/src/components/settings/models/ExperimentalConsentDialog.tsx+++ /dev/null@@ -1,61 +0,0 @@-// Consent gate for hub-held subscription login (subscription_hub_experimental,-// spec §7). Copy verbatim from the S2 ToS review §9 (ban-risk points). Shown-// ONLY when the experimental channel is chosen; recorded consent marks the-// source 实验.-import * as React from 'react';-import { TriangleAlert } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { Button } from '@/components/ui/button';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';--export const ExperimentalConsentDialog: React.FC<{- open: boolean;- onConsent: () => void;- onCancel: () => void;-}> = ({ open, onConsent, onCancel }) => {- const { t } = useTranslation();- // Three ban-risk points (S2 §9), rendered from the i18n array.- const points = t('settings.models.consent.points', { returnObjects: true }) as string[];-- return (- <Dialog open={open} onOpenChange={(v) => !v && onCancel()}>- <DialogContent className="max-w-[520px] gap-5">- <DialogHeader>- <DialogTitle className="flex items-center gap-2 text-[17px] font-bold">- <span className="grid size-8 shrink-0 place-items-center rounded-lg bg-gold/15 text-gold">- <TriangleAlert className="size-4" />- </span>- {t('settings.models.consent.title')}- </DialogTitle>- <DialogDescription>{t('settings.models.consent.subtitle')}</DialogDescription>- </DialogHeader>-- <ul className="flex flex-col gap-3 rounded-lg border border-gold/30 bg-gold/[0.06] px-4 py-3.5">- {(Array.isArray(points) ? points : []).map((point, i) => (- <li key={i} className="flex gap-2 text-[13px] leading-relaxed text-foreground">- <span className="mt-2 size-1.5 shrink-0 rounded-full bg-gold" aria-hidden />- <span>{point}</span>- </li>- ))}- </ul>-- <DialogFooter className="sm:justify-end">- <Button variant="outline" size="sm" onClick={onCancel}>- {t('common.cancel')}- </Button>- <Button variant="brand-gold" size="sm" onClick={onConsent}>- {t('settings.models.consent.confirm')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- );-};diff --git a/ui/src/components/settings/models/GatewayModule.test.tsx b/ui/src/components/settings/models/GatewayModule.test.tsxnew file mode 100644index 000000000..b74e58fe8--- /dev/null+++ b/ui/src/components/settings/models/GatewayModule.test.tsx@@ -0,0 +1,56 @@+// @vitest-environment jsdom+import { cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import { GatewayModule } from './GatewayModule';+import { failRegionRead, readyRegion } from './regionRead';+import type { AgentSupply } from './types';++const agent: AgentSupply = {+ backend: 'claude',+ cli_present: true,+ mode: 'direct',+ menu_kind: 'fixed',+ sources: null,+ routes: null,+ supply_status: null,+ model_supply: null,+ builtin_models: [],+ named_agents: [],+};++afterEach(cleanup);++describe('GatewayModule region failure treatment', () => {+ it('keeps the last good Agent rows visible with an F2 retry after a later read fails', async () => {+ const onRetry = vi.fn();+ render(+ <I18nextProvider i18n={i18n}>+ <GatewayModule+ supply={failRegionRead(readyRegion([agent]))}+ runtime={null}+ runtimeSnapshot={null}+ onRetry={onRetry}+ sources={[]}+ chains={{}}+ pendingBackends={new Set()}+ switchFailures={new Set()}+ connectingBackend={null}+ onConnectHub={vi.fn()}+ onSwitchDirect={vi.fn()}+ onOpenOrder={vi.fn()}+ onOpenRoute={vi.fn()}+ onProbeSettled={vi.fn()}+ />+ </I18nextProvider>,+ );++ expect(screen.getByText(/^Claude Code$/i)).toBeTruthy();+ expect(screen.getByText(/Could not read this backend's supply|没有读到后端列表/i)).toBeTruthy();+ await userEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));+ expect(onRetry).toHaveBeenCalledOnce();+ });+});diff --git a/ui/src/components/settings/models/GatewayModule.tsx b/ui/src/components/settings/models/GatewayModule.tsxnew file mode 100644index 000000000..b51b022ea--- /dev/null+++ b/ui/src/components/settings/models/GatewayModule.tsx@@ -0,0 +1,45 @@+import * as React from 'react';+import { LoaderCircle } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { AgentCard } from './AgentCard';+import { foldRegionRead, type RegionRead } from './regionRead';+import type { FreshRuntimeProjection } from './runtimeLifecycle';+import type { AgentSupply, RuntimeDependency } from './types';++type GatewayModuleProps = Omit<React.ComponentProps<typeof AgentCard>, 'agents'> & {+ supply: RegionRead<AgentSupply[]>;+ runtime: FreshRuntimeProjection | null;+ runtimeSnapshot: RuntimeDependency | null;+ onRetry: () => void;+};++export const GatewayModule: React.FC<GatewayModuleProps> = ({ runtime, runtimeSnapshot, supply, onRetry, ...props }) => {+ const { t } = useTranslation();+ const agents = foldRegionRead<AgentSupply[], AgentSupply[] | undefined>(supply, {+ loading: () => undefined,+ ready: (data) => data,+ unread: () => undefined,+ degraded: (staleData) => staleData,+ });+ const listening = runtimeSnapshot?.status.listening;+ return (+ <section className="relative z-20 flex max-h-full min-h-[420px] flex-col self-start overflow-hidden rounded-[14px] border border-border bg-surface">+ <header className="flex h-14 shrink-0 items-center justify-between border-b border-border px-3.5">+ <h2 className="text-[16px] font-bold text-foreground">{t('settings.models.gateway.heading')}</h2>+ {listening && <span className="model-hub-fill-white-0a rounded-full border border-border px-2 py-[3px] text-[10.5px] font-semibold text-muted">{listening.host}:{listening.port}</span>}+ </header>+ <div className="min-h-0 flex-1 overflow-y-auto p-2">+ {supply.kind === 'loading' && agents === undefined+ ? <div className="flex h-full min-h-36 items-center justify-center"><LoaderCircle className="size-4 animate-spin text-muted" /></div>+ : supply.kind === 'unread'+ ? <div className="flex h-full min-h-36 flex-col items-center justify-center gap-3 px-4 text-center"><p className="text-[12px] text-muted">{t('settings.models.gateway.supply.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.gateway.retry')}</Button></div>+ : <>+ {supply.kind === 'degraded' && supply.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive">{t('settings.models.gateway.supply.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.gateway.retry')}</Button></div>}+ <AgentCard agents={agents ?? []} runtime={runtime} {...props} />+ </>}+ </div>+ </section>+ );+};diff --git a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx b/ui/src/components/settings/models/InstallGatewayDialog.test.tsxnew file mode 100644index 000000000..c4bb573fd--- /dev/null+++ b/ui/src/components/settings/models/InstallGatewayDialog.test.tsx@@ -0,0 +1,85 @@+// @vitest-environment jsdom+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import { InstallGatewayDialog } from './InstallGatewayDialog';+import { modelsApi } from './modelsApi';+import type { RuntimeDependency } from './types';++const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({+ contract_version: 5,+ manifest: {+ name: 'cliproxyapi',+ version: '1',+ source_sha: 'sha',+ assets: [{ platform: 'darwin-arm64', url: 'https://example.invalid/runtime', size_bytes: 1, sha256: '0'.repeat(64) }],+ },+ status: { installed_version: null, verified: false, listening: null, health, last_check: null },+});++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe('InstallGatewayDialog', () => {+ it('holds install-and-start through both proven steps before closing', async () => {+ const installed = runtime('not_started');+ const running = runtime('ok');+ const install = vi.spyOn(modelsApi, 'installRuntime').mockResolvedValueOnce(installed);+ const start = vi.spyOn(modelsApi, 'startRuntime').mockResolvedValueOnce(running);+ const onRuntime = vi.fn();+ const onClose = vi.fn();+ render(+ <I18nextProvider i18n={i18n}>+ <InstallGatewayDialog runtime={runtime('not_installed')} onClose={onClose} onRuntime={onRuntime} />+ </I18nextProvider>,+ );++ await userEvent.click(screen.getByRole('button', { name: /Install and start|安装并启动/i }));++ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());+ expect(install).toHaveBeenCalledOnce();+ expect(start).toHaveBeenCalledOnce();+ expect(install.mock.invocationCallOrder[0]).toBeLessThan(start.mock.invocationCallOrder[0]);+ expect(onRuntime).toHaveBeenNthCalledWith(1, installed);+ expect(onRuntime).toHaveBeenNthCalledWith(2, running);+ });++ it('keeps the dialog open and offers retry when a background install fails', async () => {+ let settleInstall: ((value: RuntimeDependency) => void) | undefined;+ vi.spyOn(modelsApi, 'installRuntime').mockImplementation(() => new Promise((resolve) => { settleInstall = resolve; }));+ const onClose = vi.fn();+ const view = render(+ <I18nextProvider i18n={i18n}>+ <InstallGatewayDialog runtime={runtime('not_installed')} onClose={onClose} onRuntime={vi.fn()} />+ </I18nextProvider>,+ );+ await userEvent.click(screen.getByRole('button', { name: /Install and start|安装并启动/i }));+ view.rerender(<I18nextProvider i18n={i18n}><InstallGatewayDialog runtime={runtime('installing')} onClose={onClose} onRuntime={vi.fn()} /></I18nextProvider>);+ // #1326 runtime-dependency shape: the server supplies this optional failure key.+ view.rerender(<I18nextProvider i18n={i18n}><InstallGatewayDialog runtime={{ ...runtime('not_installed'), status: { ...runtime('not_installed').status, error_key: 'settings.models.install.fail.detail' } }} onClose={onClose} onRuntime={vi.fn()} /></I18nextProvider>);++ expect(await screen.findByRole('alert')).toBeTruthy();+ expect(screen.getByRole('button', { name: /Try again|重试/i })).toBeTruthy();+ expect(onClose).not.toHaveBeenCalled();+ settleInstall?.(runtime('not_installed'));+ });++ it('renders a persisted install failure immediately after reload', () => {+ const failed = runtime('not_installed');+ failed.status.error_key = 'settings.models.install.fail.detail';++ render(+ <I18nextProvider i18n={i18n}>+ <InstallGatewayDialog runtime={failed} onClose={vi.fn()} onRuntime={vi.fn()} />+ </I18nextProvider>,+ );++ expect(screen.getByRole('alert')).toBeTruthy();+ expect(screen.getByRole('button', { name: /Try again|重试/i })).toBeTruthy();+ });+});diff --git a/ui/src/components/settings/models/InstallGatewayDialog.tsx b/ui/src/components/settings/models/InstallGatewayDialog.tsxnew file mode 100644index 000000000..b5856c22d--- /dev/null+++ b/ui/src/components/settings/models/InstallGatewayDialog.tsx@@ -0,0 +1,116 @@+import * as React from 'react';+import * as DialogPrimitive from '@radix-ui/react-dialog';+import { Check, CircleX, LoaderCircle, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { modelsApi } from './modelsApi';+import { resumeInstallAndStartRuntime, runtimeIsRunning } from './runtimeLifecycle';+import type { RuntimeDependency } from './types';++const Bullet: React.FC<{ children: React.ReactNode }> = ({ children }) => (+ <p className="model-hub-adopt-bullet"><Check aria-hidden /><span>{children}</span></p>+);++export const InstallGatewayDialog: React.FC<{+ runtime: RuntimeDependency;+ onClose: () => void;+ onRuntime: (runtime: RuntimeDependency | null) => void;+}> = ({ runtime, onClose, onRuntime }) => {+ const { t } = useTranslation();+ const [requesting, setRequesting] = React.useState(false);+ const installErrorKey = 'error_key' in runtime.status ? runtime.status.error_key : null;+ const [failed, setFailed] = React.useState(+ runtime.status.health === 'not_installed' && Boolean(installErrorKey),+ );+ const initiated = React.useRef(false);+ const installing = requesting || runtime.status.health === 'installing';++ React.useEffect(() => {+ if (runtime.status.health === 'not_installed' && installErrorKey) {+ setRequesting(false);+ setFailed(true);+ return;+ }+ if (initiated.current && runtimeIsRunning(runtime)) {+ onClose();+ }+ }, [installErrorKey, onClose, runtime.status.health]);++ const install = () => {+ if (installing) return;+ initiated.current = true;+ setRequesting(true);+ setFailed(false);+ void resumeInstallAndStartRuntime(modelsApi, runtime, onRuntime)+ .then((result) => {+ if (result.failedStep) setFailed(true);+ else onClose();+ })+ .finally(() => setRequesting(false));+ };++ return (+ <DialogPrimitive.Root open onOpenChange={(open) => !open && !installing && onClose()}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay className="model-hub-adopt-overlay fixed inset-0 z-50" />+ <DialogPrimitive.Content+ className="model-hub-adopt-dialog fixed left-1/2 top-1/2 z-50 flex -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden bg-surface outline-none"+ onEscapeKeyDown={(event) => { if (installing) event.preventDefault(); }}+ onPointerDownOutside={(event) => { if (installing) event.preventDefault(); }}+ >+ <header className="model-hub-adopt-head">+ <div className="flex items-center justify-between gap-3">+ <DialogPrimitive.Title className="model-hub-adopt-title text-foreground">+ {t('settings.models.install.title')}+ </DialogPrimitive.Title>+ <DialogPrimitive.Close asChild>+ <Button type="button" variant="ghost" size="icon" className="model-hub-adopt-close" disabled={installing} aria-label={t('settings.models.install.cancel')}>+ <X />+ </Button>+ </DialogPrimitive.Close>+ </div>+ <DialogPrimitive.Description className="model-hub-adopt-subtitle">+ {t('settings.models.install.subtitle')}+ </DialogPrimitive.Description>+ </header>+ <div className="model-hub-adopt-body">+ {failed && (+ <div className="model-hub-adopt-failure" role="alert">+ <CircleX aria-hidden />+ <span className="min-w-0">+ <strong>{t('settings.models.install.fail.title')}</strong>+ <span>{t('settings.models.install.fail.detail')}</span>+ </span>+ </div>+ )}+ <section className="model-hub-adopt-section">+ <h3>{t('settings.models.install.section.effects')}</h3>+ <Bullet>{t('settings.models.install.effects.1', {+ component: runtime.manifest.name,+ duration: t('settings.models.install.duration'),+ })}</Bullet>+ <Bullet>{t('settings.models.install.effects.2')}</Bullet>+ <Bullet>{t('settings.models.install.effects.3')}</Bullet>+ </section>+ </div>+ <footer className="model-hub-adopt-foot">+ <Button type="button" variant="outline" className="model-hub-adopt-action" onClick={onClose} disabled={installing}>+ {t('settings.models.install.cancel')}+ </Button>+ <Button type="button" variant="brand" className="model-hub-adopt-action" onClick={install} disabled={installing}>+ {installing && <LoaderCircle className="animate-spin" />}+ {installing+ ? t('settings.models.install.progress')+ : failed+ ? t('settings.models.install.retry')+ : t('settings.models.install.confirm')}+ </Button>+ </footer>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>+ );+};++export default InstallGatewayDialog;diff --git a/ui/src/components/settings/models/MigrationBanner.tsx b/ui/src/components/settings/models/MigrationBanner.tsxindex dcb6a13b2..0aaa929a6 100644--- a/ui/src/components/settings/models/MigrationBanner.tsx+++ b/ui/src/components/settings/models/MigrationBanner.tsx@@ -77,7 +77,7 @@ export const MigrationBanner: React.FC<{title line where it reads as "close this strip". */}<div className="flex flex-col gap-2.5 rounded-xl border border-gold/40 bg-gold/[0.08] px-4 py-3 sm:flex-row sm:items-center sm:gap-3"><div className="flex min-w-0 flex-1 items-center gap-3">- <span className="flex size-9 shrink-0 items-center justify-center rounded-[10px] bg-gold/15 text-gold">+ <span className="model-hub-ink-gold flex size-9 shrink-0 items-center justify-center rounded-[10px] bg-gold/15"><ArrowDownToLine className="size-[18px]" /></span><div className="flex min-w-0 flex-1 flex-col gap-0.5">@@ -98,7 +98,7 @@ export const MigrationBanner: React.FC<{<Buttonvariant="outline"size="sm"- className="h-10 shrink-0 border-gold/40 text-gold hover:bg-gold/10 hover:text-gold sm:h-9"+ className="model-hub-ink-gold h-10 shrink-0 border-gold/40 hover:bg-gold/10 sm:h-9"onClick={() => setDialogOpen(true)}><ArrowDownToLine className="size-3.5" />diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsxindex d390e5767..d16ef9aa5 100644--- a/ui/src/components/settings/models/MigrationDialog.tsx+++ b/ui/src/components/settings/models/MigrationDialog.tsx@@ -1,8 +1,8 @@// 迁移对话框 · 接入模型中枢 (frame 03). Non-destructive: a per-backend checklist of// detected native configs. Actions follow migration-scan.schema (spec v1.1,-// Option 1): API keys / base URLs → import; Claude account OAuth → keep_native-// (sanctioned as-is); Codex auth.json → controlled_import behind the-// experimental flag, else keep_native. Originals are never modified or deleted.+// Option 1): API keys / base URLs → import; subscription OAuth → keep_native.+// controlled_import is reserved and not applicable in v3. Originals are never+// modified or deleted.// Scans via POST /migration/scan; applies the selection via /migration/apply.import * as React from 'react';import { ArrowDownToLine, Bot, KeyRound, ShieldCheck, Sparkles } from 'lucide-react';@@ -170,7 +170,7 @@ export const MigrationDialog: React.FC<{<DialogHeader><DialogTitle className="flex items-center gap-3 text-[18px] font-bold"><span className="flex size-10 shrink-0 items-center justify-center rounded-[12px] bg-mint-soft">- <ArrowDownToLine className="size-5 text-mint" />+ <ArrowDownToLine className="model-hub-ink-mint size-5" /></span>{t('settings.models.migration.title')}</DialogTitle>@@ -185,7 +185,7 @@ export const MigrationDialog: React.FC<{<div className="flex flex-col gap-4">{grouped.map((group) => (<div key={group.backend} className="flex flex-col gap-2">- <span className="px-1 font-mono text-[11px] font-semibold uppercase tracking-[0.08em] text-muted">+ <span className="px-1 font-mono text-[11px] font-semibold uppercase tracking-normal text-muted">{t(`settings.models.backends.${group.backend}`, { defaultValue: group.backend })}</span>{group.rows.map((item) => (@@ -196,7 +196,7 @@ export const MigrationDialog: React.FC<{</div>)}- <p className="flex items-start gap-2 text-[12px] leading-relaxed text-mint">+ <p className="model-hub-ink-mint flex items-start gap-2 text-[12px] leading-relaxed"><ShieldCheck className="mt-0.5 size-4 shrink-0" />{t('settings.models.migration.nonDestructive')}</p>diff --git a/ui/src/components/settings/models/ModelHubInfoHint.tsx b/ui/src/components/settings/models/ModelHubInfoHint.tsxnew file mode 100644index 000000000..a1098f951--- /dev/null+++ b/ui/src/components/settings/models/ModelHubInfoHint.tsx@@ -0,0 +1,37 @@+import * as React from 'react';+import { Info } from 'lucide-react';++import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';+import { cn } from '@/lib/utils';++export const ModelHubInfoHint: React.FC<{+ label: string;+ content: React.ReactNode;+ className?: string;+ align?: 'start' | 'center' | 'end';+}> = ({ label, content, className, align = 'start' }) => {+ const [open, setOpen] = React.useState(false);+ return (+ <Popover open={open} onOpenChange={setOpen} modal>+ <PopoverTrigger asChild>+ <button+ type="button"+ aria-label={label}+ onPointerEnter={(event) => { if (event.pointerType === 'mouse') setOpen(true); }}+ onPointerLeave={(event) => { if (event.pointerType === 'mouse') setOpen(false); }}+ className={cn('inline-flex size-4 shrink-0 items-center justify-center rounded-full text-muted outline-none transition hover:text-foreground focus-visible:text-foreground', className)}+ >+ <Info className="size-3.5" />+ </button>+ </PopoverTrigger>+ <PopoverContent+ align={align}+ sideOffset={6}+ onOpenAutoFocus={(event) => event.preventDefault()}+ className="w-64 p-3 text-[12px] font-normal leading-relaxed text-muted"+ >+ {content}+ </PopoverContent>+ </Popover>+ );+};diff --git a/ui/src/components/settings/models/ModelRoutePicker.tsx b/ui/src/components/settings/models/ModelRoutePicker.tsxdeleted file mode 100644index 1f3e944cf..000000000--- a/ui/src/components/settings/models/ModelRoutePicker.tsx+++ /dev/null@@ -1,167 +0,0 @@-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/OAuthConnectDialog.test.ts b/ui/src/components/settings/models/OAuthConnectDialog.test.tsnew file mode 100644index 000000000..8001f1f90--- /dev/null+++ b/ui/src/components/settings/models/OAuthConnectDialog.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import {+ initialSubscriptionChannel,+ nativeSubscriptionSlotTaken,+ recommendedSubscriptionChannel,+ subscriptionOptionOrder,+} from './subscriptionOptions';+import type { Source } from './types';++const subscription = (over: Partial<Source> = {}): Source => ({+ id: 'src_subscription',+ last_discovered_at: null,+ kind: 'subscription',+ vendor: 'anthropic',+ display_name: 'Subscription',+ protocol: 'anthropic',+ supply_channel: 'native_cli',+ billing: 'monthly',+ state: { status: 'standby' },+ models: [],+ ...over,+});++describe('add-subscription channel choice', () => {+ it('flips the recommendation and visible order by vendor', () => {+ expect(recommendedSubscriptionChannel('anthropic')).toBe('native_cli');+ expect(subscriptionOptionOrder('anthropic')).toEqual(['native_cli', 'hub']);+ expect(recommendedSubscriptionChannel('openai')).toBe('hub');+ expect(subscriptionOptionOrder('openai')).toEqual(['hub', 'native_cli']);+ });++ it('uses the recommended option while the native slot is free', () => {+ expect(initialSubscriptionChannel('anthropic', [])).toBe('native_cli');+ expect(initialSubscriptionChannel('openai', [])).toBe('hub');+ });++ it('keeps an occupied native row visible but selects the gateway option', () => {+ const sources = [subscription()];+ expect(nativeSubscriptionSlotTaken('anthropic', sources)).toBe(true);+ expect(initialSubscriptionChannel('anthropic', sources)).toBe('hub');+ });++ it('does not let another vendor or a gateway-held source occupy the slot', () => {+ const sources = [+ subscription({ vendor: 'openai' }),+ subscription({ id: 'src_hub', supply_channel: 'hub' }),+ ];+ expect(nativeSubscriptionSlotTaken('anthropic', sources)).toBe(false);+ });+});diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsxindex c0b9a3ce9..21f95b167 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx@@ -1,4 +1,4 @@-// 连接订阅 dialog (frame 09). RENDERS DECLARATIVELY from the runtime-declared+// Add-subscription dialog (frame 04). RENDERS DECLARATIVELY from the runtime-declared// oauth-flow presentation (S1 gap ③): `expects` ∈ none | paste_code |// paste_callback_url selects the step-2 control; there is NO vendor→form table// in the UI. Composes the shared OAuth atoms (OAuthLinkRow / OAuthDeviceCodeRow@@ -14,7 +14,8 @@// how one of the two ends up reading a different half of the envelope, which is// the bug `settle` below was written to fix.import * as React from 'react';-import { CheckCircle2, Sparkles, TriangleAlert } from 'lucide-react';+import * as DialogPrimitive from '@radix-ui/react-dialog';+import { ArrowRight, CheckCircle2, Info, Sparkles, TriangleAlert, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';@@ -35,12 +36,16 @@ import {type FlowAuthority,type FlowView,} from './asyncLifetime';-import { ExperimentalConsentDialog } from './ExperimentalConsentDialog';-import { SUBSCRIPTION_HUB_EXPERIMENTAL } from './featureFlags';import { apiFailure, modelsApi, type Adoption, type OAuthResult } from './modelsApi';import { REPAIR_LINE_KEY, REPAIR_TOAST, repairOutcome, repairSettles, type RepairOutcome } from './repair';import { oauthFailureKey, serverText, type OAuthJourney } from './serverCopy';-import { adoptionVerdict } from './sufficiency';+import {+ initialSubscriptionChannel,+ nativeSubscriptionSlotTaken,+ recommendedSubscriptionChannel,+ subscriptionOptionOrder,+ subscriptionVendorCopy,+} from './subscriptionOptions';import { SupplyGapNote } from './SupplyGapNote';import { ACCENT_ICON, ACCENT_TILE } from './vendorMeta';import type { Source, SupplyChannel, SupplyGap } from './types';@@ -48,6 +53,10 @@ import type { Source, SupplyChannel, SupplyGap } from './types';const POLL_MS = 2000;const DEADLINE_MS = 16 * 60 * 1000;+type ConnectPhase = 'choose' | 'flow';++const CHANNELS: SupplyChannel[] = ['native_cli', 'hub'];+const Step: React.FC<{ n: number; label: string; children: React.ReactNode }> = ({ n, label, children }) => (<div className="flex flex-col gap-2.5 rounded-lg border border-border bg-surface-2/40 px-4 py-3"><span className="text-[13px] font-medium text-foreground">@@ -69,9 +78,11 @@ export const OAuthConnectDialog: React.FC<{* subject mid-flow.*/reauth?: Source | null;+ /** Snapshot candidates used to decide whether this backend's native slot is occupied. */+ sources?: Source[];onClose: () => void;- onConnected: () => void;-}> = ({ open, vendor, reauth = null, onClose, onConnected }) => {+ onConnected: (source?: Source, placement?: Adoption) => void;+}> = ({ open, vendor, reauth = null, sources = [], onClose, onConnected }) => {const { t } = useTranslation();const { showToast } = useToast();@@ -79,10 +90,11 @@ export const OAuthConnectDialog: React.FC<{const [code, setCode] = React.useState('');const [submitting, setSubmitting] = React.useState(false);const [channel, setChannel] = React.useState<SupplyChannel>('native_cli');- const [consentOpen, setConsentOpen] = React.useState(false);+ const [phase, setPhase] = React.useState<ConnectPhase>('choose');+ const [nativeSlotTaken, setNativeSlotTaken] = React.useState(false);// Which Agents took the new subscription in, frozen at commit (api.md). Same// note as the API-key dialog: connecting a credential is not the same as- // putting it into service, and a `custom` Agent is silently absent.+ // putting it into service, and an Agent with no accepted match is absent.//// `null` means the terminal response did not report a creation — which is not// 「没有 Agent 采用」 and must not be rendered as it.@@ -114,6 +126,7 @@ export const OAuthConnectDialog: React.FC<{onConnectedRef.current = onConnected;const onCloseRef = React.useRef(onClose);onCloseRef.current = onClose;+ const initializedOpenSubject = React.useRef<string | null>(null);const accent = vendor === 'openai' ? 'gold' : 'mint';// One derivation for 「which journey is this」, read by the start call, the@@ -125,6 +138,29 @@ export const OAuthConnectDialog: React.FC<{// on a repair, and `oauthFailureKey` takes the journey rather than guessing.const journey: OAuthJourney = isReauth ? 'reauth' : 'connect';+ // Take the native-slot reading once per open. A source arriving after this is+ // the singleton race the start route owns; it must surface as Already bound,+ // not silently rewrite a choice already under the user's pointer.+ const openSubject = open ? `${vendor}:${reauthId ?? 'create'}` : null;+ React.useEffect(() => {+ if (!openSubject) {+ initializedOpenSubject.current = null;+ setPhase('choose');+ return;+ }+ if (initializedOpenSubject.current === openSubject) return;+ initializedOpenSubject.current = openSubject;+ if (isReauth) {+ setChannel(reauth?.supply_channel ?? 'native_cli');+ setPhase('flow');+ return;+ }+ const occupied = nativeSubscriptionSlotTaken(vendor, sources);+ setNativeSlotTaken(occupied);+ setChannel(initialSubscriptionChannel(vendor, sources));+ setPhase('choose');+ }, [isReauth, openSubject, reauth?.supply_channel, sources, vendor]);+/*** One owner for 「the server moved the rows the page behind this dialog draws」,* reached from EVERY path where that can have happened.@@ -153,7 +189,7 @@ export const OAuthConnectDialog: React.FC<{* none」 and 「this arrival may not answer that question」 need saying separately.* It defaults to the SILENT answer, because the two answers are not equally* wrong. This component outlives the attempt — both hosts leave it mounted and- * toggle `open` (`RepairJourney.tsx`, `SettingsModelsPage.tsx`), so `stranded`+ * toggle `open`, so `stranded`* survives a close, and a request left in flight by attempt A can land after* attempt B has already put ITS gap report on screen. A site that forgets to* speak costs nothing: the refetch it came for still runs. A site that forgets@@ -168,10 +204,10 @@ export const OAuthConnectDialog: React.FC<{* resolved-after-close path, the released flow's re-read — says nothing, and* says it by default.*/- const rowsBehindAreStale = (failure?: ReturnType<typeof apiFailure>, pairsSpeak = false) => {+ const rowsBehindAreStale = React.useCallback((failure?: ReturnType<typeof apiFailure>, pairsSpeak = false) => {if (isReauth && pairsSpeak) setStranded(failure?.interrupted ?? []);onConnectedRef.current();- };+ }, [isReauth]);/*** A request of one attempt that resolved after that attempt stopped being the one@@ -198,7 +234,7 @@ export const OAuthConnectDialog: React.FC<{* different source is one click away, and this request can land after that* one has failed.*/- const resolvedAfterAttempt = () => rowsBehindAreStale();+ const resolvedAfterAttempt = React.useCallback(() => rowsBehindAreStale(), [rowsBehindAreStale]);const copy = (text: string | null | undefined) => (e: React.MouseEvent) => {e.preventDefault();@@ -216,10 +252,9 @@ export const OAuthConnectDialog: React.FC<{.catch(() => showToast(t('common.copyFailed') as string, 'error'));};- // Drive the flow while the dialog is open. Re-runs when the target channel- // changes (experimental hub opt-in restarts the flow).+ // Drive the flow only after the user confirms one channel.React.useEffect(() => {- if (!open) return;+ if (!open || phase !== 'flow') return;let cancelled = false;let pollTimer: number | null = null;let deadline = Date.now() + DEADLINE_MS;@@ -279,21 +314,9 @@ export const OAuthConnectDialog: React.FC<{// success materializes it server-side and consumes the flow binding doing// it — there is nothing left to finalize, and a POST /sources afterwards// is refused as `flow_not_found` on a connect that in fact succeeded.- setAdoption(created ? { adopted_by: created.adopted_by, skipped_by: created.skipped_by } : null);+ setAdoption(created ? { added_to: created.added_to, adopted_by: created.adopted_by } : null);showToast(t('settings.models.oauth.status.success') as string, 'success');- // Same rule as the API-key dialog, through the same owner: 1.4s auto-dismiss- // is for a pure 「连接成功」, and every other verdict leaves an instruction on- // screen that 1.4s is not long enough to read. The old `!== 0` also read an- // ABSENT creation as adopted, which auto-dismissed the one case that knows- // least — `adoptionVerdict(null)` is indeterminate, so it now waits.- //- // `covered` and nothing weaker, and `skipped_by` is what makes it reachable- // at all: a non-empty adopter list never ruled out a `custom` backend that- // was left out, and that sentence is an instruction too. A response that- // omits the field leaves the verdict `indeterminate` and the dialog open —- // the same answer this site gave before the field existed.- if (adoptionVerdict(created?.adopted_by ?? null, created?.skipped_by).kind === 'covered')- successTimer.current = window.setTimeout(() => onCloseRef.current(), 1400);+ if (created) onConnectedRef.current(created.source, created);}// Both branches above end with the same fact about the page behind them, and// so does the failure neither of them handles: `terminalArrivalMovedRows`@@ -336,7 +359,7 @@ export const OAuthConnectDialog: React.FC<{}// A poll that lands on a just-succeeded flow is also the call that// materializes the outcome, so it can fail for reasons that have nothing- // to do with the authorization (consent_required / discovery_failed):+ // to do with the authorization (for example discovery_failed):// the vendor said yes and what came after it broke. Naming that// separately is the difference between 「重试授权」 and 「授权成功,后面// 没成」 — and WHICH object it broke is the journey's to say.@@ -374,14 +397,11 @@ export const OAuthConnectDialog: React.FC<{setStranded([]);void (async () => {try {- // Two ways in, one flow out. The reauth route opens the flow ON the- // existing source and acknowledges the irreversibility server-side (the- // page has already asked); a create opens a fresh one, and a hub-held- // connect (channel === 'hub' only after the experimental consent below)- // must carry consent or the server returns consent_required.+ // Two ways in, one flow out. The reauth route opens the flow on the+ // existing source; a create opens a fresh one for the selected channel.const started = reauthId? await modelsApi.reauthSource(reauthId)- : await modelsApi.startOAuth(vendor, channel, channel === 'hub');+ : await modelsApi.startOAuth(vendor, channel);if (cancelled) {// The dialog closed while this request was in flight, so the cleanup// below found no flow to cancel — the flow id exists nowhere but here.@@ -444,7 +464,6 @@ export const OAuthConnectDialog: React.FC<{resolvedAfterAttempt();return;}- const code = failure?.code;// Nothing can have settled this view yet — the reset above is the last// thing that touched it, and both other arrivals need the flow this call// failed to produce. It asks anyway, because 「may these pairs speak?」 is@@ -453,10 +472,7 @@ export const OAuthConnectDialog: React.FC<{// position moves.const step = transition({kind: 'error',- errorKey:- code === 'consent_required'- ? 'settings.models.oauth.error.consent'- : 'settings.models.oauth.error.start',+ errorKey: 'settings.models.oauth.error.start',});rowsBehindAreStale(failure, failureLanded(step.action));}@@ -498,7 +514,7 @@ export const OAuthConnectDialog: React.FC<{reread: () => rowsBehindAreStale(),});};- }, [open, vendor, channel, reauthId, t, showToast]);+ }, [open, phase, vendor, channel, reauthId, t, showToast, isReauth, rowsBehindAreStale, resolvedAfterAttempt, journey]);// 1-second ticker so the paste-flow countdown updates.React.useEffect(() => {@@ -507,14 +523,6 @@ export const OAuthConnectDialog: React.FC<{return () => window.clearInterval(id);}, [open]);- // Consent is per-attempt: reset the experimental hub opt-in when the dialog- // CLOSES, so the next open's start effect always begins from native_cli.- // (Resetting on open would run after the start effect and briefly launch a- // stale hub flow before the reset lands.)- React.useEffect(() => {- if (!open) setChannel('native_cli');- }, [open]);-const submit = async () => {const authority = flowAuthorityRef.current;const cur = authority?.current().flow;@@ -595,6 +603,145 @@ export const OAuthConnectDialog: React.FC<{: 'settings.models.oauth.pasteCode.hint';const step2Label = serverText(t, presentation?.instructions_key, step2Fallback) ?? '';+ const choosing = !isReauth && phase === 'choose';+ const vendorCopy = subscriptionVendorCopy(vendor);+ const vendorName = vendor === 'openai' ? 'ChatGPT' : 'Claude';+ const recommended = recommendedSubscriptionChannel(vendor);+ const optionOrder = subscriptionOptionOrder(vendor);+ const optionRefs = React.useRef<Partial<Record<SupplyChannel, HTMLButtonElement | null>>>({});+ const selectableChannels = CHANNELS.filter((candidate) => candidate !== 'native_cli' || !nativeSlotTaken);++ const moveSelection = (direction: number) => {+ const currentIndex = selectableChannels.indexOf(channel);+ const nextIndex =+ (Math.max(0, currentIndex) + direction + selectableChannels.length) % selectableChannels.length;+ const next = selectableChannels[nextIndex];+ setChannel(next);+ window.requestAnimationFrame(() => optionRefs.current[next]?.focus());+ };++ if (choosing) {+ return (+ <DialogPrimitive.Root open={open} onOpenChange={(value) => !value && onClose()}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay className="model-hub-add-sub-overlay fixed inset-0 z-50" />+ <DialogPrimitive.Content className="model-hub-add-sub-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col gap-0 overflow-y-auto border border-border-strong bg-surface p-0 shadow-xl outline-none">+ <header className="model-hub-add-sub-head flex flex-col border-b border-border">+ <div className="flex items-center justify-between gap-3">+ <DialogPrimitive.Title id="model-hub-add-sub-title" className="model-hub-add-sub-title font-bold">+ {t('settings.models.addSub.title', { vendor: vendorName })}+ </DialogPrimitive.Title>+ <DialogPrimitive.Close asChild>+ <Button type="button" variant="ghost" size="icon" className="model-hub-add-sub-close" aria-label={t('settings.models.addSub.cancel')} title={t('settings.models.addSub.cancel')}>+ <X aria-hidden />+ </Button>+ </DialogPrimitive.Close>+ </div>+ <DialogPrimitive.Description className="model-hub-add-sub-subtitle text-muted">{t(`settings.models.addSub.subtitle.${vendorCopy}`)}</DialogPrimitive.Description>+ </header>++ <div className="model-hub-add-sub-body flex flex-col">+ <div+ role="radiogroup"+ aria-labelledby="model-hub-add-sub-title"+ className="model-hub-add-sub-options flex flex-col"+ >+ {optionOrder.map((candidate) => {+ const isNative = candidate === 'native_cli';+ const disabled = isNative && nativeSlotTaken;+ const selected = channel === candidate;+ const badgeKey = disabled+ ? 'added'+ : candidate === recommended+ ? 'recommended'+ : vendorCopy === 'claude'+ ? 'secondary'+ : 'supportedNotRecommended';+ const optionKey = isNative ? 'native' : 'hub';+ return (+ <button+ key={candidate}+ ref={(node) => {+ optionRefs.current[candidate] = node;+ }}+ type="button"+ role="radio"+ aria-checked={selected}+ aria-disabled={disabled}+ tabIndex={selected ? 0 : -1}+ onClick={() => !disabled && setChannel(candidate)}+ onKeyDown={(event) => {+ if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {+ event.preventDefault();+ moveSelection(1);+ } else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {+ event.preventDefault();+ moveSelection(-1);+ }+ }}+ className={cn(+ 'model-hub-add-sub-option flex items-start gap-3 text-left transition-colors',+ selected+ ? 'border-mint/35 bg-mint/[0.06]'+ : 'model-hub-add-sub-option--idle border-border hover:border-border-strong',+ disabled && 'cursor-not-allowed opacity-55 hover:border-border',+ )}+ >+ {!disabled && (+ <span+ className={cn(+ 'mt-0.5 grid size-4 shrink-0 place-items-center rounded-full border',+ selected ? 'border-mint' : 'model-hub-border-white-33',+ )}+ aria-hidden+ >+ {selected && <span className="size-2 rounded-full bg-mint" />}+ </span>+ )}+ <span className="model-hub-add-sub-option-copy min-w-0 flex flex-1 flex-col">+ <span className="flex flex-wrap items-center gap-2">+ <span className="model-hub-add-sub-option-label font-semibold text-foreground">+ {t(`settings.models.addSub.opt.${optionKey}.label`)}+ </span>+ <span className="model-hub-accent-pill--mint model-hub-add-sub-badge rounded-full border font-semibold">+ {t(`settings.models.addSub.${disabled ? 'opt' : 'badge'}.${badgeKey}`)}+ </span>+ </span>+ <span className="model-hub-add-sub-description block text-muted">+ {t(`settings.models.addSub.opt.${optionKey}.desc.${vendorCopy}`)}+ </span>+ {vendorCopy === 'claude' && candidate === 'hub' && (+ <span className="model-hub-add-sub-risk flex items-start gap-2 border border-gold/30 bg-gold/10">+ <TriangleAlert className="mt-0.5 size-3 shrink-0" />+ <span>{t('settings.models.addSub.tos.claude')}</span>+ </span>+ )}+ </span>+ </button>+ );+ })}+ </div>+ <p className="model-hub-add-sub-hint flex items-start gap-2 text-muted">+ <Info className="mt-0.5 size-3 shrink-0" />+ <span>{t(`settings.models.addSub.hint.${vendorCopy}`)}</span>+ </p>+ </div>++ <div className="model-hub-add-sub-foot model-hub-fill-white-05 flex items-center justify-end gap-2 border-t border-border">+ <Button variant="ghost" size="sm" className="model-hub-dialog-action" onClick={onClose}>+ {t('settings.models.addSub.cancel')}+ </Button>+ <Button variant="brand" size="sm" className="model-hub-dialog-action" onClick={() => setPhase('flow')}>+ {t('settings.models.addSub.signIn')}+ <ArrowRight className="size-3.5" />+ </Button>+ </div>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>+ );+ }+return (<><Dialog open={open} onOpenChange={(v) => !v && onClose()}>@@ -635,7 +782,7 @@ export const OAuthConnectDialog: React.FC<{// something is still without a source. Only the last stays on screen.repair?.kind === 'gaps' ? (<div className="flex flex-col gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-3">- <span className="text-[12.5px] font-semibold leading-relaxed text-gold">+ <span className="model-hub-ink-gold text-[12.5px] font-semibold leading-relaxed">{t('settings.models.repair.gapsDone')}</span><SupplyGapNote gaps={repair.gaps} />@@ -646,12 +793,12 @@ export const OAuthConnectDialog: React.FC<{// that reports itself signed out lands here). A 「已恢复可用」 over// that is the dead end §4.5 forbids; the row keeps its remedy and// this line is why it is still there.- <div className="flex items-center gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-4 py-3 text-[13px] font-medium text-gold">+ <div className="model-hub-ink-gold flex items-center gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-4 py-3 text-[13px] font-medium"><TriangleAlert className="size-4 shrink-0" />{t('settings.models.repair.unresolved')}</div>) : (- <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">+ <div className="model-hub-ink-mint flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium"><CheckCircle2 className="size-4 shrink-0" />{repair? t(REPAIR_LINE_KEY[repair.kind])@@ -660,7 +807,7 @@ export const OAuthConnectDialog: React.FC<{)) : success ? (<div className="flex flex-col gap-2">- <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">+ <div className="model-hub-ink-mint flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium"><CheckCircle2 className="size-4 shrink-0" />{t('settings.models.oauth.connected')}</div>@@ -669,7 +816,7 @@ export const OAuthConnectDialog: React.FC<{a claim this response never made. The two halves come off ONEvalue, so the note can never read a skip list from one arrivalagainst an adopter list from another. */}- <AdoptionNote adoptedBy={adoption?.adopted_by ?? null} skippedBy={adoption?.skipped_by} />+ <AdoptionNote addedTo={adoption?.added_to ?? null} adoptedBy={adoption?.adopted_by ?? null} /></div>) : (active && (@@ -715,35 +862,6 @@ export const OAuthConnectDialog: React.FC<{)}</Step>- {/* Withheld on a re-auth: where a subscription is HELD is a- property of the existing source, and this flow is signing back- into it — offering to move it here would be a different- operation wearing this one's clothes. */}- {SUBSCRIPTION_HUB_EXPERIMENTAL && !isReauth && (- <button- type="button"- onClick={() => (channel === 'hub' ? setChannel('native_cli') : setConsentOpen(true))}- className={cn(- 'flex items-center justify-between gap-3 rounded-lg border px-4 py-2.5 text-left text-[12px] transition-colors',- channel === 'hub'- ? 'border-gold/40 bg-gold/[0.06]'- : 'border-border bg-background hover:border-border-strong',- )}- >- <span className="flex flex-col gap-0.5">- <span className="font-medium text-foreground">{t('settings.models.oauth.hubOption.title')}</span>- <span className="text-muted">{t('settings.models.oauth.hubOption.subtitle')}</span>- </span>- <span- className={cn(- 'shrink-0 rounded-full px-2 py-0.5 text-[11px] font-semibold',- channel === 'hub' ? 'bg-gold/20 text-gold' : 'bg-surface-2 text-muted',- )}- >- {channel === 'hub' ? t('settings.models.oauth.hubOption.on') : t('settings.models.oauth.hubOption.off')}- </span>- </button>- )}</div>))}@@ -768,14 +886,6 @@ export const OAuthConnectDialog: React.FC<{</DialogContent></Dialog>- <ExperimentalConsentDialog- open={consentOpen}- onConsent={() => {- setConsentOpen(false);- setChannel('hub');- }}- onCancel={() => setConsentOpen(false)}- /></>);};diff --git a/ui/src/components/settings/models/RecentSwitchesCard.test.tsx b/ui/src/components/settings/models/RecentSwitchesCard.test.tsxindex 543309e57..88a4ee608 100644--- a/ui/src/components/settings/models/RecentSwitchesCard.test.tsx+++ b/ui/src/components/settings/models/RecentSwitchesCard.test.tsx@@ -8,8 +8,9 @@ import { describe, expect, it } from 'vitest';import en from '../../../i18n/en.json';import zh from '../../../i18n/zh.json';-import { eventAccent } from './eventFeed';+import { emptyFeed, eventAccent } from './eventFeed';import { RecentSwitchesCard } from './RecentSwitchesCard';+import { readyRegion, unreadRegion } from './regionRead';import type { ResolutionEvent, Source } from './types';const instance = (lng: 'en' | 'zh') => {@@ -58,7 +59,7 @@ const render = () =>renderToStaticMarkup(<I18nextProvider i18n={instance(lng)}>- <RecentSwitchesCard events={events} sources={sources} hasMore={hasMore} />+ <RecentSwitchesCard events={readyRegion({ ...emptyFeed, events, exhausted: !hasMore })} sources={readyRegion(sources)} hasMore={hasMore} /></I18nextProvider>,);@@ -82,6 +83,26 @@ describe('RecentSwitchesCard (AC-18)', () => {expect(html).not.toContain(zh.settings.models.recent.deletedSource);});+ it('does not call a source deleted while the inventory read is unavailable', () => {+ const html = renderToStaticMarkup(+ <I18nextProvider i18n={instance('en')}>+ <RecentSwitchesCard events={readyRegion({ ...emptyFeed, events: [event()] })} sources={unreadRegion()} />+ </I18nextProvider>,+ );+ expect(html).not.toContain(en.settings.models.recent.deletedSource);+ });++ it('renders an event-read failure with a retry instead of an authoritative empty feed', () => {+ const html = renderToStaticMarkup(+ <I18nextProvider i18n={instance('en')}>+ <RecentSwitchesCard events={unreadRegion()} sources={readyRegion([])} />+ </I18nextProvider>,+ );+ expect(html).toContain('Couldn't refresh, please retry');+ expect(html).toContain(en.settings.models.upstream.retry);+ expect(html).not.toContain(en.settings.models.recent.empty);+ });+it('marks nothing for an event that names no source at all', () => {// A supply interruption is about a backend: both endpoints are null by// contract, and null is not a deleted source.@@ -104,19 +125,10 @@ describe('RecentSwitchesCard (AC-18)', () => {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);+ it('keeps a paging door open when more events exist', () => {+ const html = render([event()], [source('src_live01')], 'zh', true);expect(html).not.toContain(zh.settings.models.recent.empty);- expect(html).toContain(zh.settings.models.recent.loadMore);+ expect(html).toContain(zh.settings.models.recent.viewAll);});});diff --git a/ui/src/components/settings/models/RecentSwitchesCard.tsx b/ui/src/components/settings/models/RecentSwitchesCard.tsxindex 4be63a266..4a000f1a0 100644--- a/ui/src/components/settings/models/RecentSwitchesCard.tsx+++ b/ui/src/components/settings/models/RecentSwitchesCard.tsx@@ -16,15 +16,14 @@ import { useTranslation } from 'react-i18next';import { Badge } from '@/components/ui/badge';import { Dot } from './chips';-import { eventAccent } from './eventFeed';+import { emptyFeed, eventAccent, type EventFeed } from './eventFeed';+import { localCalendarRelation } from './localCalendar';+import { foldRegionRead, type RegionRead } from './regionRead';import type { ResolutionEvent, Source } from './types';const COLLAPSED = 3;/** 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();return (ts: string): string => {@@ -32,58 +31,71 @@ function useEventTime() {const now = new Date();const hh = String(d.getHours()).padStart(2, '0');const mm = String(d.getMinutes()).padStart(2, '0');- const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();- const dayMs = 86_400_000;- const dayDiff = Math.floor((startOfToday - new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()) / dayMs);+ const relation = localCalendarRelation(d, now);let day: string;- if (dayDiff === 0) day = t('settings.models.recent.today') as string;- else if (dayDiff === 1) day = t('settings.models.recent.yesterday') as string;+ if (relation === 'today') day = t('settings.models.recent.today') as string;+ else if (relation === 'yesterday') day = t('settings.models.recent.yesterday') as string;else day = `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;return `${day} ${hh}:${mm}`;};}export const RecentSwitchesCard: React.FC<{- events: ResolutionEvent[];+ events: RegionRead<EventFeed>;/** Live inventory — read only to tell a still-present source from a deleted one. */- sources: Source[];+ sources: RegionRead<Source[]>;/** The feed has older pages than the ones held here (`/events` pages by cursor). */hasMore?: boolean;loadingMore?: boolean;/** Fetch the next older page. Required for 查看全部 to mean 全部. */onLoadMore?: () => void | Promise<void>;-}> = ({ events, sources, hasMore = false, loadingMore = false, onLoadMore }) => {+ onRetry?: () => void | Promise<void>;+}> = ({ events: eventsRead, sources: sourcesRead, hasMore, loadingMore = false, onLoadMore, onRetry }) => {const { t, i18n } = useTranslation();const [expanded, setExpanded] = React.useState(false);const formatTime = useEventTime();const zh = i18n.language.startsWith('zh');+ const feed = foldRegionRead(eventsRead, {+ loading: () => emptyFeed,+ ready: (data) => data,+ unread: () => emptyFeed,+ degraded: (staleData) => staleData,+ });+ const events = feed.events;+ const sources = foldRegionRead<Source[], Source[]>(sourcesRead, {+ loading: () => [],+ ready: (data) => data,+ unread: () => [],+ degraded: (staleData) => staleData,+ });+ const sourceInventoryCurrent = sourcesRead.kind === 'ready';+ const hasOlder = hasMore ?? !feed.exhausted;const liveIds = React.useMemo(() => new Set(sources.map((s) => s.id)), [sources]);const namesDeletedSource = (e: ResolutionEvent) =>- [e.from_source, e.to_source].some((id) => typeof id === 'string' && id !== '' && !liveIds.has(id));+ sourceInventoryCurrent && [e.from_source, e.to_source].some((id) => typeof id === 'string' && id !== '' && !liveIds.has(id));- const visibleEvents = visibleResolutionEvents(events);+ const visibleEvents = 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+ // Walk older pages until the collapsed feed has three 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 (eventsRead.kind !== 'ready' || visibleEvents.length >= COLLAPSED || !hasOlder || loadingMore || !onLoadMore) return;if (backfilledTailRef.current === rawTailId) return;backfilledTailRef.current = rawTailId;void onLoadMore();- }, [hasMore, loadingMore, onLoadMore, rawTailId, visibleEvents.length]);+ }, [eventsRead.kind, hasOlder, 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 = visibleEvents.length > COLLAPSED || hasMore;+ const canExpand = eventsRead.kind === 'ready' && (visibleEvents.length > COLLAPSED || hasOlder);const expand = () => {setExpanded(true);- if (hasMore && !loadingMore) onLoadMore?.();+ if (hasOlder && !loadingMore) onLoadMore?.();};return (@@ -94,20 +106,26 @@ export const RecentSwitchesCard: React.FC<{<buttontype="button"onClick={() => (expanded ? setExpanded(false) : expand())}- className="inline-flex min-h-10 items-center text-[13px] font-medium text-mint transition-colors hover:text-mint/80 sm:min-h-0"+ className="model-hub-action-mint inline-flex min-h-10 items-center text-[13px] font-medium transition-colors sm:min-h-0">{expanded ? t('settings.models.recent.collapse') : t('settings.models.recent.viewAll')}</button>)}</div>- {shown.length === 0 ? (+ {((eventsRead.kind === 'degraded' && eventsRead.cause === 'read_failed') || eventsRead.kind === 'unread') && (+ <div className="flex items-center justify-between gap-3 border-b border-border px-4 py-3 text-[12px] text-destructive sm:px-5">+ <span>{t('settings.models.toast.refreshFailed')}</span>+ <button type="button" onClick={() => void onRetry?.()} className="model-hub-action-mint shrink-0 font-semibold">{t('settings.models.upstream.retry')}</button>+ </div>+ )}+ {((eventsRead.kind === 'degraded' && eventsRead.cause === 'read_failed') || eventsRead.kind === 'unread') && shown.length === 0 ? null : shown.length === 0 ? (<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 && (+ <span>{eventsRead.kind === 'loading' || hasOlder ? t('settings.models.recent.loadingMore') : t('settings.models.recent.empty')}</span>+ {eventsRead.kind === 'ready' && hasOlder && !loadingMore && (<buttontype="button"onClick={() => void onLoadMore?.()}- className="min-h-8 font-medium text-mint transition-colors hover:text-mint/80"+ className="model-hub-action-mint min-h-8 font-medium transition-colors">{t('settings.models.recent.loadMore')}</button>@@ -134,7 +152,7 @@ export const RecentSwitchesCard: React.FC<{{namesDeletedSource(event) && (<Badgevariant="secondary"- className="ml-1.5 translate-y-[-1px] bg-foreground/[0.03] px-2 py-0 text-[10px] font-medium"+ className="model-hub-fill-white-08 ml-1.5 translate-y-[-1px] px-2 py-0 text-[10px] font-medium">{t('settings.models.recent.deletedSource')}</Badge>@@ -142,12 +160,12 @@ export const RecentSwitchesCard: React.FC<{</span></div>))}- {expanded && hasMore && (+ {expanded && hasOlder && (<buttontype="button"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]"+ className="model-hub-action-mint min-h-11 border-t border-border px-4 py-3 text-[12.5px] font-medium transition-colors disabled:text-muted sm:px-5 sm:text-[13px]">{loadingMore ? t('settings.models.recent.loadingMore') : t('settings.models.recent.loadMore')}</button>diff --git a/ui/src/components/settings/models/RepairJourney.tsx b/ui/src/components/settings/models/RepairJourney.tsxdeleted file mode 100644index 3acb8fa13..000000000--- a/ui/src/components/settings/models/RepairJourney.tsx+++ /dev/null@@ -1,96 +0,0 @@-// The page-level host for the two repairs that need more than a menu click: a-// native/hub subscription re-login and an API-key replacement.-//-// Why the page hosts them rather than the row: both open a MODAL over the whole-// page, and a modal owned by a list item dies when the list re-renders under it —-// which is exactly what happens here, because a repair's first act is to change-// the row that started it (`mark_native_irreversible_start` writes 需处理 before-// the login page even loads).-//-// That is also why `target.source` is a SNAPSHOT, never a live lookup: the dialog-// must keep naming the source the user clicked, with the display name it had, for-// the whole journey. The page holds the object it was handed; it does not re-find-// it in the refreshed list.-//-// The re-auth confirm is UNCONDITIONAL (AC-13): asked before anything is sent,-// every time, with no remember-my-choice and no skip for a source that is already-// broken. Both channels can lose the source to this journey — a native login pays-// at 「开始」 and a hub login pays if the sign-in fails — so both are asked.-//-// What they are NOT asked is the same sentence. `reauthCost` (repair.ts) owns that-// split, because a warning that is false on the channel reading it teaches the-// user to click past the one that is true.-import * as React from 'react';-import { useTranslation } from 'react-i18next';--import { ConfirmDialog } from '@/components/ui/confirm-dialog';-import { OAuthConnectDialog } from './OAuthConnectDialog';-import { reauthBodyKey } from './repair';-import { ReplaceKeyDialog } from './ReplaceKeyDialog';-import type { RaisedRepair } from './SourceRowMenu';-import type { Source } from './types';--export type RepairTarget = { source: Source; kind: RaisedRepair };--export const RepairJourney: React.FC<{- /** The row + remedy the user picked. A snapshot — see the note above. Null closes everything. */- target: RepairTarget | null;- onClose: () => void;- /** Something committed server-side: re-fetch sources + agents. */- onChanged: () => void;-}> = ({ target, onClose, onChanged }) => {- const { t } = useTranslation();- // The confirm and the flow are two dialogs over one target, so which of them is- // showing is this component's only state.- const [acknowledged, setAcknowledged] = React.useState(false);-- const reauthTarget = target?.kind === 'reauth' ? target.source : null;- const replaceTarget = target?.kind === 'replace_key' ? target.source : null;-- // A new target always starts at the question again.- React.useEffect(() => {- setAcknowledged(false);- }, [target?.source.id, target?.kind]);-- const closeAll = () => {- setAcknowledged(false);- onClose();- };-- return (- <>- <ConfirmDialog- open={reauthTarget !== null && !acknowledged}- onOpenChange={(v) => !v && closeAll()}- title={t('settings.models.repair.reauthTitle', { name: reauthTarget?.display_name ?? '' })}- // The question is unconditional; its BODY is not the same sentence on both- // channels, and `reauthCost` owns which one is true (a native login is- // irreversible at 「开始」, a hub login only costs the source if it fails).- description={reauthTarget ? t(reauthBodyKey(reauthTarget)) : ''}- confirmLabel={t('settings.models.repair.reauthConfirm') as string}- onConfirm={() => setAcknowledged(true)}- />-- <OAuthConnectDialog- open={reauthTarget !== null && acknowledged}- // The source's own vendor: a re-login goes back to the account it has, and- // the flow's presentation comes from the runtime either way.- vendor={reauthTarget?.vendor ?? 'anthropic'}- reauth={reauthTarget}- // Refresh on the way out WHATEVER happened: the reauth route has already- // written 需处理 and cleared the discovered models by the time this dialog- // is on screen, so a cancelled or failed login leaves the page stale in a- // way the user needs to see.- onClose={() => {- onChanged();- closeAll();- }}- onConnected={onChanged}- />-- <ReplaceKeyDialog source={replaceTarget} onClose={closeAll} onReplaced={onChanged} />- </>- );-};--export default RepairJourney;diff --git a/ui/src/components/settings/models/ReplaceKeyDialog.tsx b/ui/src/components/settings/models/ReplaceKeyDialog.tsxdeleted file mode 100644index e8065f5d8..000000000--- a/ui/src/components/settings/models/ReplaceKeyDialog.tsx+++ /dev/null@@ -1,220 +0,0 @@-// 更换 API Key — the credential-replacement journey (api.md 「Credential-// replacement and reauth」, AC-3).-//-// Three things make it more than a form:-//-// 1. The write is ATOMIC and re-discovers on commit, landing the source on-// `standby` exactly like the recovery test does. So the dialog never claims-// the source is 使用中 afterwards — it reports what the server reported.-// 2. The supply guard can REFUSE it. An elective replacement is evaluated against-// the discovered replacement set before the write, so 「the new key can't serve-// what the old one did」 arrives as `source_last_supplier` with the stranded-// pairs named. That escalates in place: same typed key, one more confirm, then-// `force: true`. A dialog stacked on a dialog would ask the user to re-read-// the same field.-// 3. A SUCCESSFUL replacement can still strand something — the server refuses-// only an elective write, so a recovering one commits and reports-// `interrupted_pairs` anyway. That report holds the dialog open.-import * as React from 'react';-import { CheckCircle2, KeyRound, TriangleAlert } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { Button } from '@/components/ui/button';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';-import { Input } from '@/components/ui/input';-import { apiFailure, modelsApi } from './modelsApi';-import { Field } from './dialogFields';-import { mayHaveWritten, REPAIR_LINE_KEY, repairOutcome, repairSettles, type RepairOutcome } from './repair';-import { SupplyGapNote } from './SupplyGapNote';-import type { Source, SupplyGap } from './types';--type Phase = 'edit' | 'confirm' | 'submitting' | 'done' | 'error';--export const ReplaceKeyDialog: React.FC<{- /** The row that opened this. Null closes it. */- source: Source | null;- onClose: () => void;- /** A commit happened — re-fetch sources + agents. */- onReplaced: () => void;-}> = ({ source, onClose, onReplaced }) => {- const { t } = useTranslation();- const open = source !== null;- const [key, setKey] = React.useState('');- const [phase, setPhase] = React.useState<Phase>('edit');- const [gaps, setGaps] = React.useState<SupplyGap[]>([]);- const [outcome, setOutcome] = React.useState<RepairOutcome | null>(null);- const closeTimer = React.useRef<number | null>(null);- // Same guard as AddApiKeyDialog's: a commit resolving after the dialog closed or- // reopened on another row must not write its result into the new state.- const submitSeq = React.useRef(0);-- React.useEffect(() => {- submitSeq.current += 1;- if (open) {- setKey('');- setPhase('edit');- setGaps([]);- setOutcome(null);- }- return () => {- if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);- };- }, [open, source?.id]);-- const submit = async (force: boolean) => {- if (!source) return;- const value = key.trim();- if (!value) return;- const seq = submitSeq.current;- setPhase('submitting');- try {- const tail = await modelsApi.replaceCredential(source.id, force ? { key: value, force: true } : { key: value });- if (submitSeq.current !== seq) return;- const verdict = repairOutcome(tail);- setOutcome(verdict);- setPhase('done');- // Before the auto-close decision, unconditionally: the credential is- // committed whatever the report says, so the list is stale from here on.- onReplaced();- if (repairSettles(verdict)) closeTimer.current = window.setTimeout(onClose, 1500);- } catch (e) {- if (submitSeq.current !== seq) return;- const failure = apiFailure(e);- // The guard, in place: keep the typed key, name what would be stranded, and- // let the same button commit with `force`.- if (failure?.code === 'source_last_supplier' && !force) {- setGaps(failure.wouldInterrupt);- setPhase('confirm');- return;- }- // A refusal the route NAMED wrote nothing — that is what the guard above is,- // and what makes it safe to leave the rows alone. A failure it did not name- // is the atomic write with its answer lost coming back: the credential may- // be replaced and re-discovered already, in which case the row behind this- // dialog still shows the old key's state and 更换 would provision a second- // replacement. So the error is reported AND the list re-read — the two are- // not alternatives, and only the report is about this dialog.- if (mayHaveWritten(failure)) onReplaced();- setPhase('error');- }- };-- const busy = phase === 'submitting';- const forcing = phase === 'confirm';- const settled = phase === 'done';-- return (- // Closing mid-commit would drop a credential the server has already written.- <Dialog open={open} onOpenChange={(v) => !v && !busy && onClose()}>- <DialogContent className="max-w-[520px] gap-5">- <DialogHeader>- <DialogTitle className="text-[18px] font-bold">- {forcing- ? t('settings.models.repair.forceTitle')- : t('settings.models.repair.replaceTitle', { name: source?.display_name ?? '' })}- </DialogTitle>- <DialogDescription>- {forcing- ? t('settings.models.repair.gapsTitle')- : t('settings.models.repair.replaceBody')}- </DialogDescription>- </DialogHeader>-- {forcing ? (- <SupplyGapNote gaps={gaps} />- ) : (- <Field label={t('settings.models.repair.replaceLabel')} mono icon={KeyRound}>- {(id) => (- <Input- id={id}- type="password"- autoComplete="off"- spellCheck={false}- autoFocus- placeholder={t('settings.models.field.apiKeyPlaceholder')}- value={key}- onChange={(e) => setKey(e.target.value)}- disabled={busy || settled}- className="h-11 pl-9 font-mono text-[14px]"- onKeyDown={(e) => {- if (e.key === 'Enter' && !busy && !settled) {- e.preventDefault();- void submit(false);- }- }}- />- )}- </Field>- )}-- {settled && outcome ? (- outcome.kind === 'gaps' ? (- <div className="flex flex-col gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-3">- <span className="text-[12.5px] font-semibold leading-relaxed text-gold">- {t('settings.models.repair.gapsDone')}- </span>- <SupplyGapNote gaps={outcome.gaps} />- </div>- ) : outcome.kind === 'unresolved' ? (- // The key was accepted and the source came back stopped anyway. Same- // rule as the reauth dialog: no green check over a row that is still- // 需处理, and no auto-close over it either.- <div className="flex items-center gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-4 py-3 text-[13px] font-medium text-gold">- <TriangleAlert className="size-4 shrink-0" />- <span>{t('settings.models.repair.unresolved')}</span>- </div>- ) : (- <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">- <CheckCircle2 className="size-4 shrink-0" />- <span>{t(REPAIR_LINE_KEY[outcome.kind])}</span>- </div>- )- ) : null}-- {phase === 'error' && (- <div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive">- <TriangleAlert className="mt-0.5 size-4 shrink-0" />- {/* One sentence, no code: every failure this route can report other- than the guard above is 「that key didn't work」, and the machine- code is in the network log for whoever needs it. */}- <span>{t('settings.models.repair.replaceFailed')}</span>- </div>- )}-- <DialogFooter>- <div className="flex items-center gap-2">- {/* 关闭 once the credential is committed: 「取消」 on a completed write- reads as an undo this route does not have. */}- <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={busy}>- {t(settled ? 'common.close' : 'common.cancel')}- </Button>- {!settled && (- <Button- variant={forcing ? 'destructive' : 'brand'}- size="sm"- className="h-10 sm:h-9"- onClick={() => void submit(forcing)}- disabled={busy || !key.trim()}- >- {busy- ? t('settings.models.repair.replacing')- : forcing- ? t('settings.models.repair.forceConfirm')- : t('settings.models.repair.replaceSubmit')}- </Button>- )}- </div>- </DialogFooter>- </DialogContent>- </Dialog>- );-};--export default ReplaceKeyDialog;diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsxnew file mode 100644index 000000000..cd5ad6392--- /dev/null+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx@@ -0,0 +1,61 @@+// @vitest-environment jsdom+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++import { cleanup, render, screen } from '@testing-library/react';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import { RouteChainDialog } from './RouteChainDialog';+import { readyRegion } from './regionRead';+import type { AgentChain, AgentSupply, Source } from './types';++const agent: AgentSupply = { backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed' };+const sources: Source[] = [+ { id: 'src_a', last_discovered_at: null, kind: 'api_key', vendor: 'anthropic', display_name: 'aihub', protocol: 'anthropic', supply_channel: 'hub', billing: 'metered', state: { status: 'active', retry_at: null, detail_key: null }, models: [] },+ { id: 'src_b', last_discovered_at: null, kind: 'subscription', vendor: 'anthropic', display_name: 'Claude subscription', protocol: 'anthropic', supply_channel: 'native_cli', billing: 'monthly', state: { status: 'active', retry_at: null, detail_key: null }, models: [] },+];+const chain: AgentChain = {+ contract_version: 5,+ backend: 'claude',+ model_id: 'opus-5',+ current: { source_id: 'src_b', model_id: 'opus-5' },+ chain: [+ { source_id: 'src_a', model_id: 'claude-opus-5', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' },+ { source_id: 'src_b', model_id: 'opus-5', channel: 'native_cli', health: 'healthy', runnable: true, reason: null, retry_at: null },+ ],+ supply_state: 'ok',+};++afterEach(cleanup);++describe('RouteChainDialog', () => {+ it('renders the contracted chain order and current hop', () => {+ render(<I18nextProvider i18n={i18n}><RouteChainDialog selection={{ agent, modelId: 'opus-5', read: readyRegion(chain) }} sources={sources} onClose={vi.fn()} /></I18nextProvider>);++ expect(screen.getByText('opus-5 · Route chain')).toBeTruthy();+ const current = document.querySelector('[data-current="true"]');+ expect(current?.textContent).toContain('Claude subscription');+ expect(current?.textContent).toContain('opus-5');+ });++ it('draws every write control disabled while G-32 remains unresolved', () => {+ render(<I18nextProvider i18n={i18n}><RouteChainDialog selection={{ agent, modelId: 'opus-5', read: readyRegion(chain) }} sources={sources} onClose={vi.fn()} /></I18nextProvider>);++ for (const name of ['Remove hop', 'Add a hop', 'Reorder by source order', 'Save']) {+ const controls = screen.getAllByRole('button', { name });+ expect(controls.length).toBeGreaterThan(0);+ expect(controls.every((control) => (control as HTMLButtonElement).disabled)).toBe(true);+ }+ expect(screen.getAllByRole('button', { name: 'Cancel' }).every((control) => !(control as HTMLButtonElement).disabled)).toBe(true);+ });++ it('has no mutation client or write callback wired into the frame', () => {+ const source = readFileSync(join(__dirname, 'RouteChainDialog.tsx'), 'utf8');+ const api = readFileSync(join(__dirname, 'modelsApi.ts'), 'utf8');++ expect(source).not.toMatch(/modelsApi|putAgentChain|onCommit|onSave/);+ expect(api).not.toMatch(/putAgentChain|\/chain[^\n]*jsonInit\(['"]PUT/);+ });+});diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsxnew file mode 100644index 000000000..7f628cf6c--- /dev/null+++ b/ui/src/components/settings/models/RouteChainDialog.tsx@@ -0,0 +1,80 @@+import * as React from 'react';+import * as DialogPrimitive from '@radix-ui/react-dialog';+import { GripVertical, Info, ListRestart, Plus, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { cn } from '@/lib/utils';+import { equalHopIdentity } from './hopIdentity';+import type { ModelChainRead } from './modelRows';+import { foldRegionRead } from './regionRead';+import type { AgentSupply, Source } from './types';++const sourceName = (sources: Source[], sourceId: string): string =>+ sources.find((source) => source.id === sourceId)?.display_name ?? sourceId;++export type RouteChainSelection = {+ agent: AgentSupply;+ modelId: string;+ read: ModelChainRead | undefined;+};++export const RouteChainDialog: React.FC<{+ selection: RouteChainSelection | null;+ sources: Source[];+ onClose: () => void;+}> = ({ selection, sources, onClose }) => {+ const { t } = useTranslation();+ if (!selection) return null;+ const { agent, modelId, read } = selection;+ const chain = read ? foldRegionRead(read, {+ loading: () => null,+ ready: (value) => value,+ unread: () => null,+ degraded: () => null,+ }) : null;+ const backend = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend }) as string;+ return (+ <DialogPrimitive.Root open onOpenChange={(open) => !open && onClose()}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay className="model-hub-route-overlay fixed inset-0 z-50" />+ <DialogPrimitive.Content className="model-hub-route-dialog fixed left-1/2 top-1/2 z-50 flex -translate-x-1/2 -translate-y-1/2 flex-col gap-0 overflow-hidden border border-border-strong bg-surface p-0 shadow-xl">+ <header className="model-hub-route-head flex flex-col border-b border-border">+ <span className="flex items-center justify-between gap-3">+ <DialogPrimitive.Title className="model-hub-route-title font-bold text-foreground">{t('settings.models.routeDialog.title', { model: modelId })}</DialogPrimitive.Title>+ <DialogPrimitive.Close aria-label={t('common.cancel') as string} title={t('common.cancel') as string} className="model-hub-route-close grid shrink-0 place-items-center text-muted"><X aria-hidden="true" /></DialogPrimitive.Close>+ </span>+ <DialogPrimitive.Description className="model-hub-route-subtitle font-mono text-muted">{backend}</DialogPrimitive.Description>+ </header>++ <div className="model-hub-route-body flex flex-col">+ <h3 className="model-hub-route-label font-bold text-muted">{t('settings.models.routeDialog.label')}</h3>+ <div className="model-hub-route-list flex flex-col border border-border bg-background">+ {chain ? chain.chain.map((hop, index) => {+ const current = equalHopIdentity(chain.current, hop);+ return (+ <div key={`${hop.source_id}:${hop.model_id}:${index}`} data-current={current || undefined} className="model-hub-route-hop model-hub-fill-white-08 flex items-center border border-border">+ <GripVertical className="model-hub-ink-white-59 size-3.5 shrink-0" aria-hidden />+ <span className={cn('model-hub-route-ordinal grid shrink-0 place-items-center font-mono font-medium', current ? 'model-hub-accent-pill--mint' : 'model-hub-fill-white-0a text-muted')}>{index + 1}</span>+ <span className="model-hub-route-hop-copy flex min-w-0 flex-1 flex-col"><span className="model-hub-route-hop-name truncate font-semibold text-foreground">{sourceName(sources, hop.source_id)}</span><span className="model-hub-route-hop-model model-hub-ink-muted-b3 truncate font-mono">{hop.model_id}</span></span>+ <button type="button" disabled aria-label={t('settings.models.routeDialog.removeHop') as string} className="model-hub-route-remove model-hub-fill-white-0a grid shrink-0 place-items-center border border-border text-muted disabled:opacity-60"><X className="size-3.5" /></button>+ </div>+ );+ }) : <div className="model-hub-route-hop model-hub-fill-white-08 grid place-items-center border border-border font-mono text-xs text-muted">—</div>}+ <button type="button" disabled className="model-hub-route-add model-hub-fill-white-05 flex w-full items-center justify-center gap-1.5 border border-border font-semibold text-muted disabled:opacity-60"><Plus className="size-3.5" />{t('settings.models.routeDialog.addHop')}</button>+ </div>+ <button type="button" disabled className="model-hub-route-reseed flex items-center gap-1.5 self-start font-semibold text-cyan disabled:opacity-60"><ListRestart className="size-3" />{t('settings.models.routeDialog.reseed')}</button>+ <p className="model-hub-route-hint flex items-start gap-2 text-muted"><Info className="mt-0.5 size-3.5 shrink-0" />{t('settings.models.routeDialog.hint')}</p>+ </div>++ <footer className="model-hub-route-foot model-hub-fill-white-05 flex items-center justify-end gap-2 border-t border-border">+ <Button variant="outline" className="model-hub-dialog-action" onClick={onClose}>{t('common.cancel')}</Button>+ <Button className="model-hub-dialog-action" disabled>{t('common.save')}</Button>+ </footer>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>+ );+};++export default RouteChainDialog;diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsxindex 5e04d5988..62efd05cc 100644--- a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx@@ -1,16 +1,13 @@-import { readFileSync } from 'node:fs';-import { dirname, join } from 'node:path';-import { fileURLToPath } from 'node:url';-import { createInstance } from 'i18next';import { renderToStaticMarkup } from 'react-dom/server';import { I18nextProvider, initReactI18next } from 'react-i18next';import { describe, expect, it, vi } from 'vitest';import zh from '../../../i18n/zh.json';-import { pollRuntimeStatus, startRuntimeWithStatusRefresh } from './runtimeLifecycle';-import { ModelsPageActions, RuntimeNotStartedAction } from './SettingsModelsPage';-import type { RuntimeDependency } from './types';+import { failRegionRead, readyRegion, unreadRegion } from './regionRead';+import { agentHasLiveChainProjection, freshRuntimeProjection, pollRuntimeStatus, resumeInstallAndStartRuntime, startRuntimeWithStatusRefresh } from './runtimeLifecycle';+import { RuntimePill } from './SettingsModelsPage';+import type { AgentSupply, RuntimeDependency } from './types';const i18n = createInstance();void i18n.use(initReactI18next).init({@@ -19,33 +16,101 @@ void i18n.use(initReactI18next).init({interpolation: { escapeValue: false },});-const render = (starting = false): string => renderToStaticMarkup(+const runtime = (+ health: RuntimeDependency['status']['health'],+ withAsset = false,+ hostPlatform?: string,+): RuntimeDependency => ({+ contract_version: 5,+ // #1326 runtime-dependency shape: absent host keeps any server asset installable.+ ...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),+ manifest: {+ name: 'cliproxyapi',+ version: '1',+ source_sha: 'sha',+ assets: withAsset ? [{+ platform: 'darwin-arm64',+ url: 'https://example.invalid/runtime',+ size_bytes: 1,+ sha256: '0'.repeat(64),+ }] : [],+ },+ status: { installed_version: '1', verified: true, listening: null, health, last_check: null },+});++const renderPill = (+ health: RuntimeDependency['status']['health'],+ options: { withAsset?: boolean; hostPlatform?: string; unread?: boolean; starting?: boolean } = {},+): string => renderToStaticMarkup(<I18nextProvider i18n={i18n}>- <RuntimeNotStartedAction starting={starting} onStart={vi.fn()} />+ <RuntimePill+ read={options.unread+ ? unreadRegion()+ : readyRegion(runtime(health, options.withAsset, options.hostPlatform))}+ starting={options.starting ?? false}+ onStart={vi.fn()}+ onInstall={vi.fn()}+ /></I18nextProvider>,);-const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({- contract_version: 4,- manifest: { name: 'cliproxyapi', version: '1', source_sha: 'sha', assets: [] },- status: { installed_version: '1', verified: true, listening: null, health, last_check: null },-});+describe('Model Hub runtime pill', () => {+ it('exposes chain projections only for running Hub backends', () => {+ const agent = { backend: 'claude', mode: 'hub' } as AgentSupply;+ for (const health of ['ok', 'degraded'] as const) {+ expect(agentHasLiveChainProjection(freshRuntimeProjection(readyRegion(runtime(health))), agent)).toBe(true);+ }+ for (const health of ['down', 'not_started', 'not_installed', 'installing'] as const) {+ expect(agentHasLiveChainProjection(freshRuntimeProjection(readyRegion(runtime(health))), agent)).toBe(false);+ }+ expect(agentHasLiveChainProjection(freshRuntimeProjection(readyRegion(runtime('ok'))), { ...agent, mode: 'direct' })).toBe(false);+ expect(agentHasLiveChainProjection(null, agent)).toBe(false);+ });++ it('does not promote a retained runtime snapshot into a fresh projection', () => {+ const retained = failRegionRead(readyRegion(runtime('ok')));-describe('installed but not-started Model Hub runtime', () => {- it('renders neutral lazy-start copy with a quiet explicit start affordance', () => {- const html = render();+ expect(freshRuntimeProjection(retained)).toBeNull();+ });- expect(html).toContain(zh.settings.models.runtime.notStarted);- expect(html).toContain(zh.settings.models.runtime.startNow);- expect(html).toContain('text-muted');- expect(html).not.toContain(zh.settings.models.modelStatus.runtime);+ it('maps every runtime health to its registered shell copy and activation', () => {+ expect(renderPill('ok')).toContain(zh.settings.models.shell.running);+ expect(renderPill('ok')).not.toContain('<button');+ expect(renderPill('degraded')).toContain(zh.settings.models.shell.degraded);+ expect(renderPill('degraded')).not.toContain('<button');+ expect(renderPill('down')).toContain(zh.settings.models.shell.stopped);+ expect(renderPill('down')).toContain('<button');+ expect(renderPill('not_started')).toContain(zh.settings.models.shell.notStarted);+ expect(renderPill('not_started')).toContain('<button');});- it('shows a disabled pending state while the explicit start request runs', () => {- const html = render(true);+ it('uses server host evidence when present and keeps absent-host installation available', () => {+ expect(renderPill('not_installed', { withAsset: true })).toContain(zh.settings.models.shell.notInstalled);+ expect(renderPill('not_installed', { withAsset: true })).toContain('<button');+ expect(renderPill('not_installed')).toContain(zh.settings.models.shell.unsupported);+ expect(renderPill('not_installed')).not.toContain('<button');+ expect(renderPill('not_installed', { withAsset: true, hostPlatform: 'linux-amd64' })).toContain(zh.settings.models.shell.unsupported);+ expect(renderPill('not_installed', { withAsset: true, hostPlatform: 'linux-amd64' })).not.toContain('<button');+ });- expect(html).toContain(zh.settings.models.runtime.starting);- expect(html).toContain('disabled=""');+ it('renders the pending and unread projections without claiming healthy state', () => {+ expect(renderPill('ok', { starting: true })).toContain(zh.settings.models.shell.starting);+ expect(renderPill('ok', { starting: true })).not.toContain('<button');+ expect(renderPill('ok', { unread: true })).toContain(zh.settings.models.shell.unread);+ expect(renderPill('ok', { unread: true })).not.toContain(zh.settings.models.shell.stopped);+ expect(renderPill('ok', { unread: true })).not.toContain('<button');+ const stale = renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <RuntimePill+ read={failRegionRead(readyRegion(runtime('ok')))}+ starting={false}+ onStart={vi.fn()}+ onInstall={vi.fn()}+ />+ </I18nextProvider>,+ );+ expect(stale).toContain(zh.settings.models.shell.unread);+ expect(stale).not.toContain('<button');});it('refreshes authoritative health after an explicit start fails', async () => {@@ -54,9 +119,7 @@ describe('installed but not-started Model Hub runtime', () => {getRuntimeStatus: vi.fn().mockResolvedValue(runtime('down')),};- const result = await startRuntimeWithStatusRefresh(api);-- expect(result).toEqual({ runtime: runtime('down'), failed: true });+ await expect(startRuntimeWithStatusRefresh(api)).resolves.toMatchObject({ runtime: runtime('down'), failed: true });expect(api.startRuntime).toHaveBeenCalledOnce();expect(api.getRuntimeStatus).toHaveBeenCalledOnce();});@@ -67,51 +130,53 @@ describe('installed but not-started Model Hub runtime', () => {getRuntimeStatus: vi.fn().mockRejectedValue(new Error('status failed')),};- await expect(startRuntimeWithStatusRefresh(api)).resolves.toEqual({ runtime: null, failed: true });+ await expect(startRuntimeWithStatusRefresh(api)).resolves.toMatchObject({ runtime: null, failed: true });});- it('accepts an authoritative healthy read after the start response is lost', async () => {- const api = {- startRuntime: vi.fn().mockRejectedValue(new Error('response lost')),- getRuntimeStatus: vi.fn().mockResolvedValue(runtime('ok')),- };+ it('accepts healthy and degraded authoritative results', async () => {+ for (const health of ['ok', 'degraded'] as const) {+ const api = {+ startRuntime: vi.fn().mockResolvedValue(runtime(health)),+ getRuntimeStatus: vi.fn(),+ };- await expect(startRuntimeWithStatusRefresh(api)).resolves.toEqual({- runtime: runtime('ok'),- failed: false,- });+ await expect(startRuntimeWithStatusRefresh(api)).resolves.toEqual({ runtime: runtime(health), failed: false });+ expect(api.getRuntimeStatus).not.toHaveBeenCalled();+ }});- it('treats an unhealthy successful start response as failed', async () => {+ it('accepts an authoritative healthy read after the start response is lost', async () => {const api = {- startRuntime: vi.fn().mockResolvedValue(runtime('degraded')),- getRuntimeStatus: vi.fn(),+ startRuntime: vi.fn().mockRejectedValue(new Error('response lost')),+ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('ok')),};- await expect(startRuntimeWithStatusRefresh(api)).resolves.toEqual({- runtime: runtime('degraded'),- failed: true,- });- expect(api.getRuntimeStatus).not.toHaveBeenCalled();+ await expect(startRuntimeWithStatusRefresh(api)).resolves.toMatchObject({ runtime: runtime('ok'), failed: false });});- it('surfaces an automatic runtime transition on the next idle poll', async () => {- vi.useFakeTimers();- try {- const nextRuntime = runtime('ok');- const api = { getRuntimeStatus: vi.fn().mockResolvedValue(nextRuntime) };- const onRuntime = vi.fn();- const stop = pollRuntimeStatus(api, onRuntime, 100);+ it.each([+ ['not_installed', 1, 1, 'ok'],+ ['not_started', 0, 1, 'ok'],+ ['down', 0, 1, 'ok'],+ ['ok', 0, 0, 'ok'],+ ['degraded', 0, 0, 'degraded'],+ ] as const)(+ 'resumes install-and-start from %s at the first unproven step',+ async (initialHealth, installCalls, startCalls, finalHealth) => {+ const api = {+ installRuntime: vi.fn().mockResolvedValue(runtime('not_started')),+ startRuntime: vi.fn().mockResolvedValue(runtime('ok')),+ getRuntimeStatus: vi.fn(),+ };- await vi.advanceTimersByTimeAsync(100);+ const result = await resumeInstallAndStartRuntime(api, runtime(initialHealth), vi.fn(), 0);- expect(onRuntime).toHaveBeenCalledOnce();- expect(onRuntime).toHaveBeenCalledWith(nextRuntime);- stop();- } finally {- vi.useRealTimers();- }- });+ expect(api.installRuntime).toHaveBeenCalledTimes(installCalls);+ expect(api.startRuntime).toHaveBeenCalledTimes(startCalls);+ expect(result.failedStep).toBeNull();+ expect(result.runtime?.status.health).toBe(finalHealth);+ },+ );it('polls read-only health while idle and cancels stale async writes', async () => {vi.useFakeTimers();@@ -127,7 +192,6 @@ describe('installed but not-started Model Hub runtime', () => {await vi.advanceTimersByTimeAsync(100);expect(api.getRuntimeStatus).toHaveBeenCalledOnce();-await vi.advanceTimersByTimeAsync(500);expect(api.getRuntimeStatus).toHaveBeenCalledOnce();@@ -135,104 +199,31 @@ describe('installed but not-started Model Hub runtime', () => {resolveStatus?.(runtime('ok'));await Promise.resolve();expect(onRuntime).not.toHaveBeenCalled();-- await vi.advanceTimersByTimeAsync(100);- expect(api.getRuntimeStatus).toHaveBeenCalledOnce();} finally {vi.useRealTimers();}});- it('keeps real configuration issues visible beside lazy-start status', () => {- const html = renderToStaticMarkup(- <I18nextProvider i18n={i18n}>- <ModelsPageActions- runtimeHealth="not_started"- startingRuntime={false}- issueCount={2}- issuesOnly={false}- onStartRuntime={vi.fn()}- onFocusIssues={vi.fn()}- />- </I18nextProvider>,- );-- expect(html).toContain(zh.settings.models.runtime.notStarted);- expect(html).toContain(i18n.t('settings.models.status.needsAction', { count: 2 }));- });-- it('offers installation and transition polling for a pristine missing runtime', () => {- const html = renderToStaticMarkup(- <I18nextProvider i18n={i18n}>- <ModelsPageActions- runtimeHealth="not_installed"- startingRuntime={false}- issueCount={2}- issuesOnly={false}- onStartRuntime={vi.fn()}- onFocusIssues={vi.fn()}- />- </I18nextProvider>,- );- const here = dirname(fileURLToPath(import.meta.url));- const page = readFileSync(join(here, 'SettingsModelsPage.tsx'), 'utf8');-- expect(html).toContain(zh.settings.models.runtime.startNow);- expect(html).toContain(i18n.t('settings.models.status.needsAction', { count: 2 }));- expect(html).not.toContain(zh.settings.models.runtime.notStarted);- expect(page).toMatch(/runtimeCanRecover[\s\S]+runtimeHealth === 'not_installed'/);- });+ it('keeps polling after an unread status until an authoritative result arrives', async () => {+ vi.useFakeTimers();+ try {+ const api = {+ getRuntimeStatus: vi.fn()+ .mockRejectedValueOnce(new TypeError('unread'))+ .mockResolvedValueOnce(runtime('ok')),+ };+ const onRuntime = vi.fn();+ const stop = pollRuntimeStatus(api, onRuntime, 100);- it('keeps the explicit start action after an unhealthy attempt', () => {- for (const health of ['down', 'degraded'] as const) {- const html = renderToStaticMarkup(- <I18nextProvider i18n={i18n}>- <ModelsPageActions- runtimeHealth={health}- startingRuntime={false}- issueCount={2}- issuesOnly={false}- onStartRuntime={vi.fn()}- onFocusIssues={vi.fn()}- />- </I18nextProvider>,- );-- expect(html).toContain(zh.settings.models.runtime.startNow);- expect(html).toContain(i18n.t('settings.models.status.needsAction', { count: 2 }));- expect(html).not.toContain(zh.settings.models.runtime.notStarted);+ await vi.advanceTimersByTimeAsync(100);+ expect(api.getRuntimeStatus).toHaveBeenCalledOnce();+ expect(onRuntime).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(100);+ expect(api.getRuntimeStatus).toHaveBeenCalledTimes(2);+ expect(onRuntime).toHaveBeenCalledWith(expect.objectContaining({ status: expect.objectContaining({ health: 'ok' }) }));+ stop();+ } finally {+ vi.useRealTimers();}});-- it('keeps retry and recovery wiring when both start requests fail', () => {- const html = renderToStaticMarkup(- <I18nextProvider i18n={i18n}>- <ModelsPageActions- runtimeHealth={null}- runtimeRecoveryPending- startingRuntime={false}- issueCount={0}- issuesOnly={false}- onStartRuntime={vi.fn()}- onFocusIssues={vi.fn()}- />- </I18nextProvider>,- );- const here = dirname(fileURLToPath(import.meta.url));- const page = readFileSync(join(here, 'SettingsModelsPage.tsx'), 'utf8');-- expect(html).toContain(zh.settings.models.runtime.startNow);- expect(html).not.toContain(zh.settings.models.status.allHealthy);- expect(page).toMatch(/runtimeRecoveryPending\n\s+\|\| runtimeHealth === 'not_started'/);- });-- it('wires recoverable runtime states to the POST-backed start action', () => {- const here = dirname(fileURLToPath(import.meta.url));- const page = readFileSync(join(here, 'SettingsModelsPage.tsx'), 'utf8');- const api = readFileSync(join(here, 'modelsApi.ts'), 'utf8');-- expect(page).toMatch(/runtimeNotStarted\n\s+\|\| runtimeHealth === 'not_installed'/);- expect(page).toMatch(/startRuntimeWithStatusRefresh\(modelsApi\)/);- expect(api).toMatch(/'\/api\/models\/runtime\/start', jsonInit\('POST'\)/);- });});diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxnew file mode 100644index 000000000..8e9997412--- /dev/null+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -0,0 +1,450 @@+// @vitest-environment jsdom+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { ToastProvider } from '@/context/ToastProvider';+import i18n from '@/i18n';+import { modelsApi } from './modelsApi';+import { SettingsModelsPage } from './SettingsModelsPage';+import type { AgentBackend, AgentChain, AgentSupply, RuntimeDependency, Source } from './types';++const directAgent = (backend: AgentBackend): AgentSupply => ({+ backend,+ cli_present: true,+ mode: 'direct',+ menu_kind: backend === 'opencode' ? 'open' : 'fixed',+});++const runtime: RuntimeDependency = {+ contract_version: 5,+ manifest: { name: 'cliproxyapi', version: '1', source_sha: 'a'.repeat(40), assets: [] },+ status: { installed_version: '1', verified: true, health: 'ok' },+};++const retainedSource: Source = {+ id: 'src_retained',+ last_discovered_at: null,+ kind: 'api_key',+ vendor: 'anthropic',+ display_name: 'Retained source',+ protocol: 'anthropic',+ base_url: null,+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'standby', retry_at: null, detail_key: null },+ masked_credential: null,+ models: [],+};++const takeoverAgent: AgentSupply = {+ backend: 'codex',+ cli_present: true,+ mode: 'hub',+ menu_kind: 'fixed',+ selected_model_id: 'gpt-5.6-sol',+ selected_model_explicit: true,+ sources: { order: ['src_head', 'src_relay'], eligibility: [] },+ routes: { 'gpt-5.6-sol': { hops: [{ source_id: 'src_head', model_id: 'gpt-5.6-sol' }, { source_id: 'src_relay', model_id: 'gpt-5.6-sol' }] } },+ supply_status: 'degraded',+ model_supply: [{ model_id: 'gpt-5.6-sol', chain_length: 2, has_runnable_hop: true }],+ builtin_models: ['gpt-5.6-sol'],+ named_agents: [],+ menu: null,+};++const takeoverChain: AgentChain = {+ contract_version: 5,+ backend: 'codex',+ model_id: 'gpt-5.6-sol',+ current: { source_id: 'src_relay', model_id: 'gpt-5.6-sol' },+ chain: [+ { source_id: 'src_head', model_id: 'gpt-5.6-sol', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' },+ { source_id: 'src_relay', model_id: 'gpt-5.6-sol', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null },+ ],+ supply_state: 'ok',+};++const deferred = <T,>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+};++const renderPage = (sources: Source[]) => {+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue(sources);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([+ directAgent('claude'),+ directAgent('codex'),+ directAgent('opencode'),+ ]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);+ return render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );+};++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe('SettingsModelsPage surface branches', () => {+ it('renders Frame 09 without tabs when every backend is direct and no source exists', async () => {+ renderPage([]);++ expect(await screen.findByText(/^Currently: direct$|^当前:直连$/i)).toBeTruthy();+ expect(screen.getAllByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toHaveLength(3);+ expect(screen.getByText(/^Switch to the gateway and you gain three things$|^切换到网关,你会多出三件事$/i)).toBeTruthy();+ expect(screen.queryByRole('tab')).toBeNull();+ });++ it('renders the no-backend state when every authoritative CLI is absent', async () => {+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([+ { ...directAgent('claude'), cli_present: false },+ { ...directAgent('codex'), cli_present: false },+ { ...directAgent('opencode'), cli_present: false },+ ]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByText(/No agent backend was found|没有找到 Agent 后端/i)).toBeTruthy();+ expect(screen.queryByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toBeNull();+ expect(screen.queryByText(/backends are direct|个后端均为直连/i)).toBeNull();+ });++ it('keeps an unread runtime visible on the direct-only surface', async () => {+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([+ directAgent('claude'),+ directAgent('codex'),+ directAgent('opencode'),+ ]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockRejectedValue(new TypeError('status unread'));+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByText(/^Gateway status unavailable$|^网关状态未读到$/i)).toBeTruthy();+ expect(screen.queryByText(/^All 3 backends are direct$|^3 个后端均为直连$/i)).toBeNull();+ });++ it('keeps the stopped runtime action visible on the direct-only surface', async () => {+ const stopped = { ...runtime, status: { ...runtime.status, health: 'down' as const } };+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([+ directAgent('claude'),+ directAgent('codex'),+ directAgent('opencode'),+ ]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(stopped);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByRole('button', { name: /Gateway stopped|网关已停止/i })).toBeTruthy();+ expect(screen.queryByText(/^All 3 backends are direct$|^3 个后端均为直连$/i)).toBeNull();+ });++ it('renders Frame 01 with tabs when retained sources remain under all-direct backends', async () => {+ renderPage([retainedSource]);++ expect(await screen.findByText('Retained source')).toBeTruthy();+ expect(screen.getAllByRole('tab')).toHaveLength(2);+ expect(screen.queryByText(/^Switch to the gateway and you gain three things$|^切换到网关,你会多出三件事$/i)).toBeNull();+ });++ it('lands the operational overview without waiting for event history', async () => {+ const pendingEvents = deferred<[]>();+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([+ directAgent('claude'),+ directAgent('codex'),+ directAgent('opencode'),+ ]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockReturnValue(pendingEvents.promise);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByText(/^Currently: direct$|^当前:直连$/i)).toBeTruthy();+ expect(screen.getAllByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toHaveLength(3);+ await act(async () => {+ pendingEvents.resolve([]);+ await pendingEvents.promise;+ });+ });++ it('counts a recoverable reroute once per backend in Frame 08', async () => {+ const head = { ...retainedSource, id: 'src_head', display_name: 'Paused source', state: { status: 'cooldown' as const, retry_at: '2099-01-01T00:00:00Z', detail_key: null } };+ const relay = { ...retainedSource, id: 'src_relay', display_name: 'Replacement source', state: { status: 'active' as const, retry_at: null, detail_key: null } };+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([head, relay]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([takeoverAgent]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByText(/^1 takeover active$|^1 处接管中$/i)).toBeTruthy();+ expect(screen.getByText(/^Taken over$|^接管中$/i)).toBeTruthy();+ expect(screen.getByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeTruthy();+ });++ it('keeps a failed event read distinct from an empty history and retries it', async () => {+ const hubAgent: AgentSupply = {+ ...directAgent('claude'),+ mode: 'hub',+ sources: { order: [], eligibility: [] },+ routes: {},+ model_supply: [],+ builtin_models: [],+ named_agents: [],+ };+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([retainedSource]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([hubAgent]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ const events = vi.spyOn(modelsApi, 'listEvents')+ .mockRejectedValueOnce(new TypeError('offline'))+ .mockResolvedValueOnce([]);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect((await screen.findAllByText(/Couldn't refresh, please retry|刷新失败,请重试/i)).length).toBeGreaterThan(0);+ expect(screen.queryByText(/^No switches yet$|^暂无切换记录$/i)).toBeNull();+ await userEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));+ await waitFor(() => expect(events).toHaveBeenCalledTimes(2));+ expect(await screen.findByText(/^No switches yet$|^暂无切换记录$/i)).toBeTruthy();+ });++ it('keeps an unread runtime status distinct from an authoritative stopped state', async () => {+ const hubAgent: AgentSupply = {+ ...directAgent('claude'),+ mode: 'hub',+ sources: { order: [], eligibility: [] },+ routes: {},+ model_supply: [],+ builtin_models: [],+ named_agents: [],+ };+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([retainedSource]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([hubAgent]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockRejectedValue(new TypeError('status unread'));+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByText(/^Gateway status unavailable$|^网关状态未读到$/i)).toBeTruthy();+ expect(screen.queryByText(/^Gateway stopped|^网关已停止/i)).toBeNull();+ expect(screen.queryByRole('button', { name: /Gateway stopped|网关已停止/i })).toBeNull();+ });++ it('lands the overview without waiting for a per-model chain read', async () => {+ const hubAgent: AgentSupply = {+ ...takeoverAgent,+ backend: 'claude',+ selected_model_id: 'claude-opus-4-6',+ sources: { order: [retainedSource.id], eligibility: [{ source_id: retainedSource.id, eligible: true }] },+ routes: { 'claude-opus-4-6': { hops: [{ source_id: retainedSource.id, model_id: 'claude-opus-4-6' }] } },+ model_supply: [{ model_id: 'claude-opus-4-6', chain_length: 1, has_runnable_hop: true }],+ builtin_models: ['claude-opus-4-6'],+ };+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([retainedSource]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([hubAgent]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'getAgentChain').mockImplementation(() => new Promise(() => {}));++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByText('Retained source')).toBeTruthy();+ expect(screen.getByText(/^Claude Code$/i)).toBeTruthy();+ expect(screen.getAllByText('—').length).toBeGreaterThan(0);+ });++ it('cannot restore chains after the authoritative supply leaves hub mode', async () => {+ const head = { ...retainedSource, id: 'src_head', display_name: 'Paused source', state: { status: 'cooldown' as const, retry_at: '2099-01-01T00:00:00Z', detail_key: null } };+ const relay = { ...retainedSource, id: 'src_relay', display_name: 'Replacement source', state: { status: 'active' as const, retry_at: null, detail_key: null } };+ const direct = { ...takeoverAgent, mode: 'direct' as const, sources: null, routes: null, supply_status: null, model_supply: null };+ const pendingChain = deferred<AgentChain>();+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([head, relay]);+ const agentRead = vi.spyOn(modelsApi, 'listAgents')+ .mockResolvedValueOnce([takeoverAgent])+ .mockResolvedValueOnce([direct]);+ vi.spyOn(modelsApi, 'setAgentMode').mockResolvedValueOnce(direct);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);+ const chainRead = vi.spyOn(modelsApi, 'getAgentChain').mockImplementation(() => pendingChain.promise);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ await waitFor(() => expect(chainRead).toHaveBeenCalledOnce());+ await userEvent.click(screen.getByRole('button', { name: /^Switch to direct$|^切换到直连$/i }));+ await waitFor(() => expect(agentRead).toHaveBeenCalledTimes(2));+ expect(await screen.findByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toBeTruthy();++ await act(async () => {+ pendingChain.resolve(takeoverChain);+ await pendingChain.promise;+ });++ expect(screen.queryByRole('button', { name: /route chain|路由链/i })).toBeNull();+ expect(screen.queryByText(/^Taken over$|^接管中$/i)).toBeNull();+ expect(screen.queryByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeNull();+ });++ it('reconciles a lost Direct-mode response before rendering failure', async () => {+ const direct = { ...takeoverAgent, mode: 'direct' as const, sources: null, routes: null, supply_status: null, model_supply: null };+ const agentRead = vi.spyOn(modelsApi, 'listAgents')+ .mockResolvedValueOnce([takeoverAgent])+ .mockResolvedValueOnce([direct]);+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([retainedSource]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);+ const setMode = vi.spyOn(modelsApi, 'setAgentMode').mockRejectedValueOnce(new TypeError('response lost'));++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ await userEvent.click(await screen.findByRole('button', { name: /^Switch to direct$|^切换到直连$/i }));++ expect(await screen.findByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toBeTruthy();+ expect(screen.queryByText(/did not go through|没切换成功/i)).toBeNull();+ expect(setMode).toHaveBeenCalledOnce();+ expect(agentRead).toHaveBeenCalledTimes(2);+ });++ it('keeps retained supply rows but clears derived chain claims when a later supply read fails', async () => {+ const head = { ...retainedSource, id: 'src_head', display_name: 'Paused source', state: { status: 'cooldown' as const, retry_at: '2099-01-01T00:00:00Z', detail_key: null } };+ const relay = { ...retainedSource, id: 'src_relay', display_name: 'Replacement source', state: { status: 'active' as const, retry_at: null, detail_key: null } };+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([head, relay]);+ const agentRead = vi.spyOn(modelsApi, 'listAgents')+ .mockResolvedValueOnce([takeoverAgent])+ .mockRejectedValueOnce(new TypeError('supply unread'));+ vi.spyOn(modelsApi, 'refreshSource').mockResolvedValueOnce({ source: head, discovered: head.models.length });+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeTruthy();+ await userEvent.click(screen.getByText('Paused source').closest('button') as HTMLButtonElement);+ await userEvent.click(await screen.findByRole('button', { name: /^Refetch$|^重新拉取$/i }));++ await waitFor(() => expect(agentRead).toHaveBeenCalledTimes(2));+ await userEvent.click(screen.getByRole('button', { name: /^Back to sources$|^返回来源$/i }));+ expect(await screen.findByText(/Could not read this backend's supply|没有读到后端列表/i)).toBeTruthy();+ expect(screen.queryByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeNull();+ expect(screen.getAllByText('—').length).toBeGreaterThan(0);+ });++ it('keeps retained regions but clears live chain claims when a later runtime read fails', async () => {+ const head = { ...retainedSource, id: 'src_head', display_name: 'Paused source', state: { status: 'cooldown' as const, retry_at: '2099-01-01T00:00:00Z', detail_key: null } };+ const relay = { ...retainedSource, id: 'src_relay', display_name: 'Replacement source', state: { status: 'active' as const, retry_at: null, detail_key: null } };+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([head, relay]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([takeoverAgent]);+ const runtimeRead = vi.spyOn(modelsApi, 'getRuntimeStatus')+ .mockResolvedValueOnce(runtime)+ .mockRejectedValueOnce(new TypeError('runtime unread'));+ vi.spyOn(modelsApi, 'refreshSource').mockResolvedValueOnce({ source: head, discovered: head.models.length });+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeTruthy();+ await userEvent.click(screen.getByText('Paused source').closest('button') as HTMLButtonElement);+ await userEvent.click(await screen.findByRole('button', { name: /^Refetch$|^重新拉取$/i }));++ await waitFor(() => expect(runtimeRead).toHaveBeenCalledTimes(2));+ await userEvent.click(screen.getByRole('button', { name: /^Back to sources$|^返回来源$/i }));+ expect(await screen.findByText(/^Gateway status unavailable$|^网关状态未读到$/i)).toBeTruthy();+ expect(screen.queryByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeNull();+ expect(screen.queryByText(/^Taken over$|^接管中$/i)).toBeNull();+ expect(screen.getAllByText('—').length).toBeGreaterThan(0);+ });+});diff --git a/ui/src/components/settings/models/SettingsModelsPage.test.ts b/ui/src/components/settings/models/SettingsModelsPage.test.tsnew file mode 100644index 000000000..ec0c3fcba--- /dev/null+++ b/ui/src/components/settings/models/SettingsModelsPage.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';++import { modelsSurfaceKind, modelsSurfaceKindFromReads } from './modelHubSurfaceState';+import { failRegionRead, readyRegion } from './regionRead';+import type { AgentSupply, Source } from './types';++const directAgent = (backend: AgentSupply['backend']): AgentSupply => ({+ backend,+ cli_present: true,+ mode: 'direct',+ menu_kind: backend === 'opencode' ? 'open' : 'fixed',+});++const retainedSource = {} as Source;++describe('modelsSurfaceKind', () => {+ it('renders Frame 09 exactly when every backend is direct and no sources remain', () => {+ const agents = [directAgent('claude'), directAgent('codex'), directAgent('opencode')];++ expect(modelsSurfaceKind(agents, [])).toBe('direct_empty');+ expect(modelsSurfaceKind(agents, [retainedSource])).toBe('gateway');+ });++ it('renders Frame 01 as soon as any backend is in Hub mode', () => {+ const agents = [directAgent('claude'), { ...directAgent('codex'), mode: 'hub' as const }];++ expect(modelsSurfaceKind(agents, [])).toBe('gateway');+ });++ it('is derived from current state rather than first-run history', () => {+ const agents = [directAgent('claude')];+ const hubState = [{ ...agents[0], mode: 'hub' as const }];++ expect(modelsSurfaceKind(agents, [])).toBe('direct_empty');+ expect(modelsSurfaceKind(hubState, [])).toBe('gateway');+ expect(modelsSurfaceKind(agents, [])).toBe('direct_empty');+ });++ it.each(['sources', 'agents'] as const)('keeps Frame 09 unreachable while retained %s are degraded', (region) => {+ const agents = [directAgent('claude')];+ const agentsRead = region === 'agents'+ ? failRegionRead(readyRegion(agents))+ : readyRegion(agents);+ const sourcesRead = region === 'sources'+ ? failRegionRead(readyRegion<Source[]>([]))+ : readyRegion<Source[]>([]);++ expect(modelsSurfaceKindFromReads(agentsRead, sourcesRead)).toBe('gateway');+ });+});diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex 5b4950ff1..7fee2e07a 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -1,636 +1,701 @@-// 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, ListFilter, LoaderCircle, Play, TriangleAlert } from 'lucide-react';+import { ArrowLeft, Gauge, Info, LoaderCircle, Route } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';import { useToast } from '@/context/ToastContext';-import { SettingsPageShell } from '../SettingsPageShell';-import { SourcesCard } from './SourcesCard';-import { AgentCard } from './AgentCard';-import { MigrationBanner } from './MigrationBanner';+import { cn } from '@/lib/utils';+import { AddApiKeyDialog } from './AddApiKeyDialog';+import { AdvancedRow } from './AdvancedRow';+import { EnableGatewayDialog } from './EnableGatewayDialog';+import { GatewayModule } from './GatewayModule';+import { InstallGatewayDialog } from './InstallGatewayDialog';+import { ModelHubInfoHint } from './ModelHubInfoHint';import { RecentSwitchesCard } from './RecentSwitchesCard';+import { RouteChainDialog } from './RouteChainDialog';+import { SourceDetailPanel } from './SourceDetailPanel';import { SourceOrderDrawer } from './SourceOrderDrawer';-import { AdvancedRow } from './AdvancedRow';-import { AddApiKeyDialog } from './AddApiKeyDialog';-import { OAuthConnectDialog } from './OAuthConnectDialog';-import { RepairJourney, type RepairTarget } from './RepairJourney';-import {- agentsWithEcho,- createLatestAsyncAuthority,- createPendingWrites,- mapWithConcurrency,- sourcesWithEcho,-} from './asyncLifetime';-import {- emptyFeed,- feedAfterHeadRead,- feedAfterTailRead,- feedTailCursor,- type EventFeed,-} from './eventFeed';-import { AddCustomModelDialog } from './menus/AddCustomModelDialog';-import { OpenCodeMenuDrawer } from './menus/OpenCodeMenuDrawer';-import { modelsApi } from './modelsApi';-import { pollRuntimeStatus, startRuntimeWithStatusRefresh } from './runtimeLifecycle';-import { connectOutcome, isSupplyWarning } from './sufficiency';+import { SourcesCard } from './SourcesCard';+import { modelsSurfaceKindFromReads } from './modelHubSurfaceState';+import { buildSupplyRelations } from './supplyRelations';+import { SupplyGraph, SupplyLegend } from './SupplyGraph';+import './modelHubSurface.css';+import { agentsWithEcho, createLatestAsyncAuthority, createLatestAsyncAuthorityByKey, createLatestEntityAuthorityByKey, createPendingWrites, mapWithConcurrency } from './asyncLifetime';+import { createAgentCollectionReadAuthority, createSourceCollectionReadAuthority, type CollectionReadAuthority } from './collectionReadAuthority';+import { emptyFeed, feedAfterHeadRead, feedAfterTailRead, feedTailCursor, type EventFeed } from './eventFeed';+import { readFirstPaintRegions, type SurfaceLanding } from './firstPaintRegions';+import { modelsApi, type SourceCreated } from './modelsApi';+import { convergeMutation, createIntentAuthority } from './mutationConvergence';+import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';+import { modelChainKey, modelChainRequests, type ModelChainIndex } from './modelRows';import {- manualModelSources,- modelChainKey,- modelChainRequests,- modelIssueCount,- routableMappings,- type ModelChainIndex,-} from './modelRows';+ beginRegionRead,+ failRegionRead,+ foldRegionRead,+ loadingRegion,+ readyRegion,+ regionFailed,+ settleRegionRead,+ unreadRegion,+ type RegionRead,+} from './regionRead';+import { agentHasLiveChainProjection, freshRuntimeProjection, pollRuntimeStatus, runtimeHasInstallAsset, startRuntimeWithStatusRefresh } from './runtimeLifecycle';+import { backendVisual } from './vendorMeta';import type { AgentBackend, AgentSupply, ResolutionEvent, RuntimeDependency, Source } from './types';-const ModelStatusButton: React.FC<{ issueCount: number; active: boolean; onClick: () => void }> = ({- issueCount,- active,- onClick,-}) => {- const { t } = useTranslation();- const healthy = issueCount === 0;- const Icon = healthy ? CheckCircle2 : TriangleAlert;- return (- <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" />- {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 EVENT_PAGE = 20;++const readAgentChains = async (agent: AgentSupply): Promise<ModelChainIndex> => Object.fromEntries(+ await mapWithConcurrency(+ modelChainRequests([agent]),+ CHAIN_READ_CONCURRENCY,+ async ({ backend, modelId }) => {+ const key = modelChainKey(backend, modelId);+ try {+ return [key, readyRegion(await modelsApi.getAgentChain(backend, modelId))] as const;+ } catch {+ return [key, unreadRegion()] as const;+ }+ },+ ),+);++const settleAgentChainIndex = (+ previous: ModelChainIndex,+ agent: AgentSupply,+ incoming: ModelChainIndex,+): ModelChainIndex => {+ const prefix = `${agent.backend}\u0000`;+ const next = Object.fromEntries(Object.entries(previous).filter(([key]) => !key.startsWith(prefix)));+ for (const [key, read] of Object.entries(incoming)) {+ next[key] = settleRegionRead(previous[key] ?? loadingRegion(), read);+ }+ return next;+};++const beginAgentChainIndex = (+ previous: ModelChainIndex,+ agent: AgentSupply,+): ModelChainIndex => {+ const prefix = `${agent.backend}\u0000`;+ const next = Object.fromEntries(Object.entries(previous).filter(([key]) => !key.startsWith(prefix)));+ for (const { backend, modelId } of modelChainRequests([agent])) {+ const key = modelChainKey(backend, modelId);+ next[key] = beginRegionRead(previous[key] ?? loadingRegion());+ }+ return next;};-export const RuntimeNotStartedAction: React.FC<{+type AuthorizedSurfaceLanding = {+ landing: SurfaceLanding;+ sourceSnapshot: number;+};++const readSurfaceLanding = (+ sourceReads: CollectionReadAuthority<Source[]>,+ agentReads: CollectionReadAuthority<AgentSupply[]>,+): Promise<SurfaceLanding> => readFirstPaintRegions({+ sources: sourceReads.readValue,+ supply: agentReads.readValue,+ runtime: () => modelsApi.getRuntimeStatus(),+});++const surfaceLandingFailed = (landing: SurfaceLanding): boolean =>+ Object.values(landing).some(regionFailed);++export const RuntimePill: React.FC<{+ read: RegionRead<RuntimeDependency>;starting: boolean;- showIdleCopy?: boolean;onStart: () => void;-}> = ({- starting,- showIdleCopy = true,- onStart,-}) => {+ onInstall: () => void;+ directCount?: number;+}> = ({ read, starting, onStart, onInstall, directCount }) => {+ const { t } = useTranslation();+ const projection = foldRegionRead<RuntimeDependency, { runtime: RuntimeDependency; authoritative: boolean } | null>(read, {+ loading: () => null,+ ready: (runtime) => ({ runtime, authoritative: true }),+ unread: () => null,+ degraded: (runtime) => ({ runtime, authoritative: false }),+ });+ if (!projection) {+ const key = read.kind === 'loading' ? 'starting' : 'unread';+ return <span className={cn('model-hub-runtime-pill', read.kind !== 'loading' && 'model-hub-runtime-pill--error')}><span className="model-hub-runtime-dot" />{read.kind === 'loading' && <LoaderCircle className="animate-spin" />}{t(`settings.models.shell.${key}`)}</span>;+ }+ const { runtime, authoritative } = projection;+ const health = runtime.status.health;+ const unread = read.kind === 'degraded' && read.cause === 'read_failed';+ const canInstall = health === 'not_installed' && runtimeHasInstallAsset(runtime);+ const allDirect = authoritative && !starting && health === 'ok' && directCount !== undefined && directCount > 0;+ const key = unread+ ? 'unread'+ : starting+ ? 'starting'+ : health === 'installing'+ ? 'starting'+ : health === 'ok'+ ? allDirect ? 'allDirect' : 'running'+ : health === 'degraded'+ ? 'degraded'+ : health === 'down'+ ? 'stopped'+ : health === 'not_started'+ ? 'notStarted'+ : canInstall+ ? 'notInstalled'+ : 'unsupported';+ const action = authoritative && !starting && health !== 'installing' && (health === 'down' || health === 'not_started')+ ? onStart+ : authoritative && !starting && canInstall+ ? onInstall+ : null;+ const className = cn(+ 'model-hub-runtime-pill',+ (health === 'down' || health === 'degraded' || unread) && 'model-hub-runtime-pill--error',+ allDirect && 'model-hub-runtime-pill--direct',+ );+ const content = <><span className="model-hub-runtime-dot" />{(starting || health === 'installing') && <LoaderCircle className="animate-spin" />}{t(`settings.models.shell.${key}`, allDirect ? { count: directCount } : undefined)}</>;+ return action+ ? <button type="button" className={className} onClick={action}>{content}</button>+ : <span className={className}>{content}</span>;+};++const ModelHubShell: React.FC<{ actions?: React.ReactNode; detailBack?: () => void; children: React.ReactNode }> = ({ actions, detailBack, children }) => {const { t } = useTranslation();return (- <div className="flex max-w-[calc(100vw-2rem)] flex-wrap items-center justify-end gap-2 text-[13px] text-muted sm:max-w-none">- {showIdleCopy && <span>{t('settings.models.runtime.notStarted')}</span>}- <Button variant="secondary" size="xs" onClick={onStart} disabled={starting}>- {starting ? <LoaderCircle className="animate-spin" /> : <Play />}- {t(starting ? 'settings.models.runtime.starting' : 'settings.models.runtime.startNow')}- </Button>+ <div className="model-hub-shell">+ <header className="model-hub-shell-head">+ {detailBack+ ? <button type="button" onClick={detailBack} aria-label={t('settings.models.sourceDetail.back') as string} title={t('settings.models.sourceDetail.back') as string} className="model-hub-detail-back"><ArrowLeft aria-hidden="true" /></button>+ : <span className="flex items-center gap-[9px]">+ <h1>{t('settings.models.shell.title')}</h1>+ <ModelHubInfoHint+ label={t('settings.models.shell.gatewayInfo.label')}+ content={t('settings.models.shell.gatewayInfo.body')}+ className="model-hub-shell-info"+ />+ </span>}+ {actions}+ </header>+ {children}</div>);};-export const ModelsPageActions: React.FC<{- runtimeHealth: RuntimeDependency['status']['health'] | null;- runtimeRecoveryPending?: boolean;- startingRuntime: boolean;- issueCount: number;- issuesOnly: boolean;- onStartRuntime: () => void;- onFocusIssues: () => void;-}> = ({- runtimeHealth,- runtimeRecoveryPending = false,- startingRuntime,- issueCount,- issuesOnly,- onStartRuntime,- onFocusIssues,-}) => {- const runtimeNotStarted = runtimeHealth === 'not_started';- const runtimeStartable = runtimeRecoveryPending- || runtimeNotStarted- || runtimeHealth === 'not_installed'- || runtimeHealth === 'down'- || runtimeHealth === 'degraded';- if (!runtimeStartable) {- return <ModelStatusButton issueCount={issueCount} active={issuesOnly} onClick={onFocusIssues} />;- }+const HubTabs: React.FC<{ tab: 'sources' | 'usage'; onChange: (tab: 'sources' | 'usage') => void }> = ({ tab, onChange }) => {+ const { t } = useTranslation();return (- <div className="flex max-w-[calc(100vw-2rem)] flex-wrap items-center justify-end gap-2 sm:max-w-none">- {issueCount > 0 && (- <ModelStatusButton issueCount={issueCount} active={issuesOnly} onClick={onFocusIssues} />- )}- <RuntimeNotStartedAction- starting={startingRuntime}- showIdleCopy={runtimeNotStarted}- onStart={onStartRuntime}- />+ <div role="tablist" className="flex h-[39px] items-end gap-1 border-b border-border">+ {(['sources', 'usage'] as const).map((id) => (+ <button key={id} type="button" role="tab" aria-selected={tab === id} onClick={() => onChange(id)} className={cn('flex h-[39px] items-center gap-[7px] border-b-2 px-3.5 text-[13px] transition-colors', tab === id ? 'border-mint font-semibold text-foreground' : 'border-transparent font-normal text-muted hover:text-foreground')}>+ {id === 'sources' ? <Route className="size-3.5" /> : <Gauge className="size-3.5" />}+ {t(`settings.models.shell.tab.${id === 'sources' ? 'hub' : 'usage'}`)}+ </button>+ ))}</div>);};-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;- }- },+const DirectHome: React.FC<{ agents: AgentSupply[]; onSwitch: (agent: AgentSupply) => void }> = ({ agents, onSwitch }) => {+ const { t } = useTranslation();+ if (agents.length === 0) {+ return <section className="model-hub-direct-empty"><h2>{t('settings.models.direct.empty.title')}</h2><p>{t('settings.models.direct.empty.body')}</p><span>{t('settings.models.direct.empty.install')}</span></section>;+ }+ return (+ <div className="model-hub-direct">+ <div className="model-hub-direct-grid grid">+ <section className="model-hub-direct-card overflow-hidden border border-border bg-surface">+ <div className="model-hub-direct-head flex items-center gap-3 border-b border-border px-5 py-3">+ <div><h2 className="text-[16px] font-bold text-foreground">{t('settings.models.direct.card.current')}</h2><p className="mt-1 text-[11.5px] text-muted">{t('settings.models.direct.card.current.sub')}</p></div>+ </div>+ <div className="model-hub-direct-content flex flex-col">+ {agents.map((agent) => {+ const { Icon } = backendVisual(agent.backend);+ return (+ <div key={agent.backend} className="model-hub-direct-row model-hub-direct-row--backend flex flex-wrap items-center gap-2.5 bg-background px-3 sm:flex-nowrap">+ <span className="model-hub-direct-tile flex size-[34px] shrink-0 items-center justify-center rounded-[9px]"><Icon className="size-[17px]" /></span>+ <span className="model-hub-direct-backend-copy">+ <span className="flex min-w-0 items-center gap-1.5">+ <span className="model-hub-direct-backend-name truncate text-foreground">{t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}</span>+ <span className="model-hub-direct-kind-pill shrink-0 rounded-full border px-2 py-[3px] text-[10.5px] font-semibold">{t('settings.models.direct.pill.direct')}</span>+ </span>+ <span className="model-hub-direct-backend-detail truncate" title={t(`settings.models.direct.backend.${agent.backend}.detail`) as string}>{t(`settings.models.direct.backend.${agent.backend}.detail`)}</span>+ </span>+ <Button variant="secondary" size="sm" className="model-hub-direct-switch h-auto rounded-lg px-3 py-[9px] text-[11.5px] font-bold" onClick={() => onSwitch(agent)}>{t('settings.models.direct.action.switchToGateway')}</Button>+ </div>+ );+ })}+ </div>+ </section>+ <section className="model-hub-direct-card overflow-hidden border border-border bg-surface">+ <div className="model-hub-direct-head flex items-center border-b border-border px-5 py-3"><h2 className="text-[16px] font-bold text-foreground">{t('settings.models.direct.benefits.title')}</h2></div>+ <div className="model-hub-direct-content flex flex-col">{(['1', '2', '3'] as const).map((key) => <div key={key} className="model-hub-direct-row flex items-start gap-2.5 bg-background px-3 py-[11px]"><span className="model-hub-ink-mint grid size-5 shrink-0 place-items-center rounded-full bg-mint-soft text-[10.5px] font-bold">{key}</span><span className="model-hub-direct-benefit-copy"><span className="model-hub-direct-benefit-title-row flex items-center gap-1.5"><span className="text-[12.5px] font-semibold text-foreground">{t(`settings.models.direct.benefits.${key}`)}</span></span><span className="model-hub-direct-benefit-detail">{t(`settings.models.direct.benefits.${key}.detail`)}</span></span></div>)}</div>+ </section>+ </div>+ <p className="model-hub-direct-note flex items-center justify-center border text-center text-[11.5px]">{t('settings.models.direct.note.perBackend')}</p>+ </div>);- 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)];+const TakeoverPill: React.FC<{ count: number }> = ({ count }) => {+ const { t } = useTranslation();+ if (count === 0) return null;+ return <span className="model-hub-takeover-pill"><span className="model-hub-runtime-dot" />{t('settings.models.takeover.pill', { count })}</span>;};-type ModelSurfaceLanding =- | {- kind: 'surface';- sources: Source[];- agents: AgentSupply[];- events: ResolutionEvent[] | null;- chains: ModelChainIndex;- }- | { kind: 'source'; source: Source };--// 最近切换 is a cursor feed, not a fixed window: `/events` pages with `before`,-// so 「查看全部」 over one fetched page could never reach row 21. One page size for-// the first read and every 加载更早 read after it.-const EVENT_PAGE = 20;-export const SettingsModelsPage: React.FC = () => {const { t } = useTranslation();const { showToast } = useToast();-- 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);+ const [sourcesRead, setSourcesRead] = React.useState<RegionRead<Source[]>>(loadingRegion);+ const [supplyRead, setSupplyRead] = React.useState<RegionRead<AgentSupply[]>>(loadingRegion);+ const [chainsRead, setChainsRead] = React.useState<RegionRead<ModelChainIndex>>(loadingRegion);+ const [runtimeRead, setRuntimeRead] = React.useState<RegionRead<RuntimeDependency>>(loadingRegion);+ const [eventsRead, setEventsRead] = React.useState<RegionRead<EventFeed>>(loadingRegion);const [loadingEvents, setLoadingEvents] = React.useState(false);- const [runtime, setRuntime] = React.useState<RuntimeDependency | null>(null);+ const [tab, setTab] = React.useState<'sources' | 'usage'>('sources');const [startingRuntime, setStartingRuntime] = React.useState(false);const [runtimeRecoveryPending, setRuntimeRecoveryPending] = React.useState(false);- const [loading, setLoading] = React.useState(true);- const [loadError, setLoadError] = React.useState<string | null>(null);- const [connecting, setConnecting] = React.useState<string | null>(null);- const [refreshingSourceId, setRefreshingSourceId] = React.useState<string | null>(null);- const [issuesOnly, setIssuesOnly] = React.useState(false);- const agentSectionRef = React.useRef<HTMLDivElement>(null);-+ const [installOpen, setInstallOpen] = React.useState(false);const [apiKeyOpen, setApiKeyOpen] = React.useState(false);- const [oauthVendor, setOauthVendor] = React.useState<string | null>(null);- // The row + remedy a repair journey is running for. Holds the SOURCE OBJECT, not- // its id, on purpose: a re-auth's first act is to change that row, so a live- // lookup would rewrite the dialog's own subject mid-flow (RepairJourney.tsx).- const [repairTarget, setRepairTarget] = React.useState<RepairTarget | null>(null);- // Which backend's 模型菜单 / 来源顺序 drawer is open. Tracked by backend id (not- // the agent object) so a background refresh keeps feeding the drawer the- // freshest agent.- 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:- // 完成, the close X, Escape and the overlay all stay live while the PUT and its- // 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 [adoptAgent, setAdoptAgent] = React.useState<AgentSupply | null>(null);+ const [routeTarget, setRouteTarget] = React.useState<{ backend: AgentBackend; modelId: string } | null>(null);+ const [selectedSourceId, setSelectedSourceId] = React.useState<string | null>(null);const [agentWrites, setAgentWrites] = React.useState<ReadonlySet<string>>(() => new Set());+ const [switchFailures, setSwitchFailures] = 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.- //- // The effect must re-arm the flag, not only clear it: an unmount-only cleanup- // makes the guard one-way, and StrictMode's mount → cleanup → mount leaves it- // false on a page that is very much alive. Every guarded write is then dropped- // in silence — 查看更多 sticks on 加载中… forever because the `finally` that- // clears it is guarded too. Found by clicking it in dev.+ const [sourceIntentAuthority] = React.useState(createIntentAuthority);+ const [sourceCollectionReads] = React.useState(() => createSourceCollectionReadAuthority(modelsApi));+ const [agentCollectionReads] = React.useState(() => createAgentCollectionReadAuthority(modelsApi));+ const overviewRef = React.useRef<HTMLDivElement>(null);const aliveRef = React.useRef(true);+ const [sourceEntityAuthority] = React.useState(() => createLatestEntityAuthorityByKey(+ (source: Source) => source.id,+ (inventory) => {+ if (aliveRef.current) setSourcesRead(readyRegion(inventory));+ },+ ));+ const [sourceWriteRegistry] = React.useState(() => createPendingWrites(() => {}));React.useEffect(() => {aliveRef.current = true;- return () => {- aliveRef.current = false;- };+ return () => { aliveRef.current = false; };}, []);- const runtimeHealth = runtime?.status.health ?? null;+ const sources = foldRegionRead<Source[], Source[]>(sourcesRead, {+ loading: () => [],+ ready: (data) => data,+ unread: () => [],+ degraded: (staleData) => staleData,+ });+ const agents = foldRegionRead<AgentSupply[], AgentSupply[]>(supplyRead, {+ loading: () => [],+ ready: (data) => data,+ unread: () => [],+ degraded: (staleData) => staleData,+ });+ const chains = foldRegionRead<ModelChainIndex, ModelChainIndex>(chainsRead, {+ loading: () => ({}),+ ready: (data) => data,+ unread: () => ({}),+ degraded: () => ({}),+ });+ const runtime = freshRuntimeProjection(runtimeRead);+ const retainedRuntime = foldRegionRead<RuntimeDependency, RuntimeDependency | null>(runtimeRead, {+ loading: () => null,+ ready: (data) => data,+ unread: () => null,+ degraded: (staleData) => staleData,+ });+ const feed = foldRegionRead<EventFeed, EventFeed>(eventsRead, {+ loading: () => emptyFeed,+ ready: (data) => data,+ unread: () => emptyFeed,+ degraded: (staleData) => staleData,+ });+ const runtimeHealth = retainedRuntime?.status.health ?? null;React.useEffect(() => {- const runtimeCanRecover = runtimeRecoveryPending+ const runtimeCanRecover = runtimeRead.kind === 'unread'+ || (runtimeRead.kind === 'degraded' && runtimeRead.cause === 'read_failed')+ || runtimeRecoveryPending|| runtimeHealth === 'not_started'|| runtimeHealth === 'not_installed'+ || runtimeHealth === 'installing'|| runtimeHealth === 'down'|| runtimeHealth === 'degraded';if (!runtimeCanRecover || startingRuntime) return undefined;return pollRuntimeStatus(modelsApi, (nextRuntime) => {if (!aliveRef.current) return;- setRuntime(nextRuntime);+ setRuntimeRead(readyRegion(nextRuntime));setRuntimeRecoveryPending(false);});- }, [runtimeHealth, runtimeRecoveryPending, startingRuntime]);-- // 最近切换 is re-read here with the rows, because the writes this refresh exists- // for are the writes that FILE events: a failing 试跑 cools its head down through- // `_cooldown`, which records the `cooldown` row that explains the state change- // the user is about to see. Fetched only at mount, the row changed and the line- // explaining it appeared nowhere until the page was reloaded — the explanation- // arriving later than the thing it explains.- // It rides along as an ANCILLARY leg, though — `null` when that one read failed.- // The feed explains the rows; it is not the rows. Letting it reject the whole- // `Promise.all` would mean a slow or broken `/events` holds back the repaired- // source state and the ● 当前 the user just changed, which is the opposite of- // 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<ModelSurfaceLanding>(- (landing) => {- if (!aliveRef.current) return;- if (landing.kind === 'source') {- setSources((previous) => sourcesWithEcho(previous, landing.source));- return;- }- const { sources: nextSources, agents: nextAgents, events: headEvents, chains: nextChains } = landing;- 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 加载更早.- if (headEvents) setFeed((prev) => feedAfterHeadRead(prev, headEvents));- },- ),- );+ }, [runtimeHealth, runtimeRead.kind, runtimeRecoveryPending, startingRuntime]);++ const [chainReadAuthority] = React.useState(() => createLatestAsyncAuthorityByKey<AgentBackend, { agent: AgentSupply; chains: ModelChainIndex }>((_backend, incoming) => {+ if (!aliveRef.current) return;+ setChainsRead((previous) => readyRegion(settleAgentChainIndex(foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {+ loading: () => ({}),+ ready: (data) => data,+ unread: () => ({}),+ degraded: (staleData) => staleData,+ }), incoming.agent, incoming.chains)));+ }));++ const refreshAgentChains = React.useCallback(async (agent: AgentSupply) => {+ setChainsRead((previous) => readyRegion(beginAgentChainIndex(foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {+ loading: () => ({}),+ ready: (data) => data,+ unread: () => ({}),+ degraded: (staleData) => staleData,+ }), agent)));+ await chainReadAuthority.run(agent.backend, async () => ({+ agent,+ chains: await readAgentChains(agent),+ }));+ }, [chainReadAuthority]);++ const refreshAllAgentChains = React.useCallback((agentRows: AgentSupply[]) => {+ const hubAgents = agentRows.filter((agent) => agent.mode === 'hub');+ const activeBackends = new Set(hubAgents.map((agent) => agent.backend));+ chainReadAuthority.invalidateExcept(activeBackends);+ setChainsRead((previous) => readyRegion(Object.fromEntries(+ Object.entries(foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {+ loading: () => ({}),+ ready: (data) => data,+ unread: () => ({}),+ degraded: (staleData) => staleData,+ })).filter(([key]) => activeBackends.has(key.split('\u0000')[0] as AgentBackend)),+ )));+ for (const agent of hubAgents) void refreshAgentChains(agent);+ }, [chainReadAuthority, refreshAgentChains]);React.useEffect(() => {- let cancelled = false;- setLoading(true);- 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- // `emptyFeed` so the same 「still the feed I asked about?」 rule covers it.- setFeed((prev) => feedAfterTailRead(prev, e, EVENT_PAGE, null));- setRuntime(r);- setLoading(false);- })- .catch((err) => {- if (cancelled) return;- setLoadError(err?.code || err?.message || 'load_failed');- setLoading(false);+ const freshSupply = foldRegionRead<AgentSupply[], AgentSupply[] | null>(supplyRead, {+ loading: () => null,+ ready: (data) => data,+ unread: () => null,+ degraded: () => null,+ });+ if (freshSupply) {+ refreshAllAgentChains(freshSupply);+ setSwitchFailures((previous) => new Set(+ [...previous].filter((backend) => freshSupply.some((agent) => agent.backend === backend && agent.mode === 'hub')),+ ));+ }+ }, [refreshAllAgentChains, supplyRead]);++ const [eventReadAuthority] = React.useState(() => createLatestAsyncAuthority<RegionRead<ResolutionEvent[]>>((incoming) => {+ if (!aliveRef.current) return;+ setEventsRead((previous) => {+ if (incoming.kind !== 'ready') return failRegionRead(previous);+ const previousFeed = foldRegionRead<EventFeed, EventFeed | undefined>(previous, {+ loading: () => undefined,+ ready: (data) => data,+ unread: () => undefined,+ degraded: (staleData) => staleData,});- return () => {- cancelled = true;- };- }, []);-- const refreshSourcesAgents = React.useCallback(async () => {- try {- await refreshAuthority.run(async () => {- const [[nextSources, nextAgents, nextChains], headEvents] = await Promise.all([- readModelSurface(),- modelsApi.listEvents(EVENT_PAGE).catch(() => null),- ]);- return {- kind: 'surface' as const,- sources: nextSources,- agents: nextAgents,- events: headEvents,- chains: nextChains,- };+ const freshEvents = foldRegionRead<ResolutionEvent[], ResolutionEvent[] | null>(incoming, {+ loading: () => null,+ ready: (data) => data,+ unread: () => null,+ degraded: () => null,});- } catch {- // A mutation may have succeeded server-side but the re-read failed — tell- // the user the view might be stale rather than silently swallowing it.- if (aliveRef.current) showToast(t('settings.models.toast.refreshFailed') as string, 'error');- }- }, [refreshAuthority, showToast, t]);+ if (!freshEvents) return failRegionRead(previous);+ return readyRegion(previousFeed+ ? feedAfterHeadRead(previousFeed, freshEvents)+ : feedAfterTailRead(emptyFeed, freshEvents, EVENT_PAGE, null));+ });+ }));- /**- * The one way an Agent write reports itself: hand back the row the server- * echoed, then re-read everything else the write moved.- *- * Taking the echo is not an optimization of the re-read, it is the part that- * cannot fail. `refreshSourcesAgents` swallows a failed read into a toast and- * `refreshAuthority` drops a superseded one, so `await`ing it proves an attempt- * finished and never that the page caught up — and the drawers seed, diff and- * gate off these rows. `agentsWithEcho` explains why the echo is allowed to- * speak for one; the re-read still runs because the echo is one Agent and the- * write moved source rows, the other Agents and the feed too.- */- const agentSaved = React.useCallback(- (echoed: AgentSupply) => {- setAgents((prev) => {- const next = agentsWithEcho(prev, echoed);- agentsRef.current = next;- return next;- });- return refreshSourcesAgents();- },- [refreshSourcesAgents],- );+ const refreshEventHead = React.useCallback(async () => {+ setEventsRead(beginRegionRead);+ await eventReadAuthority.run(async () => {+ try {+ return readyRegion(await modelsApi.listEvents(EVENT_PAGE));+ } catch {+ return unreadRegion<ResolutionEvent[]>();+ }+ });+ }, [eventReadAuthority]);++ const [refreshAuthority] = React.useState(() => createLatestAsyncAuthority<AuthorizedSurfaceLanding>(({ landing, sourceSnapshot }) => {+ if (!aliveRef.current) return;+ const freshSources = foldRegionRead<Source[], Source[] | null>(landing.sources, {+ loading: () => null,+ ready: (data) => data,+ unread: () => null,+ degraded: () => null,+ });+ if (freshSources) sourceEntityAuthority.settleSnapshot(sourceSnapshot, freshSources);+ else setSourcesRead((previous) => settleRegionRead(previous, landing.sources));+ setSupplyRead((previous) => settleRegionRead(previous, landing.supply));+ setRuntimeRead((previous) => {+ const next = settleRegionRead(previous, landing.runtime);+ if (next.kind === 'ready') setRuntimeRecoveryPending(false);+ return next;+ });+ if (landing.supply.kind !== 'ready') setChainsRead(failRegionRead);+ }));++ const refresh = React.useCallback(async () => {+ void refreshEventHead();+ const outcome: { landing: SurfaceLanding | null } = { landing: null };+ const result = await refreshAuthority.run(async () => {+ const sourceSnapshot = sourceEntityAuthority.beginSnapshot();+ outcome.landing = await readSurfaceLanding(sourceCollectionReads, agentCollectionReads);+ return { landing: outcome.landing, sourceSnapshot };+ });+ if (aliveRef.current && result === 'landed' && outcome.landing && surfaceLandingFailed(outcome.landing)) {+ showToast(t('settings.models.toast.refreshFailed') as string, 'error');+ }+ }, [agentCollectionReads, refreshAuthority, refreshEventHead, showToast, sourceCollectionReads, sourceEntityAuthority, t]);++ const trackSourceMutation = React.useCallback((sourceId: string): TrackSourceMutation => async <T,>(work: (source: Source, settlement: SourceMutationSettlement) => Promise<T>): Promise<T> => {+ let result!: T;+ await sourceWriteRegistry.track(sourceId, async () => {+ const current = sourceEntityAuthority.current(sourceId);+ if (!current) throw new Error(`Source ${sourceId} is no longer available`);+ const generation = sourceEntityAuthority.begin(sourceId);+ let settled = false;+ const finish = async (apply: () => void, reconcile = true): Promise<void> => {+ if (settled) return;+ settled = true;+ apply();+ if (reconcile) await refresh();+ };+ const settlement: SourceMutationSettlement = {+ source: async (echoed) => finish(() => { sourceEntityAuthority.settle(generation, echoed); }),+ gone: async (goneId, inventory) => finish(() => {+ if (inventory) {+ sourceEntityAuthority.settleSnapshotEntries(+ inventory.snapshot,+ inventory.sources.filter((source) => source.id !== goneId),+ );+ }+ if (goneId === sourceId) sourceEntityAuthority.settleRemoval(generation);+ }),+ unread: async () => finish(() => { sourceEntityAuthority.abandon(generation); }),+ release: () => { void finish(() => { sourceEntityAuthority.abandon(generation); }, false); },+ readInventory: async () => {+ const snapshot = sourceEntityAuthority.beginSnapshot();+ return { snapshot, sources: await sourceCollectionReads.readValue() };+ },+ };+ try {+ result = await work(current, settlement);+ } finally {+ settlement.release();+ }+ });+ return result;+ }, [refresh, sourceCollectionReads, sourceEntityAuthority, sourceWriteRegistry]);- 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);- }+ React.useEffect(() => {+ void refresh();+ }, [refresh]);++ const retrySources = React.useCallback(async () => {+ setSourcesRead(beginRegionRead);+ await refresh();+ }, [refresh]);++ const retrySupply = React.useCallback(async () => {+ setSupplyRead(beginRegionRead);+ await refresh();+ }, [refresh]);++ const retryEvents = React.useCallback(async () => {+ await refreshEventHead();+ }, [refreshEventHead]);++ const applyAgentEcho = React.useCallback((echoed: AgentSupply) => {+ setSupplyRead((previous) => readyRegion(agentsWithEcho(foldRegionRead(previous, {+ loading: () => [],+ ready: (data) => data,+ unread: () => [],+ degraded: (staleData) => staleData,+ }), echoed)));+ }, []);+ const agentSaved = React.useCallback(async (echoed: AgentSupply) => {+ await convergeMutation({+ entity: echoed,+ applyEntity: applyAgentEcho,+ reconcile: refresh,+ });+ }, [applyAgentEcho, refresh]);+ const switchToDirect = (agent: AgentSupply) => {+ setSwitchFailures((previous) => {+ const next = new Set(previous);+ next.delete(agent.backend);+ return next;+ });+ void agentWriteRegistry.track(agent.backend, async () => {+ try {+ const echoed = await modelsApi.setAgentMode(agent.backend, 'direct');+ setSwitchFailures((previous) => {+ const next = new Set(previous);+ next.delete(agent.backend);+ return next;+ });+ setAdoptAgent(null);+ await agentSaved(echoed);+ } catch {try {- const echoed = await modelsApi.putMappings(backend, [...byModel.values()].filter((mapping) => mapping.enabled));- onCommitted(current, echoed);- await agentSaved(echoed);+ const result = await agentCollectionReads.read();+ if (result.kind === 'stale') return;+ const authoritative = result.value;+ setSupplyRead(readyRegion(authoritative));+ const committed = authoritative.some((row) => row.backend === agent.backend && row.mode === 'direct');+ setSwitchFailures((previous) => {+ const next = new Set(previous);+ if (committed) next.delete(agent.backend);+ else next.add(agent.backend);+ return next;+ });} catch {- showToast(t('settings.models.menus.saveFailed') as string, 'error');+ setSwitchFailures((previous) => new Set(previous).add(agent.backend));}- });- },- [agentSaved, agentWriteRegistry, showToast, sources, t],- );-+ }+ });+ };const loadOlderEvents = React.useCallback(async () => {- const oldest = feedTailCursor(feed);- if (!oldest) return;+ const cursor = feedTailCursor(feed);+ if (!cursor) return;setLoadingEvents(true);try {- const page = await modelsApi.listEvents(EVENT_PAGE, oldest);- if (!aliveRef.current) return;- // Merged by id rather than concatenated: the feed grows at the head while- // we page from the tail, so an overlapping row is normal, not a bug. Same- // owner as the mount read, because reaching the end is the same question- // there; the head re-read has its own because merging is not always right.- //- // The cursor goes back in with the page: this request is a question about- // the rows below `oldest`, and a head re-read that REPLACED the feed while- // it was in flight left it about a feed that is no longer on screen.- setFeed((prev) => feedAfterTailRead(prev, page, EVENT_PAGE, oldest));+ const events = await modelsApi.listEvents(EVENT_PAGE, cursor);+ if (aliveRef.current) {+ setEventsRead((previous) => readyRegion(feedAfterTailRead(foldRegionRead(previous, {+ loading: () => emptyFeed,+ ready: (data) => data,+ unread: () => emptyFeed,+ degraded: (staleData) => staleData,+ }), events, EVENT_PAGE, cursor)));+ }} catch {if (aliveRef.current) showToast(t('settings.models.toast.refreshFailed') as string, 'error');} finally {if (aliveRef.current) setLoadingEvents(false);}}, [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 {- // What the PATCH echo means is a rule, not an ad-hoc read of one field.- // `connectOutcome` combines mode and supply status so the copy never- // promises a Direct fallback the resolver does not perform.- const echoed = await modelsApi.setAgentMode(agent.backend, 'hub');- const outcome = connectOutcome(echoed, sources);- await agentSaved(echoed);- if (!aliveRef.current) return;- if (outcome === 'failed') {- showToast(t('settings.models.toast.connectFailed') as string, 'error');- } else if (isSupplyWarning(outcome)) {- showToast(t(`settings.models.supply.${outcome}`) as string, 'warning');- } else {- showToast(t('settings.models.toast.connected') as string, 'success');- }- } catch {- if (aliveRef.current) showToast(t('settings.models.toast.connectFailed') as string, 'error');- } finally {- if (aliveRef.current) setConnecting(null);- }- };-- const refreshSource = async (source: Source) => {- if (refreshingSourceId !== null) return;- setRefreshingSourceId(source.id);- try {- // The mutation must fail outside the read authority: that authority- // intentionally suppresses stale read errors, while a discovery failure- // writes the source's error state and must always reach the honest toast.- const refreshed = await modelsApi.refreshSource(source.id);- await refreshAuthority.run(() =>- Promise.resolve({ kind: 'source' as const, source: refreshed.source }),- );- await refreshSourcesAgents();- if (aliveRef.current) {- showToast(t('settings.models.sourceActions.refreshed', { count: refreshed.discovered }) as string, 'success');- }- } catch {- if (!aliveRef.current) return;- await refreshSourcesAgents();- if (aliveRef.current) {- showToast(t('settings.models.sourceActions.refreshFailed') as string, 'error');- }- } finally {- if (aliveRef.current) setRefreshingSourceId(null);- }- };-- // Resolve an open drawer's agent from live state so edits see fresh data.- 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 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' }));- };-const startRuntime = async () => {+ if (startingRuntime) return;setStartingRuntime(true);- setRuntimeRecoveryPending(false);try {const result = await startRuntimeWithStatusRefresh(modelsApi);- if (!aliveRef.current) return;- setRuntime(result.runtime);+ setRuntimeRead((previous) => result.runtime === null+ ? failRegionRead(previous)+ : readyRegion(result.runtime));setRuntimeRecoveryPending(result.runtime === null);if (result.failed) showToast(t('settings.models.errors.startFailed') as string, 'error');} finally {- if (aliveRef.current) setStartingRuntime(false);+ setStartingRuntime(false);}};+ const landingLoading = sourcesRead.kind === 'loading'+ && supplyRead.kind === 'loading'+ && runtimeRead.kind === 'loading';+ const directEmpty = modelsSurfaceKindFromReads(supplyRead, sourcesRead) === 'direct_empty';+ const installedAgents = agents.filter((agent) => agent.cli_present);+ const selectSource = React.useCallback((sourceId: string | null) => {+ sourceIntentAuthority.commit(() => setSelectedSourceId(sourceId));+ }, [sourceIntentAuthority]);+ const selectedSource = sources.find((source) => source.id === selectedSourceId) ?? null;+ const orderAgent = agents.find((agent) => agent.backend === orderBackend && agent.mode === 'hub') ?? null;+ const routeAgent = agents.find((agent) => agent.backend === routeTarget?.backend && agentHasLiveChainProjection(runtime, agent)) ?? null;+ const routeSelection = routeTarget && routeAgent ? {+ agent: routeAgent,+ modelId: routeTarget.modelId,+ read: chains[modelChainKey(routeTarget.backend, routeTarget.modelId)],+ } : null;+ const supplyRelations = React.useMemo(() => buildSupplyRelations(agents, sources, chains, runtime), [agents, chains, runtime, sources]);+ const takeoverCount = React.useMemo(() => new Set(+ supplyRelations.filter(({ kind }) => kind === 'takeover').map(({ backend }) => backend),+ ).size, [supplyRelations]);+ const sourceAdded = async (created: SourceCreated) => {+ await convergeMutation({+ entity: created,+ applyEntity: (answer) => {+ sourceEntityAuthority.landLatest(answer.source);+ },+ intent: {+ authority: sourceIntentAuthority,+ apply: () => {+ setApiKeyOpen(false);+ setSelectedSourceId(created.source.id);+ },+ },+ reconcile: refresh,+ });+ };return (- <SettingsPageShell- activeTab="models"- title={t('settings.models.title')}- subtitle={t('settings.models.subtitle')}- actions={- !loading && !loadError ? (- <ModelsPageActions- runtimeHealth={runtimeHealth}- runtimeRecoveryPending={runtimeRecoveryPending}- startingRuntime={startingRuntime}- issueCount={issueCount}- issuesOnly={issuesOnly}- onStartRuntime={() => void startRuntime()}- onFocusIssues={focusIssues}- />- ) : undefined- }+ <ModelHubShell+ detailBack={selectedSourceId ? () => selectSource(null) : undefined}+ actions={!landingLoading+ ? directEmpty && installedAgents.length === 0+ ? undefined+ : <span className="flex items-center gap-2">+ <RuntimePill+ read={runtimeRead}+ starting={startingRuntime}+ onStart={() => void startRuntime()}+ onInstall={() => setInstallOpen(true)}+ directCount={directEmpty ? installedAgents.length : undefined}+ />+ {!directEmpty && <TakeoverPill count={takeoverCount} />}+ </span>+ : undefined}>- {loading ? (- <div className="text-[13px] text-muted">{t('common.loading')}</div>- ) : loadError ? (- <div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive">- <TriangleAlert className="mt-0.5 size-4 shrink-0" />- <span>{t('settings.models.loadError', { detail: loadError })}</span>- </div>- ) : (- <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 refreshSource(source)}- retestingSourceId={refreshingSourceId}- onProbeSettled={() => void refreshSourcesAgents()}- connectingBackend={connecting}- />- </div>- <SourcesCard- sources={sources}- onConnectClaude={() => setOauthVendor('anthropic')}- onConnectChatGPT={() => setOauthVendor('openai')}- onAddApiKey={() => setApiKeyOpen(true)}- onSourceChanged={() => void refreshSourcesAgents()}- onRefreshSource={(source) => void refreshSource(source)}- refreshingSourceId={refreshingSourceId}- onRepair={(source, kind) => setRepairTarget({ source, kind })}- onAddModel={(source) => openCustomModel(source.id)}- />- <RecentSwitchesCard- events={feed.events}- sources={sources}- hasMore={!feed.exhausted}- loadingMore={loadingEvents}- onLoadMore={loadOlderEvents}- />- <AdvancedRow />- </div>- )}-- <AddApiKeyDialog open={apiKeyOpen} onClose={() => setApiKeyOpen(false)} onAdded={() => void refreshSourcesAgents()} />- <OAuthConnectDialog- open={oauthVendor !== null}- vendor={oauthVendor ?? 'anthropic'}- onClose={() => setOauthVendor(null)}- onConnected={() => void refreshSourcesAgents()}- />- <RepairJourney- target={repairTarget}- onClose={() => setRepairTarget(null)}- onChanged={() => void refreshSourcesAgents()}- />-- {orderAgent && (- <SourceOrderDrawer- open- agent={orderAgent}- agents={agents}- sources={sources}- onClose={() => setOrderBackend(null)}- // Returned, not discarded: the write stays marked pending for the whole- // of this, so the hand-off to the menu drawer cannot open mid-write. What- // 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}- orderWrite={{- pending: agentWrites.has(orderAgent.backend),- track: (work) => agentWriteRegistry.track(orderAgent.backend, work),+ {landingLoading ? <div className="text-[13px] text-muted">{t('common.loading')}</div>+ : selectedSourceId+ ? selectedSource+ ? <SourceDetailPanel source={selectedSource} trackMutation={trackSourceMutation(selectedSource.id)} />+ : <section className="rounded-xl border border-border bg-surface px-5 py-12 text-center text-[12px] text-muted">{t('settings.models.sourceDetail.gone')}</section>+ : directEmpty ? <DirectHome agents={installedAgents} onSwitch={setAdoptAgent} />+ : <div className="space-y-[22px]">+ <HubTabs tab={tab} onChange={setTab} />+ {tab === 'sources' ? <div className="model-hub-overview">+ <div className="model-hub-overview-body">+ <div ref={overviewRef} className="model-hub-overview-grid relative flex flex-col gap-4">+ <SourcesCard read={sourcesRead} onRetry={() => void retrySources()} onOpenSource={(source) => selectSource(source.id)} onAddApiKey={() => setApiKeyOpen(true)} />+ <div className="hidden lg:block" aria-hidden="true" />+ <GatewayModule supply={supplyRead} sources={sources} chains={chains} runtime={runtime} runtimeSnapshot={retainedRuntime} onRetry={() => void retrySupply()} pendingBackends={agentWrites} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onConnectHub={setAdoptAgent} onSwitchDirect={switchToDirect} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId) => setRouteTarget({ backend: agent.backend, modelId })} onProbeSettled={(agent) => void refreshAgentChains(agent)} />+ <SupplyGraph containerRef={overviewRef} relations={supplyRelations} />+ </div>+ <SupplyLegend relations={supplyRelations} />+ </div>+ <RecentSwitchesCard events={eventsRead} sources={sourcesRead} onRetry={retryEvents} loadingMore={loadingEvents} onLoadMore={loadOlderEvents} />+ <AdvancedRow />+ </div> : <section className="rounded-xl border border-border bg-surface px-5 py-8"><div className="flex items-start gap-3"><Info className="mt-0.5 size-4 text-muted" /><div><h2 className="text-[14px] font-semibold text-foreground">{t('settings.models.usageTab.title')}</h2><p className="mt-1 text-[12px] text-muted">{t('settings.models.usageTab.detail')}</p></div></div></section>}+ </div>}+ <AddApiKeyDialog open={apiKeyOpen} sourceReads={sourceCollectionReads} onClose={() => setApiKeyOpen(false)} onAdded={(created) => void sourceAdded(created)} />+ {orderAgent && <SourceOrderDrawer open agent={orderAgent} sources={sources} sourceReads={sourceCollectionReads} onClose={() => setOrderBackend(null)} onSaved={agentSaved} orderWrite={{ pending: agentWrites.has(orderAgent.backend), track: (work) => agentWriteRegistry.track(orderAgent.backend, work) }} />}+ <RouteChainDialog selection={routeSelection} sources={sources} onClose={() => setRouteTarget(null)} />+ {adoptAgent && (+ <EnableGatewayDialog+ key={adoptAgent.backend}+ agent={adoptAgent}+ runtime={runtimeRead}+ agentReads={agentCollectionReads}+ onClose={() => setAdoptAgent(null)}+ onAdopted={agentSaved}+ onRuntime={(next) => {+ setRuntimeRead((previous) => next === null ? failRegionRead(previous) : readyRegion(next));}}+ trackWrite={(work) => agentWriteRegistry.track(adoptAgent.backend, work)}/>)}-- {menuAgent && menuAgent.menu_kind === 'open' ? (- <OpenCodeMenuDrawer- open- agent={menuAgent}- sources={sources}- onClose={() => setMenuBackend(null)}- onSaved={(echoed) => void agentSaved(echoed)}- // A custom model is a SOURCE write: it echoes the source, not the Agent.- onRefresh={() => void refreshSourcesAgents()}+ {installOpen && retainedRuntime && (+ <InstallGatewayDialog+ runtime={retainedRuntime}+ onClose={() => setInstallOpen(false)}+ onRuntime={(next) => {+ setRuntimeRead((previous) => next === null ? failRegionRead(previous) : readyRegion(next));+ setRuntimeRecoveryPending(next === null);+ }}/>- ) : null}-- <AddCustomModelDialog- open={customModelRequest !== null}- sources={sources}- standardVendors={standardVendors}- initialSourceId={customModelRequest?.sourceId}- showOpenCodeIdentifier={customModelRequest?.backend === 'opencode'}- onClose={() => setCustomModelRequest(null)}- onSaved={() => void refreshSourcesAgents()}- />- </SettingsPageShell>+ )}+ </ModelHubShell>);};diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxnew file mode 100644index 000000000..23c26d6df--- /dev/null+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -0,0 +1,418 @@+// @vitest-environment jsdom+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import * as React from 'react';+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { ToastProvider } from '@/context/ToastProvider';+import i18n from '@/i18n';+import { createPendingWrites } from './asyncLifetime';+import { modelsApi } from './modelsApi';+import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';+import { GuardGapList, SourceDetailPanel } from './SourceDetailPanel';+import type { Source } from './types';++const source: Source = {+ id: 'src_detail',+ last_discovered_at: '2026-08-11T08:00:00Z',+ kind: 'api_key',+ vendor: 'anthropic',+ display_name: 'Production key',+ protocol: 'anthropic',+ base_url: 'https://relay.example/v1',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active', retry_at: null, detail_key: null },+ models: [{ id: 'model-a', display_name: null, origin: 'manual', reasoning_efforts: ['high'] }],+};++const deferred = <T,>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+};++let sourceSnapshot = 0;+const beginSourceSnapshot = () => ++sourceSnapshot;+const settlement = (overrides: Partial<SourceMutationSettlement> = {}): SourceMutationSettlement => ({+ source: vi.fn().mockResolvedValue(undefined),+ gone: vi.fn().mockResolvedValue(undefined),+ unread: vi.fn().mockResolvedValue(undefined),+ release: vi.fn(),+ readInventory: async () => ({ snapshot: beginSourceSnapshot(), sources: await modelsApi.listSources() }),+ ...overrides,+});+const immediateTrack: TrackSourceMutation = async (work) => work(source, settlement());+type MutationScheduler = <T>(work: () => Promise<T>) => Promise<T>;+const serializedTrack = (): MutationScheduler => {+ const writes = createPendingWrites(() => {});+ return async <T,>(work: () => Promise<T>): Promise<T> => {+ let result!: T;+ await writes.track(source.id, async () => { result = await work(); });+ return result;+ };+};++const renderPanel = (adoptedBy: Source['adopted_by'] = undefined) => render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SourceDetailPanel source={{ ...source, adopted_by: adoptedBy }} trackMutation={immediateTrack} />+ </I18nextProvider>+ </ToastProvider>,+);++const EchoPanel: React.FC<{ reconcile?: () => Promise<void> | void; scheduler?: MutationScheduler }> = ({ reconcile = vi.fn(), scheduler = async (work) => work() }) => {+ const [current, setCurrent] = React.useState<Source | null>(source);+ const currentRef = React.useRef<Source | null>(current);+ currentRef.current = current;+ const trackMutation: TrackSourceMutation = (work) => scheduler(async () => {+ const latest = currentRef.current;+ if (!latest) throw new Error('Source is gone');+ return work(latest, settlement({+ source: async (echoed) => { currentRef.current = echoed; setCurrent(echoed); await reconcile(); },+ gone: async () => { currentRef.current = null; setCurrent(null); await reconcile(); },+ unread: async () => { await reconcile(); },+ }));+ });+ return current+ ? <SourceDetailPanel source={current} trackMutation={trackMutation} />+ : <p data-testid="source-gone">Source gone</p>;+};++const renderEchoPanel = (reconcile = vi.fn(), scheduler?: MutationScheduler) => render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <EchoPanel reconcile={reconcile} scheduler={scheduler} />+ </I18nextProvider>+ </ToastProvider>,+);++afterEach(() => {+ cleanup();+ sourceSnapshot = 0;+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('SourceDetailPanel', () => {+ it('keeps the detail surface to inventory, entry kind, tiers, and refetch', () => {+ renderPanel();+ expect(screen.queryByText(/latency|延迟|enrollment|protocol|协议/i)).toBeNull();+ expect(screen.queryByText(/^Standby$|^待命$/i)).toBeNull();+ expect(screen.getByText('model-a')).toBeTruthy();+ expect(screen.getByText(/relay\.example/)).toBeTruthy();+ });++ it('shows in-use only when the response carries adoption for this source', () => {+ renderPanel([{ backend: 'claude', menu_model: 'claude-opus-4-6' }]);+ expect(screen.getByText(/^In use$|^使用中$/i)).toBeTruthy();+ });++ it('omits native refetch because that channel has no stored discovery credential', () => {+ render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={{ ...source, kind: 'subscription', supply_channel: 'native_cli' }} trackMutation={immediateTrack} /></I18nextProvider>);+ expect(screen.queryByRole('button', { name: /^Refetch$|^重新拉取$/i })).toBeNull();+ });++ it('discards an uncommitted tier on Escape', async () => {+ renderPanel();+ await userEvent.click(screen.getByRole('button', { name: /high/i }));+ const input = screen.getByPlaceholderText(/Enter to add|回车添加/i);+ await userEvent.type(input, 'draft{Escape}');+ expect(screen.queryByDisplayValue('draft')).toBeNull();+ });++ it('opens the manual model draft in the table and keeps Add disabled while blank', async () => {+ renderPanel();+ await userEvent.click(screen.getAllByRole('button', { name: /^Add model$|^添加模型$/i })[0]);+ const input = screen.getByPlaceholderText(/^Model ID$|^型号 ID$/i);+ expect(input).toBeTruthy();+ const draft = input.closest('[data-manual-model-draft]');+ expect(draft).toBeTruthy();+ const add = within(draft as HTMLElement).getByRole('button', { name: /^Add model$|^添加模型$/i });+ expect((add as HTMLButtonElement).disabled).toBe(true);+ });++ it('keeps a failed refetch visible beside the inventory it could not replace', async () => {+ vi.spyOn(modelsApi, 'refreshSource').mockRejectedValueOnce(new Error('lost response'));+ renderPanel();+ await userEvent.click(screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i }));+ expect(await screen.findByText(/fetch did not come back|拉取没有回来/i)).toBeTruthy();+ });++ it('settles a failed refetch from the authoritative Source inventory', async () => {+ const reconciled = { ...source, state: { status: 'error' as const, retry_at: null, detail_key: 'models.source.error.unclassified' as const } };+ vi.spyOn(modelsApi, 'refreshSource').mockRejectedValueOnce(new Error('lost response'));+ vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([reconciled]);+ const applySource = vi.fn().mockResolvedValue(undefined);+ const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ source: applySource }));+ render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} /></I18nextProvider>);++ await userEvent.click(screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i }));++ await waitFor(() => expect(applySource).toHaveBeenCalledWith(reconciled));+ });++ it('applies the refetch Source echo before the collection refresh settles', async () => {+ const echoed = {+ ...source,+ models: [...source.models, { id: 'model-b', display_name: null, origin: 'discovered' as const, reasoning_efforts: [] }],+ };+ const refresh = vi.spyOn(modelsApi, 'refreshSource').mockResolvedValueOnce({ source: echoed, discovered: echoed.models.length });+ const reconcile = vi.fn().mockResolvedValue(undefined);+ renderEchoPanel(reconcile);++ await userEvent.click(screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i }));++ expect(await screen.findByText('model-b')).toBeTruthy();+ expect(refresh).toHaveBeenCalledOnce();+ expect(reconcile).toHaveBeenCalledOnce();+ });++ it('serializes a tier write and a refetch for the same Source', async () => {+ const tierResponse = deferred<Source>();+ const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockReturnValueOnce(tierResponse.promise);+ const refreshed = {+ ...source,+ models: [...source.models, { id: 'model-b', display_name: null, origin: 'discovered' as const, reasoning_efforts: [] }],+ };+ const refetch = vi.spyOn(modelsApi, 'refreshSource').mockResolvedValueOnce({ source: refreshed, discovered: refreshed.models.length });+ renderEchoPanel(vi.fn(), serializedTrack());++ await userEvent.click(screen.getByRole('button', { name: /high/i }));+ await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'low{Enter}');+ await waitFor(() => expect(update).toHaveBeenCalledOnce());+ await userEvent.click(screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i }));+ expect(refetch).not.toHaveBeenCalled();++ tierResponse.resolve({+ ...source,+ models: [{ ...source.models[0], reasoning_efforts: ['high', 'low'] }],+ });+ await waitFor(() => expect(refetch).toHaveBeenCalledOnce());+ expect(await screen.findByText('model-b')).toBeTruthy();+ });++ it('orders every full-Source mutation family through the same Source queue', async () => {+ const writes = createPendingWrites(() => {});+ const started: string[] = [];+ const gates = ['tier', 'refetch', 'add', 'remove'].map(() => deferred<void>());+ const runs = ['tier', 'refetch', 'add', 'remove'].map((name, index) => writes.track(source.id, async () => {+ started.push(name);+ await gates[index].promise;+ }));++ await waitFor(() => expect(started).toEqual(['tier']));+ for (let index = 0; index < gates.length; index += 1) {+ gates[index].resolve();+ await waitFor(() => expect(started).toEqual(['tier', 'refetch', 'add', 'remove'].slice(0, index + 2)));+ }+ await Promise.all(runs);+ });++ it('routes every full-Source mutation family through the shared per-Source queue', () => {+ const detail = readFileSync(join(process.cwd(), 'src/components/settings/models/SourceDetailPanel.tsx'), 'utf8');+ expect(detail).toMatch(/const refetch = \(confirmation\?: GuardConfirmation\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);+ expect(detail).toMatch(/const addManualModel = \(\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);+ expect(detail).toMatch(/const remove = \(model: SuppliedModel, confirmation\?: GuardConfirmation\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);+ expect(detail).toMatch(/const commit = async[\s\S]*?setSaving\(true\)[\s\S]*?trackMutation\(async \(latest, settlement\)[\s\S]*?tierMutationPayload\(latest/);+ });++ it('keeps Source entities behind one generation authority without an adoption side cache', () => {+ const page = readFileSync(join(process.cwd(), 'src/components/settings/models/SettingsModelsPage.tsx'), 'utf8');+ const sourceRow = readFileSync(join(process.cwd(), 'src/components/settings/models/SourceRow.tsx'), 'utf8');+ expect(page).toMatch(/createLatestEntityAuthorityByKey/);+ expect(page).toMatch(/sourceEntityAuthority\.beginSnapshot\(\)/);+ expect(page).toMatch(/sourceEntityAuthority\.settleSnapshot/);+ expect(page).toMatch(/trackSourceMutation/);+ expect(page).toMatch(/const settlement: SourceMutationSettlement/);+ expect(page).not.toMatch(/activeSourceGenerations/);+ expect(`${page}\n${sourceRow}`).not.toMatch(/adoptionBySource/);+ expect(sourceRow).toMatch(/source\.adopted_by/);+ });++ it('applies the manual-create Source echo without waiting for a collection read', async () => {+ const echoed = {+ ...source,+ models: [...source.models, { id: 'model-b', display_name: null, origin: 'manual' as const, reasoning_efforts: [] }],+ };+ vi.spyOn(modelsApi, 'addCustomModel').mockResolvedValueOnce(echoed);+ renderEchoPanel();++ await userEvent.click(screen.getAllByRole('button', { name: /^Add model$|^添加模型$/i })[0]);+ const draft = screen.getByPlaceholderText(/^Model ID$|^型号 ID$/i).closest('[data-manual-model-draft]');+ await userEvent.type(within(draft as HTMLElement).getByPlaceholderText(/^Model ID$|^型号 ID$/i), 'model-b');+ await userEvent.click(within(draft as HTMLElement).getByRole('button', { name: /^Add model$|^添加模型$/i }));++ expect(await screen.findByText('model-b')).toBeTruthy();+ });++ it('applies the manual-delete Source echo without waiting for a collection read', async () => {+ vi.spyOn(modelsApi, 'deleteCustomModel').mockResolvedValueOnce({ ...source, models: [] });+ renderEchoPanel();++ await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));++ await waitFor(() => expect(screen.queryByText('model-a')).toBeNull());+ });++ it('keeps a rejected tier draft and offers an inline retry', async () => {+ vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(new Error('write failed'));+ renderPanel();+ await userEvent.click(screen.getByRole('button', { name: /high/i }));+ const input = screen.getByPlaceholderText(/Enter to add|回车添加/i);+ await userEvent.type(input, 'draft{Enter}');+ expect(await screen.findByText(/tier was not saved|档位没保存上/i)).toBeTruthy();+ expect((input as HTMLInputElement).value).toBe('draft');+ expect(screen.getByRole('button', { name: /^Try again$|^重试$/i })).toBeTruthy();+ });++ it('keeps an existing tier removal clickable while the editor input has focus', async () => {+ const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockResolvedValueOnce({+ ...source,+ models: [{ ...source.models[0], reasoning_efforts: [] }],+ });+ renderPanel();+ await userEvent.click(screen.getByRole('button', { name: /high/i }));+ await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'draft');+ await userEvent.click(screen.getByRole('button', { name: /Remove high|移除 high/i }));++ await waitFor(() => expect(update).toHaveBeenCalledWith(source.id, 'model-a', []));+ });++ it('sends a manual-model removal before showing any guarded-change confirm', async () => {+ const remove = vi.spyOn(modelsApi, 'deleteCustomModel').mockResolvedValueOnce(source);+ renderPanel();+ await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));+ await waitFor(() => expect(remove).toHaveBeenCalledWith(source.id, 'model-a', undefined));+ expect(screen.queryByRole('dialog')).toBeNull();+ });++ it('echoes both arrays from a refetch refusal in the forced retry', async () => {+ const hops = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 2, source_id: source.id, model_id: 'model-a' }];+ const gaps = [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['Release bot'] }];+ const bodies: unknown[] = [];+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ if (String(input) === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });+ if (String(input).endsWith(`/api/models/sources/${source.id}/refresh`)) {+ bodies.push(JSON.parse(String(init?.body)));+ if (bodies.length === 1) {+ return Response.json({ error: 'source_in_route_chain', would_remove_hops: hops, would_interrupt: gaps }, { status: 409 });+ }+ return Response.json({ source, discovered: source.models.length });+ }+ throw new Error(`unexpected request: ${String(input)}`);+ }));+ renderPanel();++ await userEvent.click(screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i }));+ await userEvent.click(await screen.findByRole('button', { name: /^Refetch anyway$|^仍要拉取$/i }));++ await waitFor(() => expect(bodies).toHaveLength(2));+ expect(bodies[1]).toEqual({ force: true, would_remove_hops: hops, would_interrupt: gaps });+ });++ it('requires confirmation again when a forced removal receives a new guard plan', async () => {+ const firstHops = [{ backend: 'claude' as const, menu_model: 'menu-a', position: 1, source_id: source.id, model_id: 'model-a' }];+ const nextHops = [{ backend: 'codex' as const, menu_model: 'menu-b', position: 3, source_id: source.id, model_id: 'model-a' }];+ const bodies: unknown[] = [];+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ if (String(input) === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });+ if (String(input).includes(`/api/models/sources/${source.id}/models/model-a`)) {+ bodies.push(JSON.parse(String(init?.body)));+ if (bodies.length === 1) return Response.json({ error: 'source_model_in_route_chain', would_remove_hops: firstHops, would_interrupt: [] }, { status: 409 });+ if (bodies.length === 2) return Response.json({ error: 'source_model_in_route_chain', would_remove_hops: nextHops, would_interrupt: [] }, { status: 409 });+ return Response.json({ source: { ...source, models: [] } });+ }+ throw new Error(`unexpected request: ${String(input)}`);+ }));+ renderPanel();++ await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));+ await userEvent.click(await screen.findByRole('button', { name: /^Remove anyway$|^仍要移除$/i }));++ expect(await screen.findByText(/menu-b/)).toBeTruthy();+ expect(bodies[1]).toEqual({ force: true, would_remove_hops: firstHops, would_interrupt: [] });+ await userEvent.click(screen.getByRole('button', { name: /^Remove anyway$|^仍要移除$/i }));+ await waitFor(() => expect(bodies).toHaveLength(3));+ expect(bodies[2]).toEqual({ force: true, would_remove_hops: nextHops, would_interrupt: [] });+ });++ it('names every model and Agent that a guarded change would interrupt', () => {+ render(+ <I18nextProvider i18n={i18n}>+ <GuardGapList gaps={[{ backend: 'claude', model_id: 'claude-opus-4-6', agents: ['Release bot', 'Triage'] }]} />+ </I18nextProvider>,+ );++ expect(screen.getByText(/Claude Code · claude-opus-4-6/)).toBeTruthy();+ expect(screen.getByText(/Release bot.*Triage/)).toBeTruthy();+ });++ it('re-reads after an unconfirmed manual deletion before offering another DELETE', async () => {+ const remove = vi.spyOn(modelsApi, 'deleteCustomModel').mockRejectedValueOnce(new TypeError('response lost'));+ const list = vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([{ ...source, models: [] }]);+ const onMutation = vi.fn().mockResolvedValue(undefined);+ const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ source: onMutation }));+ render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} /></I18nextProvider>);++ await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));++ await waitFor(() => expect(onMutation).toHaveBeenCalledWith(expect.objectContaining({ models: [] })));+ expect(list).toHaveBeenCalledOnce();+ expect(remove).toHaveBeenCalledOnce();+ expect(screen.queryByRole('button', { name: /^Try again$|^重试$/i })).toBeNull();+ });++ it('applies the reconciled deletion Source before the follow-up refresh settles', async () => {+ vi.spyOn(modelsApi, 'deleteCustomModel').mockRejectedValueOnce(new TypeError('response lost'));+ vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([{ ...source, models: [] }]);+ let finishRefresh: (() => void) | undefined;+ const refresh = vi.fn(() => new Promise<void>((resolve) => { finishRefresh = resolve; }));+ renderEchoPanel(refresh);++ await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));++ await waitFor(() => expect(screen.queryByText('model-a')).toBeNull());+ expect(refresh).toHaveBeenCalledOnce();+ finishRefresh?.();+ });++ it('offers a second DELETE only after the authoritative list proves the model remains', async () => {+ const remove = vi.spyOn(modelsApi, 'deleteCustomModel')+ .mockRejectedValueOnce(new TypeError('response lost'))+ .mockResolvedValueOnce({ ...source, models: [] });+ const list = vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([source]);+ renderPanel();++ await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));+ await userEvent.click(await screen.findByRole('button', { name: /^Try again$|^重试$/i }));++ await waitFor(() => expect(remove).toHaveBeenCalledTimes(2));+ expect(list).toHaveBeenCalledOnce();+ });++ it('settles an unknown deletion as Source gone when the authoritative inventory omits it', async () => {+ const remove = vi.spyOn(modelsApi, 'deleteCustomModel').mockRejectedValueOnce(new TypeError('response lost'));+ vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([]);+ const onGone = vi.fn().mockResolvedValue(undefined);+ const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ gone: onGone }));+ render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} /></I18nextProvider>);++ await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));++ await waitFor(() => expect(onGone).toHaveBeenCalledWith(source.id, { kind: 'gone', sources: [], snapshot: 1 }));+ expect(remove).toHaveBeenCalledOnce();+ expect(screen.queryByRole('button', { name: /^Try again$|^重试$/i })).toBeNull();+ });++});diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxnew file mode 100644index 000000000..af8f61343--- /dev/null+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -0,0 +1,503 @@+import * as React from 'react';+import * as DialogPrimitive from '@radix-ui/react-dialog';+import { Info, Loader2, MoreHorizontal, Plus, RefreshCw, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { ResponsiveMenu } from '@/components/ui/responsive-menu';+import { cn } from '@/lib/utils';+import { formatRelativeTime } from '@/lib/relativeTime';+import { apiFailure, modelsApi, type GuardConfirmation } from './modelsApi';+import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';+import { reconcileUnknownWrite } from './reconcileUnknownWrite';+import { sourceStatePresentation } from './sourceStatePresentation';+import { tierMutationPayload, type TierMutationIntent } from './tierMutation';+import { useDeadlineClock } from './useDeadlineClock';+import { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, sourceVisual } from './vendorMeta';+import type { RouteHopRef, Source, SuppliedModel, SupplyGap } from './types';++const ManualModelMenu: React.FC<{+ model: SuppliedModel;+ busy: boolean;+ onRemove: () => void;+}> = ({ model, busy, onRemove }) => {+ const { t } = useTranslation();+ const [open, setOpen] = React.useState(false);+ const label = `${t('settings.models.sourceDetail.row.remove')} ${model.id}`;+ return (+ <ResponsiveMenu+ open={open}+ onOpenChange={setOpen}+ sheetTitle={model.id}+ className="w-40"+ trigger={<button type="button" disabled={busy} aria-label={label} title={label} className="grid size-8 place-items-center rounded-md text-muted hover:bg-surface-2 hover:text-foreground"><MoreHorizontal className="size-4" /></button>}+ >+ <button type="button" role="menuitem" className="flex w-full items-center rounded-md px-2.5 py-2 text-left text-[12px] font-semibold text-destructive hover:bg-destructive/[0.08]" onClick={() => { setOpen(false); onRemove(); }}>{t('settings.models.sourceDetail.row.remove')}</button>+ </ResponsiveMenu>+ );+};++type GuardedAction =+ | { kind: 'refetch'; hops: RouteHopRef[]; gaps: SupplyGap[] }+ | { kind: 'remove'; model: SuppliedModel; hops: RouteHopRef[]; gaps: SupplyGap[] };++const confirmGuardPlan = (guard: Pick<GuardedAction, 'hops' | 'gaps'>): GuardConfirmation => ({+ force: true,+ would_remove_hops: guard.hops,+ would_interrupt: guard.gaps,+});++type SourceReconciliation =+ | { kind: 'source'; source: Source }+ | { kind: 'gone'; sources: Source[]; snapshot: number };++export const GuardGapList: React.FC<{ gaps: SupplyGap[] }> = ({ gaps }) => {+ const { t, i18n } = useTranslation();+ if (gaps.length === 0) return null;+ return (+ <>+ <div className="model-hub-guard-label"><p>{t('settings.models.guard.gap.label')}</p><span>{t('settings.models.gateway.modelCount', { count: gaps.length })}</span></div>+ <div className="model-hub-guard-list">+ {gaps.map((gap) => (+ <div key={`${gap.backend}:${gap.model_id}`} className="model-hub-guard-hop">+ <span className="min-w-0 flex-1">+ <strong>{t('settings.models.guard.gap.subject', { backend: t(`settings.models.backends.${gap.backend}`, { defaultValue: gap.backend }), menuModel: gap.model_id })}</strong>+ {gap.agents.length > 0 && <span>{t('settings.models.guard.gap.agents', { agents: gap.agents.join(i18n.language.startsWith('zh') ? '、' : ', ') })}</span>}+ </span>+ </div>+ ))}+ </div>+ </>+ );+};++const enteredHost = (source: Source): string | null => {+ if (!source.base_url || !isCustomEndpoint(source)) return null;+ try {+ return new URL(source.base_url).host;+ } catch {+ return null;+ }+};++const TierEditor: React.FC<{+ model: SuppliedModel;+ onMutating: () => void;+ trackMutation: TrackSourceMutation;+}> = ({ model, onMutating, trackMutation }) => {+ const { t } = useTranslation();+ const [tiers, setTiers] = React.useState(model.reasoning_efforts ?? []);+ const [draft, setDraft] = React.useState('');+ const [editing, setEditing] = React.useState(false);+ const [saving, setSaving] = React.useState(false);+ const [failedNext, setFailedNext] = React.useState<TierMutationIntent | null>(null);+ React.useEffect(() => setTiers(model.reasoning_efforts ?? []), [model.reasoning_efforts]);++ const commit = async (intent: TierMutationIntent): Promise<boolean> => {+ if (saving) return false;+ setSaving(true);+ try {+ return await trackMutation(async (latest, settlement) => {+ const payload = tierMutationPayload(latest, model.id, intent);+ if (!payload) {+ settlement.release();+ return false;+ }+ const { previous, next } = payload;+ onMutating();+ setFailedNext(null);+ setTiers(next);+ if (previous.length === next.length && previous.every((tier, index) => tier === next[index])) {+ settlement.release();+ return true;+ }+ try {+ const echoed = await modelsApi.updateModelReasoningEfforts(latest.id, model.id, next);+ await settlement.source(echoed);+ return true;+ } catch (error) {+ setTiers(previous);+ setFailedNext(intent);+ if (apiFailure(error)?.code === 'source_not_found') await settlement.gone(latest.id);+ else await settlement.unread();+ return false;+ }+ });+ } finally {+ setSaving(false);+ }+ };+ const add = async () => {+ const value = draft.trim();+ if (!value || tiers.includes(value)) return;+ if (await commit({ kind: 'add', tier: value })) setDraft('');+ };+ const retry = async () => {+ if (!failedNext) return;+ if (await commit(failedNext) && failedNext.kind === 'add' && draft.trim() === failedNext.tier) setDraft('');+ };+ if (!editing) {+ return (+ <button+ type="button"+ className="flex min-w-0 flex-wrap items-center gap-1.5 text-left"+ onClick={() => { setFailedNext(null); setEditing(true); }}+ >+ {tiers.length > 0 ? tiers.map((tier) => (+ <span key={tier} className="model-hub-source-tier model-hub-source-tier-chip inline-flex rounded-full border border-border text-foreground">{tier}</span>+ )) : <span className="model-hub-source-tier text-muted">{t('settings.models.sourceDetail.tiers.empty')}</span>}+ <span className="model-hub-source-tier model-hub-ink-mint font-semibold">{t(tiers.length > 0 ? 'settings.models.sourceDetail.tiers.add' : 'settings.models.sourceDetail.tiers.addFirst')}</span>+ </button>+ );+ }+ return (+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">+ {tiers.map((tier) => (+ <span key={tier} className="model-hub-source-tier model-hub-source-tier-chip inline-flex items-center gap-1 rounded-full border border-border text-foreground">+ {tier}+ <button type="button" disabled={saving} onMouseDown={(event) => event.preventDefault()} onClick={() => void commit({ kind: 'remove', tier })} aria-label={t('settings.models.sourceDetail.tiers.remove', { tier }) as string} className="text-muted hover:text-foreground disabled:opacity-50">+ <X className="size-2.5" />+ </button>+ </span>+ ))}+ <Input+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={() => { if (!failedNext) { setDraft(''); setEditing(false); } }}+ onKeyDown={(event) => {+ if (event.key === 'Enter') { event.preventDefault(); void add(); }+ if (event.key === 'Escape') { event.preventDefault(); setDraft(''); event.currentTarget.blur(); }+ }}+ disabled={saving}+ placeholder={t('settings.models.sourceDetail.tiers.inputHint') as string}+ className="model-hub-source-tier h-7 w-28 rounded-full border-mint/40 px-2.5"+ />+ {failedNext && <span className="model-hub-source-tier inline-flex items-center gap-1.5 text-destructive">+ {t('settings.models.sourceDetail.fail.tier')}+ <button type="button" disabled={saving} onMouseDown={(event) => event.preventDefault()} onClick={() => void retry()} className="font-semibold underline underline-offset-2 disabled:opacity-50">{t('settings.models.sourceDetail.retry')}</button>+ </span>}+ </div>+ );+};++const DraftTiers: React.FC<{+ tiers: string[];+ onChange: (tiers: string[]) => void;+}> = ({ tiers, onChange }) => {+ const { t } = useTranslation();+ const [draft, setDraft] = React.useState('');+ const add = () => {+ const value = draft.trim();+ if (!value || tiers.includes(value)) return;+ onChange([...tiers, value]);+ setDraft('');+ };+ return (+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">+ {tiers.map((tier) => (+ <span key={tier} className="model-hub-source-tier model-hub-source-tier-chip inline-flex items-center gap-1 rounded-full border border-border text-foreground">+ {tier}+ <button type="button" onClick={() => onChange(tiers.filter((item) => item !== tier))} aria-label={t('settings.models.sourceDetail.tiers.remove', { tier }) as string} className="text-muted hover:text-foreground"><X className="size-2.5" /></button>+ </span>+ ))}+ <Input+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter') { event.preventDefault(); add(); }+ if (event.key === 'Escape') { event.preventDefault(); setDraft(''); event.currentTarget.blur(); }+ }}+ placeholder={t('settings.models.sourceDetail.tiers.inputHint') as string}+ className="model-hub-source-tier h-7 w-36 rounded-full border-mint/40 px-2.5"+ />+ </div>+ );+};++export const SourceDetailPanel: React.FC<{+ source: Source;+ trackMutation: TrackSourceMutation;+}> = ({ source, trackMutation }) => {+ const { t, i18n } = useTranslation();+ const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);+ const { Icon, accent } = sourceVisual(source);+ const [busy, setBusy] = React.useState(false);+ const [manualDraft, setManualDraft] = React.useState<{ modelId: string; tiers: string[]; failed: boolean; retryRead: boolean } | null>(null);+ const [guard, setGuard] = React.useState<GuardedAction | null>(null);+ const [result, setResult] = React.useState<{ added: string[]; removed: string[] } | null>(null);+ const [refetchFailed, setRefetchFailed] = React.useState(false);+ const [removeFailure, setRemoveFailure] = React.useState<{ modelId: string; retryRead: boolean } | null>(null);+ const models = source.models;++ const guardedFailure = (error: unknown): { hops: RouteHopRef[]; gaps: SupplyGap[] } | null => {+ const failure = apiFailure(error);+ if (!failure || (failure.wouldRemoveHops.length === 0 && failure.wouldInterrupt.length === 0)) return null;+ return { hops: failure.wouldRemoveHops, gaps: failure.wouldInterrupt };+ };+ const refetch = (confirmation?: GuardConfirmation) => {+ if (busy) return Promise.resolve();+ setResult(null);+ setRefetchFailed(false);+ setBusy(true);+ return trackMutation(async (latest, settlement) => {+ const before = new Set(latest.models.map((model) => model.id));+ try {+ const answer = await modelsApi.refreshSource(latest.id, confirmation);+ const after = new Set(answer.source.models.map((model) => model.id));+ const added = [...after].filter((id) => !before.has(id));+ const removed = [...before].filter((id) => !after.has(id));+ setResult({ added, removed });+ setGuard(null);+ await settlement.source(answer.source);+ } catch (error) {+ if (apiFailure(error)?.code === 'source_not_found') await settlement.gone(latest.id);+ else {+ const refusal = guardedFailure(error);+ if (refusal) {+ setGuard({ kind: 'refetch', ...refusal });+ settlement.release();+ } else {+ setRefetchFailed(true);+ try {+ const inventory = await settlement.readInventory();+ const current = inventory.sources.find((item) => item.id === latest.id);+ if (current) await settlement.source(current);+ else await settlement.gone(latest.id, inventory);+ } catch {+ settlement.release();+ }+ }+ }+ }+ }).finally(() => setBusy(false));+ };+ const reconcileManualCreate = async (sourceId: string, modelId: string, settlement: SourceMutationSettlement) => reconcileUnknownWrite(+ settlement.readInventory,+ ({ sources, snapshot }) => {+ const current = sources.find((item) => item.id === sourceId);+ if (!current) return { kind: 'gone', sources, snapshot } satisfies SourceReconciliation;+ return current.models.some((model) => model.id === modelId)+ ? { kind: 'source', source: current } satisfies SourceReconciliation+ : undefined;+ },+ );+ const applyReconciliation = async (sourceId: string, value: SourceReconciliation, settlement: SourceMutationSettlement) => {+ if (value.kind === 'gone') await settlement.gone(sourceId, value);+ else await settlement.source(value.source);+ };+ const addManualModel = () => {+ if (!manualDraft || busy) return;+ const draft = manualDraft;+ const modelId = draft.modelId.trim();+ if (!modelId) return;+ setResult(null);+ setRefetchFailed(false);+ setBusy(true);+ return trackMutation(async (latest, settlement) => {+ if (latest.models.some((model) => model.id === modelId)) {+ setManualDraft(null);+ settlement.release();+ return;+ }+ if (draft.retryRead) {+ const reconciliation = await reconcileManualCreate(latest.id, modelId, settlement);+ if (reconciliation.kind === 'committed') {+ setManualDraft(null);+ await applyReconciliation(latest.id, reconciliation.value, settlement);+ } else {+ settlement.release();+ setManualDraft((current) => current ? {+ ...current,+ failed: true,+ retryRead: reconciliation.kind === 'unread',+ } : current);+ }+ return;+ }+ try {+ const echoed = await modelsApi.addCustomModel(latest.id, {+ model_id: modelId,+ display_name: null,+ reasoning_efforts: draft.tiers,+ });+ setManualDraft(null);+ setResult(null);+ await settlement.source(echoed);+ } catch (error) {+ if (apiFailure(error)?.code === 'source_not_found') {+ await settlement.gone(latest.id);+ } else {+ const reconciliation = await reconcileManualCreate(latest.id, modelId, settlement);+ if (reconciliation.kind === 'committed') {+ setManualDraft(null);+ await applyReconciliation(latest.id, reconciliation.value, settlement);+ } else {+ settlement.release();+ setManualDraft((current) => current ? {+ ...current,+ failed: true,+ retryRead: reconciliation.kind === 'unread',+ } : current);+ }+ }+ }+ }).finally(() => setBusy(false));+ };+ const reconcileRemoval = async (sourceId: string, model: SuppliedModel, settlement: SourceMutationSettlement) => {+ const reconciliation = await reconcileUnknownWrite(+ settlement.readInventory,+ ({ sources, snapshot }) => {+ const current = sources.find((item) => item.id === sourceId);+ if (!current) return { kind: 'gone', sources, snapshot } satisfies SourceReconciliation;+ return !current.models.some((entry) => entry.id === model.id)+ ? { kind: 'source', source: current } satisfies SourceReconciliation+ : undefined;+ },+ );+ if (reconciliation.kind === 'committed') {+ setGuard(null);+ setRemoveFailure(null);+ await applyReconciliation(sourceId, reconciliation.value, settlement);+ return;+ }+ settlement.release();+ setRemoveFailure({ modelId: model.id, retryRead: reconciliation.kind === 'unread' });+ };+ const remove = (model: SuppliedModel, confirmation?: GuardConfirmation) => {+ if (busy) return Promise.resolve();+ setResult(null);+ setRefetchFailed(false);+ setRemoveFailure(null);+ setBusy(true);+ return trackMutation(async (latest, settlement) => {+ if (!latest.models.some((candidate) => candidate.id === model.id)) {+ setGuard(null);+ settlement.release();+ return;+ }+ try {+ const echoed = await modelsApi.deleteCustomModel(latest.id, model.id, confirmation);+ setGuard(null);+ await settlement.source(echoed);+ } catch (error) {+ if (apiFailure(error)?.code === 'source_not_found') await settlement.gone(latest.id);+ else {+ const refusal = guardedFailure(error);+ if (refusal) {+ setGuard({ kind: 'remove', model, ...refusal });+ settlement.release();+ } else await reconcileRemoval(latest.id, model, settlement);+ }+ }+ }).finally(() => setBusy(false));+ };+ const confirmGuard = () => {+ if (!guard) return;+ const confirmation = confirmGuardPlan(guard);+ if (guard.kind === 'refetch') void refetch(confirmation);+ else void remove(guard.model, confirmation);+ };+ const adoptedBackends = [...new Set((source.adopted_by ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];+ const state = sourceStatePresentation(source.state, 'detail', i18n.language, now, {+ known: source.adopted_by !== undefined,+ backends: adoptedBackends,+ native: source.supply_channel === 'native_cli',+ });+ const host = enteredHost(source);++ return (+ <div className="model-hub-source-detail">+ <section className="model-hub-source-bar flex flex-col border border-border bg-surface sm:flex-row sm:items-center">+ <span className={cn('model-hub-source-tile flex shrink-0 items-center justify-center', ACCENT_TILE[accent])}><Icon className={cn('size-[18px]', ACCENT_ICON[accent])} /></span>+ <div className="min-w-0 flex-1">+ <h2 className="model-hub-source-title truncate font-bold text-foreground">{source.display_name}</h2>+ {(state.key || source.last_discovered_at) && <p className={cn('mt-1 flex flex-wrap items-center gap-x-2 gap-y-1', state.textClass)}>+ {state.key && <span className="model-hub-source-state flex items-center gap-1.5"><span className={cn('size-[5px] rounded-full', state.dotClass)} />{t(state.key, state.values)}</span>}+ {source.last_discovered_at && <span className="model-hub-source-age text-muted">{t('settings.models.sourceDetail.status.listUpdated', { time: formatRelativeTime(source.last_discovered_at, t) })}</span>}+ </p>}+ <p className="model-hub-source-summary mt-1 truncate font-mono">{t(host ? 'settings.models.sourceDetail.summary' : 'settings.models.gateway.modelCount', { host, count: source.models.length })}</p>+ </div>+ <div className="flex shrink-0 gap-2">+ {source.supply_channel === 'hub' && <Button variant="outline" size="sm" className="model-hub-source-action" disabled={busy} onClick={() => void refetch()}>{busy ? <Loader2 className="animate-spin" /> : <RefreshCw />}{t('settings.models.sourceDetail.action.refetch')}</Button>}+ {source.kind === 'api_key' && <Button variant="secondary" size="sm" className="model-hub-source-action model-hub-ink-mint" disabled={busy || manualDraft !== null} onClick={() => setManualDraft({ modelId: '', tiers: [], failed: false, retryRead: false })}><Plus />{t('settings.models.sourceDetail.action.addModel')}</Button>}+ </div>+ </section>+ {result && result.removed.length > 0 && <p className="model-hub-status-gold rounded-lg border px-3 py-2 text-[11.5px]">{t('settings.models.sourceDetail.refetch.removed', { count: result.removed.length, models: result.removed.join(', ') })}</p>}+ {result && result.added.length === 0 && result.removed.length === 0 && <p className="model-hub-status-mint rounded-lg border px-3 py-2 text-[11.5px]">{t('settings.models.sourceDetail.refetch.unchangedOnly')}</p>}+ {refetchFailed && <p className="rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2 text-[11.5px] text-destructive">{t('settings.models.sourceDetail.fail.refetch')}</p>}+ <section className="model-hub-source-table overflow-hidden border border-border bg-surface">+ <div className="model-hub-source-table-head hidden border-b border-border font-semibold md:grid">+ <span>{t('settings.models.sourceDetail.col.id')}</span><span>{t('settings.models.sourceDetail.col.entry')}</span><span className="flex items-center gap-1">{t('settings.models.sourceDetail.col.tiers')}<Info className="size-3" /></span><span />+ </div>+ {models.length === 0 && !manualDraft ? <p className="px-5 py-12 text-center text-[12px] text-muted">{t(source.last_discovered_at ? 'settings.models.sourceDetail.empty' : 'settings.models.sourceDetail.emptyNeverFetched')}</p> : models.map((model) => (+ <div key={model.id} className="model-hub-source-table-row grid gap-3 border-b border-border last:border-b-0 md:items-center md:gap-y-0">+ <span className="flex min-w-0 items-center gap-2"><span className="model-hub-source-model truncate font-mono text-foreground" title={model.id}>{model.id}</span>{result?.added.includes(model.id) && <span className="model-hub-accent-pill--mint model-hub-source-pill rounded-full border px-2 py-0.5 font-semibold">{t('settings.models.sourceDetail.refetch.added')}</span>}</span>+ <span className="model-hub-source-pill model-hub-source-entry-pill w-fit rounded-full border border-border font-semibold text-muted">{t(`settings.models.sourceDetail.entry.${model.origin === 'discovered' ? 'auto' : 'manual'}`)}</span>+ <TierEditor model={model} onMutating={() => { setResult(null); setRefetchFailed(false); }} trackMutation={trackMutation} />+ <div className="flex items-center justify-end gap-2">+ {removeFailure?.modelId === model.id && <span className="model-hub-source-tier text-right text-destructive">{t('settings.models.sourceDetail.fail.removeModel')} <button type="button" disabled={busy} onClick={() => {+ if (!removeFailure.retryRead) void remove(model);+ else {+ setBusy(true);+ void trackMutation(async (latest, settlement) => reconcileRemoval(latest.id, model, settlement))+ .finally(() => setBusy(false));+ }+ }} className="font-semibold underline underline-offset-2">{t('settings.models.sourceDetail.retry')}</button></span>}+ {model.origin === 'manual' && <ManualModelMenu model={model} busy={busy} onRemove={() => void remove(model)} />}+ </div>+ </div>+ ))}+ {manualDraft && (+ <div data-manual-model-draft className="model-hub-source-table-draft grid gap-3 border-y border-mint/20 bg-mint/[0.05] md:items-center md:gap-y-0">+ <Input+ autoFocus+ value={manualDraft.modelId}+ onChange={(event) => setManualDraft((current) => current ? { ...current, modelId: event.target.value, failed: false, retryRead: false } : current)}+ placeholder={t('settings.models.sourceDetail.col.id') as string}+ className="model-hub-source-manual-id model-hub-source-model h-8 font-mono"+ />+ <span className="model-hub-source-pill model-hub-source-entry-pill w-fit rounded-full border border-border font-semibold text-muted">{t('settings.models.sourceDetail.entry.manual')}</span>+ <DraftTiers tiers={manualDraft.tiers} onChange={(tiers) => setManualDraft((current) => current ? { ...current, tiers, failed: false, retryRead: false } : current)} />+ <div className="flex justify-end gap-2">+ <Button variant="ghost" size="xs" disabled={busy} onClick={() => setManualDraft(null)}>{t('common.cancel')}</Button>+ <Button size="xs" disabled={busy || !manualDraft.modelId.trim() || source.models.some((model) => model.id === manualDraft.modelId.trim())} onClick={() => void addManualModel()}>{manualDraft.failed ? t('settings.models.sourceDetail.retry') : t('settings.models.sourceDetail.action.addModel')}</Button>+ </div>+ {manualDraft.failed && <p className="text-[11px] text-destructive md:col-span-4">{t('settings.models.sourceDetail.fail.addModel')}</p>}+ </div>+ )}+ {source.kind === 'api_key' && !manualDraft && (+ <button type="button" className="model-hub-source-table-add model-hub-source-model model-hub-ink-mint flex w-full items-center gap-2 border-b border-border text-left font-semibold" onClick={() => setManualDraft({ modelId: '', tiers: [], failed: false, retryRead: false })}>+ <Plus className="size-3.5" />+ {t('settings.models.sourceDetail.action.addModel')}+ <span className="text-[10.5px] font-normal text-muted">{t('settings.models.sourceDetail.addRow.hint')}</span>+ </button>+ )}+ </section>+ <p className="model-hub-source-footnote leading-relaxed">{t('settings.models.sourceDetail.footnote')}</p>+ <DialogPrimitive.Root open={guard !== null} onOpenChange={(open) => !open && !busy && setGuard(null)}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay className="model-hub-guard-overlay fixed inset-0 z-50" />+ <DialogPrimitive.Content className="model-hub-guard-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-y-auto border border-border-strong bg-surface outline-none">+ <header className="model-hub-guard-head">+ <div className="flex items-center justify-between gap-3">+ <DialogPrimitive.Title className="model-hub-guard-title text-foreground">{t(`settings.models.guard.title.${guard?.kind === 'remove' ? 'removeModel' : 'refetch'}`, { model: guard?.kind === 'remove' ? guard.model.id : undefined, source: source.display_name })}</DialogPrimitive.Title>+ <DialogPrimitive.Close asChild><Button type="button" variant="ghost" size="icon" className="model-hub-guard-close" disabled={busy} aria-label={t('settings.models.guard.cancel')} title={t('settings.models.guard.cancel')}><X aria-hidden /></Button></DialogPrimitive.Close>+ </div>+ <DialogPrimitive.Description className="model-hub-guard-subtitle">{t(`settings.models.guard.subtitle.${guard?.kind === 'remove' ? 'removeModel' : 'refetch'}`)}</DialogPrimitive.Description>+ </header>+ {guard && <div className="model-hub-guard-body">+ {guard.hops.length > 0 && <>+ <div className="model-hub-guard-label"><p>{t('settings.models.guard.label')}</p><span>{t('settings.models.guard.count', { count: guard.hops.length })}</span></div>+ <div className="model-hub-guard-list">{guard.hops.map((hop) => <div key={`${hop.backend}:${hop.menu_model}:${hop.position}:${hop.source_id}:${hop.model_id}`} className="model-hub-guard-hop"><span className="min-w-0 flex-1"><strong>{t(`settings.models.backends.${hop.backend}`, { defaultValue: hop.backend })} · {hop.menu_model}</strong><span>{hop.model_id} · {t('settings.models.guard.hop.position', { n: hop.position })}</span></span></div>)}</div>+ </>}+ <GuardGapList gaps={guard.gaps} />+ <p className={cn('model-hub-guard-hint', guard.gaps.length > 0 && 'text-destructive')}><Info aria-hidden />{t(`settings.models.guard.hint.${guard.gaps.length > 0 ? 'interrupt' : 'safe'}`)}</p>+ </div>}+ <footer className="model-hub-guard-foot"><Button variant="outline" className="model-hub-guard-action" onClick={() => setGuard(null)} disabled={busy}>{t('settings.models.guard.cancel')}</Button><Button variant="destructive" className="model-hub-guard-action" onClick={confirmGuard} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(`settings.models.guard.confirm.${guard?.kind === 'remove' ? 'removeModel' : 'refetch'}`)}</Button></footer>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>+ </div>+ );+};diff --git a/ui/src/components/settings/models/SourceOrderDrawer.test.tsx b/ui/src/components/settings/models/SourceOrderDrawer.test.tsxnew file mode 100644index 000000000..d74227e08--- /dev/null+++ b/ui/src/components/settings/models/SourceOrderDrawer.test.tsx@@ -0,0 +1,259 @@+// @vitest-environment jsdom+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ToastProvider } from '@/context/ToastProvider';+import i18n from '@/i18n';+import { createSourceCollectionReadAuthority } from './collectionReadAuthority';+import { modelsApi } from './modelsApi';+import { SourceOrderDrawer } from './SourceOrderDrawer';+import type { AgentSupply, Source } from './types';++const source = (id: string, displayName: string): Source => ({+ id,+ last_discovered_at: null,+ kind: 'api_key',+ vendor: 'anthropic',+ display_name: displayName,+ protocol: 'anthropic',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active', retry_at: null, detail_key: null },+ models: [],+});++const sources = [source('src_a', 'Primary'), source('src_b', 'Backup')];+const deferred = <T,>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+};+const agent: AgentSupply = {+ backend: 'claude',+ cli_present: true,+ mode: 'hub',+ menu_kind: 'fixed',+ sources: {+ order: ['src_a', 'src_b'],+ eligibility: sources.map((item) => ({ source_id: item.id, eligible: true })),+ },+};++const renderDrawer = (overrides: Partial<React.ComponentProps<typeof SourceOrderDrawer>> = {}) => render(+ <I18nextProvider i18n={i18n}>+ <ToastProvider>+ <SourceOrderDrawer+ open+ agent={agent}+ sources={sources}+ sourceReads={createSourceCollectionReadAuthority(modelsApi)}+ onClose={vi.fn()}+ onSaved={vi.fn()}+ orderWrite={{ pending: false, track: async (work) => work() }}+ {...overrides}+ />+ </ToastProvider>+ </I18nextProvider>,+);++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++beforeEach(() => {+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue(sources);+});++describe('SourceOrderDrawer keyboard ordering', () => {+ it('grabs, moves, announces, and restores the pre-grab order on Escape', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);+ renderDrawer();+ const handles = await screen.findAllByRole('button', { name: 'Reorder source' });++ handles[0].focus();+ await user.keyboard('[Space]');+ expect(handles[0].getAttribute('aria-grabbed')).toBe('true');++ await user.keyboard('[ArrowDown]');+ expect(screen.getByText('Moved Primary to position 2 of 2.')).toBeTruthy();+ expect(document.activeElement).toBe(screen.getAllByRole('button', { name: 'Reorder source' })[1]);++ await user.keyboard('[Escape]');+ const restored = screen.getAllByRole('button', { name: 'Reorder source' });+ expect(restored[0].getAttribute('aria-grabbed')).toBe('false');+ expect(restored[0].closest('li')?.textContent).toContain('Primary');+ });++ it('moves focus without moving the order when the row is not grabbed', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);+ renderDrawer();+ const handles = await screen.findAllByRole('button', { name: 'Reorder source' });++ handles[0].focus();+ await user.keyboard('[ArrowDown]');++ expect(document.activeElement?.closest('li')?.textContent).toContain('Backup');+ expect(handles[0].closest('li')?.textContent).toContain('Primary');+ });++ it('reads the current order on open and keeps the moved draft after a failed save', async () => {+ const user = userEvent.setup();+ const getAgentSources = vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);+ const putAgentSources = vi.spyOn(modelsApi, 'putAgentSources').mockRejectedValue(new Error('offline'));+ renderDrawer();++ await user.click((await screen.findAllByRole('button', { name: 'Remove from order' }))[0]);+ await user.click(screen.getByRole('button', { name: 'Remove from order' }));+ await user.click(screen.getByRole('button', { name: 'Save order' }));++ await screen.findByText('The order was not saved');+ expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();+ expect(screen.getByText('This order is empty. Add a source from below.')).toBeTruthy();+ expect(getAgentSources).toHaveBeenCalledWith('claude');+ expect(putAgentSources).toHaveBeenCalledWith('claude', { order: [] });+ });++ it('keeps a read failure inside the drawer and retries the collection read', async () => {+ const user = userEvent.setup();+ const read = vi.spyOn(modelsApi, 'getAgentSources')+ .mockRejectedValueOnce(new Error('unread'))+ .mockResolvedValueOnce(agent);+ renderDrawer();++ await screen.findByText('The source list could not be read');+ await user.click(screen.getByRole('button', { name: 'Retry' }));++ await waitFor(() => expect(screen.getAllByRole('button', { name: 'Reorder source' })).toHaveLength(2));+ expect(read).toHaveBeenCalledTimes(2);+ });++ it('disables saving when no source is eligible', async () => {+ const noEligible: AgentSupply = {+ ...agent,+ sources: {+ order: [],+ eligibility: sources.map((item) => ({ source_id: item.id, eligible: false })),+ },+ };+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(noEligible);+ renderDrawer({ agent: noEligible });++ await screen.findByText('No source is available to this backend yet.');+ expect(screen.getByRole('button', { name: 'Save order' }).hasAttribute('disabled')).toBe(true);+ });++ it('uses the source inventory read in the same generation as the Agent order', async () => {+ const newest = source('src_c', 'Newest source');+ vi.mocked(modelsApi.listSources).mockResolvedValueOnce([...sources, newest]);+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue({+ ...agent,+ sources: {+ order: ['src_a', 'src_b', 'src_c'],+ eligibility: [...(agent.sources?.eligibility ?? []), { source_id: newest.id, eligible: true }],+ },+ });++ renderDrawer();++ expect(await screen.findByText('Newest source')).toBeTruthy();+ expect(screen.getAllByRole('button', { name: 'Reorder source' })).toHaveLength(3);+ });++ it('renders a composition hole and performs exactly one regroup read', async () => {+ const newest = source('src_c', 'Newest source');+ const nextAgent = {+ ...agent,+ sources: {+ order: ['src_a', 'src_b', 'src_c'],+ eligibility: [...(agent.sources?.eligibility ?? []), { source_id: newest.id, eligible: true }],+ },+ };+ const regroupedAgent = deferred<AgentSupply>();+ const regroupedSources = deferred<Source[]>();+ const agentRead = vi.spyOn(modelsApi, 'getAgentSources')+ .mockResolvedValueOnce(nextAgent)+ .mockReturnValueOnce(regroupedAgent.promise);+ vi.mocked(modelsApi.listSources)+ .mockResolvedValueOnce(sources)+ .mockReturnValueOnce(regroupedSources.promise);++ renderDrawer();++ expect(await screen.findByText('src_c')).toBeTruthy();+ expect(agentRead).toHaveBeenCalledTimes(2);+ await act(async () => {+ regroupedAgent.resolve(nextAgent);+ regroupedSources.resolve([...sources, newest]);+ await Promise.all([regroupedAgent.promise, regroupedSources.promise]);+ });+ expect(await screen.findByText('Newest source')).toBeTruthy();+ expect(agentRead).toHaveBeenCalledTimes(2);+ });++ it('regroups when the Source inventory is newer than the Agent projection', async () => {+ const newest = source('src_c', 'Newest source');+ const regroupedAgent = deferred<AgentSupply>();+ const regroupedSources = deferred<Source[]>();+ const nextAgent = {+ ...agent,+ sources: {+ order: ['src_a', 'src_b'],+ eligibility: [...(agent.sources?.eligibility ?? []), { source_id: newest.id, eligible: true }],+ },+ };+ const agentRead = vi.spyOn(modelsApi, 'getAgentSources')+ .mockResolvedValueOnce(agent)+ .mockReturnValueOnce(regroupedAgent.promise);+ vi.mocked(modelsApi.listSources)+ .mockResolvedValueOnce([...sources, newest])+ .mockReturnValueOnce(regroupedSources.promise);++ renderDrawer();++ await waitFor(() => expect(agentRead).toHaveBeenCalledTimes(2));+ await act(async () => {+ regroupedAgent.resolve(nextAgent);+ regroupedSources.resolve([...sources, newest]);+ await Promise.all([regroupedAgent.promise, regroupedSources.promise]);+ });++ expect(await screen.findByText('Newest source')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Add to order' })).toBeTruthy();+ expect(agentRead).toHaveBeenCalledTimes(2);+ });++ it('moves a persistent composition hole to the drawer F1 retry state', async () => {+ const inconsistent = {+ ...agent,+ sources: {+ order: ['src_a', 'src_deleted'],+ eligibility: [...(agent.sources?.eligibility ?? []), { source_id: 'src_deleted', eligible: true }],+ },+ };+ const agentRead = vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(inconsistent);+ vi.mocked(modelsApi.listSources).mockResolvedValue([sources[0]]);++ renderDrawer();++ expect(await screen.findByText('The source list could not be read')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();+ expect(agentRead).toHaveBeenCalledTimes(2);+ });++ it('moves a persistent inventory-newer hole to the drawer F1 retry state', async () => {+ const newest = source('src_c', 'Newest source');+ const agentRead = vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);+ vi.mocked(modelsApi.listSources).mockResolvedValue([...sources, newest]);++ renderDrawer();++ expect(await screen.findByText('The source list could not be read')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();+ expect(agentRead).toHaveBeenCalledTimes(2);+ });+});diff --git a/ui/src/components/settings/models/SourceOrderDrawer.tsx b/ui/src/components/settings/models/SourceOrderDrawer.tsxindex 14027c965..0967c74ba 100644--- a/ui/src/components/settings/models/SourceOrderDrawer.tsx+++ b/ui/src/components/settings/models/SourceOrderDrawer.tsx@@ -1,98 +1,81 @@import * as React from 'react';+import * as DialogPrimitive from '@radix-ui/react-dialog';import { Reorder, useDragControls } from 'framer-motion';-import { CirclePlus, GripVertical, X } from 'lucide-react';+import { GripVertical, LoaderCircle, Minus, Plus, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';-import { useToast } from '@/context/ToastContext';import { cn } from '@/lib/utils';-import { useIsMobile } from '@/lib/useIsMobile';-import { initialSeedState, savedSourcesKey, seedStep, type PendingWrite } from './asyncLifetime';-import { eligibilityOf } from './eligibility';-import { MenuDrawer } from './menus/MenuDrawer';+import { ModelHubInfoHint } from './ModelHubInfoHint';+import type { PendingWrite } from './asyncLifetime';+import type { CollectionReadAuthority } from './collectionReadAuthority';import { modelsApi } from './modelsApi';import { movedOrder, sameIds } from './reorder';-import { ACCENT_ICON, ACCENT_TILE, backendVisual, sourceVisual } from './vendorMeta';-import type { AgentSourcesPut, AgentSupply, Source, SourcePolicy } from './types';+import { combineSourceOrderReads } from './sourceOrderComposition';+import { sourceDetail } from './sourcePresentation';+import type { AgentSupply, Source } from './types';+import { ACCENT_PILL, sourceAccent } from './vendorMeta';-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:text-[11px]';+type OrderAnnouncement =+ | { key: 'grabbed' | 'moved' | 'dropped'; source: string; position: number; count: number }+ | { key: 'grabCancelled'; source: string }+ | null;-const SourceTile: React.FC<{ source: Source }> = ({ source }) => {- const { Icon, accent } = sourceVisual(source);+type ReadState = 'loading' | 'reconciling' | 'ready' | 'error';++const SourceIdentity: React.FC<{ source: Source }> = ({ source }) => {+ const { t } = useTranslation();+ const detail = sourceDetail(source);return (- <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>+ <>+ <span className="model-hub-order-identity">+ <span className="model-hub-order-name truncate" title={source.display_name}>{source.display_name}</span>+ {detail && <span className="model-hub-order-meta truncate" title={detail}>{detail}</span>}+ </span>+ <span className={cn('model-hub-order-tag', ACCENT_PILL[sourceAccent(source)])}>+ {t(`settings.models.sourceKind.${source.kind}`)}+ </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', first ? 'pt-0.5' : 'pt-2')}>- <span className="text-[10px] font-bold tracking-[1px] text-muted">{label}</span>- {children}- </div>-);--const EnabledRow: React.FC<{+const OrderedRow: React.FC<{source: Source;index: number;+ count: number;busy: boolean;- onCommit: () => void;- onMove: (delta: -1 | 1) => void;- onRemove: () => void;-}> = ({ source, index, busy, onCommit, onMove, onRemove }) => {+ grabbed: boolean;+ handleRef: (node: HTMLButtonElement | null) => void;+ onExclude: () => void;+ onKeyDown: (event: React.KeyboardEvent<HTMLButtonElement>) => void;+}> = ({ source, index, count, busy, grabbed, handleRef, onExclude, onKeyDown }) => {const { t } = useTranslation();const controls = useDragControls();+ const inert = count <= 1;return (<Reorder.Itemvalue={source.id}dragListener={false}dragControls={controls}- onDragEnd={onCommit}- className={cn(ROW, 'list-none border-border bg-background')}+ className="model-hub-order-row model-hub-order-row--ordered list-none"><button+ ref={handleRef}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"+ aria-label={t('settings.models.order.reorder')}+ aria-grabbed={grabbed}+ disabled={busy || inert}+ onPointerDown={(event) => !inert && controls.start(event)}+ onKeyDown={onKeyDown}+ className={cn('model-hub-order-grip', grabbed && 'is-grabbed')}>- <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 />+ <GripVertical /></button>+ <span className={cn('model-hub-order-ordinal', index === 0 && 'is-first')}>{index + 1}</span>+ <SourceIdentity source={source} />+ <Button type="button" variant="outline" className="model-hub-order-row-action" disabled={busy} onClick={onExclude}>+ {t('settings.models.order.action.exclude')}+ </Button></Reorder.Item>);};@@ -100,182 +83,324 @@ const EnabledRow: React.FC<{export const SourceOrderDrawer: React.FC<{open: boolean;agent: AgentSupply;- agents: AgentSupply[];sources: Source[];onClose: () => void;onSaved: (echoed: AgentSupply) => void | Promise<void>;orderWrite: PendingWrite;-}> = ({ open, agent, agents, sources, onClose, onSaved, orderWrite }) => {+ sourceReads: CollectionReadAuthority<Source[]>;+}> = ({ open, agent, sources, onClose, onSaved, orderWrite, sourceReads }) => {const { t } = useTranslation();- const { showToast } = useToast();- 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 ?? []);+ const [viewAgent, setViewAgent] = React.useState(agent);+ const [viewSources, setViewSources] = React.useState(sources);+ const [readState, setReadState] = React.useState<ReadState>('loading');+ const [order, setOrder] = React.useState<string[]>([]);+ const [dirty, setDirty] = React.useState(false);+ const [saveFailed, setSaveFailed] = React.useState(false);+ const [grabbedId, setGrabbedId] = React.useState<string | null>(null);+ const [announcement, setAnnouncement] = React.useState<OrderAnnouncement>(null);+ const saved = React.useRef<string[]>([]);+ const grabbedFrom = React.useRef<string[]>([]);+ const handles = React.useRef(new Map<string, HTMLButtonElement>());+ const heldOutActions = React.useRef(new Map<string, HTMLButtonElement>());+ const readAttempt = React.useRef(0);const saving = orderWrite.pending;- const saved = React.useRef<{ policy: SourcePolicy; order: string[] }>({ policy, order });- const seed = React.useRef(initialSeedState);- const authoritative = savedSourcesKey(agent);- React.useEffect(() => {- if (!open) return;- const step = seedStep(seed.current, authoritative);- seed.current = step.state;- if (!step.reseed) return;- const next = { policy: agent.sources?.policy ?? 'follow', order: agent.sources?.order ?? [] };- saved.current = next;- setPolicy(next.policy);- setOrder(next.order);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [open, authoritative]);+ const applyRead = React.useCallback((next: AgentSupply, nextSources: Source[], state: ReadState) => {+ const nextOrder = next.sources?.order ?? [];+ setViewAgent(next);+ setViewSources(nextSources);+ saved.current = nextOrder;+ setOrder(nextOrder);+ setDirty(false);+ setSaveFailed(false);+ setGrabbedId(null);+ setAnnouncement(null);+ setReadState(state);+ }, []);- 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((entry) => !entry.eligible);+ const read = React.useCallback(async () => {+ const seq = ++readAttempt.current;+ setReadState('loading');+ try {+ const readPair = () => Promise.all([+ modelsApi.getAgentSources(agent.backend),+ sourceReads.readValue(),+ ] as const);+ const [next, nextSources] = await readPair();+ if (readAttempt.current !== seq) return;+ const composition = combineSourceOrderReads(next, nextSources);+ if (!composition.hasHole) {+ applyRead(next, nextSources, 'ready');+ return;+ }++ // A composition hole is evidence that the two reads straddled a mutation,+ // not that either endpoint failed. Keep it visible while one regroup read runs.+ applyRead(next, nextSources, 'reconciling');+ const [regroupedAgent, regroupedSources] = await readPair();+ if (readAttempt.current !== seq) return;+ const regrouped = combineSourceOrderReads(regroupedAgent, regroupedSources);+ applyRead(regroupedAgent, regroupedSources, regrouped.hasHole ? 'error' : 'ready');+ } catch {+ if (readAttempt.current === seq) setReadState('error');+ }+ }, [agent.backend, applyRead, sourceReads]);- 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 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 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;+ React.useEffect(() => {+ if (open) void read();+ else readAttempt.current += 1;+ }, [open, read]);++ const composition = combineSourceOrderReads(viewAgent, viewSources);+ const available = composition.available;+ const byId = React.useMemo(() => new Map(available.map((source) => [source.id, source])), [available]);+ const orderedEntries = order.map((id) => ({ id, source: byId.get(id) }));+ const ordered = order.map((id) => byId.get(id)).filter((source): source is Source => Boolean(source));+ const heldOut = available.filter((source) => !order.includes(source.id));+ const persist = (next: string[]) => {+ if (sameIds(next, order)) return;+ setOrder(next);+ setDirty(!sameIds(next, saved.current));+ setSaveFailed(false);+ };+ const focusHandle = (sourceId: string) => handles.current.get(sourceId)?.focus();+ const focusHandleAfterRender = (sourceId: string) => requestAnimationFrame(() => focusHandle(sourceId));+ const focusHeldOutAfterRender = (sourceId: string) => requestAnimationFrame(() => heldOutActions.current.get(sourceId)?.focus());+ const startGrab = (sourceId: string) => {+ grabbedFrom.current = [...order];+ setGrabbedId(sourceId);+ setAnnouncement({+ key: 'grabbed',+ source: byId.get(sourceId)?.display_name ?? sourceId,+ position: order.indexOf(sourceId) + 1,+ count: order.length,+ });+ };+ const dropGrab = () => {+ if (!grabbedId) return;+ setAnnouncement({+ key: 'dropped',+ source: byId.get(grabbedId)?.display_name ?? grabbedId,+ position: order.indexOf(grabbedId) + 1,+ count: order.length,+ });+ setGrabbedId(null);+ };+ const cancelGrab = () => {+ if (!grabbedId) return;+ const sourceId = grabbedId;+ const restored = grabbedFrom.current;+ setOrder(restored);+ setDirty(!sameIds(restored, saved.current));+ setAnnouncement({ key: 'grabCancelled', source: byId.get(sourceId)?.display_name ?? sourceId });+ setGrabbedId(null);+ requestAnimationFrame(() => focusHandle(sourceId));+ };+ const handleRowKey = (sourceId: string, event: React.KeyboardEvent<HTMLButtonElement>) => {+ if (event.key === ' ') {+ event.preventDefault();+ if (grabbedId === sourceId) dropGrab();+ else startGrab(sourceId);+ return;+ }+ if (event.key === 'Escape' && grabbedId === sourceId) {+ event.preventDefault();+ event.stopPropagation();+ cancelGrab();+ return;+ }+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;+ event.preventDefault();+ const index = order.indexOf(sourceId);+ const delta = event.key === 'ArrowUp' ? -1 : 1;+ if (grabbedId === sourceId) {+ const next = movedOrder(order, index, delta);+ if (sameIds(next, order)) return;+ persist(next);+ setAnnouncement({+ key: 'moved',+ source: byId.get(sourceId)?.display_name ?? sourceId,+ position: next.indexOf(sourceId) + 1,+ count: next.length,+ });+ requestAnimationFrame(() => focusHandle(sourceId));+ } else {+ const target = order[index + delta];+ if (target) focusHandle(target);}- return t(reasonKey, { vendor: vendorLabel(source) }) as string;};- const persist = (body: AgentSourcesPut, next: { policy: SourcePolicy; order: string[] }) =>- orderWrite.track(async () => {- const previous = saved.current;- setPolicy(next.policy);- setOrder(next.order);+ const save = () => {+ if (saving || readState !== 'ready' || available.length === 0) return;+ void orderWrite.track(async () => {try {- const echoed = await modelsApi.putAgentSources(agent.backend, body);- const adopted = {- policy: echoed.sources?.policy ?? next.policy,- order: echoed.sources?.order ?? next.order,- };- saved.current = adopted;- setPolicy(adopted.policy);- setOrder(adopted.order);+ const echoed = await modelsApi.putAgentSources(agent.backend, { order });+ saved.current = echoed.sources?.order ?? order;+ setOrder(saved.current);+ setDirty(false);+ setSaveFailed(false);await Promise.resolve(onSaved(echoed)).catch(() => {});+ onClose();} catch {- saved.current = previous;- setPolicy(previous.policy);- setOrder([...previous.order]);- showToast(t('settings.models.toast.reorderFailed') as string, 'error');+ // F1: the request failed, not the user's draft. Keep every move and let+ // the same primary retry the exact order.+ setSaveFailed(true);}});-- const commitOrder = (nextOrder: string[]) => {- if (sameIds(saved.current.order, nextOrder)) {- setOrder([...saved.current.order]);- return;- }- void persist({ policy: 'custom', order: nextOrder }, { policy: 'custom', order: nextOrder });};- const restoreDefault = () => void persist({ policy: 'follow' }, { policy: 'follow', order });-- return (- <MenuDrawer- open={open}- onClose={onClose}- Icon={Icon}- accent={accent}- title={t('settings.models.order.title', { backend: backendName }) as string}- subtitle={t(mobile ? 'settings.models.order.subtitleShort' : 'settings.models.order.subtitle', { backend: backendName }) as string}- footer={- <Button variant="brand" size="sm" className="h-10" onClick={onClose}>- {t('settings.models.menus.done')}- </Button>- }- >- <div className="flex flex-col gap-2.5">- <GroupHeader label={t('settings.models.order.groupEnabled', { count: enabledIds.length }) as string} first>- {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>- {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.5">- {enabledSources.map((source, index) => (- <EnabledRow- key={source.id}- source={source}- index={index}- busy={saving}- onCommit={() => commitOrder(enabledIds)}- onMove={(delta) => commitOrder(movedOrder(enabledIds, index, delta))}- onRemove={() => commitOrder(enabledIds.filter((sourceId) => sourceId !== source.id))}- />- ))}- </Reorder.Group>- )}+ const backend = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend });+ const title = t('settings.models.order.title', { backend });+ const announcementText = announcement ? t(`settings.models.order.${announcement.key}`, announcement) : '';+ const saveEnabled = readState === 'ready' && available.length > 0 && (dirty || order.length === 0);- {disabledSources.length > 0 && (- <>- <GroupHeader label={t('settings.models.order.groupDisabled', { count: disabledSources.length }) as string} />- <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>- ))}+ return (+ <DialogPrimitive.Root open={open} onOpenChange={(next) => !next && !saving && onClose()}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay className="model-hub-order-overlay fixed inset-0 z-50" />+ <DialogPrimitive.Content+ className="model-hub-order-drawer fixed inset-y-0 right-0 z-50 flex flex-col overflow-hidden bg-surface outline-none"+ onEscapeKeyDown={(event) => {+ if (grabbedId) {+ event.preventDefault();+ cancelGrab();+ } else if (saving) event.preventDefault();+ }}+ >+ <header className="model-hub-order-head shrink-0 border-b border-border">+ <div className="flex items-center justify-between gap-3">+ <div className="flex min-w-0 items-center gap-[7px]">+ <DialogPrimitive.Title className="model-hub-order-title truncate font-bold text-foreground">{title}</DialogPrimitive.Title>+ <ModelHubInfoHint+ label={t('settings.models.order.subtitle')}+ content={t('settings.models.order.subtitle')}+ className="model-hub-order-info"+ />+ </div>+ <DialogPrimitive.Close asChild>+ <Button type="button" variant="ghost" size="icon" className="model-hub-order-close size-[27px]" aria-label={t('settings.models.order.cancel')} disabled={saving}>+ <X className="size-[15px]" />+ </Button>+ </DialogPrimitive.Close></div>- </>- )}+ <DialogPrimitive.Description className="model-hub-order-subtitle">+ {t('settings.models.order.subtitle')}+ </DialogPrimitive.Description>+ </header>- {ineligible.length > 0 && (- <>- <GroupHeader label={t('settings.models.order.groupIneligible', { count: ineligible.length }) as string} />- {ineligible.map(({ source, reasonKey }) => (- <div key={source.id} className={cn(ROW, 'border-border opacity-55')}>- <SourceTile source={source} />- <Identity source={source} detail={ineligibleDetail(source, reasonKey)} />- </div>- ))}- </>- )}- </div>- </MenuDrawer>+ <div className="model-hub-order-body flex min-h-0 flex-1 flex-col overflow-y-auto">+ {readState === 'loading' && (+ <div className="model-hub-order-state"><LoaderCircle className="model-hub-ink-mint size-4 animate-spin" />{t('common.loading')}</div>+ )}+ {readState === 'reconciling' && (+ <section className="model-hub-order-section" aria-busy="true">+ <div className="model-hub-order-section-head">+ <h3>{t('settings.models.order.section.ordered')}</h3>+ <LoaderCircle className="model-hub-ink-mint size-3.5 animate-spin" aria-label={t('common.loading')} />+ </div>+ <div className="flex flex-col gap-2">+ {orderedEntries.map(({ id, source: orderedSource }, index) => (+ <div key={id} className="model-hub-order-row model-hub-order-row--ordered">+ {orderedSource+ ? <span className="model-hub-order-grip" />+ : <LoaderCircle className="model-hub-order-grip animate-spin" aria-hidden />}+ <span className={cn('model-hub-order-ordinal', index === 0 && 'is-first')}>{index + 1}</span>+ {orderedSource+ ? <SourceIdentity source={orderedSource} />+ : <span className="model-hub-order-identity">+ <span className="model-hub-order-name truncate font-mono" title={id}>{id}</span>+ </span>}+ </div>+ ))}+ </div>+ </section>+ )}+ {readState === 'error' && (+ <div className="model-hub-order-state model-hub-order-state--error">{t('settings.models.order.fail.read')}</div>+ )}+ {readState === 'ready' && available.length === 0 && (+ <div className="model-hub-order-state">{t('settings.models.order.empty.noEligible')}</div>+ )}+ {readState === 'ready' && available.length > 0 && (+ <>+ <section className="model-hub-order-section">+ <div className="model-hub-order-section-head">+ <h3>{t('settings.models.order.section.ordered')}</h3>+ <span>{t('settings.models.order.section.ordered.note')}</span>+ </div>+ {ordered.length === 0+ ? <div className="model-hub-order-empty">{t('settings.models.order.empty.ordered')}</div>+ : <Reorder.Group axis="y" values={order} onReorder={persist} className="flex flex-col gap-2">+ {ordered.map((source, index) => (+ <OrderedRow+ key={source.id}+ source={source}+ index={index}+ count={ordered.length}+ busy={saving}+ grabbed={grabbedId === source.id}+ handleRef={(node) => {+ if (node) handles.current.set(source.id, node);+ else handles.current.delete(source.id);+ }}+ onExclude={() => {+ if (grabbedId === source.id) setGrabbedId(null);+ persist(order.filter((id) => id !== source.id));+ focusHeldOutAfterRender(source.id);+ }}+ onKeyDown={(event) => handleRowKey(source.id, event)}+ />+ ))}+ </Reorder.Group>}+ </section>+ <section className="model-hub-order-section">+ <div className="model-hub-order-section-head"><h3>{t('settings.models.order.section.heldOut')}</h3></div>+ <div className="flex flex-col gap-2">+ {heldOut.map((source) => (+ <div key={source.id} className="model-hub-order-row model-hub-order-row--held">+ <Minus className="model-hub-order-held-icon" />+ <SourceIdentity source={source} />+ <Button+ ref={(node) => {+ if (node) heldOutActions.current.set(source.id, node);+ else heldOutActions.current.delete(source.id);+ }}+ type="button"+ variant="outline"+ className="model-hub-order-row-action"+ disabled={saving}+ onClick={() => {+ persist([...order, source.id]);+ focusHandleAfterRender(source.id);+ }}+ >+ <Plus className="size-3.5" />+ {t('settings.models.order.action.include')}+ </Button>+ </div>+ ))}+ </div>+ </section>+ </>+ )}+ <p aria-live="polite" className="sr-only">{announcementText}</p>+ </div>++ <footer className="model-hub-order-foot flex shrink-0 items-center justify-end border-t border-border">+ {saveFailed && <span className="mr-auto text-[11px] text-destructive">{t('settings.models.order.fail.save')}</span>}+ <Button type="button" variant="outline" className="model-hub-order-action" disabled={saving} onClick={onClose}>+ {t('settings.models.order.cancel')}+ </Button>+ {readState === 'error'+ ? <Button type="button" variant="brand" className="model-hub-order-action" onClick={() => void read()}>{t('settings.models.order.retry')}</Button>+ : <Button type="button" variant="brand" className="model-hub-order-action" disabled={!saveEnabled || saving} onClick={save}>+ {saving && <LoaderCircle className="size-3 animate-spin" />}+ {saveFailed ? t('settings.models.order.retry') : t('settings.models.order.save')}+ </Button>}+ </footer>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>);};diff --git a/ui/src/components/settings/models/SourceRow.test.tsx b/ui/src/components/settings/models/SourceRow.test.tsxindex 7241cda18..a79ace6c9 100644--- a/ui/src/components/settings/models/SourceRow.test.tsx+++ b/ui/src/components/settings/models/SourceRow.test.tsx@@ -1,94 +1,64 @@-import { createInstance } from 'i18next';-import { renderToStaticMarkup } from 'react-dom/server';-import { I18nextProvider, initReactI18next } from 'react-i18next';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+// @vitest-environment jsdom+import { act, cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';-import { ToastProvider } from '@/context/ToastProvider';-import en from '../../../i18n/en.json';-import zh from '../../../i18n/zh.json';+import i18n from '@/i18n';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: Source = {+ id: 'src_a', last_discovered_at: null, kind: 'api_key', vendor: 'anthropic', display_name: 'Production',+ protocol: 'anthropic', base_url: null, supply_channel: 'hub', billing: 'metered',+ state: { status: 'standby', retry_at: null, detail_key: null }, masked_credential: 'sk-ant-…1234', models: [],+};-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 },- last_discovered_at: null,- models: [],+afterEach(() => {+ cleanup();+ vi.useRealTimers();});-const render = (row: Source, refreshing = false) => renderToStaticMarkup(- <I18nextProvider i18n={i18n}>- <ToastProvider>- <SourceRow- source={row}- onChanged={vi.fn()}- onRefresh={vi.fn()}- refreshing={refreshing}- refreshDisabled={refreshing}- 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);+describe('SourceRow', () => {+ it('opens the Source detail without exposing inline source mutations', async () => {+ const onOpen = vi.fn();+ render(<I18nextProvider i18n={i18n}><SourceRow source={source} onOpen={onOpen} /></I18nextProvider>);+ await userEvent.click(screen.getByRole('button', { name: /Production/ }));+ expect(onOpen).toHaveBeenCalledWith(source);+ expect(screen.queryByText(/latency/i)).toBeNull();});- 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);+ it('uses the authoritative Source adoption to name an active supplying source', () => {+ render(+ <I18nextProvider i18n={i18n}>+ <SourceRow+ source={{ ...source, supply_channel: 'native_cli', state: { ...source.state, status: 'active' }, adopted_by: [{ backend: 'claude', menu_model: 'claude-opus-4-6' }] }}+ onOpen={vi.fn()}+ />+ </I18nextProvider>,+ );+ expect(screen.getByText(/Supplying Claude Code|正在供给 Claude Code/i)).toBeTruthy();});-});-describe('SourceRow discovery refresh', () => {- beforeEach(() => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-07-31T05:20:00Z'));+ it('consumes persisted adoption when the source projection carries it', () => {+ render(<I18nextProvider i18n={i18n}><SourceRow source={{ ...source, state: { ...source.state, status: 'active' }, adopted_by: [{ backend: 'codex', menu_model: 'gpt-5' }] }} onOpen={vi.fn()} /></I18nextProvider>);+ expect(screen.getByText(/Supplying Codex|正在供给 Codex/i)).toBeTruthy();});- afterEach(() => vi.useRealTimers());-- it('shows the persisted discovery time beside a quiet refresh action', () => {- const html = render({ ...source('api_key'), last_discovered_at: '2026-07-31T05:15:00Z' });-- expect(html).toContain('上次自动获取 5 分钟前');- expect(html).toContain(`aria-label="${zh.settings.models.sourceActions.refresh}"`);- });-- it('shows an honest never-fetched state and a stable refreshing control', () => {- const html = render(source('api_key'), true);-- expect(html).toContain(zh.settings.models.sources.neverDiscovered);- expect(html).toContain(`aria-label="${zh.settings.models.sourceActions.refreshing}"`);- expect(html).toContain('aria-busy="true"');- expect(html).toContain('animate-spin');- expect(html).toContain('disabled=""');- });+ it('advances cooldown copy when its retry deadline passes', () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-08-11T14:00:00Z'));+ render(+ <I18nextProvider i18n={i18n}>+ <SourceRow+ source={{ ...source, state: { status: 'cooldown', retry_at: '2026-08-11T14:01:00Z', detail_key: null } }}+ onOpen={vi.fn()}+ />+ </I18nextProvider>,+ );- it('keeps failure copy explicit that the last successful list remains visible', () => {- expect(zh.settings.models.sourceActions.refreshFailed).toContain('仍显示上次成功获取的清单');- expect(en.settings.models.sourceActions.refreshFailed).toContain('last successful list is still shown');+ expect(screen.getByText(/retrying automatically after|后自动重试/i)).toBeTruthy();+ act(() => vi.advanceTimersByTime(60_000));+ expect(screen.getByText(/retry is due|已到重试时间/i)).toBeTruthy();});});diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsxindex d7cbc2a8d..8b9b0894e 100644--- a/ui/src/components/settings/models/SourceRow.tsx+++ b/ui/src/components/settings/models/SourceRow.tsx@@ -1,286 +1,60 @@-// One row of the 来源 list (design.pen 「产品改造 V6 01」): icon + name/mono-sub-// (supply tooltip on hover) · fixed-width usage column · billing chip · state-// column · overflow menu. Presentation-only.-//-// V6 removed the drag handle and the priority number: a source is an asset here,-// and ordering is a per-Agent property that lives in the 来源顺序 drawer. The-// state column is still reserved on sm+ even though a healthy source draws no-// chip in V6, so the billing column stays aligned down the list.-//-// Mobile (< sm): the frame's single aligned row cannot hold that many columns in-// 390px — it squeezed the name to zero width and pushed the state chip and the-// row menu off-screen entirely (clipped, not scrollable, so unreachable). So the-// row stacks into two tiers per design.pen M01 (m01SrcL1 / m01SrcL2): identity +-// the row menu on top, then billing · state · usage on a single second line,-// 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, RefreshCw } from 'lucide-react';+import { ChevronRight } 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 { formatRelativeTime } from '@/lib/relativeTime';-import { BillingChip, ExperimentalChip, StateChip } from './chips';-import { SupplyTooltip } from './SupplyTooltip';-import { SourceRowMenu, type RaisedRepair } from './SourceRowMenu';-import { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, sourceVisual } from './vendorMeta';-import { cooldownEtaMinutes, formatSpend } from './format';-import { isUnhealthy, needsAttention } from './supply';+import { sourceDetail } from './sourcePresentation';+import { sourceStatePresentation } from './sourceStatePresentation';+import { useDeadlineClock } from './useDeadlineClock';+import { ACCENT_ICON, ACCENT_PILL, ACCENT_TILE, sourceVisual } from './vendorMeta';import type { Source } from './types';-// The mono sub-line shows the source identity: account_label (subscriptions)-// or masked_credential (api keys) — both server-provided display data (contract-// v1.1, 07-23, from the L4 finding). Falls back to the supply channel / endpoint-// (原生供给 / 中枢托管 / 官方地址 / 自定义地址) when neither is set, e.g. hub-held-// experimental sources before a later adapter rev.-//-// A custom endpoint is named even when an identity exists (V6 01's relay row-// reads `key …9c1 · 自定义地址 · 47 分后重试`): a relay is a materially different-// thing to route through, while 官方地址 / 原生供给 / 中枢托管 beside an identity-// is just noise.-//-// An unhealthy source appends WHY and (when it heals itself) WHEN, which is the-// whole of V6 04's amber sub-line 「[email protected] · 本周期额度用完 · 明天 08:00-// 恢复」. `detail_key` is already a full i18n key in the frozen contract, so it-// is translated as-is — the UI never maps upstream text to copy of its own.-function useSubline(source: Source): string {- const { t } = useTranslation();-- const customEndpoint = source.kind === 'api_key' && isCustomEndpoint(source);- const channel =- source.kind === 'subscription'- ? source.supply_channel === 'native_cli'- ? (t('settings.models.source.nativeSupply') as string)- : (t('settings.models.source.hubHosted') as string)- : customEndpoint- ? (t('settings.models.source.customEndpoint') as string)- : (t('settings.models.source.officialEndpoint') as string);-- const identity = source.account_label ?? source.masked_credential ?? null;- const parts = identity ? [identity] : [channel];- if (identity && customEndpoint) parts.push(channel);- if (isUnhealthy(source.state) && source.state.detail_key) parts.push(t(source.state.detail_key) as string);- if (source.state.status === 'cooldown') {- parts.push(t('settings.models.source.retryIn', { minutes: cooldownEtaMinutes(source.state.retry_at) }) as string);- }- return parts.join(' · ');-}--// On phones usage sits at the RIGHT END of the second tier and absorbs the slack-// (design.pen M01 m01Use: fill_container + justify end), which also puts it after-// the chips — hence `order-last`. On sm+ it reverts to the desktop frame's-// leading fixed-width column.-const USAGE_CELL = 'order-last flex-1 sm:order-none sm:w-[130px] sm:flex-none';--const UsageCell: React.FC<{ source: Source }> = ({ source }) => {- const { t } = useTranslation();- const pct = source.usage?.cycle_used_pct;- const spend = source.usage?.month_spend_cents;-- if (source.billing === 'monthly' && typeof pct === 'number') {- const clamped = Math.min(100, Math.max(0, pct));- return (- <div className={cn(USAGE_CELL, 'flex items-center justify-end gap-2')}>- <div className="h-[5px] w-14 overflow-hidden rounded-[3px] bg-foreground/[0.07] sm:w-16">- {/* Gold at a full cycle: the bar itself carries the 「用完了」 the amber- sub-line spells out, so a glance down the column finds it. */}- <div- className={cn('h-full rounded-[3px]', clamped >= 100 ? 'bg-gold' : 'bg-mint')}- style={{ width: `${clamped}%` }}- />- </div>- <span className="w-8 text-right font-mono text-[10.5px] text-muted sm:text-[11px]">{Math.round(pct)}%</span>- </div>- );- }- if (typeof spend === 'number') {- return (- <div className={cn(USAGE_CELL, 'truncate text-right font-mono text-[10.5px] text-muted sm:text-[11px]')}>- {t('settings.models.usage.monthSpend', { amount: formatSpend(spend, source.usage?.currency) })}- </div>- );- }- // No usage data: on mobile the chips just stay left-aligned, so the spacer only- // exists to hold the desktop column open.- return <div className="hidden sm:block sm:w-[130px] sm:shrink-0" />;-};--// V6 draws a state chip only when the source is NOT serving normally, so the-// healthy majority of rows stays quiet. The column is still held open on sm+ —-// otherwise the one cooling row would push its own billing chip 86px left of-// every other row's.-const StateCell: React.FC<{ source: Source }> = ({ source }) => (- // sm:ml-1.5 is the 6px the frame gets from right-aligning an 86px chip inside a- // 92px column — spent as a margin here so the row keeps one flat flex line.- <div className={cn('sm:ml-1.5 sm:w-[86px] sm:shrink-0', !isUnhealthy(source.state) && 'hidden sm:block')}>- <StateChip state={source.state} />- </div>-);--export const SourceRow: React.FC<{- source: Source;- /** Re-fetch after a row action (rename / delete). */- onChanged: () => void;- onRefresh: (source: Source) => void;- refreshing: boolean;- refreshDisabled: boolean;- /** Open a repair journey the page hosts — see SourceRowMenu's `onRepair`. */- onRepair?: (source: Source, kind: RaisedRepair) => void;- /** Open the shared manual-model action with this source preselected. */- onAddModel: (source: Source) => void;-}> = ({ source, onChanged, onRefresh, refreshing, refreshDisabled, onRepair, onAddModel }) => {- const { t } = useTranslation();+export const SourceRow: React.FC<{ source: Source; onOpen: (source: Source) => void }> = ({ source, onOpen }) => {+ const { t, i18n } = useTranslation();+ const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);const { Icon, accent } = sourceVisual(source);- const subline = useSubline(source);- const isExperimental = source.kind === 'subscription' && source.supply_channel === 'hub';-+ const detail = sourceDetail(source);+ const adoptedBackends = [...new Set((source.adopted_by ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];+ const state = sourceStatePresentation(source.state, 'card', i18n.language, now, {+ known: source.adopted_by !== undefined,+ backends: adoptedBackends,+ native: source.supply_channel === 'native_cli',+ });+ const kindKey = source.supply_channel === 'native_cli'+ ? 'nativeCredential'+ : source.kind === 'subscription'+ ? 'subscription'+ : 'apiKey';+ const adopted = source.state.status === 'active' && (source.adopted_by?.length ?? 0) > 0;return (- // One wrapping flex line, not two stacked tiers: the row menu has to sit at- // the end of the FIRST line on phones and at the end of the (single) row on- // 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 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">- <span className={cn('flex size-[34px] shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>- <Icon className={cn('size-4', ACCENT_ICON[accent])} />+ <button+ type="button"+ data-source-id={source.id}+ onClick={() => onOpen(source)}+ className={cn(+ 'flex h-20 w-full items-center gap-2.5 rounded-[10px] border border-border bg-background px-3 text-left transition-colors hover:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',+ adopted && source.supply_channel === 'native_cli' && 'border-cyan/30 bg-cyan/[0.04]',+ adopted && source.supply_channel === 'hub' && 'border-mint/30 bg-mint/[0.04]',+ source.state.status === 'cooldown' && 'border-gold/20 bg-gold/[0.04]',+ )}+ >+ <span className={cn('flex size-[34px] shrink-0 items-center justify-center rounded-[9px]', ACCENT_TILE[accent])}>+ <Icon className={cn('size-[17px]', ACCENT_ICON[accent])} />+ </span>+ <span className="min-w-0 flex-1">+ <span className="flex min-w-0 items-center gap-1.5">+ <span className="truncate text-[12.5px] font-bold text-foreground" title={source.display_name}>{source.display_name}</span>+ <span className={cn('shrink-0 rounded-full border px-2 py-[3px] text-[10.5px] font-semibold', ACCENT_PILL[accent])}>+ {t(`settings.models.upstream.kind.${kindKey}`)}</span>- <span className="flex min-w-0 flex-col gap-0.5 sm:gap-[3px]">- <span className="flex min-w-0 items-center gap-2">- <span className="truncate text-[13.5px] font-semibold text-foreground">{source.display_name}</span>- {isExperimental && <ExperimentalChip />}- </span>- {/* Gold when the outage is waiting on a person (V6 04's exhausted- subscription), muted when it will heal on its own (V6 01's timed-out- relay) — see `needsAttention`. */}- <span- className={cn(- 'truncate font-mono text-[10.5px] sm:text-[11px]',- needsAttention(source.state) ? 'text-gold' : 'text-muted',- )}- >- {subline}- </span>- </span>- </SupplyTooltip>- </div>-- {/* Metric / state strip — a full-width second line on phones, indented to- the V6 M01 frame's second tier; the aligned desktop chip columns on sm+.- flex-wrap here is the safety net, not the plan: measured at 360/390/430- in both locales every row stays on one line, including the widest English- combination ("$3.2 this month" · "Metered $" · "Cooling down"). It stays- wrap-capable so an unusually long future state label degrades to two- lines instead of clipping. sm:flex-nowrap keeps the desktop row- single-line.-- The desktop gaps are the frame's uniform 14px row gap (sm:gap-3.5 here- and on the row itself), with the 6px each pill is inset by right-aligning- it in its wider column spent as an sm:ml-1.5 on the pill. */}- <div className="order-3 flex w-full flex-wrap items-center gap-x-2 gap-y-2 pl-[26px] sm:order-2 sm:w-auto sm:shrink-0 sm:flex-nowrap sm:gap-3.5 sm:pl-0">- <UsageCell source={source} />- <BillingChip billing={source.billing} className="sm:ml-1.5" />- <StateCell source={source} />- </div>-- {/* Thumb-reachable on the identity line on phones (design.pen M01 m01More,- 36×36), trailing the desktop row on sm+. A flex line rather than a bare- slot because a stopped row puts its one-tap remedy beside the ⋯ — both- come from the menu component, which owns the actions. */}- <div className="order-2 flex shrink-0 items-center gap-1.5 sm:order-3">- <SourceRowMenu- source={source}- onChanged={onChanged}- onRefresh={onRefresh}- refreshing={refreshing}- refreshDisabled={refreshDisabled}- 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">- <div className="flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1">- <span className="text-[11px] font-semibold text-muted">- {t('settings.models.sources.modelCount', { count: source.models.length })}- </span>- <span className="text-[10.5px] text-muted">- {source.last_discovered_at- ? t('settings.models.sources.lastDiscovery', {- time: formatRelativeTime(source.last_discovered_at, t),- })- : t('settings.models.sources.neverDiscovered')}- </span>- {source.supply_channel === 'hub' && (- <button- type="button"- onClick={() => onRefresh(source)}- disabled={refreshDisabled}- aria-busy={refreshing}- aria-label={t(- refreshing- ? 'settings.models.sourceActions.refreshing'- : 'settings.models.sourceActions.refresh',- ) as string}- title={t('settings.models.sourceActions.refresh') as string}- className="inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:bg-surface-2 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-45"- >- <RefreshCw className={cn('size-3.5', refreshing && 'animate-spin')} />- </button>- )}- </div>- {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>+ </span>+ {detail && <span className="model-hub-upstream-detail mt-1 block truncate font-mono text-[10.5px]" title={detail}>{detail}</span>}+ {state.key && <span className={cn('mt-1 flex items-center gap-[5px] text-[10.5px] font-semibold', state.textClass)}>+ <span className={cn('size-[5px] rounded-full', state.dotClass)} />+ {t(state.key, state.values)}+ </span>}+ </span>+ <ChevronRight className="model-hub-overview-chevron size-[15px] shrink-0" />+ </button>);};diff --git a/ui/src/components/settings/models/SourceRowMenu.tsx b/ui/src/components/settings/models/SourceRowMenu.tsxdeleted file mode 100644index ae04d860c..000000000--- a/ui/src/components/settings/models/SourceRowMenu.tsx+++ /dev/null@@ -1,397 +0,0 @@-// Per-row lifecycle actions for the 来源 list (design.pen 「产品改造 V6 01」): an-// overflow menu that stays out of the way (hidden until row hover / focus on-// desktop) and exposes the contracted source mutations the list otherwise-// couldn't reach — rename (PATCH) and delete (DELETE, with the only-supplier guard escalating to a forced-// delete). Presentation lives in SourceRow; this owns the actions + their-// dialogs so the row stays declarative.-//-// It also owns the ENTRY to the repair journeys: an inline, always-visible button-// on a stopped row (§4.5's 「one tap to fix it」) plus the elective credential-// entries in the menu. The journeys themselves are raised to the page — see-// RepairJourney — because completing one refetches the list this row lives in.-//-// No reorder actions: in V6 an order belongs to an Agent, not to the source-// inventory, so 上移/下移 moved into the per-Agent 来源顺序 drawer (which keeps a-// keyboard/screen-reader path of its own alongside drag).-//-// On phones the menu presents as a bottom sheet (design.pen M02 m02SheetA) with-// the row's identity in the header and a one-line rationale under each action,-// because a thumb menu has no hover to explain itself.-import * as React from 'react';-import { KeyRound, LogIn, MoreHorizontal, Pencil, RefreshCw, Trash2 } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { Button } from '@/components/ui/button';-import { ConfirmDialog } from '@/components/ui/confirm-dialog';-import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';-import { Input } from '@/components/ui/input';-import { ResponsiveMenu } from '@/components/ui/responsive-menu';-import { cn } from '@/lib/utils';-import { useIsMobile } from '@/lib/useIsMobile';-import { useToast } from '@/context/ToastContext';-import { apiFailure, modelsApi } from './modelsApi';-import { canReauth, canReplaceKey, reauthCost, repairAction, REPAIR_LABEL_KEY, type RepairKind } from './repair';-import { SupplyGapNote } from './SupplyGapNote';-import { ACCENT_ICON, ACCENT_TILE, sourceVisual } from './vendorMeta';-import type { Source, SupplyGap } from './types';--/** The two remedies that need a dialog of their own, so the page hosts them. */-export type RaisedRepair = Exclude<RepairKind, 'retest'>;--const REPAIR_ICON: Record<RepairKind, React.ComponentType<{ className?: string }>> = {- reauth: LogIn,- replace_key: KeyRound,- retest: RefreshCw,-};--const MenuAction: React.FC<{- Icon: React.ComponentType<{ className?: string }>;- label: string;- /** Shown in the mobile sheet only — the popover stays a compact list. */- description?: string;- onClick: () => void;- disabled?: boolean;- destructive?: boolean;-}> = ({ Icon, label, description, onClick, disabled, destructive }) => (- <button- type="button"- onClick={onClick}- disabled={disabled}- className={cn(- // min-h-11 keeps each action a comfortable thumb target on phones.- 'flex min-h-11 w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] transition-colors sm:min-h-0',- description && 'items-start gap-3 rounded-none border-b border-border px-4 py-3.5 last:border-b-0',- destructive ? 'text-destructive' : 'text-foreground',- disabled ? 'opacity-40' : destructive ? 'hover:bg-destructive/[0.08]' : 'hover:bg-surface-2',- )}- >- <Icon className={cn('size-4 shrink-0', description && 'mt-0.5 size-[18px]')} />- {description ? (- <span className="flex min-w-0 flex-col gap-0.5">- <span className="text-[14px] font-semibold">{label}</span>- <span className="text-[12px] leading-relaxed text-muted">{description}</span>- </span>- ) : (- label- )}- </button>-);--export const SourceRowMenu: React.FC<{- source: Source;- /** Re-fetch sources + agents after a rename or delete. */- onChanged: () => void;- onRefresh: (source: Source) => void;- refreshing: boolean;- refreshDisabled: boolean;- /**- * Raise a remedy that needs a dialog + a server flow to the page, which- * outlives this row: a re-auth replaces the source's models and a key- * replacement re-discovers them, so both trigger the refetch that unmounts- * whatever hosted the dialog. `retest` delegates to the page-owned refresh- * operation so the row action and the inventory button share one lifetime.- */- onRepair?: (source: Source, kind: RaisedRepair) => void;-}> = ({ source, onChanged, onRefresh, refreshing, refreshDisabled, onRepair }) => {- const { t } = useTranslation();- const { showToast } = useToast();- const isMobile = useIsMobile();- const { Icon: SourceIcon, accent } = sourceVisual(source);-- const [menuOpen, setMenuOpen] = React.useState(false);- const [renameOpen, setRenameOpen] = React.useState(false);- const [renameValue, setRenameValue] = React.useState(source.display_name);- const [renaming, setRenaming] = React.useState(false);- const [deleteOpen, setDeleteOpen] = React.useState(false);- // Set once the server refuses a plain delete (only-supplier guard); the- // confirm then escalates to a forced delete instead of silently failing.- const [forceMode, setForceMode] = React.useState(false);- // What that refusal said it would strand. Kept as the server sent it: the- // confirm has to name the Agents, and re-deriving them from the loaded list- // would answer a question the guard already answered.- const [gaps, setGaps] = React.useState<SupplyGap[]>([]);-- // Re-armed on mount, not only cleared on unmount: a cleanup-only guard is- // one-way, so StrictMode's mount → cleanup → mount would leave every 测试- // result and delete outcome silently discarded on a live menu.- const aliveRef = React.useRef(true);- React.useEffect(() => {- aliveRef.current = true;- return () => {- aliveRef.current = false;- };- }, []);-- const openRename = () => {- setMenuOpen(false);- setRenameValue(source.display_name);- setRenameOpen(true);- };-- const submitRename = async () => {- const name = renameValue.trim();- if (!name || name === source.display_name) {- setRenameOpen(false);- return;- }- setRenaming(true);- try {- await modelsApi.patchSource(source.id, { display_name: name });- if (!aliveRef.current) return;- setRenameOpen(false);- onChanged();- showToast(t('settings.models.sourceActions.renamed') as string, 'success');- } catch {- if (aliveRef.current) showToast(t('settings.models.sourceActions.renameFailed') as string, 'error');- } finally {- if (aliveRef.current) setRenaming(false);- }- };-- const openDelete = () => {- setMenuOpen(false);- setForceMode(false);- setGaps([]);- setDeleteOpen(true);- };-- const confirmDelete = async () => {- try {- await modelsApi.deleteSource(source.id, forceMode);- if (!aliveRef.current) return;- setDeleteOpen(false);- onChanged();- showToast(t('settings.models.sourceActions.deleted') as string, 'success');- } catch (err) {- const failure = apiFailure(err);- // The supply guard: `source_last_supplier` is the code DELETE actually- // sends (`mode_switch_blocked` belongs to the mode route, so the old test- // never matched and every guarded delete failed with a generic toast).- // Escalate to `?force=true` AND show what the server said it would strand —- // that list is the reason a second confirm exists.- if (failure?.code === 'source_last_supplier' && !forceMode) {- if (aliveRef.current) {- setGaps(failure.wouldInterrupt);- setForceMode(true);- }- return;- }- if (aliveRef.current) {- setDeleteOpen(false);- // A failed DELETE is not necessarily read-only. The supply guard is the- // one refusal that provably- // wrote nothing — `delete_source` raises it off a CLONED config, before- // `_commit_synced` — and it left through the branch above. Everything that- // reaches here got past that commit or died inside it: a response lost on- // the way back arrives as `bad_response`, invented by this client about a- // delete that may well have happened, and `source_not_found` means the row- // is already gone. Deliberately not gated on `serverNamed`: that says- // whether the ROUTE named the failure, never whether the server wrote —- // `oauth_cancel` is the standing proof those are different questions. The- // toast reports the attempt, the row reports the state.- onChanged();- showToast(t('settings.models.sourceActions.deleteFailed') as string, 'error');- }- }- };-- // ── Repair ───────────────────────────────────────────────────────────────- // §4.5: a `needs_action` row 「carries a detail_key naming the cause, so the row- // can offer ONE TAP to fix it … instead of a dead-end error string」. `repair.ts`- // owns which tap that is; this only routes it.- const blockedRemedy = repairAction(source);- const runRepair = (kind: RepairKind) => {- setMenuOpen(false);- if (kind === 'retest') {- onRefresh(source);- return;- }- onRepair?.(source, kind);- };- // A raised remedy needs the page's host; without it the row would open nothing.- const offer = (kind: RepairKind | null): kind is RepairKind =>- kind !== null && (kind === 'retest' || Boolean(onRepair));- const inlineRemedy = offer(blockedRemedy) ? blockedRemedy : null;-- // Descriptions only exist in the sheet; passing undefined on desktop is what- // keeps the popover a compact label list.- const hint = (key: string, opts?: Record<string, unknown>) =>- isMobile ? (t(`settings.models.sourceActions.${key}`, opts) as string) : undefined;-- const RemedyIcon = inlineRemedy ? REPAIR_ICON[inlineRemedy] : null;-- return (- <>- {inlineRemedy && RemedyIcon ? (- // Always visible, unlike the ⋯ trigger next to it: the whole failure of a- // status-only row is that the remedy hides behind a hover the blocked- // state gives no reason to try. Geometry from design.pen V6 03's row-level- // button (`d6Btn 启用`): outline, radius 8, 6/12 padding, 11.5/600.- <Button- variant="outline"- size="xs"- className="h-7 shrink-0 rounded-md px-3 text-[11.5px] font-semibold"- // Composed rather than a per-kind string: the label already says what- // happens, and every row on the page repeats it.- aria-label={`${t(REPAIR_LABEL_KEY[inlineRemedy])} · ${source.display_name}`}- disabled={refreshDisabled}- onClick={() => runRepair(inlineRemedy)}- >- {refreshing && inlineRemedy === 'retest' ? (- <RefreshCw className="size-3 animate-spin" />- ) : (- <RemedyIcon className="size-3" />- )}- {t(REPAIR_LABEL_KEY[inlineRemedy])}- </Button>- ) : null}-- <ResponsiveMenu- open={menuOpen}- onOpenChange={setMenuOpen}- sheetTitle={source.display_name}- sheetTitleVisible={false}- className="w-[200px]"- sheetHeader={- <div className="flex items-center gap-3 px-4 pb-3.5 pt-1">- <span className={cn('flex size-10 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>- <SourceIcon className={cn('size-5', ACCENT_ICON[accent])} />- </span>- <span className="flex min-w-0 flex-col gap-0.5">- <span className="truncate text-[15px] font-bold text-foreground">{source.display_name}</span>- <span className="truncate text-[12px] text-muted">- {[- t(`settings.models.state.${source.state.status}`),- t(`settings.models.billing.${source.billing}`),- ].join(' · ')}- </span>- </span>- </div>- }- trigger={- <button- type="button"- aria-label={t('settings.models.sourceActions.more') as string}- className={cn(- // The button is a 44×44 touch target while the drawn box inside it- // is the design's 36×36 (design.pen M01 m01More). Negative margins- // cancel the extra 8px so the visual box lands exactly where a bare- // 36px button would and the row height is unchanged — design size- // and the touch-target floor both hold, with no reliance on- // pseudo-element hit testing.- 'group/more -my-1 -mr-1 flex size-11 shrink-0 items-center justify-center text-muted sm:m-0 sm:size-8',- // Quiet on desktop (revealed on row hover / focus / when open),- // always reachable on touch where hover doesn't exist.- menuOpen ? 'opacity-100' : 'opacity-100 md:opacity-0 md:group-hover:opacity-100 md:focus-visible:opacity-100',- )}- >- <span className="flex size-9 items-center justify-center rounded-[10px] border border-border bg-surface/60 transition-colors group-hover/more:bg-surface-2 group-hover/more:text-foreground sm:size-8 sm:border-transparent sm:bg-transparent">- <MoreHorizontal className="size-4" />- </span>- </button>- }- >- <MenuAction- Icon={Pencil}- label={t('settings.models.sourceActions.rename') as string}- description={hint('renameHint')}- onClick={openRename}- />- {/* Elective credential maintenance — available on a HEALTHY source too- (api.md gives both routes an elective form, guard included), which is- why these read the per-route predicates rather than `repairAction`.- Suppressed for the remedy the inline button already offers, so a- blocked row doesn't show the same action twice. */}- {onRepair && canReauth(source) && inlineRemedy !== 'reauth' && (- <MenuAction- Icon={LogIn}- label={t('settings.models.sourceActions.reauth') as string}- // Only the native channel pays at 「开始」, so only it has something to- // warn about before the confirm does. On a hub source the same line- // would promise a loss that does not happen — and the confirm one tap- // later states that channel's real cost. Deleting the sentence beats- // qualifying it.- description={reauthCost(source) === 'immediate' ? hint('reauthHint') : undefined}- onClick={() => runRepair('reauth')}- />- )}- {onRepair && canReplaceKey(source) && inlineRemedy !== 'replace_key' && (- <MenuAction- Icon={KeyRound}- label={t('settings.models.sourceActions.replaceKey') as string}- description={hint('replaceKeyHint')}- onClick={() => runRepair('replace_key')}- />- )}- <MenuAction- Icon={Trash2}- label={t('settings.models.sourceActions.delete') as string}- description={hint('deleteHint')}- onClick={openDelete}- destructive- />- </ResponsiveMenu>-- <Dialog open={renameOpen} onOpenChange={(v) => !v && !renaming && setRenameOpen(false)}>- <DialogContent className="max-w-[420px] gap-4">- <DialogHeader>- <DialogTitle>{t('settings.models.sourceActions.renameTitle')}</DialogTitle>- </DialogHeader>- <div className="flex flex-col gap-2">- <span className="text-[12px] font-semibold text-foreground">{t('settings.models.sourceActions.renameLabel')}</span>- <Input- value={renameValue}- onChange={(e) => setRenameValue(e.target.value)}- maxLength={64}- autoFocus- placeholder={t('settings.models.sourceActions.renamePlaceholder') as string}- onKeyDown={(e) => {- if (e.key === 'Enter') {- e.preventDefault();- void submitRename();- }- }}- className="h-11 text-[14px]"- />- </div>- <DialogFooter className="sm:justify-end">- <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={() => setRenameOpen(false)} disabled={renaming}>- {t('common.cancel')}- </Button>- <Button- variant="brand"- size="sm"- className="h-10 sm:h-9"- onClick={() => void submitRename()}- disabled={renaming || !renameValue.trim() || renameValue.trim() === source.display_name}- >- {t('common.save')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>-- <ConfirmDialog- open={deleteOpen}- onOpenChange={(v) => {- setDeleteOpen(v);- if (!v) {- setForceMode(false);- setGaps([]);- }- }}- destructive- title={t(forceMode ? 'settings.models.sourceActions.deleteForceTitle' : 'settings.models.sourceActions.deleteTitle')}- description={t(forceMode ? 'settings.models.sourceActions.deleteForceBody' : 'settings.models.sourceActions.deleteBody', {- name: source.display_name,- })}- confirmLabel={t(forceMode ? 'settings.models.sourceActions.deleteForceConfirm' : 'settings.models.sourceActions.deleteConfirm') as string}- onConfirm={confirmDelete}- >- {/* No title: `deleteForceBody` above already states the consequence, and a- second sentence saying it again is the line worth deleting. */}- {forceMode ? <SupplyGapNote gaps={gaps} /> : null}- </ConfirmDialog>- </>- );-};diff --git a/ui/src/components/settings/models/SourcesCard.test.tsx b/ui/src/components/settings/models/SourcesCard.test.tsxnew file mode 100644index 000000000..db577b7ec--- /dev/null+++ b/ui/src/components/settings/models/SourcesCard.test.tsx@@ -0,0 +1,74 @@+// @vitest-environment jsdom+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import { failRegionRead, readyRegion } from './regionRead';+import { SourcesCard } from './SourcesCard';+import type { Source } from './types';++const retained: Source = {+ id: 'src_retained',+ last_discovered_at: null,+ kind: 'api_key',+ vendor: 'anthropic',+ display_name: 'Retained source',+ protocol: 'anthropic',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active', retry_at: null, detail_key: null },+ models: [],+};++afterEach(cleanup);++describe('SourcesCard footer', () => {+ it('exposes the upstream info note to keyboard activation and Escape dismissal', async () => {+ const user = userEvent.setup();+ render(+ <I18nextProvider i18n={i18n}>+ <SourcesCard read={readyRegion([])} onRetry={vi.fn()} onOpenSource={vi.fn()} onAddApiKey={vi.fn()} />+ </I18nextProvider>,+ );++ const info = screen.getByRole('button', { name: /What the gateway is|什么是网关/i });+ await user.tab();+ expect(document.activeElement).toBe(info);+ await user.keyboard('[Enter]');+ expect(await screen.findByText(/dispatch layer|调度/i)).toBeTruthy();+ await user.keyboard('[Escape]');+ await waitFor(() => expect(screen.queryByText(/dispatch layer|调度/i)).toBeNull());+ });++ it('draws the two Frame 01 commands without restoring the retired vendor menu', async () => {+ const onAddApiKey = vi.fn();+ render(+ <I18nextProvider i18n={i18n}>+ <SourcesCard read={readyRegion([])} onRetry={vi.fn()} onOpenSource={vi.fn()} onAddApiKey={onAddApiKey} />+ </I18nextProvider>,+ );++ const subscription = screen.getByRole('button', { name: /Add subscription|添加订阅/i });+ expect((subscription as HTMLButtonElement).disabled).toBe(true);+ expect(screen.queryByRole('button', { name: /^Add source$|^添加来源$/i })).toBeNull();++ await userEvent.click(screen.getByRole('button', { name: /Add API key|添加 API Key/i }));+ expect(onAddApiKey).toHaveBeenCalledOnce();+ });++ it('keeps the last good source rows visible with an F2 retry after a later read fails', async () => {+ const onRetry = vi.fn();+ render(+ <I18nextProvider i18n={i18n}>+ <SourcesCard read={failRegionRead(readyRegion([retained]))} onRetry={onRetry} onOpenSource={vi.fn()} onAddApiKey={vi.fn()} />+ </I18nextProvider>,+ );++ expect(screen.getByText('Retained source')).toBeTruthy();+ expect(screen.getByText(/Could not read the source list|没有读到来源列表/i)).toBeTruthy();+ await userEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));+ expect(onRetry).toHaveBeenCalledOnce();+ });+});diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsxindex eb6ea052f..07afd988f 100644--- a/ui/src/components/settings/models/SourcesCard.tsx+++ b/ui/src/components/settings/models/SourcesCard.tsx@@ -1,76 +1,78 @@-// 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-// button — at 360px the side-by-side desktop header squeezed the sub-line to two-// or three lines and left the button a cramped tap target.import * as React from 'react';+import { LoaderCircle, Plus } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { AddSourceMenu } from './AddSourceMenu';+import { Button } from '@/components/ui/button';+import { ModelHubInfoHint } from './ModelHubInfoHint';+import { foldRegionRead, type RegionRead } from './regionRead';import { SourceRow } from './SourceRow';-import type { RaisedRepair } from './SourceRowMenu';import type { Source } from './types';export const SourcesCard: React.FC<{- sources: Source[];- onConnectClaude: () => void;- onConnectChatGPT: () => void;+ read: RegionRead<Source[]>;+ onRetry: () => void;+ onOpenSource: (source: Source) => void;onAddApiKey: () => void;- /** Re-fetch after a per-row action (rename / delete). */- onSourceChanged: () => void;- onRefreshSource: (source: Source) => void;- refreshingSourceId: string | null;- /** Open a repair journey the page hosts — see SourceRowMenu's `onRepair`. */- onRepair?: (source: Source, kind: RaisedRepair) => void;- onAddModel: (source: Source) => void;-}> = ({- sources,- onConnectClaude,- onConnectChatGPT,- onAddApiKey,- onSourceChanged,- onRefreshSource,- refreshingSourceId,- onRepair,- onAddModel,-}) => {+}> = ({ read, onRetry, onOpenSource, onAddApiKey }) => {const { t } = useTranslation();-+ const sources = foldRegionRead<Source[], Source[] | undefined>(read, {+ loading: () => undefined,+ ready: (data) => data,+ unread: () => undefined,+ degraded: (staleData) => staleData,+ });+ const groups = [+ { id: 'native', sources: (sources ?? []).filter((source) => source.supply_channel === 'native_cli') },+ { id: 'hub', sources: (sources ?? []).filter((source) => source.supply_channel === 'hub') },+ ].filter((group) => group.sources.length > 0);return (- // Not overflow-hidden: the row supply tooltip must escape the card bounds.- <section className="rounded-xl border border-border bg-background">- <div className="flex flex-col gap-2.5 border-b border-border px-4 py-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4 sm:px-5">- <div className="flex min-w-0 flex-col gap-1">- <h2 className="text-[15px] font-semibold text-foreground">{t('settings.models.sources.title')}</h2>- <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.sources.subtitle')}</p>- </div>- <AddSourceMenu- onConnectClaude={onConnectClaude}- onConnectChatGPT={onConnectChatGPT}- onAddApiKey={onAddApiKey}- />+ <section className="relative z-20 flex max-h-full min-h-[420px] flex-col self-start overflow-hidden rounded-[14px] border border-border bg-surface">+ <div className="flex h-14 shrink-0 items-center justify-between border-b border-border px-3.5">+ <span className="flex items-center gap-[7px]">+ <h2 className="text-[16px] font-bold text-foreground">{t('settings.models.upstream.heading')}</h2>+ <ModelHubInfoHint+ label={t('settings.models.shell.gatewayInfo.label')}+ content={t('settings.models.shell.gatewayInfo.body')}+ className="model-hub-upstream-info"+ />+ </span>+ {sources !== undefined && <span className="model-hub-upstream-count rounded-full border px-2 py-[3px] text-[10.5px] font-semibold">{t('settings.models.upstream.count', { count: sources.length })}</span>}+ </div>+ <div className="min-h-0 flex-1 space-y-2.5 overflow-y-auto p-3">+ {read.kind === 'loading' && sources === undefined+ ? <div className="flex h-full min-h-36 items-center justify-center"><LoaderCircle className="size-4 animate-spin text-muted" /></div>+ : read.kind === 'unread'+ ? <div className="flex h-full min-h-36 flex-col items-center justify-center gap-3 px-4 text-center"><p className="text-[12px] text-muted">{t('settings.models.upstream.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.upstream.retry')}</Button></div>+ : <>+ {read.kind === 'degraded' && read.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive">{t('settings.models.upstream.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.upstream.retry')}</Button></div>}+ {groups.length > 0+ ? groups.map((group) => <div key={group.id} className="space-y-2"><h3 className="model-hub-upstream-group-label flex h-[18px] items-center uppercase">{t(`settings.models.upstream.group.${group.id}`)}</h3>{group.sources.map((source) => <SourceRow key={source.id} source={source} onOpen={onOpenSource} />)}</div>)+ : <p className="px-3 py-10 text-center text-[12px] text-muted">{t('settings.models.upstream.empty')}</p>}+ </>}+ </div>+ <div className="flex h-14 shrink-0 items-center gap-2 border-t border-border px-3.5">+ {/* G-21: the frame supplies no vendor for the per-vendor subscription+ dialog. Keep the drawn command visible without inventing a picker or+ a default vendor. */}+ <Button+ variant="default"+ size="xs"+ disabled+ className="model-hub-footer-action shadow-none disabled:opacity-100"+ >+ <Plus className="size-3" />+ {t('settings.models.upstream.addSubscription')}+ </Button>+ <Button+ variant="outline"+ size="xs"+ className="model-hub-footer-action"+ onClick={onAddApiKey}+ >+ <Plus className="size-3" />+ {t('settings.models.upstream.addApiKey')}+ </Button></div>-- {sources.length === 0 ? (- <div className="px-4 py-12 text-center sm:px-5 text-[13px] text-muted">{t('settings.models.sources.empty')}</div>- ) : (- <div className="flex flex-col">- {sources.map((source) => (- <SourceRow- key={source.id}- source={source}- onChanged={onSourceChanged}- onRefresh={onRefreshSource}- refreshing={refreshingSourceId === source.id}- refreshDisabled={refreshingSourceId !== null}- onRepair={onRepair}- onAddModel={onAddModel}- />- ))}- </div>- )}</section>);};diff --git a/ui/src/components/settings/models/SupplyGapNote.tsx b/ui/src/components/settings/models/SupplyGapNote.tsxindex f7b726da7..11e008c7f 100644--- a/ui/src/components/settings/models/SupplyGapNote.tsx+++ b/ui/src/components/settings/models/SupplyGapNote.tsx@@ -4,7 +4,7 @@// says why that naming matters: 「删除后 pm 将没有可用来源」 is actionable where a// bare (backend, model) pair is not. So this renders the Agents first and the// model second, and falls back to the backend only when no named Agent runs the-// pair — which is a real case (a mapping or Agent selection supplies it) and not a reason+// pair — which is a real case (a configured Route or Agent selection supplies it) and not a reason// to drop the entry.//// One component for all three sites — the forced-delete confirm, the forceddiff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.tsnew file mode 100644index 000000000..b8f3526e1--- /dev/null+++ b/ui/src/components/settings/models/SupplyGraph.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from 'vitest';++import { modelChainKey } from './modelRows';+import { readyRegion } from './regionRead';+import { freshRuntimeProjection } from './runtimeLifecycle';+import { buildSupplyRelations as buildRelations } from './supplyRelations';+import type { AgentChain, AgentSupply, RuntimeDependency, Source } from './types';++const runtime: RuntimeDependency = {+ contract_version: 5,+ manifest: { name: 'cliproxyapi', version: '1.0.0', source_sha: 'fixture', assets: [] },+ status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },+};+const buildSupplyRelations = (+ agents: AgentSupply[],+ sources: Source[],+ chains: Parameters<typeof buildRelations>[2],+) => buildRelations(agents, sources, chains, freshRuntimeProjection(readyRegion(runtime)));++const source = (id: string, channel: Source['supply_channel'], status: Source['state']['status'] = 'active'): Source => ({+ id,+ last_discovered_at: null,+ kind: channel === 'native_cli' ? 'subscription' : 'api_key',+ vendor: 'anthropic',+ display_name: id,+ protocol: 'anthropic',+ supply_channel: channel,+ billing: channel === 'native_cli' ? 'monthly' : 'metered',+ state: { status, retry_at: status === 'cooldown' ? '2099-01-01T00:00:00Z' : null, detail_key: null },+ models: [],+});++const agent: AgentSupply = {+ backend: 'claude',+ cli_present: true,+ mode: 'hub',+ menu_kind: 'fixed',+ selected_model_id: 'model-a',+ selected_model_explicit: true,+ sources: { order: ['native', 'relay', 'unused'], eligibility: [] },+ routes: { 'model-a': { hops: [{ source_id: 'native', model_id: 'model-a' }, { source_id: 'relay', model_id: 'model-a' }, { source_id: 'unused', model_id: 'model-a' }] } },+ supply_status: 'degraded',+ model_supply: [{ model_id: 'model-a', chain_length: 3, has_runnable_hop: true }],+ named_agents: [],+ builtin_models: ['model-a'],+ menu: null,+};++const chain = (current: string, headHealth: AgentChain['chain'][number]['health'] = 'healthy', headRunnable = true, reason: AgentChain['chain'][number]['reason'] = null): AgentChain => ({+ contract_version: 5,+ backend: 'claude',+ model_id: 'model-a',+ current: { source_id: current, model_id: 'model-a' },+ chain: [+ { source_id: 'native', model_id: 'model-a', channel: 'native_cli', health: headHealth, runnable: headRunnable, reason, retry_at: headHealth === 'cooldown' || headHealth === 'backoff' ? '2099-01-01T00:00:00Z' : null },+ { source_id: 'relay', model_id: 'model-a', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null },+ { source_id: 'unused', model_id: 'model-a', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null },+ ],+ supply_state: 'ok',+});++describe('buildSupplyRelations', () => {+ it('derives relation ink from configured routes and the exact current hop', () => {+ const sources = [source('native', 'native_cli'), source('relay', 'hub'), source('unused', 'hub')];+ const key = modelChainKey('claude', 'model-a');+ expect(buildSupplyRelations([agent], sources, { [key]: readyRegion(chain('native')) })).toEqual([+ { sourceId: 'native', backend: 'claude', kind: 'native' },+ { sourceId: 'relay', backend: 'claude', kind: 'connected_unused' },+ { sourceId: 'unused', backend: 'claude', kind: 'connected_unused' },+ ]);+ expect(buildSupplyRelations([agent], sources, { [key]: readyRegion(chain('relay', 'cooldown', false)) })[1]).toEqual(+ { sourceId: 'relay', backend: 'claude', kind: 'takeover' },+ );+ expect(buildSupplyRelations([agent], sources, { [key]: readyRegion(chain('relay', 'backoff', false, 'models.source.backoff.connection_failed')) })[1]).toEqual(+ { sourceId: 'relay', backend: 'claude', kind: 'takeover' },+ );+ expect(buildSupplyRelations([agent], sources, { [key]: readyRegion(chain('relay', 'cooldown', false, 'native_cli_unavailable')) })[1]).toEqual(+ { sourceId: 'relay', backend: 'claude', kind: 'gateway' },+ );+ for (const health of ['needs_action', 'error'] as const) {+ const reason = health === 'needs_action'+ ? 'models.source.needs_action.oauth_expired' as const+ : 'models.source.error.unclassified' as const;+ const relations = buildSupplyRelations([agent], sources, { [key]: readyRegion(chain('relay', health, false, reason)) });+ expect(relations[1]).toEqual(+ { sourceId: 'relay', backend: 'claude', kind: 'gateway' },+ );+ expect(relations[0]).toEqual({ sourceId: 'native', backend: 'claude', kind: 'unavailable' });+ }+ expect(buildSupplyRelations([agent], sources, { [key]: readyRegion(chain('relay')) })[0]).toEqual(+ { sourceId: 'native', backend: 'claude', kind: 'connected_unused' },+ );+ const staleCooldown = [source('native', 'native_cli'), source('relay', 'hub', 'cooldown'), source('unused', 'hub')];+ expect(buildSupplyRelations([agent], staleCooldown, { [key]: readyRegion(chain('relay')) })[1]).toEqual(+ { sourceId: 'relay', backend: 'claude', kind: 'gateway' },+ );+ });++ it('renders cooling relations as unavailable and draws no relations for direct backends', () => {+ const sources = [source('native', 'native_cli', 'cooldown'), source('relay', 'hub'), source('unused', 'hub')];+ expect(buildSupplyRelations([agent], sources, {} )[0]?.kind).toBe('unavailable');+ expect(buildSupplyRelations([{ ...agent, mode: 'direct', routes: null, sources: null }], sources, {})).toEqual([]);+ const stopped = { ...runtime, status: { ...runtime.status, health: 'not_started' as const } };+ expect(buildRelations([agent], sources, {}, freshRuntimeProjection(readyRegion(stopped)))).toEqual([]);+ });++ it('matches current and takeover relations by the exact mapped hop identity', () => {+ const mappedAgent: AgentSupply = {+ ...agent,+ routes: {+ 'custom/model-a': {+ hops: [+ { source_id: 'native', model_id: 'model-a' },+ { source_id: 'relay', model_id: 'model-a' },+ ],+ },+ },+ };+ const mappedChain: AgentChain = {+ ...chain('relay', 'cooldown', false),+ model_id: 'custom/model-a',+ };++ expect(buildSupplyRelations(+ [mappedAgent],+ [source('native', 'native_cli'), source('relay', 'hub')],+ { [modelChainKey('claude', 'custom/model-a')]: readyRegion(mappedChain) },+ )).toContainEqual({ sourceId: 'relay', backend: 'claude', kind: 'takeover' });+ });+});diff --git a/ui/src/components/settings/models/SupplyGraph.test.tsx b/ui/src/components/settings/models/SupplyGraph.test.tsxnew file mode 100644index 000000000..b168ba147--- /dev/null+++ b/ui/src/components/settings/models/SupplyGraph.test.tsx@@ -0,0 +1,64 @@+// @vitest-environment jsdom+import * as React from 'react';+import { cleanup, fireEvent, render, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { SupplyGraph } from './SupplyGraph';+import type { SupplyRelation } from './supplyRelations';++const relation: SupplyRelation = { sourceId: 'src_a', backend: 'claude', kind: 'gateway' };++const rect = (left: number, top: number, width: number, height: number): DOMRect => ({+ x: left,+ y: top,+ left,+ top,+ right: left + width,+ bottom: top + height,+ width,+ height,+ toJSON: () => ({}),+});++const Fixture: React.FC = () => {+ const ref = React.useRef<HTMLDivElement>(null);+ const [mounted, setMounted] = React.useState(false);+ React.useLayoutEffect(() => setMounted(true), []);+ return (+ <div ref={ref} data-testid="graph-root">+ <div data-source-id="src_a" />+ <div data-agent-backend="claude" />+ {mounted && <SupplyGraph containerRef={ref} relations={[relation]} />}+ </div>+ );+};++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe('SupplyGraph', () => {+ it('re-measures wires when a nested card scrolls without resizing the shell', async () => {+ let sourceTop = 10;+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function bounds() {+ if (this.dataset.testid === 'graph-root') return rect(0, 0, 120, 100);+ if (this.dataset.sourceId === 'src_a') return rect(10, sourceTop, 20, 10);+ if (this.dataset.agentBackend === 'claude') return rect(90, 40, 20, 20);+ return rect(0, 0, 0, 0);+ });++ const view = render(<Fixture />);+ const path = await waitFor(() => {+ const element = view.container.querySelector<SVGPathElement>('.model-hub-wire');+ expect(element).not.toBeNull();+ return element as SVGPathElement;+ });+ expect(path.getAttribute('d')).toContain('M 30 15');++ sourceTop = 30;+ fireEvent.scroll(view.container.querySelector('[data-source-id="src_a"]') as Element);++ await waitFor(() => expect(path.getAttribute('d')).toContain('M 30 35'));+ });+});diff --git a/ui/src/components/settings/models/SupplyGraph.tsx b/ui/src/components/settings/models/SupplyGraph.tsxnew file mode 100644index 000000000..f30f8946c--- /dev/null+++ b/ui/src/components/settings/models/SupplyGraph.tsx@@ -0,0 +1,112 @@+import * as React from 'react';+import { useTranslation } from 'react-i18next';++import { cn } from '@/lib/utils';+import { ModelHubInfoHint } from './ModelHubInfoHint';+import type { AgentBackend } from './types';+import type { SupplyRelation, SupplyRelationKind } from './supplyRelations';++type DrawnRelation = SupplyRelation & {+ path: string;+ startX: number;+ startY: number;+ endX: number;+ endY: number;+};++export const SupplyGraph: React.FC<{+ containerRef: React.RefObject<HTMLDivElement | null>;+ relations: SupplyRelation[];+}> = ({ containerRef, relations }) => {+ const [drawing, setDrawing] = React.useState<{ width: number; height: number; railX: number; wires: DrawnRelation[] } | null>(null);++ React.useLayoutEffect(() => {+ const container = containerRef.current;+ if (!container) return undefined;+ const measure = () => {+ const root = container.getBoundingClientRect();+ const byBackend = new Map<AgentBackend, SupplyRelation[]>();+ for (const relation of relations) byBackend.set(relation.backend, [...(byBackend.get(relation.backend) ?? []), relation]);+ const wires: DrawnRelation[] = [];+ for (const relation of relations) {+ const source = Array.from(container.querySelectorAll<HTMLElement>('[data-source-id]')).find((element) => element.dataset.sourceId === relation.sourceId);+ const backend = Array.from(container.querySelectorAll<HTMLElement>('[data-agent-backend]')).find((element) => element.dataset.agentBackend === relation.backend);+ if (!source || !backend) continue;+ const sourceBounds = source.getBoundingClientRect();+ const backendBounds = backend.getBoundingClientRect();+ const siblings = byBackend.get(relation.backend) ?? [];+ const backendIndex = siblings.findIndex((candidate) => candidate.sourceId === relation.sourceId);+ const startX = sourceBounds.right - root.left;+ const startY = sourceBounds.top - root.top + sourceBounds.height / 2;+ const endX = backendBounds.left - root.left;+ const endY = backendBounds.top - root.top + backendBounds.height * ((backendIndex + 1) / (siblings.length + 1));+ const railX = startX + (endX - startX) / 2;+ wires.push({ ...relation, startX, startY, endX, endY, path: `M ${startX} ${startY} C ${railX} ${startY}, ${railX} ${endY}, ${endX} ${endY}` });+ }+ const railX = wires.length > 0 ? wires.reduce((sum, wire) => sum + (wire.startX + wire.endX) / 2, 0) / wires.length : 0;+ setDrawing({ width: root.width, height: root.height, railX, wires });+ };+ measure();+ const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure);+ resize?.observe(container);+ container.addEventListener('scroll', measure, true);+ window.addEventListener('resize', measure);+ return () => {+ resize?.disconnect();+ container.removeEventListener('scroll', measure, true);+ window.removeEventListener('resize', measure);+ };+ }, [containerRef, relations]);++ if (!drawing || drawing.wires.length === 0) return null;+ const yValues = drawing.wires.flatMap((wire) => [wire.startY, wire.endY]);+ return (+ <svg aria-hidden="true" className="pointer-events-none absolute inset-0 z-10 hidden size-full overflow-visible lg:block" viewBox={`0 0 ${drawing.width} ${drawing.height}`} preserveAspectRatio="none">+ <line className="model-hub-rail-line" x1={drawing.railX} x2={drawing.railX} y1={Math.min(...yValues)} y2={Math.max(...yValues)} />+ {drawing.wires.map((wire) => (+ <g key={`${wire.sourceId}:${wire.backend}`}>+ <path className={`model-hub-wire model-hub-wire--${wire.kind}`} d={wire.path} />+ <circle className={`model-hub-wire-node model-hub-wire-node--${wire.kind}`} cx={wire.startX} cy={wire.startY} />+ <circle className={`model-hub-wire-node model-hub-wire-node--${wire.kind}`} cx={wire.endX} cy={wire.endY} />+ </g>+ ))}+ </svg>+ );+};++const LEGEND_ORDER: SupplyRelationKind[] = ['native', 'gateway', 'connected_unused', 'takeover', 'unavailable'];+const LEGEND_COPY: Record<SupplyRelationKind, string> = {+ native: 'native',+ gateway: 'viaGateway',+ connected_unused: 'connectedUnused',+ takeover: 'takeover',+ unavailable: 'unavailable',+};++export const SupplyLegend: React.FC<{ relations: SupplyRelation[] }> = ({ relations }) => {+ const { t } = useTranslation();+ const visible = new Set(relations.map((relation) => relation.kind));+ if (visible.size === 0) return null;+ return (+ <div className="model-hub-legend flex flex-wrap items-center justify-between gap-x-5 gap-y-2 px-0.5 py-2 text-[11px] text-muted">+ <div className="flex flex-wrap items-center gap-x-[18px] gap-y-2">+ {LEGEND_ORDER.filter((kind) => visible.has(kind)).map((kind) => (+ <span key={kind} className="flex items-center gap-[7px] font-medium">+ <span className={cn(`model-hub-legend-swatch model-hub-legend-swatch--${kind}`, {+ 'bg-cyan': kind === 'native',+ 'bg-mint': kind === 'gateway',+ 'bg-foreground/15': kind === 'connected_unused',+ 'bg-violet': kind === 'takeover',+ 'bg-gold': kind === 'unavailable',+ })} />+ {t(`settings.models.legend.${LEGEND_COPY[kind]}`)}+ </span>+ ))}+ </div>+ <span className="model-hub-ink-white-59 flex items-center gap-1.5">+ <span className="hidden sm:inline">{t('settings.models.legend.note')}</span>+ <ModelHubInfoHint label={t('settings.models.legend.note')} content={t('settings.models.legend.note')} className="model-hub-ink-white-59 size-[20px]" align="end" />+ </span>+ </div>+ );+};diff --git a/ui/src/components/settings/models/SupplyTooltip.tsx b/ui/src/components/settings/models/SupplyTooltip.tsxdeleted file mode 100644index ca81f851a..000000000--- a/ui/src/components/settings/models/SupplyTooltip.tsx+++ /dev/null@@ -1,48 +0,0 @@-// Dark hover/focus tooltip listing the models a source supplies (frame 01r:-// "supply list appears ONLY as hover tooltip on icon/title"). CSS group-hover-// keeps it dependency-free; the trigger must not sit inside an overflow-hidden-// ancestor (the 来源 card container is deliberately not clipped).-//-// bg-foreground/text-background is token-driven: dark tooltip in Light mode-// (matches the V4 mock) and auto-inverts in Dark (refine when Dark mocks land).-import * as React from 'react';-import { Cpu } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { cn } from '@/lib/utils';-import type { SuppliedModel } from './types';--const MAX_SHOWN = 6;--export const SupplyTooltip: React.FC<{- models: SuppliedModel[];- children: React.ReactNode;- /** Layout classes for the wrapper (e.g. flex-1). Defaults to inline. */- className?: string;-}> = ({ models, children, className }) => {- const { t } = useTranslation();- const names = models.map((m) => m.display_name || m.id);- const shown = names.slice(0, MAX_SHOWN);- const more = names.length - shown.length;-- return (- <span className={cn('group/supply relative', className ?? 'inline-flex items-center')}>- {children}- {names.length > 0 && (- <span- role="tooltip"- className="pointer-events-none absolute left-0 top-full z-30 mt-2 hidden w-max max-w-sm group-hover/supply:block group-focus-within/supply:block"- >- <span className="flex items-center gap-2 rounded-lg bg-foreground px-3 py-2 text-[12px] leading-snug text-background shadow-lg">- <Cpu className="size-3.5 shrink-0 text-mint" />- <span>- <span className="text-background/70">{t('settings.models.supplyTooltip.label')}</span>- {shown.join(' · ')}- {more > 0 ? ` +${more}` : ''}- </span>- </span>- </span>- )}- </span>- );-};diff --git a/ui/src/components/settings/models/addApiKeyState.test.ts b/ui/src/components/settings/models/addApiKeyState.test.tsnew file mode 100644index 000000000..831317b24--- /dev/null+++ b/ui/src/components/settings/models/addApiKeyState.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';++import { classifyObservation, protocolOrderWithHint } from './addApiKeyState';+import { CONTRACT_VERSION, SOURCE_PROTOCOLS, type SourceObservation } from './types';++const observation = (patch: Partial<SourceObservation>): SourceObservation => ({+ contract_version: CONTRACT_VERSION,+ outcome: 'observed',+ reachable: true,+ authenticated: 'authenticated',+ protocol: 'openai_chat',+ discovery: 'succeeded',+ models: ['model-a'],+ ...patch,+});++describe('Add API key observation state', () => {+ it('turns a one-time hint into a complete probe order without duplicating the protocol table', () => {+ const order = protocolOrderWithHint('openai_responses');+ expect(order?.[0]).toBe('openai_responses');+ expect(new Set(order)).toEqual(new Set(SOURCE_PROTOCOLS));+ expect(order).toHaveLength(SOURCE_PROTOCOLS.length);+ });++ it('separates proven inventory failure from unknown protocol and connectivity failures', () => {+ const inventory = observation({ discovery: 'failed', models: [] });+ expect(classifyObservation(inventory)).toEqual({ kind: 'inventory', observation: inventory });+ expect(classifyObservation(observation({+ outcome: 'ambiguous',+ authenticated: 'unknown',+ protocol: null,+ discovery: 'not_attempted',+ models: [],+ })).kind).toBe('undetermined');+ expect(classifyObservation(observation({+ outcome: 'authentication_failed',+ authenticated: 'rejected',+ protocol: null,+ discovery: 'not_attempted',+ models: [],+ }))).toEqual({ kind: 'failure', cause: 'auth' });+ expect(classifyObservation(observation({+ outcome: 'timeout',+ reachable: null,+ authenticated: 'unknown',+ protocol: null,+ discovery: 'not_attempted',+ models: [],+ }))).toEqual({ kind: 'failure', cause: 'network' });+ expect(classifyObservation(observation({+ outcome: 'unreachable',+ reachable: false,+ authenticated: 'unknown',+ protocol: null,+ discovery: 'not_attempted',+ models: [],+ }))).toEqual({ kind: 'failure', cause: 'network' });+ });+});diff --git a/ui/src/components/settings/models/addApiKeyState.ts b/ui/src/components/settings/models/addApiKeyState.tsnew file mode 100644index 000000000..7b54f80ab--- /dev/null+++ b/ui/src/components/settings/models/addApiKeyState.ts@@ -0,0 +1,51 @@+import {+ SOURCE_PROTOCOLS,+ type SourceObservation,+ type SourceProtocol,+} from './types';++export type AddApiKeyOrigin = 'add' | 'pull';+export type AddApiKeyFailure = 'auth' | 'network' | 'unclassified' | 'engineDown';++export type ObservationVerdict =+ | { kind: 'ready'; observation: SourceObservation }+ | { kind: 'undetermined'; observation: SourceObservation }+ | { kind: 'inventory'; observation: SourceObservation }+ | { kind: 'failure'; cause: AddApiKeyFailure };++export const PROTOCOL_COPY_KEYS: Record<SourceProtocol, string> = {+ anthropic: 'settings.models.addKey.protocol.anthropicMessages',+ openai_responses: 'settings.models.addKey.protocol.openaiResponses',+ openai_chat: 'settings.models.addKey.protocol.openaiChatCompletions',+};++export function protocolOrderWithHint(hint: SourceProtocol | null): SourceProtocol[] | undefined {+ if (!hint) return undefined;+ return [hint, ...SOURCE_PROTOCOLS.filter((protocol) => protocol !== hint)];+}++export function classifyObservation(observation: SourceObservation): ObservationVerdict {+ switch (observation.outcome) {+ case 'observed':+ if (observation.protocol && observation.discovery === 'succeeded') {+ return { kind: 'ready', observation };+ }+ if (observation.protocol && observation.discovery === 'failed') {+ return { kind: 'inventory', observation };+ }+ return { kind: 'failure', cause: 'unclassified' };+ case 'ambiguous':+ return { kind: 'undetermined', observation };+ case 'authentication_failed':+ return { kind: 'failure', cause: 'auth' };+ case 'unreachable':+ case 'timeout':+ return { kind: 'failure', cause: 'network' };+ case 'adapter_error':+ return { kind: 'failure', cause: 'unclassified' };+ }+}++export function isAbortError(error: unknown): boolean {+ return error instanceof DOMException && error.name === 'AbortError';+}diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.tsindex 67c44c862..29d285300 100644--- a/ui/src/components/settings/models/apiFailure.test.ts+++ b/ui/src/components/settings/models/apiFailure.test.ts@@ -31,15 +31,33 @@ afterEach(() => {});describe('apiFailure — whether the route named the failure', () => {+ it('posts installation to the dedicated runtime route', async () => {+ const runtime = {+ contract_version: 5,+ manifest: { name: 'cliproxyapi', version: '1', source_sha: 'sha', assets: [] },+ status: { installed_version: null, verified: false, listening: null, health: 'installing', last_check: null },+ } as const;+ let installInit: RequestInit | undefined;+ const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ if (input === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });+ if (input === '/api/models/runtime/install') installInit = init;+ return Response.json({ runtime });+ });+ vi.stubGlobal('fetch', fetch);++ await expect(modelsApi.installRuntime()).resolves.toEqual(runtime);+ expect(installInit?.method).toBe('POST');+ });+it('reads a route-declared code as named', async () => {const failure = await failureFor(() => Response.json({ error: 'discovery_failed' }, { status: 409 }));- expect(failure).toMatchObject({ code: 'discovery_failed', serverNamed: true });+ expect(failure).toMatchObject({ code: 'discovery_failed', serverNamed: true, responseStatus: 409 });});it('reads a body that would not parse as UNNAMED', async () => {// The server may well have written before this response was truncated.const failure = await failureFor(() => new Response('<html>502</html>', { status: 502 }));- expect(failure).toMatchObject({ code: 'bad_response', serverNamed: false });+ expect(failure).toMatchObject({ code: 'bad_response', serverNamed: false, responseStatus: 502 });});it('reads a status this client had to summarize itself as UNNAMED', async () => {diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.tsindex fb06374ba..aa1177df3 100644--- a/ui/src/components/settings/models/asyncLifetime.test.ts+++ b/ui/src/components/settings/models/asyncLifetime.test.ts@@ -65,6 +65,8 @@ import {agentsWithEcho,createFlowAuthority,createLatestAsyncAuthority,+ createLatestAsyncAuthorityByKey,+ createLatestEntityAuthorityByKey,createPendingWrites,failureLanded,flowLetGo,@@ -75,12 +77,10 @@ import {mapWithConcurrency,pollFailureSettles,releaseFlow,- savedMappingsKey,savedMenuKey,savedSourcesKey,seedStep,startNeedsStatusRead,- sourcesWithEcho,terminalArrivalMovedRows,type FlowView,} from './asyncLifetime';@@ -88,9 +88,10 @@ import type { AgentSupply, OAuthFlow, Source } from './types';const agent = (over: Partial<AgentSupply> = {}): AgentSupply => ({backend: 'claude',+ cli_present: true,mode: 'hub',menu_kind: 'fixed',- sources: { policy: 'custom', order: ['src_a', 'src_b'] },+ sources: { order: ['src_a', 'src_b'] },...over,});@@ -145,6 +146,93 @@ describe('latest async authority', () => {await expect(authority.run(() => Promise.reject(new Error('read failed')))).rejects.toThrow('read failed');expect(landed).toEqual(['newest']);});++ it('orders reads per key without making independent backends supersede each other', async () => {+ const olderClaude = deferred<string>();+ const newerClaude = deferred<string>();+ const codex = deferred<string>();+ const landed: string[] = [];+ const authority = createLatestAsyncAuthorityByKey<string, string>((key, value) => landed.push(`${key}:${value}`));++ const olderRun = authority.run('claude', () => olderClaude.promise);+ const codexRun = authority.run('codex', () => codex.promise);+ const newerRun = authority.run('claude', () => newerClaude.promise);+ newerClaude.resolve('new');+ codex.resolve('independent');+ await Promise.all([newerRun, codexRun]);+ olderClaude.resolve('old');++ expect(await olderRun).toBe('stale');+ expect(landed).toEqual(['claude:new', 'codex:independent']);+ });++ it('invalidates pending generations whose keys lose active ownership', async () => {+ const claude = deferred<string>();+ const codex = deferred<string>();+ const landed: string[] = [];+ const authority = createLatestAsyncAuthorityByKey<string, string>((key, value) => landed.push(`${key}:${value}`));++ const claudeRun = authority.run('claude', () => claude.promise);+ const codexRun = authority.run('codex', () => codex.promise);+ authority.invalidateExcept(new Set(['codex']));+ claude.resolve('no longer owned');+ codex.resolve('still active');++ expect(await claudeRun).toBe('stale');+ expect(await codexRun).toBe('landed');+ expect(landed).toEqual(['codex:still active']);+ });+});++describe('latest Source entity authority', () => {+ it('lands the later per-Source generation and rejects an older echo', () => {+ const landed: Source[][] = [];+ const authority = createLatestEntityAuthorityByKey((source: Source) => source.id, (sources) => landed.push(sources));+ const initialSnapshot = authority.beginSnapshot();+ const initial = { id: 'src_a', display_name: 'initial' } as Source;+ authority.settleSnapshot(initialSnapshot, [initial]);+ const older = authority.begin('src_a');+ const newer = authority.begin('src_a');+ const newerSource = { ...initial, display_name: 'newer' };++ expect(authority.settle(newer, newerSource)).toBe('landed');+ expect(authority.settle(older, { ...initial, display_name: 'older' })).toBe('stale');+ expect(authority.current('src_a')).toEqual(newerSource);+ expect(landed.at(-1)).toEqual([newerSource]);+ });++ it('does not let a snapshot reserved before a mutation overwrite its echo', () => {+ const landed: Source[][] = [];+ const authority = createLatestEntityAuthorityByKey((source: Source) => source.id, (sources) => landed.push(sources));+ const initial = { id: 'src_a', display_name: 'initial' } as Source;+ const initialSnapshot = authority.beginSnapshot();+ authority.settleSnapshot(initialSnapshot, [initial]);+ const olderSnapshot = authority.beginSnapshot();+ const mutation = authority.begin('src_a');+ const echoed = { ...initial, display_name: 'echoed' };++ expect(authority.settle(mutation, echoed)).toBe('landed');+ authority.settleSnapshot(olderSnapshot, [initial]);+ expect(landed.at(-1)).toEqual([echoed]);+ });++ it('does not let a scoped gone reconciliation invalidate a sibling write already in flight', () => {+ const landed: Source[][] = [];+ const authority = createLatestEntityAuthorityByKey((source: Source) => source.id, (sources) => landed.push(sources));+ const sourceA = { id: 'src_a', display_name: 'A' } as Source;+ const sourceB = { id: 'src_b', display_name: 'B' } as Source;+ const initial = authority.beginSnapshot();+ authority.settleSnapshot(initial, [sourceA, sourceB]);+ const removingA = authority.begin(sourceA.id);+ const mutatingB = authority.begin(sourceB.id);+ const reconciliation = authority.beginSnapshot();++ authority.settleSnapshotEntries(reconciliation, [sourceB]);+ expect(authority.settleRemoval(removingA)).toBe('landed');+ const echoedB = { ...sourceB, display_name: 'B after mutation' };+ expect(authority.settle(mutatingB, echoedB)).toBe('landed');+ expect(landed.at(-1)).toEqual([echoedB]);+ });});describe('bounded async map', () => {@@ -169,11 +257,11 @@ describe('bounded async map', () => {});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'] } });+ const claude = agent({ backend: 'claude', sources: { order: ['src_a'] } });+ const codex = agent({ backend: 'codex', sources: { order: ['src_b'] } });it('takes the write’s echo into the row it is about', () => {- const echoed = agent({ backend: 'claude', sources: { policy: 'custom', order: ['src_a', 'src_c'] } });+ const echoed = agent({ backend: 'claude', sources: { order: ['src_a', 'src_c'] } });expect(agentsWithEcho([claude, codex], echoed)).toEqual([echoed, codex]);});@@ -181,7 +269,7 @@ describe('agentsWithEcho — what speaks for a row when no read does', () => {it('leaves every other Agent to the read that owns it', () => {// An order write is per backend; it says nothing about the others, so it may// not answer for them either.- const echoed = agent({ backend: 'codex', sources: { policy: 'custom', order: ['src_b', 'src_c'] } });+ const echoed = agent({ backend: 'codex', sources: { order: ['src_b', 'src_c'] } });expect(agentsWithEcho([claude, codex], echoed)[0]).toBe(claude);});@@ -195,7 +283,7 @@ describe('agentsWithEcho — what speaks for a row when no read does', () => {it('does not mutate the list it was handed', () => {const before = [claude, codex];- agentsWithEcho(before, agent({ backend: 'claude', sources: { policy: 'follow', order: [] } }));+ agentsWithEcho(before, agent({ backend: 'claude', sources: { order: [] } }));expect(before).toEqual([claude, codex]);});@@ -207,60 +295,42 @@ 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(/const next = agentsWithEcho\(prev, echoed\)/);+ expect(page).toMatch(/setSupplyRead\(\(previous\) => readyRegion\(agentsWithEcho\(foldRegionRead\(previous,[\s\S]*?echoed\)\)\)/);+ expect(page).toMatch(/const agentSaved[\s\S]*?convergeMutation\(\{/);// 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(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\(\)\}/);+ expect(page).toMatch(/onSaved=\{agentSaved\}/);+ expect(page).toMatch(/const echoed = await modelsApi\.setAgentMode[\s\S]*?await agentSaved\(echoed\)/);});});-describe('sourcesWithEcho — one refresh result inside the shared authority', () => {- const source = (id: string, models: string[]): Source => ({- id,- kind: 'api_key',- vendor: 'anthropic',- display_name: id,- protocol: 'anthropic',- supply_channel: 'hub',- billing: 'metered',- state: { status: 'standby', retry_at: null, detail_key: null },- last_discovered_at: '2026-07-31T05:00:00Z',- models: models.map((id) => ({ id, provenance: 'discovered' })),- });-- it('replaces only the source named by the server echo', () => {- const first = source('src_first000', ['old-model']);- const second = source('src_second00', ['other-model']);- const echoed = source('src_first000', ['old-model', 'claude-opus-5']);-- expect(sourcesWithEcho([first, second], echoed)).toEqual([echoed, second]);- });-- it('does not append a row the inventory read never saw', () => {- const first = source('src_first000', ['old-model']);-- expect(sourcesWithEcho([first], source('src_missing00', ['new-model']))).toEqual([first]);- });-- it('routes refresh and full reads through the same latest-result authority', () => {+describe('Source entity landing through the shared authority', () => {+ it('routes Source-detail rereads and full reads through the same per-Source settlement', () => {const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');-- expect(page).toMatch(/const refreshed = await modelsApi\.refreshSource\(source\.id\);\s*await refreshAuthority\.run/);- expect(page).toMatch(/if \(landing\.kind === 'source'\)[\s\S]*?sourcesWithEcho\(previous, landing\.source\)/);+ const detail = readFileSync(join(__dirname, 'SourceDetailPanel.tsx'), 'utf8');+ const sourceRetry = page.slice(page.indexOf('const retrySources'), page.indexOf('const retrySupply'));+ const supplyRetry = page.slice(page.indexOf('const retrySupply'), page.indexOf('const retryEvents'));++ expect(detail).toMatch(/trackMutation\(async \(latest, settlement\)[\s\S]*?modelsApi\.refreshSource\(latest\.id, confirmation\)/);+ expect(detail).toMatch(/await settlement\.source\(answer\.source\)/);+ expect(page).toMatch(/sourceWriteRegistry\.track\(sourceId[\s\S]*?sourceEntityAuthority\.current\(sourceId\)[\s\S]*?sourceEntityAuthority\.begin\(sourceId\)[\s\S]*?const settlement: SourceMutationSettlement/);+ expect(page).toMatch(/source: async \(echoed\)[\s\S]*?sourceEntityAuthority\.settle\(generation/);+ expect(page).not.toMatch(/const sourceMutation|activeSourceGenerations/);+ expect(page).toMatch(/await refreshAuthority\.run/);+ expect(sourceRetry).toMatch(/await refresh\(\)/);+ expect(supplyRetry).toMatch(/await refresh\(\)/);+ expect(sourceRetry).not.toMatch(/modelsApi\.listSources/);+ expect(supplyRetry).not.toMatch(/modelsApi\.listAgents/);});it('keeps the mutating refresh failure outside stale-read suppression', () => {- const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');- const refresh = page.slice(page.indexOf('const refreshSource ='), page.indexOf('// Resolve an open drawer'));+ const detail = readFileSync(join(__dirname, 'SourceDetailPanel.tsx'), 'utf8');+ const refresh = detail.slice(detail.indexOf('const refetch ='), detail.indexOf('const remove ='));- expect(refresh.indexOf('modelsApi.refreshSource')).toBeLessThan(refresh.indexOf('refreshAuthority.run'));- expect(refresh).toMatch(/catch \{[\s\S]*?sourceActions\.refreshFailed/);+ expect(refresh).toMatch(/modelsApi\.refreshSource/);+ expect(refresh).toMatch(/catch \(error\)[\s\S]*?setRefetchFailed\(true\)/);+ expect(detail).toMatch(/refetchFailed[\s\S]*?sourceDetail\.fail\.refetch/);});});@@ -454,21 +524,19 @@ describe('createPendingWrites — a write that outlives the drawer that issued iexpect(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\)/);+ // The page owns the write after the drawer unmounts, and only a Hub backend+ // can remain the owner of an open order drawer.+ expect(page).toMatch(/agents\.find\(\(agent\) => agent\.backend === orderBackend && agent\.mode === 'hub'\)/);+ expect(page).toMatch(/pending: agentWrites\.has\(orderAgent\.backend\)/);});});-describe('savedSourcesKey / savedMappingsKey / savedMenuKey', () => {+describe('savedSourcesKey / savedMenuKey', () => {it('moves when the saved state moves', () => {- expect(savedSourcesKey(agent({ sources: { policy: 'custom', order: ['src_b', 'src_a'] } }))).not.toBe(- savedSourcesKey(agent()),- );- expect(savedSourcesKey(agent({ sources: { policy: 'follow', order: ['src_a', 'src_b'] } }))).not.toBe(+ expect(savedSourcesKey(agent({ sources: { order: ['src_b', 'src_a'] } }))).not.toBe(savedSourcesKey(agent()),);+ expect(savedSourcesKey(agent({ sources: { order: ['src_a', 'src_b', 'src_c'] } }))).not.toBe(savedSourcesKey(agent()));});it('holds still across a refetch that changed nothing', () => {@@ -478,16 +546,12 @@ describe('savedSourcesKey / savedMappingsKey / savedMenuKey', () => {});it('cannot be spoofed by an id that contains the separator', () => {- expect(savedSourcesKey(agent({ sources: { policy: 'custom', order: ['src_a src_b'] } }))).not.toBe(+ expect(savedSourcesKey(agent({ sources: { order: ['src_a src_b'] } }))).not.toBe(savedSourcesKey(agent()),);});- it('reads the mapping overrides and the menu the drawers seed from', () => {- const base = agent({ mappings: [{ builtin_id: 'claude-opus-4-6', target_model_id: 'm1', enabled: true }] });- expect(savedMappingsKey(base)).not.toBe(- savedMappingsKey(agent({ mappings: [{ builtin_id: 'claude-opus-4-6', target_model_id: 'm1', enabled: false }] })),- );+ it('reads the menu the drawer seeds from', () => {expect(savedMenuKey({ view: 'featured', checked: ['zhipuai/glm-5.2'] })).not.toBe(savedMenuKey({ view: 'full', checked: ['zhipuai/glm-5.2'] }),);@@ -515,8 +579,8 @@ describe('seedStep', () => {// so it seeds from the pre-save props — and only then does the save land and// the refetch deliver [b, a]. Whatever the drawer is holding at that point// came from a snapshot the server has since replaced.- const stale = savedSourcesKey(agent({ sources: { policy: 'custom', order: ['src_a', 'src_b'] } }));- const landed = savedSourcesKey(agent({ sources: { policy: 'custom', order: ['src_b', 'src_a'] } }));+ const stale = savedSourcesKey(agent({ sources: { order: ['src_a', 'src_b'] } }));+ const landed = savedSourcesKey(agent({ sources: { order: ['src_b', 'src_a'] } }));const reopened = seedStep(initialSeedState, stale).state;const after = seedStep(reopened, landed);@@ -526,7 +590,7 @@ describe('seedStep', () => {});it('re-seats only once per move, so a redundant refetch stays inert', () => {- const landed = savedSourcesKey(agent({ sources: { policy: 'custom', order: ['src_b', 'src_a'] } }));+ const landed = savedSourcesKey(agent({ sources: { order: ['src_b', 'src_a'] } }));const reseated = seedStep(seedStep(initialSeedState, savedSourcesKey(agent())).state, landed).state;expect(seedStep(reseated, landed).reseed).toBe(false);});@@ -900,7 +964,9 @@ describe('failureLanded — whose account of the rows is the one on screen', ()// The two paths reached after the attempt is over take the default rather than// restating it — including the release re-read, which awaits the cancel first// and is therefore the latest-landing arrival in the file.- expect(dialog).toMatch(/const resolvedAfterAttempt = \(\) => rowsBehindAreStale\(\);/);+ expect(dialog).toMatch(+ /const resolvedAfterAttempt = React\.useCallback\(\(\) => rowsBehindAreStale\(\), \[rowsBehindAreStale\]\);/,+ );expect(dialog).toMatch(/reread: \(\) => rowsBehindAreStale\(\),/);});});diff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.tsindex 0c5de3bf2..54e7e5dfd 100644--- a/ui/src/components/settings/models/asyncLifetime.ts+++ b/ui/src/components/settings/models/asyncLifetime.ts@@ -2,7 +2,7 @@// be exercised directly: which request may land, what speaks for a row when no// read does, how long a write counts as outstanding, when a drawer re-seeds, and// whether a connect-flow transition may change an already terminal view.-import type { AgentMenu, AgentSupply, OAuthFlow, OAuthFlowState, Source } from './types';+import type { AgentMenu, AgentSupply, OAuthFlow, OAuthFlowState } from './types';// ── Latest async result ────────────────────────────────────────────────────/**@@ -28,6 +28,112 @@ export const createLatestAsyncAuthority = <T>(land: (value: T) => void) => {};};+/** Gives each independent key its own latest-result generation. */+export const createLatestAsyncAuthorityByKey = <K, T>(+ land: (key: K, value: T) => void,+) => {+ const latestRequest = new Map<K, number>();+ const advance = (key: K) => {+ latestRequest.set(key, (latestRequest.get(key) ?? 0) + 1);+ };++ return {+ /** Advances retired keys so their pending requests cannot regain ownership. */+ invalidateExcept: (activeKeys: ReadonlySet<K>): void => {+ for (const key of latestRequest.keys()) {+ if (!activeKeys.has(key)) advance(key);+ }+ },+ run: async (key: K, read: () => Promise<T>): Promise<'landed' | 'stale'> => {+ const request = (latestRequest.get(key) ?? 0) + 1;+ latestRequest.set(key, request);+ try {+ const value = await read();+ if (latestRequest.get(key) !== request) return 'stale';+ land(key, value);+ return 'landed';+ } catch (error) {+ if (latestRequest.get(key) !== request) return 'stale';+ throw error;+ }+ },+ };+};++export type EntityGeneration<K> = Readonly<{ key: K; generation: number }>;++/** Owns a keyed entity collection across mutation echoes and list snapshots. */+export const createLatestEntityAuthorityByKey = <K, T>(+ keyOf: (value: T) => K,+ land: (values: T[]) => void,+) => {+ let generation = 0;+ const generations = new Map<K, number>();+ const pending = new Map<K, number>();+ const values = new Map<K, T>();+ const publish = () => land([...values.values()]);+ const begin = (key: K): EntityGeneration<K> => {+ const ticket = { key, generation: ++generation } as const;+ generations.set(key, ticket.generation);+ pending.set(key, ticket.generation);+ return ticket;+ };++ return {+ begin,+ current: (key: K): T | undefined => values.get(key),+ beginSnapshot: (): number => ++generation,+ settle: (ticket: EntityGeneration<K>, value: T): 'landed' | 'stale' => {+ if (ticket.key !== keyOf(value) || generations.get(ticket.key) !== ticket.generation) return 'stale';+ values.set(ticket.key, value);+ if (pending.get(ticket.key) === ticket.generation) pending.delete(ticket.key);+ publish();+ return 'landed';+ },+ settleRemoval: (ticket: EntityGeneration<K>): 'landed' | 'stale' => {+ if (generations.get(ticket.key) !== ticket.generation) return 'stale';+ values.delete(ticket.key);+ if (pending.get(ticket.key) === ticket.generation) pending.delete(ticket.key);+ publish();+ return 'landed';+ },+ abandon: (ticket: EntityGeneration<K>): void => {+ if (pending.get(ticket.key) === ticket.generation) pending.delete(ticket.key);+ },+ settleSnapshot: (snapshotGeneration: number, incoming: readonly T[]): void => {+ const incomingByKey = new Map(incoming.map((value) => [keyOf(value), value]));+ const keys = new Set([...values.keys(), ...incomingByKey.keys()]);+ for (const key of keys) {+ if (pending.has(key) || (generations.get(key) ?? 0) > snapshotGeneration) continue;+ generations.set(key, snapshotGeneration);+ const value = incomingByKey.get(key);+ if (value === undefined) values.delete(key);+ else values.set(key, value);+ }+ publish();+ },+ /** Lands only the named snapshot rows. Callers use this for a scoped+ * reconciliation so an absent, concurrently mutating sibling is untouched. */+ settleSnapshotEntries: (snapshotGeneration: number, incoming: readonly T[]): void => {+ for (const value of incoming) {+ const key = keyOf(value);+ if (pending.has(key) || (generations.get(key) ?? 0) > snapshotGeneration) continue;+ generations.set(key, snapshotGeneration);+ values.set(key, value);+ }+ publish();+ },+ landLatest: (value: T): void => {+ const ticket = begin(keyOf(value));+ if (generations.get(ticket.key) === ticket.generation) {+ values.set(ticket.key, value);+ pending.delete(ticket.key);+ publish();+ }+ },+ };+};+/** Maps a potentially large read set without allowing it to fan out unbounded. */export async function mapWithConcurrency<T, R>(items: readonly T[],@@ -90,11 +196,6 @@ export const agentsWithEcho = (echoed: AgentSupply,): AgentSupply[] => agents.map((agent) => (agent.backend === echoed.backend ? echoed : agent));-/** Takes one source mutation echo into the already-loaded inventory without- * letting that single-row response answer which other rows exist. */-export const sourcesWithEcho = (sources: readonly Source[], echoed: Source): Source[] =>- sources.map((source) => (source.id === echoed.id ? echoed : source));-// ── A write that outlives the drawer that issued it ────────────────────────/*** Which keys have a write outstanding, where 「outstanding」 spans the read-back@@ -197,13 +298,9 @@ export type PendingWrite = {// colliding with ['a b'].const sig = (parts: readonly (string | number | boolean)[]): string => parts.join('\u0000');-/** 来源顺序 drawer: the per-backend policy + ordered subset it edits. */+/** Source-order drawer: the exact ordered subset it edits. */export const savedSourcesKey = (agent: AgentSupply): string =>- sig([agent.sources?.policy ?? 'follow', ...(agent.sources?.order ?? [])]);--/** 映射 drawer: the stored overrides its draft is seeded from. */-export const savedMappingsKey = (agent: AgentSupply): string =>- sig((agent.mappings ?? []).flatMap((m) => [m.builtin_id, m.target_model_id, m.enabled]));+ sig(agent.sources?.order ?? []);/** OpenCode 模型菜单 drawer: the stored view + checked identifiers. */export const savedMenuKey = (menu: AgentMenu | null | undefined): string =>diff --git a/ui/src/components/settings/models/chips.tsx b/ui/src/components/settings/models/chips.tsxindex c14886021..94858d8bd 100644--- a/ui/src/components/settings/models/chips.tsx+++ b/ui/src/components/settings/models/chips.tsx@@ -3,7 +3,7 @@// 来源 and Agent bands stay visually consistent and the fixed-width chip// columns (frame 01r) align across rows.import * as React from 'react';-import { FlaskConical, Hourglass, TriangleAlert, Unplug, Zap } from 'lucide-react';+import { Hourglass, TriangleAlert, Unplug, Zap } from 'lucide-react';import { Badge } from '@/components/ui/badge';import { cn } from '@/lib/utils';@@ -37,7 +37,7 @@ export const BillingChip: React.FC<{const { t } = useTranslation();if (billing === 'monthly') {return (- <Badge variant="secondary" className={cn(BILLING_CHIP, 'bg-foreground/[0.03]', className)}>+ <Badge variant="secondary" className={cn(BILLING_CHIP, 'model-hub-fill-white-08', className)}>{t('settings.models.billing.monthly')}</Badge>);@@ -106,20 +106,9 @@ export const ModeChip: React.FC<{ mode: AgentMode }> = ({ mode }) => {{t('settings.models.mode.hub')}</Badge>) : (- <Badge variant="secondary" className={cn(base, 'bg-foreground/[0.03]')}>+ <Badge variant="secondary" className={cn(base, 'model-hub-fill-white-08')}><Unplug className="size-3 sm:hidden" />{t('settings.models.mode.direct')}</Badge>);};--/** 实验 — marks a consent-gated hub-held subscription source. */-export const ExperimentalChip: React.FC = () => {- const { t } = useTranslation();- return (- <Badge variant="warning" className="rounded-md px-2 py-0.5 text-[10px] font-medium">- <FlaskConical className="size-3" />- {t('settings.models.experimental')}- </Badge>- );-};diff --git a/ui/src/components/settings/models/collectionReadAuthority.test.ts b/ui/src/components/settings/models/collectionReadAuthority.test.tsnew file mode 100644index 000000000..6e80d59c9--- /dev/null+++ b/ui/src/components/settings/models/collectionReadAuthority.test.ts@@ -0,0 +1,58 @@+import { readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it, vi } from 'vitest';++import { createAgentCollectionReadAuthority } from './collectionReadAuthority';+import type { AgentSupply } from './types';++const agent = (mode: AgentSupply['mode']): AgentSupply => ({+ backend: 'claude',+ cli_present: true,+ mode,+ menu_kind: 'fixed',+ sources: mode === 'hub' ? { order: [], eligibility: [] } : null,+});++const deferred = <T,>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+};++const productFiles = (directory: string): string[] => readdirSync(directory, { withFileTypes: true })+ .flatMap((entry) => {+ const path = join(directory, entry.name);+ if (entry.isDirectory()) return productFiles(path);+ return /\.(?:ts|tsx)$/.test(entry.name) && !/\.test\.(?:ts|tsx)$/.test(entry.name) ? [path] : [];+ });++describe('collection read authority', () => {+ it('rejects an older Agent collection response after a newer generation lands', async () => {+ const older = deferred<AgentSupply[]>();+ const newer = deferred<AgentSupply[]>();+ const api = {+ listAgents: vi.fn()+ .mockReturnValueOnce(older.promise)+ .mockReturnValueOnce(newer.promise),+ };+ const authority = createAgentCollectionReadAuthority(api);++ const first = authority.read();+ const second = authority.read();+ newer.resolve([agent('hub')]);+ await expect(second).resolves.toEqual({ kind: 'current', value: [agent('hub')] });++ older.resolve([agent('direct')]);+ await expect(first).resolves.toEqual({ kind: 'stale' });+ });++ it('keeps collection endpoints private to the generation authority', () => {+ const allowed = new Set(['collectionReadAuthority.ts', 'modelsApi.ts']);+ const violations = productFiles(__dirname).flatMap((path) => {+ if (allowed.has(path.split('/').at(-1) ?? '')) return [];+ return /\.list(?:Agents|Sources)\s*\(/.test(readFileSync(path, 'utf8')) ? [path] : [];+ });++ expect(violations).toEqual([]);+ });+});diff --git a/ui/src/components/settings/models/collectionReadAuthority.ts b/ui/src/components/settings/models/collectionReadAuthority.tsnew file mode 100644index 000000000..e3fbbed46--- /dev/null+++ b/ui/src/components/settings/models/collectionReadAuthority.ts@@ -0,0 +1,53 @@+import { modelsApi, type ModelsApi } from './modelsApi';+import type { AgentSupply, Source } from './types';++export type CollectionReadResult<T> =+ | { kind: 'current'; value: T }+ | { kind: 'stale' };++export type CollectionReadAuthority<T> = {+ read: () => Promise<CollectionReadResult<T>>;+ readValue: () => Promise<T>;+ invalidate: () => void;+};++class SupersededCollectionRead extends Error {+ constructor() {+ super('Collection read was superseded');+ this.name = 'SupersededCollectionRead';+ }+}++/** The only owner allowed to call a collection endpoint. Every read carries a+ * generation, including reconciliation reads that do not directly render. */+const createCollectionReadAuthority = <T>(readCollection: () => Promise<T>): CollectionReadAuthority<T> => {+ let generation = 0;+ const read = async (): Promise<CollectionReadResult<T>> => {+ const mine = ++generation;+ try {+ const value = await readCollection();+ return mine === generation ? { kind: 'current', value } : { kind: 'stale' };+ } catch (error) {+ if (mine !== generation) return { kind: 'stale' };+ throw error;+ }+ };++ return {+ read,+ readValue: async () => {+ const result = await read();+ if (result.kind === 'stale') throw new SupersededCollectionRead();+ return result.value;+ },+ invalidate: () => { generation += 1; },+ };+};++export const createSourceCollectionReadAuthority = (+ api: Pick<ModelsApi, 'listSources'> = modelsApi,+): CollectionReadAuthority<Source[]> => createCollectionReadAuthority(() => api.listSources());++export const createAgentCollectionReadAuthority = (+ api: Pick<ModelsApi, 'listAgents'> = modelsApi,+): CollectionReadAuthority<AgentSupply[]> => createCollectionReadAuthority(() => api.listAgents());diff --git a/ui/src/components/settings/models/copyAgreement.test.ts b/ui/src/components/settings/models/copyAgreement.test.tsindex b528bbce1..b37e6ff53 100644--- a/ui/src/components/settings/models/copyAgreement.test.ts+++ b/ui/src/components/settings/models/copyAgreement.test.ts@@ -6,27 +6,22 @@// translated from reads correctly and the English silently did not.//// The reported string was not the class. The same page also wrote 「{{count}} agents-// have no supply」, which breaks at the MOST common count — one. So the rule below is-// TOTAL rather than a list of known-bad keys; that is the only way it catches copy-// that does not exist yet. Two shapes, two scopes:+// have no supply」, which breaks at the MOST common count — one. The final UI copy+// register resolves that class with i18next plural families. The rule below is TOTAL+// rather than a list of known-bad keys; that is the only way it catches copy that does+// not exist yet. Two shapes, two scopes://// 1. a list placeholder in front of a singular verb — checked over the WHOLE// bundle, because no string anywhere passes a joined list to a singular verb.-// 2. `{{count}}` in front of a plural noun — checked over `settings.models`, this-// page's own copy, with no allowances. The wider bundle has a long-standing-// 「{{count}} items」 habit across File Browser, Vaults, Skills and Chat;-// rewriting forty strings on other surfaces is not this lane's change to make,-// so the rule stops at the page boundary rather than carrying an exception list.-//-// Neither shape is fixed with a plural key. This bundle has no `_one`/`_other` keys-// at all, and adding them would mean dead `_one` entries in zh (whose plural rule has-// only `other`) — a trap for the next translator, and a break of the zh/en key-// correspondence that `supplyCopyRedline.test.ts` guards. `attribution.unassigned`-// and `order.groupDisabled` already show the cheaper answer that this file enforces:-// word it so the subject's number stops mattering.+// 2. every `{{count}}` key under `settings.models` belongs to a complete+// `_one`/`_other` family. Both locale files carry both leaves; zh deliberately+// repeats the value so locale parity remains a plain set equality.+import { readFileSync } from 'node:fs';import { describe, expect, it } from 'vitest';import en from '../../../i18n/en.json';+import zh from '../../../i18n/zh.json';+import { BACKEND_ADOPTION_VENDOR_KEY } from './vendorMeta';/** Placeholders a join can fill with more than one item. */const LIST_PLACEHOLDER = /\{\{(?:names|models|agents|sources|backends|list|skipped)\}\}/;@@ -39,14 +34,9 @@ const LIST_PLACEHOLDER = /\{\{(?:names|models|agents|sources|backends|list|skippconst SINGULAR_VERB =/\{\{(?:names|models|agents|sources|backends|list|skipped)\}\}\s+(?:has|is|was|does|hasn't|isn't|wasn't|doesn't)\b/i;-/**- * `{{count}}` followed by a noun that has already committed to plural.- *- * `{{count}} model(s)` passes on purpose: it is correct at every count, and it is- * what the rest of this subtree already writes (`migration.applied`,- * `sourceActions.refreshed`, `migrationBanner.body`).- */-const PLURAL_NOUN = /\{\{count\}\}\s+(?:more\s+)?[a-z]+s\b/i;+const COUNT = /\{\{count\}\}/;+const PARENTHESIZED_PLURAL = /\b[a-z]+\(s\)/i;+const PLURAL_SUFFIX = /_(one|other)$/;type Leaf = { key: string; text: string };@@ -64,9 +54,9 @@ describe('English copy agrees with the number of things it interpolates', () =>it('walks a non-trivial bundle, so the rules have something to check', () => {// Guards the walks themselves: a renamed namespace would otherwise make every// assertion below pass over an empty list.- expect(all.filter((l) => LIST_PLACEHOLDER.test(l.text)).length).toBeGreaterThan(0);- expect(models.length).toBeGreaterThan(100);- expect(models.map((l) => l.key)).toContain('statusPill.interrupted');+ expect(all.some((leaf) => LIST_PLACEHOLDER.test(leaf.text))).toBe(true);+ expect(models.some((leaf) => COUNT.test(leaf.text))).toBe(true);+ expect(models.some((leaf) => PLURAL_SUFFIX.test(leaf.key))).toBe(true);});it('never gives a joined list a singular verb, anywhere in the bundle', () => {@@ -74,8 +64,34 @@ describe('English copy agrees with the number of things it interpolates', () =>expect(broken.map((l) => `${l.key}: ${l.text}`)).toEqual([]);});- it('never gives a count a plural noun on the Models page', () => {- const broken = models.filter((l) => PLURAL_NOUN.test(l.text));- expect(broken.map((l) => `${l.key}: ${l.text}`)).toEqual([]);+ it.each([['en', en], ['zh', zh]] as const)('gives every Models count a complete plural family in %s', (_lng, bundle) => {+ const localized = leaves(bundle.settings.models);+ const byKey = new Map(localized.map((leaf) => [leaf.key, leaf.text]));+ const bareCounts = localized.filter((leaf) => COUNT.test(leaf.text) && !PLURAL_SUFFIX.test(leaf.key));+ const orphaned = localized.filter((leaf) => {+ const match = leaf.key.match(PLURAL_SUFFIX);+ if (!match) return false;+ const base = leaf.key.replace(PLURAL_SUFFIX, '');+ return !byKey.has(`${base}_one`) || !byKey.has(`${base}_other`);+ });+ expect(bareCounts.map((leaf) => leaf.key)).toEqual([]);+ expect(orphaned.map((leaf) => leaf.key)).toEqual([]);+ });++ it('uses real plural families instead of parenthesized English plurals', () => {+ const broken = models.filter((leaf) => PARENTHESIZED_PLURAL.test(leaf.text));+ expect(broken.map((leaf) => `${leaf.key}: ${leaf.text}`)).toEqual([]);+ });++ it('resolves gateway-adoption vendor interpolation through locale keys', () => {+ const component = readFileSync(new URL('./EnableGatewayDialog.tsx', import.meta.url), 'utf8');+ const vendorKeys = new Set(Object.values(BACKEND_ADOPTION_VENDOR_KEY));+ expect(component).toContain('BACKEND_ADOPTION_VENDOR_KEY[agent.backend]');+ expect(new Set(Object.keys(en.settings.models.adopt.vendor))).toEqual(vendorKeys);+ expect(new Set(Object.keys(zh.settings.models.adopt.vendor))).toEqual(vendorKeys);+ for (const key of vendorKeys) {+ expect(en.settings.models.adopt.vendor[key]).toBeTruthy();+ expect(zh.settings.models.adopt.vendor[key]).toBeTruthy();+ }});});diff --git a/ui/src/components/settings/models/dialogFields.test.tsx b/ui/src/components/settings/models/dialogFields.test.tsxindex 38ba4783f..46dbd81d9 100644--- a/ui/src/components/settings/models/dialogFields.test.tsx+++ b/ui/src/components/settings/models/dialogFields.test.tsx@@ -90,16 +90,14 @@ describe('the class: the models dialogs do not hand-roll a field', () => {it('sweeps a non-trivial file set', () => {expect(files.length).toBeGreaterThan(10);- expect(files).toContain('ReplaceKeyDialog.tsx');+ expect(files).toContain('AddApiKeyDialog.tsx');});/*** An upper bound, not an equality: a NEW file that writes its own `<label>` is- * the regression, while `menus/AddCustomModelDialog.tsx` is a pre-existing local- * copy from another lane (disclosed in the PR, not silently rewritten here) and- * this list must not start failing on the day someone deletes it.+ * the regression. The shared field itself is the only allowed owner.*/- const MAY_WRITE_A_LABEL = ['dialogFields.tsx', join('menus', 'AddCustomModelDialog.tsx')];+ const MAY_WRITE_A_LABEL = ['dialogFields.tsx'];it('leaves <label> to the shared field', () => {const handRolled = files.filter((f) => /<label\b/.test(read(f)));diff --git a/ui/src/components/settings/models/dialogFields.tsx b/ui/src/components/settings/models/dialogFields.tsxindex 8c1b32b64..4eb684f19 100644--- a/ui/src/components/settings/models/dialogFields.tsx+++ b/ui/src/components/settings/models/dialogFields.tsx@@ -18,9 +18,10 @@ import { cn } from '@/lib/utils';/** Never exported: a label that does not name a control is the defect above, so* `htmlFor` is required and `Field` is the only thing that can supply it. */-const FieldLabel: React.FC<{ htmlFor: string; mono?: boolean; children: React.ReactNode }> = ({+const FieldLabel: React.FC<{ htmlFor: string; mono?: boolean; className?: string; children: React.ReactNode }> = ({htmlFor,mono,+ className,children,}) => (<label@@ -28,8 +29,9 @@ const FieldLabel: React.FC<{ htmlFor: string; mono?: boolean; children: React.ReclassName={cn('text-muted',mono- ? 'font-mono text-[11px] font-medium uppercase tracking-wide'+ ? 'font-mono text-[11px] font-medium uppercase tracking-normal': 'text-[12px] font-semibold text-foreground',+ className,)}>{children}@@ -62,15 +64,18 @@ export const Field: React.FC<{mono?: boolean;icon?: React.ComponentType<{ className?: string }>;hint?: React.ReactNode;-}> = ({ label, children, mono, icon, hint }) => {+ className?: string;+ labelClassName?: string;+ hintClassName?: string;+}> = ({ label, children, mono, icon, hint, className, labelClassName, hintClassName }) => {const id = React.useId();return (- <div className="flex flex-col gap-2">- <FieldLabel htmlFor={id} mono={mono}>+ <div className={cn('flex flex-col gap-2', className)}>+ <FieldLabel htmlFor={id} mono={mono} className={labelClassName}>{label}</FieldLabel>{icon ? <IconField icon={icon}>{children(id)}</IconField> : children(id)}- {hint ? <p className="text-[12px] leading-relaxed text-muted">{hint}</p> : null}+ {hint ? <p className={cn('text-[12px] leading-relaxed text-muted', hintClassName)}>{hint}</p> : null}</div>);};diff --git a/ui/src/components/settings/models/eligibility.test.ts b/ui/src/components/settings/models/eligibility.test.tsindex aaabb5aed..c7c208a2e 100644--- a/ui/src/components/settings/models/eligibility.test.ts+++ b/ui/src/components/settings/models/eligibility.test.ts@@ -26,7 +26,6 @@ const agent = (sources: AgentSupply['sources']): Agent => ({ sources });describe('eligibilityOf', () => {it('returns the server’s verdict verbatim, reason included', () => {const a = agent({- policy: 'custom',order: [],eligibility: [{ source_id: 'src_ok', eligible: true, reason_key: null },@@ -41,7 +40,7 @@ describe('eligibilityOf', () => {});it('grays out an ineligible row whose reason the payload omitted', () => {- const a = agent({ policy: 'custom', order: [], eligibility: [{ source_id: 'src_x', eligible: false }] });+ const a = agent({ order: [], eligibility: [{ source_id: 'src_x', eligible: false }] });expect(eligibilityOf(a, 'src_x')).toEqual({ eligible: false, reasonKey: null });});@@ -49,7 +48,7 @@ describe('eligibilityOf', () => {// when the optional field is missing (or when a source is created between the// /sources and /agents reads).it('trusts the order when `eligibility` does not mention the id', () => {- const a = agent({ policy: 'follow', order: ['src_in'] });+ const a = agent({ order: ['src_in'] });expect(eligibilityOf(a, 'src_in')).toEqual({ eligible: true, reasonKey: null });expect(eligibilityOf(a, 'src_out')).toEqual({ eligible: false, reasonKey: null });});@@ -69,7 +68,6 @@ describe('offCurrentModelChain', () => {// markers the chain strip has always been right to draw.it('speaks only when the server says false', () => {const a = agent({- policy: 'follow',order: ['src_on', 'src_off', 'src_unknown'],eligibility: [{ source_id: 'src_on', eligible: true, in_current_model_chain: true },@@ -83,7 +81,7 @@ describe('offCurrentModelChain', () => {});it('is silent for a row the payload never mentions, and in Direct mode', () => {- expect(offCurrentModelChain(agent({ policy: 'follow', order: ['src_a'] }), 'src_a')).toBe(false);+ expect(offCurrentModelChain(agent({ order: ['src_a'] }), 'src_a')).toBe(false);expect(offCurrentModelChain(agent(null), 'src_a')).toBe(false);});});@@ -92,7 +90,6 @@ describe('eligibleSources', () => {it('keeps inventory order and drops what the server refused', () => {const sources = [source('src_a'), source('src_b'), source('src_c')];const a = agent({- policy: 'custom',order: ['src_c'],eligibility: [{ source_id: 'src_a', eligible: true, reason_key: null },diff --git a/ui/src/components/settings/models/eligibility.ts b/ui/src/components/settings/models/eligibility.tsindex cac6909e1..4f131a011 100644--- a/ui/src/components/settings/models/eligibility.ts+++ b/ui/src/components/settings/models/eligibility.ts@@ -3,10 +3,9 @@//// This replaces `isSourceEligible` in `menus/identifiers.ts`, a UI mirror of the// backend predicate that was escalated at review time and is deleted with this-// module. The mirror could not be right: eligibility depends on the-// `subscription_hub_experimental` flag and on recorded consent, neither of which-// the UI can see, so it was guaranteed to drift and to offer rows the live API-// rejects. Contract v3 publishes `sources.eligibility` on+// module. The mirror could not be right: eligibility is server-owned inventory+// state, so a client reconstruction was guaranteed to drift and offer rows the+// live API rejects. Contract v5 publishes `sources.eligibility` on// `GET /api/models/agents`, and this file is the only place the UI reads it.import type { AgentSupply, EligibilityReasonKey, ProcessAvailabilityReason, Source } from './types';@@ -20,7 +19,7 @@ const INELIGIBLE: Eligibility = { eligible: false, reasonKey: null };** Total over every id, including one the payload does not mention:* - `sources === null` — Direct mode. Hub eligibility is undefined there and no- * Hub surface (order drawer, model menu, mapping targets) is reachable.+ * Hub surface (order drawer, model menu, route targets) is reachable.* - listed in `eligibility` — the server's answer, verbatim.* - absent from `eligibility` but present in `order` — the server validated it* into the order and §4.4 forbids an ineligible id there, so it is eligible@@ -93,7 +92,7 @@ export function offCurrentModelChain(agent: Pick<AgentSupply, 'sources'>, sourcereturn entry?.in_current_model_chain === false;}-/** The subset of `sources` this Agent may use — the menu/mapping surfaces' input. */+/** The subset of `sources` this Agent may use — the menu/route surfaces' input. */export function eligibleSources(sources: Source[], agent: Pick<AgentSupply, 'sources'>): Source[] {return sources.filter((s) => eligibilityOf(agent, s.id).eligible);}diff --git a/ui/src/components/settings/models/eventFeed.test.ts b/ui/src/components/settings/models/eventFeed.test.tsindex be99ff001..fb36c2c96 100644--- a/ui/src/components/settings/models/eventFeed.test.ts+++ b/ui/src/components/settings/models/eventFeed.test.ts@@ -200,30 +200,37 @@ describe('feedAfterTailRead — 加载更早, and the first page at mount', () =describe('the page reads the feed through this owner', () => {const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');+ const firstPaint = readFileSync(join(__dirname, 'firstPaintRegions.ts'), 'utf8');it('re-reads events in the shared post-write refresh', () => {// The whole point: the refresh every mutation site already calls is what has// to move the feed, not a probe-only twin bolted onto one call site.- expect(page).toMatch(/refreshAuthority\.run\([\s\S]*?modelsApi\.listEvents\(EVENT_PAGE\)/);- expect(page).toMatch(/if \(headEvents\) setFeed\(\(prev\) => feedAfterHeadRead\(prev, headEvents\)\)/);+ expect(page).toMatch(/const refresh = React\.useCallback[\s\S]*?void refreshEventHead\(\)[\s\S]*?refreshAuthority\.run/);+ expect(page).toMatch(/eventReadAuthority\.run[\s\S]*?modelsApi\.listEvents\(EVENT_PAGE\)/);+ expect(page).toMatch(/setEventsRead[\s\S]*?foldRegionRead<ResolutionEvent\[\],[\s\S]*?\(incoming,[\s\S]*?feedAfterHeadRead\(previousFeed, freshEvents\)/);+ expect(page).toMatch(/feedAfterTailRead\(emptyFeed, freshEvents, EVENT_PAGE, null\)/);});it('lets the ancillary feed read fail without losing the rows', () => {- // A slow or broken /events must not veto the supply refresh: joined bare into- // 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<ModelSurfaceLanding>/);- // 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/);+ // A slow or broken /events must not enter the operational first-paint barrier.+ const landing = page.slice(page.indexOf('const readSurfaceLanding'), page.indexOf('\n\nconst surfaceLandingFailed'));+ expect(landing).not.toMatch(/listEvents|events/);+ expect(page).toMatch(/createLatestAsyncAuthority<RegionRead<ResolutionEvent\[\]>>/);+ expect(page).toMatch(/createLatestAsyncAuthority<AuthorizedSurfaceLanding>/);+ expect(page).toMatch(/sourceEntityAuthority\.beginSnapshot\(\)/);+ expect(page).toMatch(/foldRegionRead<Source\[\],[\s\S]*?\(landing\.sources,[\s\S]*?sourceEntityAuthority\.settleSnapshot\(sourceSnapshot, freshSources\)/);+ // Region reads also settle independently: a failed source list cannot erase+ // a successful backend projection, and vice versa.+ expect(firstPaint).toMatch(/\[K in keyof FirstPaintRegionValues\]: RegionRead<FirstPaintRegionValues\[K\]>/);+ expect(firstPaint).toMatch(/satisfies Record<keyof FirstPaintRegionValues, string>/);});it('moves rows and end-of-feed together, through the owners', () => {// One state, so no transition can move the rows and leave the flag behind.- expect(page).toMatch(/const \[feed, setFeed\] = React\.useState<EventFeed>\(emptyFeed\)/);- expect(page).toMatch(/setFeed\(\(prev\) => feedAfterTailRead\(prev, e, EVENT_PAGE, null\)\)/);- expect(page).toMatch(/setFeed\(\(prev\) => feedAfterTailRead\(prev, page, EVENT_PAGE, oldest\)\)/);+ expect(page).toMatch(/const \[eventsRead, setEventsRead\] = React\.useState<RegionRead<EventFeed>>/);+ expect(page).toMatch(/feedAfterTailRead\(emptyFeed, freshEvents, EVENT_PAGE, null\)/);+ expect(page).toMatch(/setEventsRead\(\(previous\) => readyRegion\(feedAfterTailRead\(foldRegionRead\(previous,[\s\S]*?events, EVENT_PAGE, cursor\)\)\)/);+ expect(page).not.toMatch(/\bregionData\s*\(/);// Nothing left that could set one half on its own.expect(page).not.toMatch(/setEventsExhausted|setEvents\(/);// And no hand-rolled dedupe or page-length test outside the owners.@@ -232,13 +239,13 @@ describe('the page reads the feed through this owner', () => {});it('reads 加载更早 off the same feed it renders', () => {- expect(page).toMatch(/hasMore=\{!feed\.exhausted\}/);- expect(page).toMatch(/events=\{feed\.events\}/);+ expect(page).toMatch(/events=\{eventsRead\}/);+ expect(page).toMatch(/sources=\{sourcesRead\}/);// Through the owner, and the SAME cursor is handed back to the merge — the// request and the answer have to be about one row for the check to mean// anything, which a second hand-rolled read of the tail would not guarantee.- expect(page).toMatch(/const oldest = feedTailCursor\(feed\)/);- expect(page).toMatch(/modelsApi\.listEvents\(EVENT_PAGE, oldest\)/);+ expect(page).toMatch(/const cursor = feedTailCursor\(feed\)/);+ expect(page).toMatch(/modelsApi\.listEvents\(EVENT_PAGE, cursor\)/);expect(page).not.toMatch(/feed\.events\[feed\.events\.length - 1\]/);});});diff --git a/ui/src/components/settings/models/featureFlags.ts b/ui/src/components/settings/models/featureFlags.tsindex 85c0c5514..057839cdd 100644--- a/ui/src/components/settings/models/featureFlags.ts+++ b/ui/src/components/settings/models/featureFlags.ts@@ -20,12 +20,3 @@ export const modelHubEnabledFromConfig = (config: unknown): boolean => {* to 'mock' only for hermetic pixel/screenshot runs with no backend.)*/export const MODELS_API_MODE: 'mock' | 'live' = 'live';--/**- * Offers the consent-gated hub-held subscription option (`subscription_hub_- * experimental`, spec §4.1/§7) inside the connect-subscription dialog. OFF by- * default: subscriptions connect via the sanctioned native_cli channel only.- * When ON, choosing "hub" for a subscription requires the ban-risk consent- * dialog (copy from S2 §9) and marks the resulting source 实验.- */-export const SUBSCRIPTION_HUB_EXPERIMENTAL = false;diff --git a/ui/src/components/settings/models/firstPaintRegions.ts b/ui/src/components/settings/models/firstPaintRegions.tsnew file mode 100644index 000000000..b30a56900--- /dev/null+++ b/ui/src/components/settings/models/firstPaintRegions.ts@@ -0,0 +1,38 @@+import { readRegion, type RegionRead } from './regionRead';+import type { AgentSupply, RuntimeDependency, Source } from './types';++/**+ * The operational overview cannot wait for ancillary history or per-model+ * projections. Every member names why it owns a place in the first-paint+ * barrier, so adding another member requires an explicit policy decision.+ */+type FirstPaintRegionValues = {+ sources: Source[];+ supply: AgentSupply[];+ runtime: RuntimeDependency;+};++export const FIRST_PAINT_REGION_WHITELIST = {+ sources: 'draws the source inventory',+ supply: 'draws backend supply groups',+ runtime: 'determines runtime availability',+} as const satisfies Record<keyof FirstPaintRegionValues, string>;++export type FirstPaintRegionReaders = {+ [K in keyof FirstPaintRegionValues]: () => Promise<FirstPaintRegionValues[K]>;+};++export type SurfaceLanding = {+ [K in keyof FirstPaintRegionValues]: RegionRead<FirstPaintRegionValues[K]>;+};++export const readFirstPaintRegions = async (+ readers: FirstPaintRegionReaders,+): Promise<SurfaceLanding> => {+ const keys = Object.keys(FIRST_PAINT_REGION_WHITELIST) as (keyof FirstPaintRegionReaders)[];+ const entries = await Promise.all(keys.map(async (key) => {+ const reader = readers[key] as () => Promise<unknown>;+ return [key, await readRegion(reader)] as const;+ }));+ return Object.fromEntries(entries) as SurfaceLanding;+};diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.tsnew file mode 100644index 000000000..2440be817--- /dev/null+++ b/ui/src/components/settings/models/gatewayAdoption.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it, vi } from 'vitest';++import { createAgentCollectionReadAuthority } from './collectionReadAuthority';+import { resumeGatewayAdoption } from './gatewayAdoption';+import type { ModelsApi } from './modelsApi';+import type { AgentSupply, RuntimeDependency } from './types';++const agent = (mode: AgentSupply['mode']): AgentSupply => ({+ backend: 'claude',+ cli_present: true,+ mode,+ menu_kind: 'fixed',+ sources: { order: [], eligibility: [] },+});++const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({+ contract_version: 5,+ manifest: { name: 'cliproxyapi', version: '1', source_sha: 'a'.repeat(40), assets: [] },+ status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },+});++type GatewayClient = Pick<ModelsApi, 'listAgents' | 'getRuntimeStatus' | 'installRuntime' | 'startRuntime' | 'setAgentMode'>;++const api = (overrides: Partial<GatewayClient> = {}): GatewayClient => ({+ listAgents: vi.fn().mockResolvedValue([agent('direct')]),+ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('ok')),+ installRuntime: vi.fn().mockResolvedValue(runtime('not_started')),+ startRuntime: vi.fn().mockResolvedValue(runtime('ok')),+ setAgentMode: vi.fn().mockResolvedValue(agent('hub')),+ ...overrides,+});++const adopt = (+ client: ReturnType<typeof api>,+ intervalMs?: number,+) => resumeGatewayAdoption(client, createAgentCollectionReadAuthority(client), 'claude', intervalMs);++describe('resumeGatewayAdoption', () => {+ it('treats degraded as already started and goes straight to the mode PATCH', async () => {+ const client = api({ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('degraded')) });++ await expect(adopt(client)).resolves.toMatchObject({ ok: true });++ expect(client.startRuntime).not.toHaveBeenCalled();+ expect(client.setAgentMode).toHaveBeenCalledWith('claude', 'hub');+ });++ it('returns the mode PATCH AgentSupply with its newly materialized native source', async () => {+ const adopted = { ...agent('hub'), sources: { order: ['src_native'], eligibility: [] } };+ const client = api({ setAgentMode: vi.fn().mockResolvedValue(adopted) });++ await expect(adopt(client)).resolves.toMatchObject({+ ok: true,+ agent: { mode: 'hub', sources: { order: ['src_native'] } },+ });+ });++ it('starts an idle runtime before switching the one backend', async () => {+ const client = api({ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('not_started')) });++ await expect(adopt(client)).resolves.toMatchObject({ ok: true });++ expect(client.startRuntime).toHaveBeenCalledOnce();+ expect(client.setAgentMode).toHaveBeenCalledWith('claude', 'hub');+ });++ it('installs, starts, and switches in the order of the first unproven step', async () => {+ const calls: string[] = [];+ const client = api({+ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('not_installed')),+ installRuntime: vi.fn().mockImplementation(async () => { calls.push('install'); return runtime('not_started'); }),+ startRuntime: vi.fn().mockImplementation(async () => { calls.push('start'); return runtime('ok'); }),+ setAgentMode: vi.fn().mockImplementation(async () => { calls.push('mode'); return agent('hub'); }),+ });++ await expect(adopt(client, 0)).resolves.toMatchObject({ ok: true });++ expect(calls).toEqual(['install', 'start', 'mode']);+ });++ it('keeps a terminal install failure in the install step and never sends the mode PATCH', async () => {+ const client = api({+ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('not_installed')),+ installRuntime: vi.fn().mockResolvedValue(runtime('not_installed')),+ });++ await expect(adopt(client)).resolves.toEqual({+ ok: false,+ failure: { step: 'install', reason: 'unknown' },+ runtime: runtime('not_installed'),+ });++ expect(client.startRuntime).not.toHaveBeenCalled();+ expect(client.setAgentMode).not.toHaveBeenCalled();+ });++ it('re-reads agents after a lost mode response and accepts the committed hub mode', async () => {+ const client = api({+ listAgents: vi.fn()+ .mockResolvedValueOnce([agent('direct')])+ .mockResolvedValueOnce([agent('hub')]),+ setAgentMode: vi.fn().mockRejectedValue(new TypeError('response lost')),+ });++ await expect(adopt(client)).resolves.toMatchObject({+ ok: true,+ agent: { mode: 'hub' },+ });++ expect(client.listAgents).toHaveBeenCalledTimes(2);+ });++ it('closes an already-committed retry without touching runtime or mode', async () => {+ const client = api({ listAgents: vi.fn().mockResolvedValue([agent('hub')]) });++ await expect(adopt(client)).resolves.toMatchObject({ ok: true });++ expect(client.getRuntimeStatus).not.toHaveBeenCalled();+ expect(client.startRuntime).not.toHaveBeenCalled();+ expect(client.setAgentMode).not.toHaveBeenCalled();+ });+});diff --git a/ui/src/components/settings/models/gatewayAdoption.ts b/ui/src/components/settings/models/gatewayAdoption.tsnew file mode 100644index 000000000..df9c3094e--- /dev/null+++ b/ui/src/components/settings/models/gatewayAdoption.ts@@ -0,0 +1,115 @@+import { apiFailure, type ModelsApi } from './modelsApi';+import type { CollectionReadAuthority } from './collectionReadAuthority';+import { resumeInstallAndStartRuntime } from './runtimeLifecycle';+import type { AgentBackend, AgentSupply, RuntimeDependency } from './types';++export type GatewayAdoptionFailure = {+ step: 'install' | 'start' | 'mode' | 'read';+ request?: string;+ responseStatus?: number;+ reason: 'transport' | 'refused' | 'notReady' | 'unknown';+};++export type GatewayAdoptionResult =+ | { ok: true; agent: AgentSupply; runtime: RuntimeDependency | null }+ | { ok: false; failure: GatewayAdoptionFailure; runtime: RuntimeDependency | null };++const classifiedFailure = (+ error: unknown,+ step: GatewayAdoptionFailure['step'],+ request?: string,+): GatewayAdoptionFailure => {+ const failure = apiFailure(error);+ if (!failure || !failure.serverNamed) {+ return { step, request, responseStatus: failure?.responseStatus, reason: 'transport' };+ }+ if (failure.code === 'engine_down' || failure.code === 'runtime_not_ready') {+ return { step, request, responseStatus: failure.responseStatus, reason: 'notReady' };+ }+ if (failure.responseStatus && failure.responseStatus >= 400 && failure.responseStatus < 500) {+ return { step, request, responseStatus: failure.responseStatus, reason: 'refused' };+ }+ return { step, request, responseStatus: failure.responseStatus, reason: 'unknown' };+};++const readFailure = (error: unknown, request: string): GatewayAdoptionResult => ({+ ok: false,+ failure: classifiedFailure(error, 'read', request),+ runtime: null,+});++const backendRow = (agents: AgentSupply[], backend: AgentBackend): AgentSupply | null =>+ agents.find((agent) => agent.backend === backend) ?? null;++/**+ * Reconciles before every attempt, so retry resumes at the first unproven step.+ * Installation, startup, and mode adoption are separate proven steps. A retry+ * resumes at the first step the server state has not already confirmed.+ */+export async function resumeGatewayAdoption(+ api: Pick<ModelsApi, 'getRuntimeStatus' | 'installRuntime' | 'startRuntime' | 'setAgentMode'>,+ agentReads: CollectionReadAuthority<AgentSupply[]>,+ backend: AgentBackend,+ installPollIntervalMs = 2_000,+): Promise<GatewayAdoptionResult> {+ let agents: AgentSupply[];+ try {+ agents = await agentReads.readValue();+ } catch (error) {+ return readFailure(error, 'GET /api/models/agents');+ }++ const current = backendRow(agents, backend);+ if (!current) {+ return {+ ok: false,+ failure: { step: 'read', request: 'GET /api/models/agents', reason: 'unknown' },+ runtime: null,+ };+ }+ if (current.mode === 'hub') return { ok: true, agent: current, runtime: null };++ let runtime: RuntimeDependency;+ try {+ runtime = await api.getRuntimeStatus();+ } catch (error) {+ return readFailure(error, 'GET /api/models/runtime/status');+ }++ const runtimeSequence = await resumeInstallAndStartRuntime(api, runtime, () => {}, installPollIntervalMs);+ if (runtimeSequence.runtime) runtime = runtimeSequence.runtime;+ if (runtimeSequence.failedStep === 'install') {+ return {+ ok: false,+ failure: { step: 'install', reason: 'unknown' },+ runtime,+ };+ }+ if (runtimeSequence.failedStep === 'start') {+ return {+ ok: false,+ failure: runtimeSequence.error+ ? classifiedFailure(runtimeSequence.error, 'start', 'POST /api/models/runtime/start')+ : { step: 'start', request: 'POST /api/models/runtime/start', reason: 'notReady' },+ runtime,+ };+ }++ try {+ const agent = await api.setAgentMode(backend, 'hub');+ return { ok: true, agent, runtime };+ } catch (error) {+ try {+ agents = await agentReads.readValue();+ const reconciled = backendRow(agents, backend);+ if (reconciled?.mode === 'hub') return { ok: true, agent: reconciled, runtime };+ } catch {+ // The write failure remains the best evidence; retry will run both reads.+ }+ return {+ ok: false,+ failure: classifiedFailure(error, 'mode', `PATCH /api/models/agents/${backend}/mode`),+ runtime,+ };+ }+}diff --git a/ui/src/components/settings/models/hopIdentity.test.ts b/ui/src/components/settings/models/hopIdentity.test.tsnew file mode 100644index 000000000..62861d496--- /dev/null+++ b/ui/src/components/settings/models/hopIdentity.test.ts@@ -0,0 +1,28 @@+import { readFileSync, readdirSync } from 'node:fs';+import { basename, dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';++import { equalHopIdentity, hopIdentity } from './hopIdentity';++const sourceDirectory = dirname(fileURLToPath(import.meta.url));+const implementationFiles = (): string[] => readdirSync(sourceDirectory, { withFileTypes: true })+ .filter((entry) => entry.isFile() && /\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name))+ .map((entry) => join(sourceDirectory, entry.name))+ .filter((file) => basename(file) !== 'hopIdentity.ts')+ .filter((file) => /(?:chain\.current|isTakeoverChain|currentChainLink|SupplyRelation)/.test(readFileSync(file, 'utf8')));++describe('hop identity', () => {+ it('compares the complete source/model tuple', () => {+ const hop = hopIdentity({ source_id: 'source-a', model_id: 'model-a' });+ expect(equalHopIdentity(hop, { source_id: 'source-a', model_id: 'model-a' })).toBe(true);+ expect(equalHopIdentity(hop, { source_id: 'source-a', model_id: 'model-b' })).toBe(false);+ expect(equalHopIdentity(hop, { source_id: 'source-b', model_id: 'model-a' })).toBe(false);+ });++ it('keeps hop-field equality inside the identity primitive', () => {+ const directComparison = /(?:\.(?:source_id|model_id)\s*(?:===|!==)|(?:===|!==)[^\n;]*\.(?:source_id|model_id))/;+ const offenders = implementationFiles().filter((file) => directComparison.test(readFileSync(file, 'utf8')));+ expect(offenders).toEqual([]);+ });+});diff --git a/ui/src/components/settings/models/hopIdentity.ts b/ui/src/components/settings/models/hopIdentity.tsnew file mode 100644index 000000000..505831acd--- /dev/null+++ b/ui/src/components/settings/models/hopIdentity.ts@@ -0,0 +1,22 @@+export type HopIdentity = Readonly<{+ source_id: string;+ model_id: string;+}>;++export const hopIdentity = (hop: HopIdentity): HopIdentity => ({+ source_id: hop.source_id,+ model_id: hop.model_id,+});++export const equalHopIdentity = (+ left: HopIdentity | null | undefined,+ right: HopIdentity | null | undefined,+): boolean => Boolean(+ left+ && right+ && left.source_id === right.source_id+ && left.model_id === right.model_id,+);++export const hopBelongsToSource = (hop: HopIdentity, sourceId: string): boolean =>+ hop.source_id === sourceId;diff --git a/ui/src/components/settings/models/localCalendar.test.ts b/ui/src/components/settings/models/localCalendar.test.tsnew file mode 100644index 000000000..51965ee3a--- /dev/null+++ b/ui/src/components/settings/models/localCalendar.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from 'vitest';++import { localCalendarRelation } from './localCalendar';++describe('local calendar relation', () => {+ it.each([+ ['spring-forward', '2026-03-09T00:30:00-04:00', '2026-03-08T00:30:00-05:00'],+ ['fall-back', '2026-11-02T00:30:00-05:00', '2026-11-01T00:30:00-04:00'],+ ])('labels the prior New York calendar day across %s', (_name, now, prior) => {+ expect(localCalendarRelation(new Date(prior), new Date(now), 'America/New_York')).toBe('yesterday');+ });+});diff --git a/ui/src/components/settings/models/localCalendar.ts b/ui/src/components/settings/models/localCalendar.tsnew file mode 100644index 000000000..b349a1db6--- /dev/null+++ b/ui/src/components/settings/models/localCalendar.ts@@ -0,0 +1,39 @@+type LocalCalendarDate = Readonly<{ year: number; month: number; day: number }>;++const dateParts = (date: Date, timeZone?: string): LocalCalendarDate => {+ if (timeZone === undefined) {+ return { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate() };+ }+ const values = Object.fromEntries(+ new Intl.DateTimeFormat('en-US', {+ timeZone,+ year: 'numeric',+ month: 'numeric',+ day: 'numeric',+ }).formatToParts(date).map(({ type, value }) => [type, value]),+ );+ return { year: Number(values.year), month: Number(values.month), day: Number(values.day) };+};++const previousDate = ({ year, month, day }: LocalCalendarDate): LocalCalendarDate => {+ const previous = new Date(Date.UTC(year, month - 1, day - 1));+ return {+ year: previous.getUTCFullYear(),+ month: previous.getUTCMonth() + 1,+ day: previous.getUTCDate(),+ };+};++const sameDate = (left: LocalCalendarDate, right: LocalCalendarDate): boolean =>+ left.year === right.year && left.month === right.month && left.day === right.day;++export const localCalendarRelation = (+ date: Date,+ now: Date,+ timeZone?: string,+): 'today' | 'yesterday' | 'other' => {+ const current = dateParts(now, timeZone);+ const candidate = dateParts(date, timeZone);+ if (sameDate(candidate, current)) return 'today';+ return sameDate(candidate, previousDate(current)) ? 'yesterday' : 'other';+};diff --git a/ui/src/components/settings/models/menus/AddCustomModelDialog.test.ts b/ui/src/components/settings/models/menus/AddCustomModelDialog.test.tsdeleted file mode 100644index 4b567dd1c..000000000--- a/ui/src/components/settings/models/menus/AddCustomModelDialog.test.ts+++ /dev/null@@ -1,28 +0,0 @@-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.tsxdeleted file mode 100644index 87d106812..000000000--- a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx+++ /dev/null@@ -1,328 +0,0 @@-// 添加自定义模型 (frame 08). Supplements a source's supply list with a model the-// auto-discovery missed. OpenCode callers show its provider-prefixed identifier;-// fixed-backend and source-list callers keep the upstream's raw model id. Persists-// through the Source-model subresource; 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';--import { Button } from '@/components/ui/button';-import { ConfirmDialog } from '@/components/ui/confirm-dialog';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';-import { Input } from '@/components/ui/input';-import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';-import { 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 { manualModelIdentifier, type StandardVendors } from './identifiers';--const FieldLabel: React.FC<{ mono?: boolean; children: React.ReactNode }> = ({ mono, children }) => (- <span- className={cn(- 'text-muted',- mono ? 'font-mono text-[11px] font-medium uppercase tracking-wide' : 'text-[12px] font-semibold text-foreground',- )}- >- {children}- </span>-);--const useEndpointSuffix = () => {- const { t } = useTranslation();- return (source: Source): string => {- if (source.kind === 'subscription') return ''; // subscriptions carry no endpoint suffix- // Reuse the 来源-list rule (base URL differs from the vendor's official one),- // so an official vendor edited to a relay reads as 自定义地址, not 官方地址.- return isCustomEndpoint(source)- ? (t('settings.models.source.customEndpoint') as string)- : (t('settings.models.source.officialEndpoint') as string);- };-};--const SourceSelect: React.FC<{- sources: Source[];- value: Source | null;- onChange: (source: Source) => void;- disabled?: boolean;-}> = ({ sources, value, onChange, disabled }) => {- const [open, setOpen] = React.useState(false);- const suffix = useEndpointSuffix();- const renderRow = (source: Source) => {- const { Icon, accent } = sourceVisual(source);- const suf = suffix(source);- return (- <>- <span className={cn('flex size-7 shrink-0 items-center justify-center rounded-md', ACCENT_TILE[accent])}>- <Icon size={15} className={ACCENT_ICON[accent]} />- </span>- <span className="truncate text-[14px] text-foreground">- {source.display_name}- {suf ? <span className="text-muted"> · {suf}</span> : null}- </span>- </>- );- };- return (- <Popover open={open} onOpenChange={(v) => !disabled && setOpen(v)}>- <PopoverTrigger asChild>- <button- type="button"- disabled={disabled}- className="flex h-11 w-full items-center gap-2.5 rounded-lg border border-border bg-background px-3 text-left transition-colors hover:border-border-strong disabled:opacity-60"- >- {value ? renderRow(value) : <span className="text-muted">—</span>}- <ChevronDown className="ml-auto size-4 shrink-0 text-muted" />- </button>- </PopoverTrigger>- <PopoverContent align="start" sideOffset={6} className="max-h-[300px] w-[var(--radix-popover-trigger-width)] overflow-y-auto p-1.5">- {sources.map((source) => (- <button- key={source.id}- type="button"- onClick={() => {- onChange(source);- setOpen(false);- }}- className={cn(- 'flex w-full items-center gap-2.5 rounded-md px-2 py-2 text-left hover:bg-surface-2',- value?.id === source.id && 'bg-surface-2',- )}- >- {renderRow(source)}- </button>- ))}- </PopoverContent>- </Popover>- );-};--export const AddCustomModelDialog: React.FC<{- open: boolean;- sources: Source[];- /** 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,- initialSourceId,- showOpenCodeIdentifier = false,- edit,- onClose,- onSaved,- onDeleted,-}) => {- const { t } = useTranslation();- const { showToast } = useToast();-- const [source, setSource] = React.useState<Source | null>(null);- const [modelId, setModelId] = React.useState('');- 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: 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 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 ?? '');- setSaving(false);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [open]);-- const trimmedId = modelId.trim();- const identifier = manualModelIdentifier(- trimmedId,- source?.vendor ?? null,- standardVendors,- showOpenCodeIdentifier,- );-- const copyIdentifier = () => {- if (!identifier || !navigator.clipboard?.writeText) {- if (identifier) showToast(t('common.copyFailed') as string, 'error');- return;- }- navigator.clipboard- .writeText(identifier)- .then(() => showToast(t('common.copied') as string, 'success'))- .catch(() => showToast(t('common.copyFailed') as string, 'error'));- };-- const submit = async () => {- if (!source || source.kind !== 'api_key' || !trimmedId || saving) return;- setSaving(true);- try {- await modelsApi.addCustomModel(source.id, {- model_id: trimmedId,- display_name: displayName.trim() || null,- reasoning_efforts: [],- });- onSaved(identifier);- onClose();- } catch {- showToast(t('settings.models.menus.custom.failed') as string, 'error');- } finally {- setSaving(false);- }- };-- const submitDelete = async () => {- if (!edit) return;- try {- await modelsApi.deleteCustomModel(edit.sourceId, edit.modelId);- onDeleted?.(identifier);- setDeleteOpen(false);- onClose();- showToast(t('settings.models.menus.custom.deleted') as string, 'success');- } catch (err) {- // The server guards a delete while the model is still the only selected- // supplier for some agent — surface that honestly instead of a generic fail.- const code = (err as { code?: string } | null)?.code;- showToast(- t(- code === 'mode_switch_blocked'- ? 'settings.models.menus.custom.deleteInUse'- : 'settings.models.menus.custom.deleteFailed',- ) as string,- 'error',- );- }- };-- return (- <>- <Dialog open={open} onOpenChange={(v) => !v && !saving && onClose()}>- <DialogContent className="max-w-[560px] gap-5">- <DialogHeader>- <DialogTitle className="text-[18px] font-bold">{t('settings.models.menus.custom.title')}</DialogTitle>- <DialogDescription>{t('settings.models.menus.custom.subtitle')}</DialogDescription>- </DialogHeader>-- <div className="flex flex-col gap-2">- <FieldLabel>{t('settings.models.menus.custom.sourceLabel')}</FieldLabel>- <SourceSelect sources={writableSources} value={source} onChange={setSource} disabled={Boolean(edit)} />- </div>-- <div className="flex flex-col gap-2">- <FieldLabel mono>{t('settings.models.menus.custom.modelIdLabel')}</FieldLabel>- <Input- value={modelId}- onChange={(e) => setModelId(e.target.value)}- placeholder={t('settings.models.menus.custom.modelIdPlaceholder') as string}- autoComplete="off"- spellCheck={false}- disabled={Boolean(edit)}- className="h-11 font-mono text-[14px]"- />- </div>-- <div className="flex flex-col gap-2">- <FieldLabel>{t('settings.models.menus.custom.displayNameLabel')}</FieldLabel>- <Input- value={displayName}- onChange={(e) => setDisplayName(e.target.value)}- placeholder={t('settings.models.menus.custom.displayNamePlaceholder') as string}- autoComplete="off"- className="h-11 text-[14px]"- />- </div>-- {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>- <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 && (- <Button- variant="ghost"- size="sm"- className="h-10 text-destructive hover:bg-destructive/[0.08] hover:text-destructive sm:h-9"- onClick={() => setDeleteOpen(true)}- disabled={saving}- >- <Trash2 className="size-4" />- {t('settings.models.menus.custom.delete')}- </Button>- )}- <div className="flex items-center gap-2 max-sm:w-full max-sm:justify-end">- <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 || source.kind !== 'api_key' || !trimmedId || saving}- >- <Plus className="size-4" />- {t(edit ? 'common.save' : 'settings.models.menus.custom.add')}- </Button>- </div>- </DialogFooter>- </DialogContent>- </Dialog>-- <ConfirmDialog- open={deleteOpen}- onOpenChange={setDeleteOpen}- destructive- title={t('settings.models.menus.custom.deleteConfirmTitle')}- description={t('settings.models.menus.custom.deleteConfirmBody', {- model: identifier || edit?.modelId,- source: source?.display_name ?? '',- })}- confirmLabel={t('settings.models.menus.custom.delete') as string}- onConfirm={submitDelete}- />- </>- );-};diff --git a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsxdeleted file mode 100644index e1b71e317..000000000--- a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx+++ /dev/null@@ -1,296 +0,0 @@-// 模型菜单 · OpenCode — the open-menu drawer (frame 05r). Models are grouped BY-// provider prefix (one taxonomy); the full identifier is visible by construction-// (group prefix + mono row id), friendly name secondary. 精选/全量 toggle,-// checkbox = appears in OpenCode's picker, colored dots = supplying sources,-// custom rows carry a 自定义 badge + edit. Commits via PUT .../menu on 完成.-import * as React from 'react';-import { Pencil, Plus } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { Badge } from '@/components/ui/badge';-import { Button } from '@/components/ui/button';-import { Checkbox } from '@/components/ui/checkbox';-import { SegmentedRadio } from '@/components/ui/segmented';-import { useToast } from '@/context/ToastContext';-import { initialSeedState, savedMenuKey, seedStep } from '../asyncLifetime';-import { modelsApi } from '../modelsApi';-import { backendVisual } from '../vendorMeta';-import type { AgentMenu, AgentSupply, Source } from '../types';-import { MenuDrawer } from './MenuDrawer';-import { AddCustomModelDialog } from './AddCustomModelDialog';-import { eligibleSources as filterEligible } from '../eligibility';-import { buildMenuGroups, type MenuModelRow } from './identifiers';-import { SupplyDots } from './supplyBits';-import { useAnnounceEnrollment } from './enrollment';--type EditTarget = { sourceId: string; modelId: string; displayName: string | null } | null;--const sameSet = (a: Set<string>, b: string[]): boolean =>- a.size === b.length && b.every((x) => a.has(x));--const ModelRow: React.FC<{- row: MenuModelRow;- checked: boolean;- onToggle: () => void;- onEdit: () => void;-}> = ({ row, checked, onToggle, onEdit }) => {- const { t } = useTranslation();- return (- <div className="flex items-center gap-3 rounded-xl border border-border px-3.5 py-3">- <Checkbox checked={checked} onCheckedChange={onToggle} label={row.identifier} />- {/* min-h-11 makes the label span the row's full height, so the tap area- matches the row the user actually aims at (the 18px checkbox alone is- not a thumb target). */}- <button type="button" onClick={onToggle} className="flex min-h-11 min-w-0 flex-1 items-center gap-2.5 text-left sm:min-h-0">- {/* Never truncate the model id: frame 05r's contract is that the full- identifier is visible by construction, and custom ids are unbounded- (the Source-model create route sets no length limit). break-all wraps instead, so- a long id can't overflow the row without hiding its suffix. */}- <span className="min-w-0 break-all font-mono text-[14px] font-medium text-foreground">{row.modelId}</span>- {row.displayName && <span className="truncate text-[13px] text-muted">{row.displayName}</span>}- {row.isCustom && (- <Badge className="shrink-0 rounded-md bg-violet-soft px-2 py-0.5 text-[10px] font-medium text-violet">- {t('settings.models.menus.opencode.customBadge')}- </Badge>- )}- </button>- <SupplyDots accents={row.accents} className="flex shrink-0 items-center gap-1" />- {row.isCustom && (- <button- type="button"- aria-label={t('common.edit') as string}- onClick={onEdit}- className="flex size-10 shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:text-foreground sm:size-6"- >- <Pencil className="size-3.5" />- </button>- )}- </div>- );-};--export const OpenCodeMenuDrawer: React.FC<{- open: boolean;- agent: AgentSupply;- sources: Source[];- onClose: () => void;- /** Hands the page the Agent row this write echoed — see `agentsWithEcho`. */- onSaved: (echoed: AgentSupply) => void;- /** Re-fetch sources after a custom model is added/edited. */- onRefresh: () => void;-}> = ({ open, agent, sources, onClose, onSaved, onRefresh }) => {- const { t } = useTranslation();- const { showToast } = useToast();- const { Icon, accent } = backendVisual('opencode');-- // Standard OpenCode vendor prefixes, server-populated (agent-supply v1.2) so- // identifiers byte-match the backend's opencode_model_id — never hand-mirrored.- const standardVendors = React.useMemo(() => new Set(agent.standard_vendors ?? []), [agent.standard_vendors]);-- // Only sources the SERVER says may serve OpenCode materialize as providers —- // `agent.sources.eligibility`, not a UI-side predicate — so we never offer a- // row the live `set_opencode_menu` would reject.- const eligibleSources = React.useMemo(() => filterEligible(sources, agent), [sources, agent]);- const groups = React.useMemo(() => buildMenuGroups(eligibleSources, standardVendors), [eligibleSources, standardVendors]);- const allRows = React.useMemo(() => groups.flatMap((g) => g.rows), [groups]);- // Identifiers a source currently supplies. Persisted `checked` is self-healed- // against this so an identifier whose only supplier was deleted (e.g. a- // force-deleted source) is dropped rather than shown as an invisible checked- // row or sent to putMenu (which the server rejects as mapping_target_unavailable).- const availableIds = React.useMemo(() => new Set(allRows.map((r) => r.identifier)), [allRows]);- // Ticking a model may also enroll its supplier into OpenCode's source order- // (api.md → "Mapping and menu enrollment"). Read off the echo at commit.- const announceEnrollment = useAnnounceEnrollment('opencode', sources);-- const [view, setView] = React.useState<'featured' | 'full'>(agent.menu?.view ?? 'featured');- const [checked, setChecked] = React.useState<Set<string>>(() => new Set(agent.menu?.checked ?? []));- const initialRef = React.useRef<AgentMenu>({ view, checked: [...checked] });- const [saving, setSaving] = React.useState(false);- const [customOpen, setCustomOpen] = React.useState(false);- const [editTarget, setEditTarget] = React.useState<EditTarget>(null);-- // Seed from the stored menu; `seedStep` owns *when*, so a save that lands after- // this drawer was closed and reopened re-seats it instead of being written back- // over (asyncLifetime.ts). A refresh that changed nothing stays inert, which is- // what keeps an edit in flight safe.- const seed = React.useRef(initialSeedState);- const authoritative = savedMenuKey(agent.menu);- React.useEffect(() => {- if (!open) return;- const step = seedStep(seed.current, authoritative);- seed.current = step.state;- if (!step.reseed) return;- const v = agent.menu?.view ?? 'featured';- const raw = agent.menu?.checked ?? [];- // Self-heal the DISPLAY: drop checked ids whose supplier no longer exists- // (e.g. after a force-delete). Seed initialRef with the RAW persisted list so,- // when the heal removed entries, the drawer is dirty and Done PERSISTS the- // cleaned menu — a no-op close still heals the stored config.- const healed = raw.filter((id) => availableIds.has(id));- setView(v);- setChecked(new Set(healed));- initialRef.current = { view: v, checked: [...raw] };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [open, authoritative]);-- const featuredCount = allRows.filter((r) => checked.has(r.identifier)).length;- const fullCount = allRows.length;-- const toggle = (identifier: string) =>- setChecked((prev) => {- const next = new Set(prev);- if (next.has(identifier)) next.delete(identifier);- else next.add(identifier);- return next;- });-- const dirty = () => view !== initialRef.current.view || !sameSet(checked, initialRef.current.checked);-- const commitAndClose = async () => {- if (saving) return;- if (!dirty()) {- onClose();- return;- }- setSaving(true);- try {- // `checked` is already self-healed at open and only grows via toggles/adds- // of available (or just-added) identifiers, so send it as-is — filtering- // here would strip a just-added custom model before onRefresh lands.- const echoed = await modelsApi.putMenu({ view, checked: [...checked] });- announceEnrollment(agent, echoed);- onSaved(echoed);- onClose();- } catch {- showToast(t('settings.models.menus.saveFailed') as string, 'error');- } finally {- setSaving(false);- }- };-- const providerAnnotation = (provider: string) =>- t(`settings.models.menus.opencode.provider.${provider}`, { defaultValue: '' }) as string;-- const visibleGroups = groups- .map((g) => ({- ...g,- rows: view === 'featured' ? g.rows.filter((r) => checked.has(r.identifier)) : g.rows,- }))- .filter((g) => g.rows.length > 0);-- return (- <>- <MenuDrawer- open={open}- onClose={() => void commitAndClose()}- Icon={Icon}- accent={accent}- title={t('settings.models.menus.opencode.title') as string}- subtitle={t('settings.models.menus.opencode.subtitle') as string}- footer={- <>- <span />- <Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={() => void commitAndClose()} disabled={saving}>- {t('settings.models.menus.done')}- </Button>- </>- }- >- {/* 220px segmented + the 自定义模型 button exceed a 360px phone side by- side, so they stack there and the toggle spans the width. */}- <div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">- <div className="w-full sm:w-[220px]">- <SegmentedRadio- value={view}- onChange={setView}- ariaLabel={t('settings.models.menus.opencode.viewLabel') as string}- tone="muted"- options={[- { id: 'featured', label: t('settings.models.menus.opencode.featured', { count: featuredCount }) as string },- { id: 'full', label: t('settings.models.menus.opencode.full', { count: fullCount }) as string },- ]}- />- </div>- <Button- variant="outline"- size="sm"- className="h-10 shrink-0 border-violet/40 text-violet hover:border-violet/60 hover:text-violet sm:h-9"- onClick={() => {- setEditTarget(null);- setCustomOpen(true);- }}- >- <Plus className="size-4" />- {t('settings.models.menus.opencode.addCustom')}- </Button>- </div>-- {visibleGroups.length === 0 ? (- <p className="px-1 py-8 text-center text-[13px] text-muted">{t('settings.models.menus.opencode.empty')}</p>- ) : (- <div className="flex flex-col gap-5">- {visibleGroups.map((group) => {- const annotation = providerAnnotation(group.provider);- return (- <div key={group.provider} className="flex flex-col gap-2">- <div className="flex items-baseline gap-2 px-1">- <span className="font-mono text-[13px] font-bold text-violet">{group.provider}/</span>- {annotation && <span className="text-[12px] text-muted">{annotation}</span>}- </div>- <div className="flex flex-col gap-2">- {group.rows.map((row) => (- <ModelRow- key={row.identifier}- row={row}- checked={checked.has(row.identifier)}- onToggle={() => toggle(row.identifier)}- onEdit={() => {- // Pull the display name from the CHOSEN manual model, not the- // aggregate row label (which may come from a discovered source),- // so saving unchanged can't overwrite it with another source's name.- const custom = row.sources.find((s) => s.models.some((m) => m.id === row.modelId && m.provenance === 'manual'));- const manual = custom?.models.find((m) => m.id === row.modelId && m.provenance === 'manual');- if (!custom || !manual) return;- setEditTarget({ sourceId: custom.id, modelId: row.modelId, displayName: manual.display_name ?? null });- setCustomOpen(true);- }}- />- ))}- </div>- </div>- );- })}- </div>- )}-- <p className="mt-5 px-1 text-[12px] leading-relaxed text-muted">- {t('settings.models.menus.opencode.footnote')}- </p>- </MenuDrawer>-- <AddCustomModelDialog- open={customOpen}- sources={eligibleSources}- standardVendors={standardVendors}- showOpenCodeIdentifier- edit={editTarget}- onClose={() => setCustomOpen(false)}- onSaved={(identifier) => {- // Auto-check only a NEWLY added model (so it shows in 精选). Editing an- // existing entry's metadata must not flip its menu-selection state — a- // display-name edit on an unchecked model would otherwise re-add it.- if (!editTarget) setChecked((prev) => new Set(prev).add(identifier));- onRefresh();- }}- onDeleted={() => {- // No local uncheck: the backend only lets the delete through when the- // model is NOT the sole selected supplier, so any checked identifier that- // survives a successful delete is still supplied by another source and- // must stay checked. A sole-supplier checked model is blocked (the dialog- // shows an honest "in use" message). Just refresh the source list.- onRefresh();- }}- />- </>- );-};diff --git a/ui/src/components/settings/models/menus/enrollment.test.ts b/ui/src/components/settings/models/menus/enrollment.test.tsdeleted file mode 100644index 9b5a612cf..000000000--- a/ui/src/components/settings/models/menus/enrollment.test.ts+++ /dev/null@@ -1,55 +0,0 @@-// api.md → "Mapping and menu enrollment": accepting a target auto-appends its-// supplier to the backend's order, and 「the confirm step must surface the-// append」. These pin the one rule that makes the notice safe to show — the-// append is READ, never predicted — and the two silences that must not become a-// sentence.-import { describe, expect, it } from 'vitest';--import { enrolledByCommit } from './enrollment';-import type { AgentSupply } from '../types';--const withOrder = (order: string[] | null): Pick<AgentSupply, 'sources'> => ({- sources: order === null ? null : { policy: 'custom', order, eligibility: null },-});--describe('enrolledByCommit', () => {- it('names what the commit added, and nothing that was already there', () => {- expect(enrolledByCommit(withOrder(['src_a']), withOrder(['src_a', 'src_b']))).toEqual(['src_b']);- });-- it('says nothing when the order came back unchanged', () => {- // The ordinary case: the ticked model's supplier was already enrolled, so the- // save changed the menu and nothing else. A notice here would fire on every- // 完成 and teach the user to dismiss the one that matters.- expect(enrolledByCommit(withOrder(['src_a', 'src_b']), withOrder(['src_a', 'src_b']))).toEqual([]);- });-- it('reports several appends in the order the server put them', () => {- // One per target group, and the contract caps each group at one — but a- // multi-target commit can still enroll more than one supplier.- expect(enrolledByCommit(withOrder([]), withOrder(['src_b', 'src_c']))).toEqual(['src_b', 'src_c']);- });-- it('reads a missing baseline as nothing to report, never as everything new', () => {- // `sources` is null in direct mode, and a drawer that opened against one- // would otherwise announce the entire order as freshly enrolled — the one- // sentence this must never produce.- expect(enrolledByCommit(withOrder(null), withOrder(['src_a', 'src_b']))).toEqual([]);- });-- it('claims nothing when the echo itself carries no order', () => {- expect(enrolledByCommit(withOrder(['src_a']), withOrder(null))).toEqual([]);- });-- it('ignores a reordering that enrolled nobody', () => {- // The diff is membership, not position: the drawer does not edit the order,- // so a server that re-sorted it has still enrolled nothing.- expect(enrolledByCommit(withOrder(['src_a', 'src_b']), withOrder(['src_b', 'src_a']))).toEqual([]);- });-- it('does not report a source the commit REMOVED as if it were added', () => {- // A dropped id (deleted, or newly ineligible) is a shrinking order. The- // notice is about what came in; a subtraction has no sentence here.- expect(enrolledByCommit(withOrder(['src_a', 'src_b']), withOrder(['src_a']))).toEqual([]);- });-});diff --git a/ui/src/components/settings/models/menus/enrollment.ts b/ui/src/components/settings/models/menus/enrollment.tsdeleted file mode 100644index bae67196f..000000000--- a/ui/src/components/settings/models/menus/enrollment.ts+++ /dev/null@@ -1,101 +0,0 @@-// What accepting a menu edit ALSO did to the backend's source order.-//-// api.md → "Mapping and menu enrollment": a mapping or open-menu target is-// accepted only when its selected source is enrolled in the post-mutation-// effective order, and acceptance auto-appends that source — 「the confirm step-// must surface the append」. The user ticked a model; the server also changed-// which accounts that backend will spend, and nothing on screen said so.-//-// Read from the echo, never predicted. The server picks the first supplier in ITS-// recommended order (`_enroll_target_sources`), so a client that computed the-// append before committing would be re-deriving a server rule from a snapshot-// that may already be stale — and would name the wrong source the first time the-// two disagree. Both orders below are `effective_source_order` as the payload-// reports it, for either policy, so the diff is one subtraction and no rule.-import * as React from 'react';-import { useTranslation } from 'react-i18next';--import { useToast } from '@/context/ToastContext';-import type { AgentBackend, AgentSupply, Source } from '../types';-import { useCompactSourceLabel } from './sourceLabel';--/**- * The ids the commit added to the order, in the order the server put them.- *- * `[]` when nothing was appended AND when either side is missing, because the two- * are the same statement here: with no baseline every id looks new, and 「保存后- * 自动加入了全部来源」 is the one sentence this must never produce. Both callers- * only speak when the list is non-empty, so silence needs no second member.- *- * WHAT `before` HAS TO BE: the order the server held when this write began. It is- * the page's own Agent list, so a `sources.order` PUT that lands in the window- * between the page reading it and this write returning would show up in the diff- * and be reported as this write's doing. The one path that could reach that window- * is closed where it opens rather than compensated for here, in two parts that meet:- * 来源顺序's hand-off to these drawers is shut while its write is in flight — the- * outstanding-write fact held by the PAGE, not by the drawer issuing it, since the- * user can close that drawer, which unmounts it, and reopen it mid-write- * (`createPendingWrites`) — and the order it wrote reaches this list as the WRITE'S- * OWN ECHO (`agentsWithEcho`), so the baseline is caught up even when the re-read- * that would otherwise have carried it fails or is superseded.- * The general case — any order write from outside this page's read cycle — is not- * client-answerable, and its fix is the mutation response naming its own appends- * (`enrolled_source_ids`), server-side and escalated rather than approximated here.- */-export function enrolledByCommit(- before: Pick<AgentSupply, 'sources'>,- after: Pick<AgentSupply, 'sources'>,-): string[] {- const was = before.sources?.order;- const now = after.sources?.order;- if (!was || !now) return [];- const enrolled = new Set(was);- return now.filter((id) => !enrolled.has(id));-}--/**- * Both drawers' 完成, in one place: diff the echo against what was on screen and- * say what the save also enrolled.- *- * Shared rather than written twice for the reason `AdoptionNote` was: two dialogs- * reporting one server behaviour in their own words is how they end up saying- * different things about the same event. The append is per-commit and identical- * for a fixed menu and an open one — only the backend's name differs.- *- * Silent when nothing was appended, which is the ordinary case: a ticked model- * whose supplier is already in the order changes only the menu, and a toast that- * fires every time teaches the user to dismiss the one that matters. It says- * nothing about the policy either — under `follow` the effective order is- * exhaustive over eligible sources, so an append means the order was already- * `custom` and no recommendation was lost.- */-export function useAnnounceEnrollment(- backend: AgentBackend,- sources: readonly Source[],-): (before: Pick<AgentSupply, 'sources'>, after: Pick<AgentSupply, 'sources'>) => void {- const { t } = useTranslation();- const { showToast } = useToast();- const compactLabel = useCompactSourceLabel();- return React.useCallback(- (before, after) => {- const enrolled = enrolledByCommit(before, after);- if (enrolled.length === 0) return;- const byId = new Map(sources.map((s) => [s.id, s]));- const names = enrolled.map((id) => {- const source = byId.get(id);- // An id the inventory on screen does not carry is still an enrollment- // that happened. Naming it by id is worse copy and a true sentence;- // dropping it would silently under-report what the save did.- return source ? compactLabel(source) : id;- });- showToast(- t('settings.models.menus.enrolled', {- sources: names.join(' · '),- backend: t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string,- }) as string,- 'success',- );- },- [backend, compactLabel, showToast, sources, t],- );-}diff --git a/ui/src/components/settings/models/menus/identifiers.ts b/ui/src/components/settings/models/menus/identifiers.tsindex cd9ff019c..01be8da25 100644--- a/ui/src/components/settings/models/menus/identifiers.ts+++ b/ui/src/components/settings/models/menus/identifiers.ts@@ -2,12 +2,7 @@// Identifiers are `provider/model-id`. The provider segment is the standard// vendor id; unrecognizable vendors fall back to a single `custom/` provider.// Identifiers are STABLE across Hub/Direct switches and across source-// add/remove/failover — they never encode a concrete source. Users never-// hand-assemble the string: the menu checkboxes and the custom-model form-// generate and preview it.-import type { Accent } from '../vendorMeta';-import { sourceAccent } from '../vendorMeta';-import type { Source } from '../types';+// add/remove/failover — they never encode a concrete source.// The standard OpenCode vendor ids come from the backend via the opencode// agent's `standard_vendors` projection (agent-supply v1.2), server-populated@@ -21,8 +16,8 @@ export type StandardVendors = ReadonlySet<string>;* contract: it is the SOURCE's vendor when that is a standard vendor id, else* the single `custom` provider. It is deliberately NOT inferred from the model* name — that must byte-match the backend's `opencode_model_id(source.vendor,- * model.id)`, or `set_opencode_menu` rejects the checked value with- * `mapping_target_unavailable`. So `relay.example` (vendor `custom`) supplying+ * model.id)`, or `set_opencode_menu` rejects the checked value. So+ * `relay.example` (vendor `custom`) supplying* `glm-5.2-air` yields `custom/glm-5.2-air` (not `zhipuai/…`).*/export function inferProvider(sourceVendor: string, standardVendors: StandardVendors): string {@@ -34,125 +29,9 @@ 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 was-// guaranteed to drift and to offer rows the live API rejects. Contract v3+// `_eligible_for_agent` predicate, whose server-owned inventory inputs the UI+// cannot reconstruct, so it was guaranteed to drift and offer rows the live API+// rejects. Contract v5// publishes the answer as `AgentSupply.sources.eligibility`; read it through// `../eligibility`.--// ── Grouped menu model, derived from the ordered sources list ──────────────--export type MenuModelRow = {- /** Full prefixed identifier, e.g. `zhipuai/glm-5.2`. */- identifier: string;- /** Group prefix (the provider segment). */- provider: string;- /** Bare model id (no prefix). */- modelId: string;- displayName: string | null;- /** True when any supplying entry is a manual (custom) model. */- isCustom: boolean;- /** Supplying sources, in the order they appear in the input list (priority). */- sources: Source[];- /** Deduped supplying-source accents, for the row's supply dots. */- accents: Accent[];-};--export type MenuGroup = {- provider: string;- rows: MenuModelRow[];-};--/**- * Build the grouped, deduped model rows for the OpenCode open menu (frame 05r).- * `sources` MUST already be in priority order so the supply dots and candidate- * order track the 来源 band. The same identifier supplied by several sources- * collapses into one row carrying every supplying source.- */-export function buildMenuGroups(sources: Source[], standardVendors: StandardVendors): MenuGroup[] {- const byIdentifier = new Map<string, MenuModelRow>();- for (const source of sources) {- for (const model of source.models) {- const identifier = buildIdentifier(source.vendor, model.id, standardVendors);- let row = byIdentifier.get(identifier);- if (!row) {- row = {- identifier,- provider: identifier.slice(0, identifier.indexOf('/')),- modelId: model.id,- displayName: model.display_name ?? null,- isCustom: model.provenance === 'manual',- sources: [],- accents: [],- };- byIdentifier.set(identifier, row);- }- if (model.display_name && !row.displayName) row.displayName = model.display_name;- if (model.provenance === 'manual') row.isCustom = true;- row.sources.push(source);- const accent = sourceAccent(source);- if (!row.accents.includes(accent)) row.accents.push(accent);- }- }- // Group by provider, preserving first-seen order (which follows priority).- const groups: MenuGroup[] = [];- const byProvider = new Map<string, MenuGroup>();- for (const row of byIdentifier.values()) {- let group = byProvider.get(row.provider);- if (!group) {- group = { provider: row.provider, rows: [] };- byProvider.set(row.provider, group);- groups.push(group);- }- group.rows.push(row);- }- return groups;-}--// ── Fixed-menu (mapping) helpers ───────────────────────────────────────────--export type TargetModel = {- /** Bare model id. */- id: string;- displayName: string | null;- /** Sources able to supply it, in priority order. */- sources: Source[];- accents: Accent[];-};--/**- * Distinct target models a fixed-menu override can point at — the union of every- * source's supplied model ids, in priority order (frame 04 dropdown).- */-export function buildTargetModels(sources: Source[]): TargetModel[] {- const byId = new Map<string, TargetModel>();- for (const source of sources) {- for (const model of source.models) {- let target = byId.get(model.id);- if (!target) {- target = { id: model.id, displayName: model.display_name ?? null, sources: [], accents: [] };- byId.set(model.id, target);- }- if (model.display_name && !target.displayName) target.displayName = model.display_name;- target.sources.push(source);- const accent = sourceAccent(source);- if (!target.accents.includes(accent)) target.accents.push(accent);- }- }- return [...byId.values()];-}diff --git a/ui/src/components/settings/models/menus/sourceLabel.ts b/ui/src/components/settings/models/menus/sourceLabel.tsdeleted file mode 100644index 88fd32f90..000000000--- a/ui/src/components/settings/models/menus/sourceLabel.ts+++ /dev/null@@ -1,23 +0,0 @@-// Compact source label used in the mapping candidate line ("智谱 / relay.example",-// frame 04): the vendor's friendly name for known vendors, else the source-// display name (host for a custom endpoint). Kept in its own module so-// `supplyBits.tsx` stays component-only (react-refresh).-import * as React from 'react';-import { useTranslation } from 'react-i18next';--import type { Source } from '../types';--/** Returns a stable function mapping a source to a compact label. */-export function useCompactSourceLabel(): (source: Source) => string {- const { t } = useTranslation();- return React.useCallback(- (source: Source) => {- if (source.vendor && source.vendor !== 'custom') {- const label = t(`settings.models.addKey.vendors.${source.vendor}`, { defaultValue: '' }) as string;- if (label) return label;- }- return source.display_name;- },- [t],- );-}diff --git a/ui/src/components/settings/models/menus/supplyBits.tsx b/ui/src/components/settings/models/menus/supplyBits.tsxdeleted file mode 100644index afdf8a7fb..000000000--- a/ui/src/components/settings/models/menus/supplyBits.tsx+++ /dev/null@@ -1,16 +0,0 @@-// The supply dots — one colored dot per supplying source (frames 04 / 05r).-// (The compact source label hook lives in ./sourceLabel to keep this file-// component-only for fast refresh.)-import * as React from 'react';--import { Dot } from '../chips';-import type { Accent } from '../vendorMeta';--/** A run of supply dots — colored per supplying source. */-export const SupplyDots: React.FC<{ accents: Accent[]; className?: string }> = ({ accents, className }) => (- <span className={className}>- {accents.map((accent, i) => (- <Dot key={`${accent}-${i}`} accent={accent} />- ))}- </span>-);diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.tsindex f60f577e3..2cd77e10b 100644--- a/ui/src/components/settings/models/mockData.ts+++ b/ui/src/components/settings/models/mockData.ts@@ -1,5 +1,5 @@-// Typed fixtures for the Model Hub UI while the L2 REST API is unmerged.-// Mirrors the V6 design mock story (design.pen `产品改造 V6 01`) and the frozen+// Typed fixtures for hermetic Model Hub visual tests.+// Mirrors the frozen// v3 contract example payloads. Timestamps are computed relative to "now" at// fetch time so the 最近切换 list always renders 今天 / 昨天 correctly.//@@ -17,7 +17,6 @@ import type {Source,SourceEligibility,} from './types';-import { SUBSCRIPTION_HUB_EXPERIMENTAL } from './featureFlags';const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString();const MIN = 60_000;@@ -42,9 +41,9 @@ export function buildMockSources(): Source[] {account_label: '[email protected]',masked_credential: null,models: [- { id: 'claude-opus-4-6', display_name: 'Opus 4.6', provenance: 'discovered', discovered_at: iso(-3 * HOUR) },- { id: 'claude-sonnet-4-6', display_name: 'Sonnet 4.6', provenance: 'discovered', discovered_at: iso(-3 * HOUR) },- { id: 'claude-haiku-4-5', display_name: 'Haiku 4.5', provenance: 'discovered', discovered_at: iso(-3 * HOUR) },+ { id: 'claude-opus-4-6', display_name: 'Opus 4.6', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-3 * HOUR) },+ { id: 'claude-sonnet-4-6', display_name: 'Sonnet 4.6', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-3 * HOUR) },+ { id: 'claude-haiku-4-5', display_name: 'Haiku 4.5', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-3 * HOUR) },],credential_ref: null,},@@ -64,8 +63,8 @@ export function buildMockSources(): Source[] {account_label: '[email protected]',masked_credential: null,models: [- { id: 'gpt-5.6', display_name: 'GPT-5.6', provenance: 'discovered', discovered_at: iso(-3 * HOUR) },- { id: 'gpt-5.6-mini', display_name: 'GPT-5.6 mini', provenance: 'discovered', discovered_at: iso(-3 * HOUR) },+ { id: 'gpt-5.6', display_name: 'GPT-5.6', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-3 * HOUR) },+ { id: 'gpt-5.6-mini', display_name: 'GPT-5.6 mini', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-3 * HOUR) },],credential_ref: null,},@@ -85,9 +84,9 @@ export function buildMockSources(): Source[] {account_label: null,masked_credential: 'sk-ant-…8f2A',models: [- { id: 'claude-opus-4-6', display_name: 'Opus 4.6', provenance: 'discovered', discovered_at: iso(-6 * HOUR) },- { id: 'claude-sonnet-4-6', display_name: 'Sonnet 4.6', provenance: 'discovered', discovered_at: iso(-6 * HOUR) },- { id: 'claude-haiku-4-5', display_name: 'Haiku 4.5', provenance: 'discovered', discovered_at: iso(-6 * HOUR) },+ { id: 'claude-opus-4-6', display_name: 'Opus 4.6', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },+ { id: 'claude-sonnet-4-6', display_name: 'Sonnet 4.6', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },+ { id: 'claude-haiku-4-5', display_name: 'Haiku 4.5', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },],credential_ref: 'cred_anth01',},@@ -107,10 +106,10 @@ export function buildMockSources(): Source[] {account_label: null,masked_credential: 'glm-…c31b',models: [- { id: 'glm-5.2', display_name: 'GLM 5.2', provenance: 'discovered', discovered_at: iso(-6 * HOUR) },- { id: 'glm-5.2-air', display_name: 'GLM 5.2 Air', provenance: 'discovered', discovered_at: iso(-6 * HOUR) },- { id: 'glm-5-flash', display_name: 'GLM 5 Flash', provenance: 'discovered', discovered_at: iso(-6 * HOUR) },- { id: 'glm-5.2-pro', display_name: 'GLM 5.2 Pro', provenance: 'manual', discovered_at: null },+ { id: 'glm-5.2', display_name: 'GLM 5.2', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },+ { id: 'glm-5.2-air', display_name: 'GLM 5.2 Air', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },+ { id: 'glm-5-flash', display_name: 'GLM 5 Flash', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },+ { id: 'glm-5.2-pro', display_name: 'GLM 5.2 Pro', origin: 'manual', reasoning_efforts: [], discovered_at: null },],credential_ref: 'cred_zhipu01',},@@ -128,12 +127,12 @@ export function buildMockSources(): Source[] {base_url: 'https://relay.example/v1',supply_channel: 'hub',billing: 'metered',- state: { status: 'cooldown', retry_at: iso(47 * MIN), detail_key: 'models.source.cooldown.timeout' },+ state: { status: 'cooldown', retry_at: iso(47 * MIN), detail_key: 'models.source.cooldown.server_error' },usage: { cycle_used_pct: null, month_spend_cents: 320, currency: 'USD' },account_label: null,masked_credential: 'key …9c1',models: [- { id: 'glm-5.2-air', display_name: 'GLM 5.2 Air', provenance: 'manual', discovered_at: null },+ { id: 'glm-5.2-air', display_name: 'GLM 5.2 Air', origin: 'manual', reasoning_efforts: [], discovered_at: null },],credential_ref: 'cred_relay01',},@@ -149,6 +148,7 @@ export function buildMockAgents(sources: Source[] = buildMockSources()): AgentSureturn [{backend: 'claude',+ cli_present: true,mode: 'hub',menu_kind: 'fixed',selected_by_agent: null,@@ -157,7 +157,6 @@ export function buildMockAgents(sources: Source[] = buildMockSources()): AgentSu// as explicit — the resolver-picked case only exists on the open menu.selected_model_explicit: true,sources: {- policy: 'custom',order: claudeOrder,eligibility: mockEligibility(sources, 'claude'),},@@ -169,50 +168,47 @@ export function buildMockAgents(sources: Source[] = buildMockSources()): AgentSu// 智谱 is 未启用 here. Depth 0 is the honest answer, and AC-9's Case A: a// menu-model gap that must NOT render any Agent as interrupted.model_supply: [- { model_id: 'claude-opus-4-6', chain_length: 2 },- { model_id: 'claude-sonnet-4-6', chain_length: 2 },- { model_id: 'claude-haiku-4-5', chain_length: 0 },+ { model_id: 'claude-opus-4-6', chain_length: 2, has_runnable_hop: true },+ { model_id: 'claude-sonnet-4-6', chain_length: 2, has_runnable_hop: true },+ { model_id: 'claude-haiku-4-5', chain_length: 0, has_runnable_hop: false },],named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' },{ name: 'pm', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' },],- // Fixed-menu backends surface their full built-in id list as mappings; an- // enabled entry is an override (frame 04), disabled = 跟随原生 (identity).- mappings: [- { builtin_id: 'claude-opus-4-6', target_model_id: '', enabled: false },- { builtin_id: 'claude-sonnet-4-6', target_model_id: '', enabled: false },- { builtin_id: 'claude-haiku-4-5', target_model_id: 'glm-5.2', enabled: true },- ],+ routes: {+ 'claude-opus-4-6': { hops: [{ source_id: 'src_claudepro1', model_id: 'claude-opus-4-6' }, { source_id: 'src_anthkey01', model_id: 'claude-opus-4-6' }] },+ 'claude-sonnet-4-6': { hops: [{ source_id: 'src_claudepro1', model_id: 'claude-sonnet-4-6' }, { source_id: 'src_anthkey01', model_id: 'claude-sonnet-4-6' }] },+ 'claude-haiku-4-5': { hops: [] },+ },menu: null,// Fixed-menu backends carry the server-populated built-in catalog- // (agent-supply v1.2); the mapping drawer renders these rows.+ // The server projects these ids; the route editor never hardcodes them.builtin_models: ['claude-opus-4-6', 'claude-sonnet-4-6', 'claude-haiku-4-5'],standard_vendors: null,},{backend: 'codex',+ cli_present: true,mode: 'hub',menu_kind: 'fixed',selected_by_agent: 'codex',selected_model_id: 'gpt-5.6',selected_model_explicit: true,sources: {- policy: 'follow',- // Recomputed on every read: 跟随推荐 means a new source joins by itself.order: mockRecommendedOrder(sources, 'codex'),eligibility: mockEligibility(sources, 'codex'),},supply_status: 'ok',model_supply: [- { model_id: 'gpt-5.6', chain_length: 1 },- { model_id: 'gpt-5.6-mini', chain_length: 1 },+ { model_id: 'gpt-5.6', chain_length: 1, has_runnable_hop: true },+ { model_id: 'gpt-5.6-mini', chain_length: 1, has_runnable_hop: true },],named_agents: [{ name: 'codex', effective_model_id: 'gpt-5.6', supply_status: 'ok' }],- mappings: [- { builtin_id: 'gpt-5.6', target_model_id: '', enabled: false },- { builtin_id: 'gpt-5.6-mini', target_model_id: '', enabled: false },- ],+ routes: {+ 'gpt-5.6': { hops: [{ source_id: 'src_chatgptplus', model_id: 'gpt-5.6' }] },+ 'gpt-5.6-mini': { hops: [{ source_id: 'src_chatgptplus', model_id: 'gpt-5.6-mini' }] },+ },menu: null,builtin_models: ['gpt-5.6', 'gpt-5.6-mini'],standard_vendors: null,@@ -221,6 +217,7 @@ export function buildMockAgents(sources: Source[] = buildMockSources()): AgentSu// 直连: the CLI runs its own native config. Every hub-side projection is// null by contract — no order, no chain, no probe (AC-7's gate).backend: 'opencode',+ cli_present: true,mode: 'direct',menu_kind: 'open',selected_by_agent: null,@@ -230,7 +227,6 @@ export function buildMockAgents(sources: Source[] = buildMockSources()): AgentSusupply_status: null,model_supply: null,named_agents: [{ name: 'opencode', effective_model_id: null, supply_status: null }],- mappings: [],// Prefixed identifiers (opencode-overlay.md): provider = the SOURCE's// vendor (custom fallback). Retained across the mode switch — it is stored// config, not live state, and applies again the moment OpenCode rejoins.@@ -377,15 +373,10 @@ export function buildMockRuntime(): RuntimeDependency {// Migration scan fixture (frame 03). Mirrors the frozen migration-scan schema// example, adapted to the mock backends. Per spec v1.1 + the 2026-07-23 L6// finding: API keys / base URLs → import; subscription OAuth (Claude account +-// Codex auth.json) → keep_native ALWAYS (controlled_import is deferred — adapter-// v1.2 forbids OAuth material in provision_credential). When the experimental-// flag is on, those rows only add a "re-authorize inside the hub" hint; they-// never become an import. So this fixture emits only import / keep_native.+// Codex auth.json) → keep_native. controlled_import is reserved and not+// applicable in v3, so this fixture emits only import / keep_native.export function buildMockMigration(): MigrationScan {- // Subscription-OAuth rows stay native; the flag only swaps their hint line.- const oauthNote = SUBSCRIPTION_HUB_EXPERIMENTAL- ? 'settings.models.migration.notes.keepNativeReauthHint'- : 'settings.models.migration.notes.keepNativeSanctioned';+ const oauthNote = 'settings.models.migration.notes.keepNativeSanctioned';return {items: [{diff --git a/ui/src/components/settings/models/modelHubStylePolicy.test.ts b/ui/src/components/settings/models/modelHubStylePolicy.test.tsnew file mode 100644index 000000000..dd2c7b015--- /dev/null+++ b/ui/src/components/settings/models/modelHubStylePolicy.test.ts@@ -0,0 +1,32 @@+import { readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';++import { describe, expect, it } from 'vitest';++const productFiles = (directory: string): string[] => readdirSync(directory, { withFileTypes: true })+ .flatMap((entry) => {+ const path = join(directory, entry.name);+ if (entry.isDirectory()) return productFiles(path);+ return /\.(?:ts|tsx)$/.test(entry.name) && !/\.test\.(?:ts|tsx)$/.test(entry.name) ? [path] : [];+ });++const surfaceCss = readFileSync(join(__dirname, 'modelHubSurface.css'), 'utf8');++describe('Model Hub visual token policy', () => {+ it('keeps approximate utility colors out of product surfaces', () => {+ const forbidden = /(?:text-(?:foreground|muted)\/\d+|bg-foreground\/\[[^\]]+\]|border-foreground\/\d+|\btext-(?:gold|violet|mint)\b)/g;+ const violations = productFiles(__dirname).flatMap((path) => (+ [...readFileSync(path, 'utf8').matchAll(forbidden)].map((match) => `${path}:${match[0]}`)+ ));++ expect(violations).toEqual([]);+ });++ it('routes accent-role colors through named tokens', () => {+ const roleBodies = [...surfaceCss.matchAll(/\.model-hub-accent-(?:tile|pill)--[\w-]+\s*\{([^}]*)\}/g)]+ .map((match) => match[1]);+ const literals = roleBodies.flatMap((body) => body.match(/#[\da-f]{6,8}/gi) ?? []);++ expect(literals).toEqual([]);+ });+});diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssnew file mode 100644index 000000000..4a70fb922--- /dev/null+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -0,0 +1,1258 @@+:root {+ --model-hub-white-03: #FFFFFF03;+ --model-hub-white-05: #FFFFFF05;+ --model-hub-white-06: #FFFFFF06;+ --model-hub-white-08: #FFFFFF08;+ --model-hub-white-0a: #FFFFFF0A;+ --model-hub-white-0f: #FFFFFF0F;+ --model-hub-white-14: #FFFFFF14;+ --model-hub-white-24: #FFFFFF24;+ --model-hub-white-26: #FFFFFF26;+ --model-hub-white-33: #FFFFFF33;+ --model-hub-white-40: #FFFFFF40;+ --model-hub-white-4d: #FFFFFF4D;+ --model-hub-white-59: #FFFFFF59;+ --model-hub-white-73: #FFFFFF73;+ --model-hub-white-8c: #FFFFFF8C;+ --model-hub-gold-14: #FFC85714;+ --model-hub-gold-1a: #FFC8571A;+ --model-hub-gold-33: #FFC85733;+ --model-hub-gold-4d: #FFC8574D;+ --model-hub-gold-59: #FFC85759;+ --model-hub-gold-66: #FFC85766;+ --model-hub-gold-d9: #FFC857D9;+ --model-hub-violet-1a: #7C5BFF1A;+ --model-hub-violet-24: #7C5BFF24;+ --model-hub-violet-4d: #7C5BFF4D;+ --model-hub-violet-cc: #7C5BFFCC;+ --model-hub-mint-14: #5BFFA014;+ --model-hub-mint-1a: #5BFFA01A;+ --model-hub-mint-4d: #5BFFA04D;+ --model-hub-mint-cc: #5BFFA0CC;+ --model-hub-cyan-1a: #3FE0E51A;+ --model-hub-cyan-4d: #3FE0E54D;+ --model-hub-muted-b3: #9BA3B8B3;+ --model-hub-muted-cc: #9BA3B8CC;+ --model-hub-error-8a: #FF8A8A;+}++.model-hub-accent-tile--cyan { background: var(--model-hub-cyan-1a); }+.model-hub-accent-tile--mint { background: var(--model-hub-mint-1a); }+.model-hub-accent-tile--gold { background: var(--model-hub-gold-1a); }+.model-hub-accent-tile--violet { background: var(--model-hub-violet-24); }+.model-hub-accent-tile--neutral { background: var(--model-hub-white-0a); }+.model-hub-accent-ink--cyan { color: var(--cyan); }+.model-hub-accent-ink--mint { color: var(--mint); }+.model-hub-accent-ink--gold { color: var(--gold); }+.model-hub-accent-ink--violet { color: var(--violet); }+.model-hub-accent-ink--neutral { color: var(--muted); }+.model-hub-accent-pill--cyan { border-color: var(--model-hub-cyan-4d); background: var(--model-hub-cyan-1a); color: var(--cyan); }+.model-hub-accent-pill--mint { border-color: var(--model-hub-mint-4d); background: var(--model-hub-mint-1a); color: var(--mint); }+.model-hub-accent-pill--gold { border-color: var(--model-hub-gold-4d); background: var(--model-hub-gold-1a); color: var(--gold); }+.model-hub-accent-pill--violet { border-color: var(--model-hub-violet-4d); background: var(--model-hub-violet-1a); color: var(--violet); }+.model-hub-accent-pill--neutral { border-color: var(--model-hub-white-14); background: var(--model-hub-white-0a); color: var(--muted); }++.model-hub-ink-mint { color: var(--mint); }+.model-hub-ink-gold { color: var(--gold); }+.model-hub-ink-violet { color: var(--violet); }+.model-hub-ink-white-40 { color: var(--model-hub-white-40); }+.model-hub-ink-white-59 { color: var(--model-hub-white-59); }+.model-hub-ink-white-73 { color: var(--model-hub-white-73); }+.model-hub-ink-muted-b3 { color: var(--model-hub-muted-b3); }+.model-hub-fill-white-03 { background: var(--model-hub-white-03); }+.model-hub-fill-white-05 { background: var(--model-hub-white-05); }+.model-hub-fill-white-08 { background: var(--model-hub-white-08); }+.model-hub-fill-white-0a { background: var(--model-hub-white-0a); }+.model-hub-border-white-14 { border-color: var(--model-hub-white-14); }+.model-hub-border-white-33 { border-color: var(--model-hub-white-33); }+.model-hub-action-mint { color: var(--mint); }+.model-hub-action-mint:hover { color: var(--model-hub-mint-cc); }+.model-hub-status-gold { border-color: var(--model-hub-gold-66); background: var(--model-hub-gold-14); color: var(--gold); }+.model-hub-status-mint { border-color: var(--model-hub-mint-4d); background: var(--model-hub-mint-14); color: var(--mint); }+.model-hub-add-key-error-ink { color: var(--model-hub-error-8a); }++.model-hub-shell {+ display: flex;+ flex-direction: column;+ gap: 22px;+ width: 100%;+}++.model-hub-shell-head {+ display: flex;+ min-height: 38px;+ align-items: center;+ justify-content: space-between;+}++.model-hub-shell-head h1 {+ color: var(--foreground);+ font-size: 26px;+ font-weight: 700;+ letter-spacing: 0;+ line-height: normal;+}++.model-hub-shell-info {+ width: 26px;+ height: 26px;+ color: var(--model-hub-white-40);+}++.model-hub-shell-info svg {+ width: 13px;+ height: 13px;+}++.model-hub-detail-back {+ display: grid;+ width: 28px;+ height: 28px;+ place-items: center;+ border: 1px solid var(--border);+ border-radius: 7px;+ background: var(--model-hub-white-0a);+ color: var(--muted);+}++.model-hub-detail-back:hover { color: var(--foreground); }+.model-hub-detail-back > svg { width: 14px; height: 14px; }++.model-hub-runtime-pill {+ display: inline-flex;+ width: fit-content;+ align-items: center;+ gap: 5px;+ border: 1px solid var(--model-hub-mint-4d);+ border-radius: 999px;+ background: var(--model-hub-mint-1a);+ padding: 3px 8px;+ color: var(--mint);+ font-size: 10.5px;+ font-weight: 600;+ letter-spacing: 0;+ line-height: normal;+}++.model-hub-runtime-pill > svg {+ width: 12px;+ height: 12px;+}++.model-hub-runtime-pill--error {+ border-color: color-mix(in srgb, var(--destructive) 30%, transparent);+ background: color-mix(in srgb, var(--destructive) 10%, transparent);+ color: var(--destructive);+}++.model-hub-runtime-pill--direct {+ border-color: var(--model-hub-white-14);+ background: var(--model-hub-white-0a);+ color: var(--muted);+}++.model-hub-runtime-dot {+ width: 5px;+ height: 5px;+ flex: none;+ border-radius: 50%;+ background: currentColor;+}++.model-hub-takeover-pill {+ display: inline-flex;+ width: fit-content;+ align-items: center;+ gap: 6px;+ border: 1px solid var(--model-hub-violet-4d);+ border-radius: 999px;+ background: var(--model-hub-violet-1a);+ padding: 4px 10px;+ color: var(--violet);+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0;+}++.model-hub-overview {+ --model-hub-upstream-track: 384px;+ --model-hub-rail-track: 72px;+ --model-hub-track-gap: 16px;+ --model-hub-track-height: 806px;+ --model-hub-legend-height: 34px;+ --model-hub-wire-active-width: 1.75px;+ --model-hub-wire-muted-width: 1px;+ --model-hub-wire-node: 7px;+ --model-hub-footer-action-height: 31px;+ --model-hub-footer-action-radius: 7px;+ --model-hub-footer-action-font-size: 11.5px;+ --model-hub-upstream-info-ink: var(--model-hub-white-40);+ --model-hub-upstream-group-ink: var(--model-hub-white-59);+ --model-hub-upstream-detail-ink: var(--model-hub-muted-cc);+ --model-hub-model-row-fill: var(--model-hub-white-05);+ --model-hub-model-mode-fill: var(--model-hub-white-0a);+ --model-hub-model-current-ink: var(--model-hub-muted-cc);+ --model-hub-model-collapse-ink: var(--model-hub-white-59);+ --model-hub-takeover-current-ink: var(--model-hub-violet-cc);+ display: flex;+ flex-direction: column;+ gap: 16px;+}++.model-hub-overview-chevron,+.model-hub-overview-info { color: var(--model-hub-white-40); }+.model-hub-upstream-count {+ border-color: var(--model-hub-white-14);+ background: var(--model-hub-white-0a);+ color: var(--muted);+}+.model-hub-takeover-chip {+ border-color: var(--model-hub-violet-4d);+ background: var(--model-hub-violet-1a);+ color: var(--violet);+}++.model-hub-overview-body { position: relative; }++.model-hub-upstream-info {+ width: 13px;+ height: 13px;+ color: var(--model-hub-upstream-info-ink);+}++.model-hub-upstream-info svg { width: 13px; height: 13px; }++.model-hub-upstream-group-label {+ color: var(--model-hub-upstream-group-ink);+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 1.3px;+}++.model-hub-upstream-detail { color: var(--model-hub-upstream-detail-ink); }+.model-hub-model-row { background: var(--model-hub-model-row-fill); }+.model-hub-model-mode-chip { background: var(--model-hub-model-mode-fill); }+.model-hub-model-current { color: var(--model-hub-model-current-ink); }+.model-hub-model-current--takeover { color: var(--model-hub-takeover-current-ink); }+.model-hub-model-collapse {+ justify-content: flex-start;+ padding: 0 12px;+ color: var(--model-hub-model-collapse-ink);+ font-size: 11px;+ font-weight: 500;+}+.model-hub-model-collapse svg { width: 13px; height: 13px; }++.model-hub-footer-action {+ height: var(--model-hub-footer-action-height);+ padding-inline: 12px;+ border-radius: var(--model-hub-footer-action-radius);+ font-size: var(--model-hub-footer-action-font-size);+}++.model-hub-add-sub-overlay { background: #05050be0; }++.model-hub-add-sub-dialog {+ --model-hub-add-sub-width: 620px;+ --model-hub-add-sub-head-height: 72px;+ --model-hub-add-sub-title-size: 15px;+ --model-hub-add-sub-subtitle-size: 10.5px;+ --model-hub-add-sub-body-gap: 14px;+ --model-hub-add-sub-body-padding: 20px;+ --model-hub-add-sub-option-padding: 14px;+ --model-hub-add-sub-option-radius: 10px;+ --model-hub-add-sub-option-gap: 12px;+ --model-hub-add-sub-copy-gap: 6px;+ --model-hub-add-sub-label-size: 13.5px;+ --model-hub-add-sub-description-size: 11.5px;+ --model-hub-add-sub-description-line: 18px;+ --model-hub-add-sub-risk-radius: 8px;+ --model-hub-add-sub-risk-padding-y: 9px;+ --model-hub-add-sub-risk-padding-x: 11px;+ --model-hub-add-sub-risk-size: 11px;+ --model-hub-add-sub-risk-line: 17px;+ --model-hub-add-sub-risk-ink: var(--model-hub-gold-d9);+ --model-hub-add-sub-hint-size: 11px;+ --model-hub-add-sub-hint-line: 17px;+ --model-hub-add-sub-option-idle-fill: var(--model-hub-white-05);+ --model-hub-dialog-foot-height: 61px;+ --model-hub-dialog-action-height: 33px;+ --model-hub-dialog-action-radius: 7px;+ --model-hub-dialog-action-size: 12px;+ width: min(var(--model-hub-add-sub-width), calc(100vw - 32px));+ max-width: var(--model-hub-add-sub-width);+ border-radius: 14px;+}++.model-hub-add-sub-head {+ height: var(--model-hub-add-sub-head-height);+ padding: 16px 20px;+ gap: 4px;+}++.model-hub-add-sub-title { font-size: var(--model-hub-add-sub-title-size); }+.model-hub-add-sub-subtitle { font-size: var(--model-hub-add-sub-subtitle-size); }+.model-hub-add-sub-close {+ width: 27px;+ height: 27px;+ color: var(--model-hub-white-59);+}+.model-hub-add-sub-close svg { width: 15px; height: 15px; }++.model-hub-add-sub-body {+ gap: var(--model-hub-add-sub-body-gap);+ padding: var(--model-hub-add-sub-body-padding);+}++.model-hub-add-sub-options { gap: var(--model-hub-add-sub-body-gap); }++.model-hub-add-sub-option {+ padding: var(--model-hub-add-sub-option-padding);+ border-width: 1px;+ border-radius: var(--model-hub-add-sub-option-radius);+ gap: var(--model-hub-add-sub-option-gap);+}+.model-hub-add-sub-option--idle { background: var(--model-hub-add-sub-option-idle-fill); }++.model-hub-add-sub-option-copy { gap: var(--model-hub-add-sub-copy-gap); }+.model-hub-add-sub-option-label { font-size: var(--model-hub-add-sub-label-size); }+.model-hub-add-sub-badge { padding: 3px 8px; font-size: 10px; }+.model-hub-add-sub-description {+ font-size: var(--model-hub-add-sub-description-size);+ line-height: var(--model-hub-add-sub-description-line);+}+.model-hub-add-sub-risk {+ padding: var(--model-hub-add-sub-risk-padding-y) var(--model-hub-add-sub-risk-padding-x);+ border-radius: var(--model-hub-add-sub-risk-radius);+ font-size: var(--model-hub-add-sub-risk-size);+ color: var(--model-hub-add-sub-risk-ink);+ line-height: var(--model-hub-add-sub-risk-line);+}+.model-hub-add-sub-hint {+ min-height: var(--model-hub-add-sub-hint-line);+ font-size: var(--model-hub-add-sub-hint-size);+ line-height: var(--model-hub-add-sub-hint-line);+}+.model-hub-add-sub-foot {+ height: var(--model-hub-dialog-foot-height);+ padding: 14px 20px;+}+.model-hub-dialog-action {+ height: var(--model-hub-dialog-action-height);+ padding-inline: 14px;+ border-radius: var(--model-hub-dialog-action-radius);+ font-size: var(--model-hub-dialog-action-size);+}++.model-hub-add-key-overlay { background: #05050be0; }++.model-hub-add-key-dialog {+ --model-hub-add-key-width: 560px;+ --model-hub-add-key-radius: 14px;+ --model-hub-add-key-head-padding-y: 16px;+ --model-hub-add-key-head-padding-x: 20px;+ --model-hub-add-key-head-gap: 4px;+ --model-hub-add-key-title-size: 15px;+ --model-hub-add-key-subtitle-size: 10.5px;+ --model-hub-add-key-body-padding: 20px;+ --model-hub-add-key-body-gap: 14px;+ --model-hub-add-key-field-gap: 6px;+ --model-hub-add-key-label-size: 11.5px;+ --model-hub-add-key-input-height: 36px;+ --model-hub-add-key-input-radius: 8px;+ --model-hub-add-key-input-padding: 12px;+ --model-hub-add-key-input-size: 11.5px;+ --model-hub-add-key-hint-size: 10.5px;+ --model-hub-add-key-strip-padding-y: 11px;+ --model-hub-add-key-strip-padding-x: 13px;+ --model-hub-add-key-strip-gap: 10px;+ --model-hub-add-key-strip-radius: 9px;+ --model-hub-add-key-inventory-height: 59px;+ --model-hub-add-key-strip-title-size: 12px;+ --model-hub-add-key-strip-detail-size: 10.5px;+ --model-hub-add-key-strip-detail-line: 16px;+ --model-hub-add-key-outcome-padding-y: 14px;+ --model-hub-add-key-outcome-padding-x: 20px;+ --model-hub-add-key-segment-padding-y: 7px;+ --model-hub-add-key-segment-padding-x: 14px;+ --model-hub-add-key-segment-radius: 6px;+ --model-hub-add-key-segment-size: 11.5px;+ --model-hub-add-key-foot-padding-y: 14px;+ --model-hub-add-key-foot-padding-x: 20px;+ --model-hub-add-key-foot-gap: 8px;+ --model-hub-add-key-action-padding-y: 8px;+ --model-hub-add-key-action-padding-x: 14px;+ --model-hub-add-key-action-radius: 7px;+ --model-hub-add-key-action-size: 12px;+ --model-hub-add-key-control-fill: var(--model-hub-white-08);+ --model-hub-add-key-footer-fill: var(--model-hub-white-05);+ --model-hub-add-key-error-fill: #FF6B6B14;+ --model-hub-add-key-error-border: #FF6B6B40;+ --model-hub-add-key-advisory-fill: var(--model-hub-gold-14);+ --model-hub-add-key-advisory-border: var(--model-hub-gold-59);+ --model-hub-add-key-success-fill: #5BFFA014;+ --model-hub-add-key-success-border: #5BFFA040;+ --model-hub-add-key-dim-primary: #5BFFA059;+ width: min(var(--model-hub-add-key-width), calc(100vw - 32px));+ max-width: var(--model-hub-add-key-width);+ border-radius: var(--model-hub-add-key-radius);+}++.model-hub-add-key-head {+ padding: var(--model-hub-add-key-head-padding-y) var(--model-hub-add-key-head-padding-x);+ gap: var(--model-hub-add-key-head-gap);+}+.model-hub-add-key-title { font-size: var(--model-hub-add-key-title-size); }+.model-hub-add-key-subtitle { font-size: var(--model-hub-add-key-subtitle-size); }+.model-hub-add-key-body {+ padding: var(--model-hub-add-key-body-padding);+ gap: var(--model-hub-add-key-body-gap);+}+.model-hub-add-key-field {+ display: flex;+ width: 100%;+ flex-direction: column;+ gap: var(--model-hub-add-key-field-gap);+}+.model-hub-add-key-label {+ color: var(--model-hub-white-8c);+ font-size: var(--model-hub-add-key-label-size);+ font-weight: 600;+}+.model-hub-add-key-input {+ height: var(--model-hub-add-key-input-height);+ border-radius: var(--model-hub-add-key-input-radius);+ border-color: var(--border);+ background: var(--model-hub-add-key-control-fill);+ padding-inline: var(--model-hub-add-key-input-padding);+ font-size: var(--model-hub-add-key-input-size);+}+.model-hub-add-key-secret { width: 100%; }+.model-hub-add-key-hint {+ color: var(--model-hub-muted-b3);+ font-family: "JetBrains Mono", ui-monospace, monospace;+ font-size: var(--model-hub-add-key-hint-size);+}+.model-hub-add-key-test-row { min-height: 34px; }+.model-hub-add-key-secondary,+.model-hub-add-key-action {+ height: auto;+ border-radius: var(--model-hub-add-key-action-radius);+ padding: var(--model-hub-add-key-action-padding-y) var(--model-hub-add-key-action-padding-x);+ font-size: var(--model-hub-add-key-action-size);+ font-weight: 600;+}+.model-hub-add-key-strip {+ display: flex;+ align-items: flex-start;+ gap: var(--model-hub-add-key-strip-gap);+ width: 100%;+ padding: var(--model-hub-add-key-strip-padding-y) var(--model-hub-add-key-strip-padding-x);+ border: 1px solid var(--border);+ border-radius: var(--model-hub-add-key-strip-radius);+}+.model-hub-add-key-strip--working { background: var(--model-hub-add-key-control-fill); }+.model-hub-add-key-strip--error {+ border-color: var(--model-hub-add-key-error-border);+ background: var(--model-hub-add-key-error-fill);+}+.model-hub-add-key-strip--advisory {+ border-color: var(--model-hub-add-key-advisory-border);+ background: var(--model-hub-add-key-advisory-fill);+}+.model-hub-add-key-strip--inventory {+ min-height: var(--model-hub-add-key-inventory-height);+ align-items: center;+}+.model-hub-add-key-strip--success {+ align-items: center;+ border-color: var(--model-hub-add-key-success-border);+ background: var(--model-hub-add-key-success-fill);+ color: var(--mint);+ font-size: var(--model-hub-add-key-strip-title-size);+ font-weight: 600;+}+.model-hub-add-key-strip-title {+ font-size: var(--model-hub-add-key-strip-title-size);+ font-weight: 600;+}+.model-hub-add-key-strip-detail {+ color: var(--model-hub-muted-b3);+ font-family: "JetBrains Mono", ui-monospace, monospace;+ font-size: var(--model-hub-add-key-strip-detail-size);+ line-height: var(--model-hub-add-key-strip-detail-line);+}+.model-hub-add-key-outcome-wrap {+ padding: var(--model-hub-add-key-outcome-padding-y) var(--model-hub-add-key-outcome-padding-x);+}+.model-hub-add-key-protocol-field {+ gap: var(--model-hub-add-key-field-gap);+ padding: 4px var(--model-hub-add-key-outcome-padding-x) 16px;+}+.model-hub-add-key-segments {+ width: fit-content;+ gap: 3px;+ padding: 3px;+ border: 1px solid var(--border);+ border-radius: var(--model-hub-add-key-strip-radius);+ background: var(--model-hub-white-0a);+}+.model-hub-add-key-segment {+ border-radius: var(--model-hub-add-key-segment-radius);+ padding: var(--model-hub-add-key-segment-padding-y) var(--model-hub-add-key-segment-padding-x);+ color: var(--muted);+ font-size: var(--model-hub-add-key-segment-size);+ font-weight: 500;+}+.model-hub-add-key-segment.is-selected {+ background: var(--model-hub-add-key-success-fill);+ color: var(--mint);+}+.model-hub-add-key-foot {+ gap: var(--model-hub-add-key-foot-gap);+ padding: var(--model-hub-add-key-foot-padding-y) var(--model-hub-add-key-foot-padding-x);+ background: var(--model-hub-add-key-footer-fill);+}+.model-hub-add-key-action--dim {+ background: var(--model-hub-add-key-dim-primary);+}+.model-hub-add-key-action--dim:hover {+ background: var(--model-hub-add-key-dim-primary);+}++.model-hub-route-overlay { background: #05050be0; }++.model-hub-route-dialog {+ --model-hub-route-width: 520px;+ --model-hub-route-radius: 14px;+ --model-hub-route-head-height: 72px;+ --model-hub-route-title-size: 15px;+ --model-hub-route-subtitle-size: 10.5px;+ --model-hub-route-body-height: 302px;+ --model-hub-route-body-gap: 14px;+ --model-hub-route-label-size: 10.5px;+ --model-hub-route-list-radius: 10px;+ --model-hub-route-list-padding: 8px;+ --model-hub-route-list-gap: 6px;+ --model-hub-route-hop-height: 52px;+ --model-hub-route-hop-radius: 8px;+ --model-hub-route-hop-gap: 10px;+ --model-hub-route-ordinal-size: 22px;+ --model-hub-route-ordinal-radius: 6px;+ --model-hub-route-add-height: 38px;+ --model-hub-route-add-size: 11.5px;+ --model-hub-route-hint-size: 11.5px;+ --model-hub-route-hint-line: 18px;+ --model-hub-dialog-foot-height: 61px;+ --model-hub-dialog-action-height: 33px;+ --model-hub-dialog-action-radius: 7px;+ --model-hub-dialog-action-size: 12px;+ width: min(var(--model-hub-route-width), calc(100vw - 32px));+ max-width: var(--model-hub-route-width);+ border-radius: var(--model-hub-route-radius);+}+.model-hub-route-head { height: var(--model-hub-route-head-height); padding: 16px 20px; gap: 4px; }+.model-hub-route-close { width: 26px; height: 26px; margin: -5px -5px -5px 0; }+.model-hub-route-close > svg { width: 15px; height: 15px; }+.model-hub-route-title { font-size: var(--model-hub-route-title-size); }+.model-hub-route-subtitle { font-size: var(--model-hub-route-subtitle-size); }+.model-hub-route-body { min-height: var(--model-hub-route-body-height); padding: 20px; gap: var(--model-hub-route-body-gap); }+.model-hub-route-label { font-size: var(--model-hub-route-label-size); }+.model-hub-route-list { padding: var(--model-hub-route-list-padding); gap: var(--model-hub-route-list-gap); border-radius: var(--model-hub-route-list-radius); }+.model-hub-route-hop { height: var(--model-hub-route-hop-height); padding-inline: 10px; gap: var(--model-hub-route-hop-gap); border-radius: var(--model-hub-route-hop-radius); }+.model-hub-route-ordinal { width: var(--model-hub-route-ordinal-size); height: var(--model-hub-route-ordinal-size); border-radius: var(--model-hub-route-ordinal-radius); font-size: 11px; }+.model-hub-route-hop-copy { gap: 3px; }+.model-hub-route-hop-name { font-size: 12px; }+.model-hub-route-hop-model { font-size: 10.5px; }+.model-hub-route-remove { width: 26px; height: 26px; border-radius: 6px; }+.model-hub-route-add { height: var(--model-hub-route-add-height); border-radius: var(--model-hub-route-hop-radius); font-size: var(--model-hub-route-add-size); }+.model-hub-route-reseed { font-size: 12px; }+.model-hub-route-hint { font-size: var(--model-hub-route-hint-size); line-height: var(--model-hub-route-hint-line); }+.model-hub-route-foot { height: var(--model-hub-dialog-foot-height); padding: 14px 20px; }++.model-hub-source-detail {+ --model-hub-source-gap: 16px;+ --model-hub-source-radius: 12px;+ --model-hub-source-bar-height: 64px;+ --model-hub-source-bar-padding-y: 14px;+ --model-hub-source-bar-padding-x: 18px;+ --model-hub-source-bar-gap: 14px;+ --model-hub-source-tile-size: 36px;+ --model-hub-source-tile-radius: 9px;+ --model-hub-source-action-width: 95px;+ --model-hub-source-action-height: 33px;+ --model-hub-source-action-radius: 7px;+ --model-hub-source-table-head-height: 36px;+ --model-hub-source-table-row-height: 54px;+ --model-hub-source-table-draft-height: 55px;+ --model-hub-source-table-add-height: 41px;+ --model-hub-source-table-columns: 250px 84px minmax(220px, 470px) 1fr;+ --model-hub-source-table-gap: 16px;+ --model-hub-source-table-padding-x: 18px;+ --model-hub-source-table-padding-y: 11px;+ --model-hub-source-title-size: 14px;+ --model-hub-source-state-size: 12px;+ --model-hub-source-age-size: 11px;+ --model-hub-source-summary-size: 10.5px;+ --model-hub-source-label-size: 11px;+ --model-hub-source-model-size: 12px;+ --model-hub-source-pill-size: 10px;+ --model-hub-source-tier-size: 10.5px;+ --model-hub-source-footnote-size: 11.5px;+ --model-hub-source-manual-input-radius: 7px;+ --model-hub-source-summary-ink: var(--model-hub-muted-b3);+ --model-hub-source-label-ink: var(--model-hub-white-73);+ --model-hub-source-footnote-ink: var(--model-hub-white-8c);+ --model-hub-source-table-head-fill: var(--model-hub-white-05);+ --model-hub-source-chip-fill: var(--model-hub-white-0f);+ --model-hub-source-chip-padding-y: 4px;+ --model-hub-source-chip-padding-x: 9px;+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-source-gap);+}++.model-hub-source-bar {+ min-height: var(--model-hub-source-bar-height);+ padding: var(--model-hub-source-bar-padding-y) var(--model-hub-source-bar-padding-x);+ gap: var(--model-hub-source-bar-gap);+ border-radius: var(--model-hub-source-radius);+}+.model-hub-source-tile {+ width: var(--model-hub-source-tile-size);+ height: var(--model-hub-source-tile-size);+ border-radius: var(--model-hub-source-tile-radius);+}+.model-hub-source-title { font-size: var(--model-hub-source-title-size); }+.model-hub-source-state { font-size: var(--model-hub-source-state-size); }+.model-hub-source-age { font-size: var(--model-hub-source-age-size); }+.model-hub-source-summary { color: var(--model-hub-source-summary-ink); font-size: var(--model-hub-source-summary-size); }+.model-hub-source-action {+ width: var(--model-hub-source-action-width);+ height: var(--model-hub-source-action-height);+ border-radius: var(--model-hub-source-action-radius);+}+.model-hub-source-table { border-radius: var(--model-hub-source-radius); }+.model-hub-source-table-head,+.model-hub-source-table-row,+.model-hub-source-table-draft {+ grid-template-columns: var(--model-hub-source-table-columns);+ column-gap: var(--model-hub-source-table-gap);+ padding-inline: var(--model-hub-source-table-padding-x);+}+.model-hub-source-table-head {+ height: var(--model-hub-source-table-head-height);+ background: var(--model-hub-source-table-head-fill);+ color: var(--model-hub-source-label-ink);+ font-size: var(--model-hub-source-label-size);+}+.model-hub-source-table-row {+ min-height: var(--model-hub-source-table-row-height);+ padding-block: var(--model-hub-source-table-padding-y);+}+.model-hub-source-table-draft {+ min-height: var(--model-hub-source-table-draft-height);+ padding-block: var(--model-hub-source-table-padding-y);+}+.model-hub-source-table-add {+ min-height: var(--model-hub-source-table-add-height);+ padding-inline: var(--model-hub-source-table-padding-x);+}+.model-hub-source-model { font-size: var(--model-hub-source-model-size); }+.model-hub-source-manual-id { border-radius: var(--model-hub-source-manual-input-radius); }+.model-hub-source-pill { font-size: var(--model-hub-source-pill-size); }+.model-hub-source-tier { font-size: var(--model-hub-source-tier-size); }+.model-hub-source-entry-pill,+.model-hub-source-tier-chip {+ background: var(--model-hub-source-chip-fill);+ padding: var(--model-hub-source-chip-padding-y) var(--model-hub-source-chip-padding-x);+}+.model-hub-source-footnote {+ min-height: 17px;+ color: var(--model-hub-source-footnote-ink);+ font-size: var(--model-hub-source-footnote-size);+}++.model-hub-guard-overlay { background: #05050be0; }+.model-hub-guard-dialog {+ --model-hub-guard-width: 520px;+ --model-hub-guard-radius: 14px;+ --model-hub-guard-head-padding-y: 16px;+ --model-hub-guard-head-padding-x: 20px;+ --model-hub-guard-head-gap: 4px;+ --model-hub-guard-title-size: 15px;+ --model-hub-guard-subtitle-size: 10.5px;+ --model-hub-guard-close-size: 27px;+ --model-hub-guard-close-icon-size: 15px;+ --model-hub-guard-body-padding: 20px;+ --model-hub-guard-body-gap: 14px;+ --model-hub-guard-label-gap: 6px;+ --model-hub-guard-label-size: 10.5px;+ --model-hub-guard-count-padding-y: 3px;+ --model-hub-guard-count-padding-x: 8px;+ --model-hub-guard-count-size: 10px;+ --model-hub-guard-list-padding: 8px;+ --model-hub-guard-list-gap: 6px;+ --model-hub-guard-list-radius: 10px;+ --model-hub-guard-hop-height: 52px;+ --model-hub-guard-hop-padding-x: 10px;+ --model-hub-guard-hop-gap: 10px;+ --model-hub-guard-hop-radius: 8px;+ --model-hub-guard-hop-name-size: 12px;+ --model-hub-guard-hop-detail-gap: 3px;+ --model-hub-guard-hop-detail-size: 10.5px;+ --model-hub-guard-hint-gap: 7px;+ --model-hub-guard-hint-size: 11.5px;+ --model-hub-guard-hint-line: 17px;+ --model-hub-guard-hint-icon-size: 13px;+ --model-hub-guard-hint-icon-offset: 2px;+ --model-hub-guard-foot-padding-y: 14px;+ --model-hub-guard-foot-padding-x: 20px;+ --model-hub-guard-foot-gap: 8px;+ --model-hub-guard-action-padding-y: 8px;+ --model-hub-guard-action-padding-x: 14px;+ --model-hub-guard-action-radius: 7px;+ --model-hub-guard-action-size: 12px;+ width: min(var(--model-hub-guard-width), calc(100vw - 32px));+ gap: 0;+ border-radius: var(--model-hub-guard-radius);+ box-shadow: 0 16px 40px #00000099;+}+.model-hub-guard-head {+ padding: var(--model-hub-guard-head-padding-y) var(--model-hub-guard-head-padding-x);+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-guard-head-gap);+ border-bottom: 1px solid var(--border);+}+.model-hub-guard-title { font-size: var(--model-hub-guard-title-size); font-weight: 700; }+.model-hub-guard-subtitle { color: var(--muted); font-family: 'JetBrains Mono', monospace; font-size: var(--model-hub-guard-subtitle-size); }+.model-hub-guard-close { width: var(--model-hub-guard-close-size); height: var(--model-hub-guard-close-size); color: var(--model-hub-white-59); }+.model-hub-guard-close svg { width: var(--model-hub-guard-close-icon-size); height: var(--model-hub-guard-close-icon-size); }+.model-hub-guard-body { padding: var(--model-hub-guard-body-padding); display: flex; flex-direction: column; gap: var(--model-hub-guard-body-gap); }+.model-hub-guard-label { display: flex; align-items: center; justify-content: flex-start; gap: var(--model-hub-guard-label-gap); color: var(--model-hub-white-73); font-size: var(--model-hub-guard-label-size); font-weight: 700; }+.model-hub-guard-label > span { padding: var(--model-hub-guard-count-padding-y) var(--model-hub-guard-count-padding-x); border: 1px solid var(--border); border-radius: 999px; background: var(--model-hub-white-0a); color: var(--muted); font-size: var(--model-hub-guard-count-size); font-weight: 600; }+.model-hub-guard-list { padding: var(--model-hub-guard-list-padding); display: flex; flex-direction: column; gap: var(--model-hub-guard-list-gap); border: 1px solid var(--border); border-radius: var(--model-hub-guard-list-radius); background: var(--background); }+.model-hub-guard-hop { min-height: var(--model-hub-guard-hop-height); padding: 0 var(--model-hub-guard-hop-padding-x); display: flex; align-items: center; gap: var(--model-hub-guard-hop-gap); border: 1px solid var(--border); border-radius: var(--model-hub-guard-hop-radius); background: var(--model-hub-white-08); }+.model-hub-guard-hop strong { display: block; color: #f5f1e8b3; font-size: var(--model-hub-guard-hop-name-size); font-weight: 600; }+.model-hub-guard-hop span span { margin-top: var(--model-hub-guard-hop-detail-gap); display: block; color: var(--model-hub-muted-b3); font-family: 'JetBrains Mono', monospace; font-size: var(--model-hub-guard-hop-detail-size); }+.model-hub-guard-hint { display: flex; align-items: flex-start; gap: var(--model-hub-guard-hint-gap); color: var(--model-hub-white-73); font-size: var(--model-hub-guard-hint-size); line-height: var(--model-hub-guard-hint-line); }+.model-hub-guard-hint svg { width: var(--model-hub-guard-hint-icon-size); height: var(--model-hub-guard-hint-icon-size); margin-top: var(--model-hub-guard-hint-icon-offset); flex: none; color: var(--model-hub-white-59); }+.model-hub-guard-foot { padding: var(--model-hub-guard-foot-padding-y) var(--model-hub-guard-foot-padding-x); display: flex; align-items: center; justify-content: flex-end; gap: var(--model-hub-guard-foot-gap); border-top: 1px solid var(--border); background: var(--model-hub-white-05); }+.model-hub-guard-action { height: auto; padding: var(--model-hub-guard-action-padding-y) var(--model-hub-guard-action-padding-x); border-radius: var(--model-hub-guard-action-radius); font-size: var(--model-hub-guard-action-size); font-weight: 600; }++.model-hub-direct {+ --model-hub-direct-gap: 16px;+ --model-hub-direct-benefits-width: 452px;+ --model-hub-direct-card-height: 330px;+ --model-hub-direct-radius: 14px;+ --model-hub-direct-head-height: 56px;+ --model-hub-direct-content-padding: 12px;+ --model-hub-direct-content-gap: 10px;+ --model-hub-direct-row-radius: 10px;+ --model-hub-direct-note-height: 49px;+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-direct-gap);+}+.model-hub-direct-grid { gap: var(--model-hub-direct-gap); }+.model-hub-direct-card {+ min-height: var(--model-hub-direct-card-height);+ border-radius: var(--model-hub-direct-radius);+}+.model-hub-direct-head { min-height: var(--model-hub-direct-head-height); }+.model-hub-direct-content {+ padding: var(--model-hub-direct-content-padding);+ gap: var(--model-hub-direct-content-gap);+}+.model-hub-direct-row {+ border: 1px solid var(--model-hub-white-14);+ border-radius: var(--model-hub-direct-row-radius);+}+.model-hub-direct-row--backend { height: 64px; }+.model-hub-direct-backend-copy,+.model-hub-direct-benefit-copy {+ display: flex;+ min-width: 0;+ flex: 1;+ flex-direction: column;+ align-items: flex-start;+ gap: 4px;+}+.model-hub-direct-backend-name { font-size: 12.5px; font-weight: 600; }+.model-hub-direct-backend-detail { color: var(--model-hub-muted-cc); font-size: 11px; line-height: normal; }+.model-hub-direct-benefit-title-row { width: 100%; }+.model-hub-direct-benefit-detail { width: 100%; color: var(--muted); font-size: 11.5px; line-height: 19px; }+.model-hub-direct-note {+ min-height: var(--model-hub-direct-note-height);+ padding: 14px 18px;+ border-radius: var(--model-hub-direct-radius);+ border-color: var(--model-hub-white-14);+ background: var(--model-hub-white-06);+ color: var(--muted);+}+.model-hub-direct-kind-pill {+ display: inline-flex;+ align-items: center;+ justify-content: flex-start;+ gap: 5px;+ border-color: var(--model-hub-white-14);+ background: var(--model-hub-white-0a);+ color: var(--muted);+}+.model-hub-direct-tile { background: var(--model-hub-white-0a); color: var(--muted); }+.model-hub-direct-switch { border-color: var(--model-hub-white-24); background: var(--model-hub-white-0a); }++.model-hub-direct-empty {+ display: flex;+ min-height: 330px;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 8px;+ text-align: center;+}++.model-hub-direct-empty h2 {+ color: var(--foreground);+ font-size: 15px;+ font-weight: 700;+}++.model-hub-direct-empty p,+.model-hub-direct-empty span {+ max-width: 520px;+ color: var(--muted);+ font-size: 12px;+ line-height: 18px;+}++.model-hub-order-overlay {+ --model-hub-order-scrim: #05050be0;+ background: var(--model-hub-order-scrim);+}++.model-hub-order-drawer {+ --model-hub-order-width: 460px;+ --model-hub-order-shadow: -18px 0 48px #000000a6;+ --model-hub-order-head-padding-y: 18px;+ --model-hub-order-head-padding-x: 20px;+ --model-hub-order-head-gap: 6px;+ --model-hub-order-title-size: 15px;+ --model-hub-order-subtitle-size: 11.5px;+ --model-hub-order-subtitle-line: 17px;+ --model-hub-order-body-padding: 20px;+ --model-hub-order-body-gap: 18px;+ --model-hub-order-section-gap: 8px;+ --model-hub-order-section-size: 10.5px;+ --model-hub-order-row-height: 58px;+ --model-hub-order-row-radius: 9px;+ --model-hub-order-row-padding-x: 12px;+ --model-hub-order-row-gap: 10px;+ --model-hub-order-row-ordered: var(--model-hub-white-08);+ --model-hub-order-row-held: var(--model-hub-white-05);+ --model-hub-order-grip-size: 14px;+ --model-hub-order-grip-ink: var(--model-hub-white-4d);+ --model-hub-order-grip-dim: var(--model-hub-white-33);+ --model-hub-order-ordinal-size: 22px;+ --model-hub-order-ordinal-radius: 6px;+ --model-hub-order-ordinal-fill: var(--model-hub-white-0a);+ --model-hub-order-name-size: 12.5px;+ --model-hub-order-meta-size: 10.5px;+ --model-hub-order-tag-padding-y: 3px;+ --model-hub-order-tag-padding-x: 8px;+ --model-hub-order-tag-size: 10px;+ --model-hub-order-action-padding-y: 9px;+ --model-hub-order-action-padding-x: 12px;+ --model-hub-order-action-radius: 8px;+ --model-hub-order-action-size: 11.5px;+ --model-hub-order-foot-padding-y: 14px;+ --model-hub-order-foot-padding-x: 20px;+ --model-hub-order-foot-gap: 8px;+ --model-hub-order-foot-fill: var(--model-hub-white-05);+ --model-hub-order-foot-action-padding-y: 8px;+ --model-hub-order-foot-action-padding-x: 14px;+ --model-hub-order-foot-action-radius: 7px;+ --model-hub-order-foot-action-size: 12px;+ width: min(var(--model-hub-order-width), 100vw);+ border-left: 1px solid var(--border-strong);+ box-shadow: var(--model-hub-order-shadow);+}++.model-hub-order-head {+ min-height: 82px;+ padding: var(--model-hub-order-head-padding-y) var(--model-hub-order-head-padding-x);+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-order-head-gap);+}+.model-hub-order-title { font-size: var(--model-hub-order-title-size); }+.model-hub-order-info { width: 13px; height: 13px; color: var(--model-hub-white-59); }+.model-hub-order-subtitle {+ color: var(--model-hub-white-73);+ font-size: var(--model-hub-order-subtitle-size);+ line-height: var(--model-hub-order-subtitle-line);+}+.model-hub-order-close { color: var(--model-hub-white-59); }+.model-hub-order-body {+ padding: var(--model-hub-order-body-padding);+ gap: var(--model-hub-order-body-gap);+}+.model-hub-order-section {+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-order-section-gap);+}+.model-hub-order-section-head {+ display: flex;+ align-items: center;+ justify-content: flex-start;+ gap: 6px;+ font-size: var(--model-hub-order-section-size);+ font-weight: 700;+ letter-spacing: 1.1px;+ color: var(--model-hub-white-73);+}+.model-hub-order-section-head > span {+ display: inline-flex;+ flex: none;+ align-items: center;+ justify-content: flex-start;+ gap: 0;+ padding: 3px 8px;+ border: 1px solid var(--model-hub-white-14);+ border-radius: 999px;+ background: var(--model-hub-white-0a);+ color: var(--muted);+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0;+ line-height: normal;+}+.model-hub-order-row {+ height: var(--model-hub-order-row-height);+ padding-inline: var(--model-hub-order-row-padding-x);+ display: flex;+ align-items: center;+ gap: var(--model-hub-order-row-gap);+ border: 1px solid var(--border);+ border-radius: var(--model-hub-order-row-radius);+}+.model-hub-order-row--ordered { background: var(--model-hub-order-row-ordered); }+.model-hub-order-row--held { background: var(--model-hub-order-row-held); }+.model-hub-order-grip {+ width: var(--model-hub-order-grip-size);+ height: var(--model-hub-order-grip-size);+ flex: none;+ color: var(--model-hub-order-grip-ink);+}+.model-hub-order-grip svg { width: 100%; height: 100%; }+.model-hub-order-grip:disabled { color: var(--model-hub-order-grip-dim); }+.model-hub-order-grip.is-grabbed { color: var(--mint); }+.model-hub-order-ordinal {+ width: var(--model-hub-order-ordinal-size);+ height: var(--model-hub-order-ordinal-size);+ display: inline-flex;+ flex: none;+ align-items: center;+ justify-content: center;+ border-radius: var(--model-hub-order-ordinal-radius);+ background: var(--model-hub-order-ordinal-fill);+ color: var(--muted);+ font-family: 'JetBrains Mono', monospace;+ font-size: 11px;+ font-weight: 400;+}+.model-hub-order-ordinal.is-first { background: var(--mint-soft); color: var(--mint); }+.model-hub-order-name { font-size: var(--model-hub-order-name-size); font-weight: 600; }+.model-hub-order-identity {+ display: flex;+ min-width: 0;+ flex: 1;+ flex-direction: column;+ align-items: flex-start;+ justify-content: flex-start;+ gap: 3px;+}+.model-hub-order-meta {+ color: var(--model-hub-muted-b3);+ font-family: 'JetBrains Mono', monospace;+ font-size: var(--model-hub-order-meta-size);+ line-height: normal;+}+.model-hub-order-tag {+ padding: var(--model-hub-order-tag-padding-y) var(--model-hub-order-tag-padding-x);+ flex: none;+ border: 1px solid var(--border);+ border-radius: 999px;+ color: var(--muted);+ font-size: var(--model-hub-order-tag-size);+ font-weight: 600;+}+.model-hub-order-row-action {+ min-height: 31px;+ padding: var(--model-hub-order-action-padding-y) var(--model-hub-order-action-padding-x);+ border-radius: var(--model-hub-order-action-radius);+ font-size: var(--model-hub-order-action-size);+ font-weight: 700;+}+.model-hub-order-held-icon { width: var(--model-hub-order-grip-size); height: var(--model-hub-order-grip-size); flex: none; color: var(--model-hub-order-grip-dim); }+.model-hub-order-empty,+.model-hub-order-state {+ min-height: var(--model-hub-order-row-height);+ padding: 14px;+ display: flex;+ align-items: center;+ gap: 8px;+ border: 1px dashed var(--border);+ border-radius: var(--model-hub-order-row-radius);+ color: var(--muted);+ font-size: 11.5px;+}+.model-hub-order-state--error { color: var(--destructive); }+.model-hub-order-foot {+ min-height: 61px;+ padding: var(--model-hub-order-foot-padding-y) var(--model-hub-order-foot-padding-x);+ gap: var(--model-hub-order-foot-gap);+ background: var(--model-hub-order-foot-fill);+}+.model-hub-order-action {+ min-height: 33px;+ padding: var(--model-hub-order-foot-action-padding-y) var(--model-hub-order-foot-action-padding-x);+ border-radius: var(--model-hub-order-foot-action-radius);+ font-size: var(--model-hub-order-foot-action-size);+ font-weight: 600;+}++.model-hub-adopt-overlay {+ --model-hub-adopt-scrim: #05050be0;+ background: var(--model-hub-adopt-scrim);+}++.model-hub-adopt-dialog {+ --model-hub-adopt-width: 560px;+ --model-hub-adopt-radius: 14px;+ --model-hub-adopt-shadow: 0 16px 40px #00000099;+ --model-hub-adopt-head-padding-y: 16px;+ --model-hub-adopt-head-padding-x: 20px;+ --model-hub-adopt-head-gap: 4px;+ --model-hub-adopt-title-size: 15px;+ --model-hub-adopt-close-size: 15px;+ --model-hub-adopt-subtitle-size: 11.5px;+ --model-hub-adopt-body-padding: 20px;+ --model-hub-adopt-body-gap: 16px;+ --model-hub-adopt-section-gap: 8px;+ --model-hub-adopt-section-size: 11.5px;+ --model-hub-adopt-bullet-gap: 9px;+ --model-hub-adopt-bullet-icon: 13px;+ --model-hub-adopt-bullet-size: 12.5px;+ --model-hub-adopt-bullet-line: 20px;+ --model-hub-adopt-failure-bg: #ff6b6b14;+ --model-hub-adopt-failure-border: #ff6b6b40;+ --model-hub-adopt-failure-icon: #ff8a8a;+ --model-hub-adopt-foot-fill: var(--model-hub-white-05);+ --model-hub-adopt-foot-padding-y: 14px;+ --model-hub-adopt-foot-padding-x: 20px;+ --model-hub-adopt-action-padding-y: 8px;+ --model-hub-adopt-action-padding-x: 14px;+ --model-hub-adopt-action-radius: 7px;+ --model-hub-adopt-action-size: 12px;+ width: min(var(--model-hub-adopt-width), calc(100vw - 32px));+ max-width: var(--model-hub-adopt-width);+ max-height: calc(100dvh - 32px);+ border: 1px solid var(--border-strong);+ border-radius: var(--model-hub-adopt-radius);+ box-shadow: var(--model-hub-adopt-shadow);+}+.model-hub-adopt-head {+ padding: var(--model-hub-adopt-head-padding-y) var(--model-hub-adopt-head-padding-x);+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-adopt-head-gap);+ border-bottom: 1px solid var(--border);+}+.model-hub-adopt-title { font-size: var(--model-hub-adopt-title-size); font-weight: 700; }+.model-hub-adopt-close {+ width: 27px;+ height: 27px;+ color: var(--model-hub-white-59);+}+.model-hub-adopt-close svg { width: var(--model-hub-adopt-close-size); height: var(--model-hub-adopt-close-size); }+.model-hub-adopt-subtitle {+ color: var(--model-hub-muted-b3);+ font-family: 'JetBrains Mono', monospace;+ font-size: var(--model-hub-adopt-subtitle-size);+}+.model-hub-adopt-body {+ padding: var(--model-hub-adopt-body-padding);+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-adopt-body-gap);+ overflow-y: auto;+}+.model-hub-adopt-section {+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-adopt-section-gap);+}+.model-hub-adopt-section h3 {+ color: var(--model-hub-white-8c);+ font-size: var(--model-hub-adopt-section-size);+ font-weight: 600;+}+.model-hub-adopt-bullet {+ display: flex;+ align-items: flex-start;+ gap: var(--model-hub-adopt-bullet-gap);+ color: var(--foreground);+ font-size: var(--model-hub-adopt-bullet-size);+ line-height: var(--model-hub-adopt-bullet-line);+}+.model-hub-adopt-bullet svg {+ width: var(--model-hub-adopt-bullet-icon);+ height: var(--model-hub-adopt-bullet-icon);+ margin-top: 3px;+ flex: none;+ color: var(--mint);+}+.model-hub-adopt-failure {+ padding: 11px 13px;+ display: flex;+ align-items: flex-start;+ gap: 10px;+ border: 1px solid var(--model-hub-adopt-failure-border);+ border-radius: 9px;+ background: var(--model-hub-adopt-failure-bg);+}+.model-hub-adopt-failure > svg {+ width: 16px;+ height: 16px;+ flex: none;+ color: var(--model-hub-adopt-failure-icon);+}+.model-hub-adopt-failure strong { display: block; font-size: 12px; font-weight: 600; }+.model-hub-adopt-failure span span {+ margin-top: 3px;+ display: block;+ color: var(--muted);+ font-family: 'JetBrains Mono', monospace;+ font-size: 10.5px;+}+.model-hub-adopt-foot {+ padding: var(--model-hub-adopt-foot-padding-y) var(--model-hub-adopt-foot-padding-x);+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 8px;+ border-top: 1px solid var(--border);+ background: var(--model-hub-adopt-foot-fill);+}+.model-hub-adopt-action {+ min-height: 33px;+ padding: var(--model-hub-adopt-action-padding-y) var(--model-hub-adopt-action-padding-x);+ border-radius: var(--model-hub-adopt-action-radius);+ font-size: var(--model-hub-adopt-action-size);+ font-weight: 600;+}++@media (min-width: 1024px) {+ .model-hub-direct-grid {+ grid-template-columns: minmax(0, 1fr) var(--model-hub-direct-benefits-width);+ }+}++@media (max-width: 767px) {+ .model-hub-source-table-head { display: none; }+ .model-hub-source-table-row,+ .model-hub-source-table-draft { grid-template-columns: minmax(0, 1fr); }+ .model-hub-source-bar { align-items: stretch; }+ .model-hub-source-action { width: auto; flex: 1 1 0; }+ .model-hub-direct-card { min-height: 0; }+}++@media (min-width: 1024px) {+ .model-hub-shell { padding-top: 4px; }+ .model-hub-overview-body { height: 854px; }+ .model-hub-overview-grid {+ display: grid;+ grid-template-columns: var(--model-hub-upstream-track) var(--model-hub-rail-track) minmax(0, 1fr);+ gap: var(--model-hub-track-gap);+ height: var(--model-hub-track-height);+ align-items: start;+ }+ .model-hub-legend {+ position: absolute;+ top: 820px;+ left: 0;+ width: 100%;+ height: var(--model-hub-legend-height);+ padding-block: 0;+ }+}++.model-hub-wire {+ fill: none;+ stroke-linecap: round;+ stroke-linejoin: round;+}++.model-hub-wire--native {+ stroke: var(--cyan);+ stroke-width: var(--model-hub-wire-active-width);+ filter: drop-shadow(0 0 4px color-mix(in srgb, var(--cyan) 40%, transparent));+}++.model-hub-wire--gateway {+ stroke: var(--mint);+ stroke-width: var(--model-hub-wire-active-width);+ filter: drop-shadow(0 0 4px color-mix(in srgb, var(--mint) 40%, transparent));+}++.model-hub-wire--connected_unused {+ stroke: color-mix(in srgb, var(--foreground) 15%, transparent);+ stroke-width: var(--model-hub-wire-muted-width);+}++.model-hub-wire--takeover {+ stroke: var(--violet);+ stroke-width: var(--model-hub-wire-active-width);+ filter: drop-shadow(0 0 4px color-mix(in srgb, var(--violet) 40%, transparent));+}++.model-hub-wire--unavailable {+ stroke: var(--gold);+ stroke-width: var(--model-hub-wire-muted-width);+}++.model-hub-wire-node {+ r: calc(var(--model-hub-wire-node) / 2);+}++.model-hub-wire-node--native { fill: var(--cyan); }+.model-hub-wire-node--gateway { fill: var(--mint); }+.model-hub-wire-node--connected_unused {+ fill: var(--background);+ stroke: color-mix(in srgb, var(--foreground) 15%, transparent);+ stroke-width: 1.25px;+}+.model-hub-wire-node--takeover { fill: var(--violet); }+.model-hub-wire-node--unavailable { fill: var(--gold); }++.model-hub-rail-line {+ stroke: color-mix(in srgb, var(--mint) 20%, transparent);+ stroke-width: 2px;+}++.model-hub-legend {+ min-height: var(--model-hub-legend-height);+}++.model-hub-legend-swatch {+ width: 20px;+ height: 2px;+ border-radius: 2px;+}++.model-hub-legend-swatch--connected_unused {+ height: 1px;+}diff --git a/ui/src/components/settings/models/modelHubSurfaceState.ts b/ui/src/components/settings/models/modelHubSurfaceState.tsnew file mode 100644index 000000000..17e3531a8--- /dev/null+++ b/ui/src/components/settings/models/modelHubSurfaceState.ts@@ -0,0 +1,29 @@+import { foldRegionRead, type RegionRead } from './regionRead';+import type { AgentSupply, Source } from './types';++export type ModelsSurfaceKind = 'direct_empty' | 'gateway';++export const modelsSurfaceKind = (agents: AgentSupply[], sources: Source[]): ModelsSurfaceKind =>+ agents.every((agent) => agent.mode === 'direct') && sources.length === 0+ ? 'direct_empty'+ : 'gateway';++/** Frame 09 has no region failure surface, so only two fresh reads may select it. */+export const modelsSurfaceKindFromReads = (+ agentsRead: RegionRead<AgentSupply[]>,+ sourcesRead: RegionRead<Source[]>,+): ModelsSurfaceKind => {+ const agents = foldRegionRead<AgentSupply[], AgentSupply[] | null>(agentsRead, {+ loading: () => null,+ ready: (data) => data,+ unread: () => null,+ degraded: () => null,+ });+ const sources = foldRegionRead<Source[], Source[] | null>(sourcesRead, {+ loading: () => null,+ ready: (data) => data,+ unread: () => null,+ degraded: () => null,+ });+ return agents && sources ? modelsSurfaceKind(agents, sources) : 'gateway';+};diff --git a/ui/src/components/settings/models/modelRows.test.ts b/ui/src/components/settings/models/modelRows.test.tsindex 553e65fa3..e3e519513 100644--- a/ui/src/components/settings/models/modelRows.test.ts+++ b/ui/src/components/settings/models/modelRows.test.ts@@ -1,197 +1,72 @@import { describe, expect, it } from 'vitest';-import {- 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',- 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: 5,- 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 => ({- contract_version: 5,- 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_chat',- supply_channel: 'hub',- billing: 'metered',- state: { status: 'active' },- last_discovered_at: null,- 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']);+import { collapsedModelRows, listedModelIds, modelChainKey, modelChainRequests, modelSupplyState, NOMINAL_MODEL_BASELINE } from './modelRows';+import type { AgentSupply } from './types';++const agent: AgentSupply = {+ backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed', sources: { order: [], eligibility: [] },+ routes: { 'route-only': { hops: [] } }, builtin_models: ['builtin'], model_supply: [{ model_id: 'builtin', chain_length: 0, has_runnable_hop: false }],+ selected_model_id: null, selected_model_explicit: false, supply_status: null, named_agents: [], menu: null,+};++describe('modelRows', () => {+ it('lists backend menu models and every persisted Route row exactly once', () => {+ expect(listedModelIds(agent)).toEqual(['builtin', 'route-only']);});- 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('requests chains only for hub model rows', () => {+ expect(modelChainRequests([agent])).toEqual([+ { backend: 'claude', modelId: 'builtin' },+ { backend: 'claude', modelId: 'route-only' },]);+ expect(modelChainKey('claude', 'builtin')).toBe('claude\u0000builtin');});- 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);+describe('collapsedModelRows', () => {+ const menu = Array.from({ length: 12 }, (_, index) => `model-${index + 1}`);+ const withEmptyRoutes = (count: number): AgentSupply => ({+ ...agent,+ builtin_models: menu,+ routes: {},+ model_supply: menu.map((modelId, index) => ({ model_id: modelId, chain_length: index < count ? 0 : 1, has_runnable_hop: index >= count })),});- 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.each([0, 2, 5, menu.length])('keeps every unsupplied row plus the nominal baseline (%i unsupplied)', (unsupplied) => {+ const result = collapsedModelRows(withEmptyRoutes(unsupplied));+ const nominalCount = Math.min(NOMINAL_MODEL_BASELINE, menu.length - unsupplied);- 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']);+ expect(result.visible).toHaveLength(unsupplied + nominalCount);+ expect(result.hidden).toHaveLength(menu.length - unsupplied - nominalCount);+ expect(result.visible).toEqual(menu.filter((_, index) => index < unsupplied + nominalCount));});- 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('preserves the backend menu order and reveals every row when expanded', () => {+ expect(collapsedModelRows(withEmptyRoutes(2), true)).toEqual({ visible: menu, hidden: [] });});- it('counts an interrupted model without treating absent selection as another issue', () => {- const row = read({ supply_state: 'interrupted', chain: [] });- const a = agent({ selected_model_id: null, builtin_models: ['builtin-model'], model_supply: [] });- expect(modelIssueCount([a], { [modelChainKey('claude', 'builtin-model')]: row })).toBe(1);+ it('keeps a nonempty but wholly unrunnable Route visible after the nominal baseline', () => {+ const paused = {+ ...withEmptyRoutes(0),+ model_supply: menu.map((modelId, index) => ({+ model_id: modelId,+ chain_length: 1,+ has_runnable_hop: index !== menu.length - 1,+ })),+ };++ expect(modelSupplyState(paused, menu.at(-1) as string)).toBe('paused');+ expect(collapsedModelRows(paused).visible).toContain(menu.at(-1));});- 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);- expect(modelNeedsAttention(agent(), 'builtin-model', read(), runtime('not_started'))).toBe(false);- 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('classifies structural emptiness before the forced unrunnable reading', () => {+ expect(modelSupplyState(withEmptyRoutes(1), menu[0])).toBe('unconfigured');});- 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('treats direct rows as nominal because direct mode has no model_supply projection', () => {+ const result = collapsedModelRows({ ...withEmptyRoutes(0), mode: 'direct', model_supply: null });- it('does not claim health when the live chain could not be read', () => {- expect(modelNeedsAttention(agent(), 'builtin-model', { kind: 'error' })).toBe(true);+ expect(result.visible).toEqual(menu.slice(0, NOMINAL_MODEL_BASELINE));});});diff --git a/ui/src/components/settings/models/modelRows.ts b/ui/src/components/settings/models/modelRows.tsindex 007525b76..c6b97b56f 100644--- a/ui/src/components/settings/models/modelRows.ts+++ b/ui/src/components/settings/models/modelRows.ts@@ -1,10 +1,9 @@import { eligibleSources } from './eligibility';import { buildIdentifier } from './menus/identifiers';-import type { AgentBackend, AgentChain, AgentMapping, AgentSupply, RuntimeDependency, Source } from './types';+import type { RegionRead } from './regionRead';+import type { AgentBackend, AgentChain, AgentSupply, Source } from './types';-export type ModelChainRead =- | { kind: 'ready'; chain: AgentChain }- | { kind: 'error' };+export type ModelChainRead = RegionRead<AgentChain>;export type ModelChainIndex = Record<string, ModelChainRead>;@@ -16,10 +15,6 @@ export type ModelChainRequest = {export const modelChainKey = (backend: AgentBackend, modelId: string): string =>`${backend}\u0000${modelId}`;-/** Lazy-start idleness is runnable-on-demand; only actual failures block Hub rows. */-export const runtimeHealthNeedsAttention = (health: RuntimeDependency['status']['health']): boolean =>- health !== 'ok' && health !== 'not_started';-/** 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');@@ -60,21 +55,13 @@ export function modelHasOffOrderSupplier(agent: AgentSupply, sources: Source[],);}-/** 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) : []),+ ...Object.keys(agent.routes ?? {}),];const seen = new Set<string>();return [...primary, ...extras].filter((modelId) => {@@ -84,6 +71,40 @@ export function listedModelIds(agent: AgentSupply): string[] {});}+export const NOMINAL_MODEL_BASELINE = 3;++export type CollapsedModelRows = {+ visible: string[];+ hidden: string[];+};++export type ModelSupplyState = 'available' | 'paused' | 'unconfigured';++/** Structural emptiness wins before live runnability, exactly as the contract specifies. */+export function modelSupplyState(agent: AgentSupply, modelId: string): ModelSupplyState {+ const supply = agent.model_supply?.find((row) => row.model_id === modelId);+ if (!supply) return 'available';+ if (supply.chain_length === 0) return 'unconfigured';+ return supply.has_runnable_hop ? 'available' : 'paused';+}++/**+ * Keep every structurally unsupplied model plus a small nominal baseline.+ * This reads only AgentSupply, so late or failed per-model chain reads cannot+ * reorganize the group under the user's pointer.+ */+export function collapsedModelRows(agent: AgentSupply, expanded = false): CollapsedModelRows {+ const models = listedModelIds(agent);+ if (expanded) return { visible: models, hidden: [] };+ const needsAttention = new Set(models.filter((modelId) => modelSupplyState(agent, modelId) !== 'available'));+ const baseline = new Set(+ models.filter((modelId) => !needsAttention.has(modelId)).slice(0, NOMINAL_MODEL_BASELINE),+ );+ const visible = models.filter((modelId) => needsAttention.has(modelId) || baseline.has(modelId));+ const visibleSet = new Set(visible);+ return { visible, hidden: models.filter((modelId) => !visibleSet.has(modelId)) };+}+/** 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>();@@ -96,33 +117,3 @@ export function modelChainRequests(agents: AgentSupply[]): ModelChainRequest[] {}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 && runtimeHealthNeedsAttention(runtime.status.health)) return true;- return read.chain.supply_state !== 'ok';- }- return agent.model_supply?.find((model) => model.model_id === modelId)?.chain_length === 0;-}--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;- }, 0);-}diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 81049cb83..8dc5b2c05 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -1,6 +1,6 @@// Model Hub API client. Presents ONE typed surface to the UI; internally it-// either serves in-memory fixtures (mock mode, default while L2 is unmerged) or-// calls the frozen `/api/models/*` REST endpoints (live mode). Components never+// either serves in-memory fixtures for hermetic visual tests or calls the frozen+// `/api/models/*` REST endpoints (live mode). Components never// branch on the mode — flip `MODELS_API_MODE` in featureFlags.ts to switch.//// Methods unwrap the frozen envelope ({ok:true, …} | {ok:false, error}) and@@ -18,20 +18,20 @@ import {mockEligibility,mockRecommendedOrder,} from './mockData';-import { buildIdentifier } from './menus/identifiers';import { canReauth, canReplaceKey, wasBlocked } from './repair';import { isUnhealthy } from './supply';import type {AdoptedBy,+ AddedTo,AgentBackend,AgentChain,AgentChainLink,- AgentMapping,AgentMenu,AgentMode,AgentSourcesPut,AgentSupply,ApiKeySourceCreate,+ ApiKeySourceObservation,CredentialReplace,CustomModelCreate,MigrationApplyResult,@@ -39,37 +39,27 @@ import type {OAuthFlow,ProbeResult,ResolutionEvent,+ RouteHopRef,RuntimeDependency,- SkippedBy,Source,+ SourceObservation,SourcePatch,SourceRepaired,SupplyChannel,SupplyGap,} from './types';-import { AGENT_CHAIN_CONTRACT_VERSION, PROBE_RESULT_CONTRACT_VERSION } from './types';+import { equalHopIdentity } from './hopIdentity';+import { AGENT_CHAIN_CONTRACT_VERSION, CONTRACT_VERSION, PROBE_RESULT_CONTRACT_VERSION } from './types';-/**- * The terminal result of BOTH creation paths (api.md 「The terminal result of both- * ordinary API-key creation and OAuth creation is」).- *- * `adopted_by` travels with the source rather than being re-read from- * `/agents` afterwards, and that is the whole point: it is a snapshot frozen at- * commit time, listing only the eligible `follow` backends that took the source- * in and at which one-based position. A `custom` backend is absent — not because- * nothing happened to it, but because nothing did, which is exactly the case the- * user has to be told about while the dialog is still open.- *- * `skipped_by` is the server naming that case: the backends that COULD have used- * this source and were left out because they keep a `custom` order. It is carried- * beside `adopted_by` rather than derived from it, because 「absent」 covers both- * that and 「never eligible」, and only the server can tell the two apart. Kept- * nullable through this reader: an absent array is a server that did not answer- * the question, which is not the same as one answering 「nobody」.- */-export type Adoption = { adopted_by: AdoptedBy[]; skipped_by: SkippedBy[] | null };+/** Add-time Route placement returned by both source-creation paths. */+export type Adoption = { added_to: AddedTo[]; adopted_by: AdoptedBy[] };export type SourceCreated = { source: Source } & Adoption;export type SourceRefresh = { source: Source; discovered: number };+export type GuardConfirmation = {+ force: true;+ would_remove_hops: RouteHopRef[];+ would_interrupt: SupplyGap[];+};/*** The response of BOTH oauth status and submit (api.md → OAuth completion): the@@ -98,6 +88,8 @@ export type OAuthResult = {export type ModelsApi = {listSources(): Promise<Source[]>;+ /** Unsaved observation; its transient credential is revoked before settling. */+ observeApiKeySource(draft: ApiKeySourceObservation, signal?: AbortSignal): Promise<SourceObservation>;createApiKeySource(draft: ApiKeySourceCreate): Promise<SourceCreated>;/** Rename / re-point a source (display_name, base_url). */patchSource(id: string, patch: SourcePatch): Promise<Source>;@@ -105,7 +97,7 @@ export type ModelsApi = {* Contractually ALSO the recovery test: run on a needs_action / error source* it clears the blocker and returns the source to standby. v3 adds no second* 「recover」 endpoint, so this is the whole retry affordance. */- refreshSource(id: string): Promise<SourceRefresh>;+ refreshSource(id: string, confirmation?: GuardConfirmation): Promise<SourceRefresh>;/** Delete a source. `force` overrides the only-supplier guard. */deleteSource(id: string, force?: boolean): Promise<void>;/** Replace the credential of a hub-channel api_key source. Refuses with@@ -119,30 +111,28 @@ export type ModelsApi = {* status/submit response as `OAuthResult.repaired`. */reauthSource(id: string): Promise<OAuthFlow>;listAgents(): Promise<AgentSupply[]>;- /** Per-backend enabled subset + order + policy (the 来源顺序 drawer's read). */+ /** Per-backend enabled subset + order (the 来源顺序 drawer's read). */getAgentSources(backend: AgentBackend): Promise<AgentSupply>;- /** Total write: `follow` hands the order back to the server, `custom` freezes- * exactly the ids sent. The response re-echoes the canonical order. */+ /** Total write of the exact stored source order. */putAgentSources(backend: AgentBackend, body: AgentSourcesPut): Promise<AgentSupply>;/** Resolution chain for one model. Hub mode only — direct answers `direct_mode`. */getAgentChain(backend: AgentBackend, model: string): Promise<AgentChain>;/** One real request through the chain. Hub mode only, same reason. */probeAgent(backend: AgentBackend, model?: string): Promise<ProbeResult>;setAgentMode(backend: AgentBackend, mode: AgentMode): Promise<AgentSupply>;- putMappings(backend: AgentBackend, mappings: AgentMapping[]): Promise<AgentSupply>;putMenu(menu: AgentMenu): Promise<AgentSupply>;addCustomModel(sourceId: string, draft: CustomModelCreate): Promise<Source>;updateModelReasoningEfforts(sourceId: string, modelId: string, reasoningEfforts: string[]): Promise<Source>;- deleteCustomModel(sourceId: string, modelId: string): Promise<Source>;+ deleteCustomModel(sourceId: string, modelId: string, confirmation?: GuardConfirmation): Promise<Source>;scanMigration(): Promise<MigrationScan>;applyMigration(itemIds: string[]): Promise<MigrationApplyResult>;/** `before` is an event id cursor (「查看全部」 pagination). */listEvents(limit?: number, before?: string): Promise<ResolutionEvent[]>;getRuntimeStatus(): Promise<RuntimeDependency>;+ /** Start the contract-owned client installation transaction. */+ installRuntime(): Promise<RuntimeDependency>;startRuntime(): Promise<RuntimeDependency>;- /** `experimentalConsent` MUST be true for a consent-gated hub-held- * subscription connect, or the server returns consent_required. */- startOAuth(vendor: string, channel: SupplyChannel, experimentalConsent?: boolean): Promise<OAuthFlow>;+ startOAuth(vendor: string, channel: SupplyChannel): Promise<OAuthFlow>;getOAuthStatus(flowId: string): Promise<OAuthResult>;submitOAuth(flowId: string, value: string): Promise<OAuthResult>;cancelOAuth(flowId: string): Promise<void>;@@ -165,6 +155,7 @@ class ApiCallError extends Error {* first proving which error it has.*/wouldInterrupt: SupplyGap[];+ wouldRemoveHops: RouteHopRef[];/*** The OTHER half, and deliberately not the same field: `would_interrupt` names* what a REFUSED write would have stranded (nothing changed, the copy is future@@ -192,12 +183,16 @@ class ApiCallError extends Error {* it says so at both sites.*/serverNamed: boolean;+ /** HTTP status observed by this client. Absent when no response arrived. */+ responseStatus?: number;constructor(code: string,detail?: string,serverNamed = true,wouldInterrupt: SupplyGap[] = [],interrupted: SupplyGap[] = [],+ wouldRemoveHops: RouteHopRef[] = [],+ responseStatus?: number,) {super(detail || code);this.name = 'ApiCallError';@@ -206,6 +201,8 @@ class ApiCallError extends Error {this.serverNamed = serverNamed;this.wouldInterrupt = wouldInterrupt;this.interrupted = interrupted;+ this.wouldRemoveHops = wouldRemoveHops;+ this.responseStatus = responseStatus;}}@@ -223,6 +220,11 @@ const supplyGaps = (raw: unknown): SupplyGap[] =>})): [];+const routeHopRefs = (raw: unknown): RouteHopRef[] =>+ Array.isArray(raw)+ ? raw.filter((hop): hop is RouteHopRef => Boolean(hop) && typeof hop === 'object')+ : [];+/*** The one reader every call site uses instead of casting a caught `unknown`.*@@ -240,6 +242,8 @@ export const apiFailure = (serverNamed: boolean;wouldInterrupt: SupplyGap[];interrupted: SupplyGap[];+ wouldRemoveHops: RouteHopRef[];+ responseStatus?: number;} | null =>err instanceof ApiCallError? {@@ -248,29 +252,35 @@ export const apiFailure = (serverNamed: err.serverNamed,wouldInterrupt: err.wouldInterrupt,interrupted: err.interrupted,+ wouldRemoveHops: err.wouldRemoveHops,+ responseStatus: err.responseStatus,}: null;async function call<T>(path: string, init?: RequestInit): Promise<T> {const res = await apiFetch(path, init);- let payload: any = null;+ let payload: unknown = null;try {payload = await res.json();} catch {// Invented here, not read off the wire: the request may well have been// carried out and its answer lost coming back.- throw new ApiCallError('bad_response', `Non-JSON response from ${path}`, false);+ throw new ApiCallError('bad_response', `Non-JSON response from ${path}`, false, [], [], [], res.status);}- if (!res.ok || payload?.ok === false) {+ const envelope = payload && typeof payload === 'object' ? payload as Record<string, unknown> : {};+ if (!res.ok || envelope.ok === false) {+ const error = typeof envelope.error === 'string' ? envelope.error : null;throw new ApiCallError(- payload?.error || `http_${res.status}`,- payload?.detail,+ error ?? `http_${res.status}`,+ typeof envelope.detail === 'string' ? envelope.detail : undefined,// `payload.error` is the only thing that carries a route's own verdict, so// its presence IS the answer. `http_502` is this client summarizing a// response that never gave one.- Boolean(payload?.error),- supplyGaps(payload?.would_interrupt),- supplyGaps(payload?.interrupted_pairs),+ error !== null,+ supplyGaps(envelope.would_interrupt),+ supplyGaps(envelope.interrupted_pairs),+ routeHopRefs(envelope.would_remove_hops),+ res.status,);}return payload as T;@@ -282,27 +292,14 @@ const jsonInit = (method: string, body?: unknown): RequestInit => ({body: body === undefined ? undefined : JSON.stringify(body),});-/**- * The adoption tail, defaulted. Both creation routes answer with it — the plain- * one and the oauth envelope — and the two defaults below are DIFFERENT rules, so- * they get one reader rather than two copies that would eventually agree.- *- * `adopted_by` is a list of things that happened: absent can only mean none did.- * (Absent-is-not-empty holds in the contract for reauth, which never reaches here.)- *- * `skipped_by` is the answer to 「who was left out」, and `[]` there is a positive- * claim that nobody was. A server that never sent the field has not made that- * claim, so silence stays null — defaulting it to `[]` would upgrade 「did not- * say」 into 「fully covered」, which is the one thing the adoption note exists to- * avoid.- */-type AdoptionTail = { adopted_by?: AdoptedBy[]; skipped_by?: SkippedBy[] };+/** The creation response's add-time placement projection. */+type AdoptionTail = { added_to?: AddedTo[]; adopted_by?: AdoptedBy[] };const adoption = (r: AdoptionTail): Adoption => ({+ added_to: r.added_to ?? [],adopted_by: r.adopted_by ?? [],- skipped_by: r.skipped_by ?? null,});-/** api.md pins the shape to `{source, adopted_by, skipped_by}` with no extra+/** api.md pins the shape to `{source, added_to, adopted_by}` with no extra* nesting; the bare-`Source` arm is the same tolerance every other write here* keeps. */type SourceCreatedResponse = { source?: Source } & AdoptionTail & Source;@@ -360,12 +357,17 @@ export const oauthResult = (r: OAuthResultResponse): OAuthResult => {const liveApi: ModelsApi = {listSources: () => call<{ sources: Source[] }>('/api/models/sources').then((r) => r.sources),+ observeApiKeySource: (draft, signal) =>+ call<{ observation: SourceObservation }>('/api/models/sources/observe', {+ ...jsonInit('POST', draft),+ signal,+ }).then((r) => r.observation),// Both keep `adopted_by`. The old unwrap-to-`source` dropped it on the floor,// and no later read can put it back: `/agents` shows today's orders, not which// of them this commit changed.createApiKeySource: (draft) => call<SourceCreatedResponse>('/api/models/sources', jsonInit('POST', draft)).then(created),patchSource: (id, patch) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(id)}`, jsonInit('PATCH', patch)).then((r) => (r.source ?? r) as Source),- refreshSource: (id) => call<SourceRefresh>(`/api/models/sources/${encodeURIComponent(id)}/refresh`, jsonInit('POST')),+ refreshSource: (id, confirmation) => call<SourceRefresh>(`/api/models/sources/${encodeURIComponent(id)}/refresh`, jsonInit('POST', confirmation ?? {})),deleteSource: (id, force) => call(`/api/models/sources/${encodeURIComponent(id)}${force ? '?force=true' : ''}`, jsonInit('DELETE')).then(() => undefined),// Both repair routes reject unknown body keys outright (`discovery_failed` /// `reauth_confirmation_required`), so these bodies are exactly the contract's@@ -384,11 +386,10 @@ const liveApi: ModelsApi = {getAgentChain: (backend, model) => call<{ chain: AgentChain }>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`).then((r) => r.chain),probeAgent: (backend, model) => call<{ probe: ProbeResult }>(`/api/models/agents/${backend}/probe`, jsonInit('POST', model ? { model } : {})).then((r) => r.probe),setAgentMode: (backend, mode) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mode`, jsonInit('PATCH', { mode })).then((r) => (r.agent ?? r) as AgentSupply),- putMappings: (backend, mappings) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mappings`, jsonInit('PUT', { mappings })).then((r) => (r.agent ?? r) as AgentSupply),putMenu: (menu) => call<{ agent?: AgentSupply } & AgentSupply>('/api/models/agents/opencode/menu', jsonInit('PUT', { menu })).then((r) => (r.agent ?? r) as AgentSupply),addCustomModel: (sourceId, draft) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models`, jsonInit('POST', draft)).then((r) => (r.source ?? r) as Source),updateModelReasoningEfforts: (sourceId, modelId, reasoningEfforts) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models/${encodeURIComponent(modelId)}`, jsonInit('PATCH', { reasoning_efforts: reasoningEfforts })).then((r) => (r.source ?? r) as Source),- deleteCustomModel: (sourceId, modelId) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models/${encodeURIComponent(modelId)}`, jsonInit('DELETE', {})).then((r) => (r.source ?? r) as Source),+ deleteCustomModel: (sourceId, modelId, confirmation) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models/${encodeURIComponent(modelId)}`, jsonInit('DELETE', confirmation ?? {})).then((r) => (r.source ?? r) as Source),scanMigration: () => call<{ scan?: MigrationScan } & MigrationScan>('/api/models/migration/scan', jsonInit('POST')).then((r) => (r.scan ?? r) as MigrationScan),applyMigration: (itemIds) => call<MigrationApplyResult>('/api/models/migration/apply', jsonInit('POST', { item_ids: itemIds })),listEvents: (limit = 20, before) =>@@ -396,11 +397,12 @@ const liveApi: ModelsApi = {`/api/models/events?limit=${limit}${before ? `&before=${encodeURIComponent(before)}` : ''}`,).then((r) => r.events),getRuntimeStatus: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/status').then((r) => (r.runtime ?? r) as RuntimeDependency),+ installRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/install', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),startRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/start', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),- startOAuth: (vendor, channel, experimentalConsent) =>+ startOAuth: (vendor, channel) =>call<{ flow?: OAuthFlow } & OAuthFlow>('/api/models/oauth/start',- jsonInit('POST', { vendor, channel, ...(experimentalConsent ? { experimental_consent: true } : {}) }),+ jsonInit('POST', { vendor, channel }),).then((r) => (r.flow ?? r) as OAuthFlow),getOAuthStatus: (flowId) => call<OAuthResultResponse>(`/api/models/oauth/status/${encodeURIComponent(flowId)}`).then(oauthResult),submitOAuth: (flowId, value) => call<OAuthResultResponse>('/api/models/oauth/submit', jsonInit('POST', { flow_id: flowId, value })).then(oauthResult),@@ -413,10 +415,31 @@ const liveApi: ModelsApi = {/** `recovered` is captured when a reauth flow STARTS, like the server's own* `recovered = source.state.status in {needs_action, error}` — read before the* native irreversible step rewrites that very status. */-type MockFlow = { flow: OAuthFlow; polls: number; submitted: boolean; recovered?: boolean };+type MockFlow = {+ flow: OAuthFlow;+ polls: number;+ submitted: boolean;+ recovered?: boolean;+ placement?: Adoption;+};const rid = (prefix: string) => `${prefix}_${Math.random().toString(36).slice(2, 10)}`;-const delay = <T>(value: T, ms = 260): Promise<T> => new Promise((r) => setTimeout(() => r(value), ms));+const delay = <T>(value: T, ms = 260, signal?: AbortSignal): Promise<T> =>+ new Promise((resolve, reject) => {+ const timer = globalThis.setTimeout(() => resolve(value), ms);+ signal?.addEventListener('abort', () => {+ globalThis.clearTimeout(timer);+ reject(new DOMException('The operation was aborted.', 'AbortError'));+ }, { once: true });+ });+const listedModelIdsForPlacement = (agent: AgentSupply): string[] => {+ const values = [+ ...(agent.builtin_models ?? []),+ ...(agent.menu?.checked ?? []),+ ...Object.keys(agent.routes ?? {}),+ ];+ return [...new Set(values)];+};class MockStore {sources = buildMockSources();@@ -426,31 +449,23 @@ class MockStore {flows = new Map<string, MockFlow>();// ── Fake server-side recomputation ───────────────────────────────────- // Every read of an agent re-derives what the real server derives: the- // per-backend order (recommended under `follow`, pruned under `custom`),- // eligibility, and the supply rollup. That is what makes a drag-reorder or a- // source deletion update supply status in the demo instead of leaving it stale.+ // Reads refresh server-authoritative eligibility while preserving the stored+ // order. Matching and Route construction happen only at add time.private syncAgents() {for (const a of this.agents) {if (a.mode === 'direct') {a.sources = null;} else {- const policy = a.sources?.policy ?? 'follow';const eligibility = mockEligibility(this.sources, a.backend);const eligible = new Set(eligibility.filter((e) => e.eligible).map((e) => e.source_id));- const order =- policy === 'follow'- ? mockRecommendedOrder(this.sources, a.backend)- : // A `custom` subset is frozen, never extended — but a deleted or- // newly ineligible id drops out (the invariant the server enforces).- (a.sources?.order ?? []).filter((id) => eligible.has(id));- a.sources = { policy, order, eligibility };+ const order = (a.sources?.order ?? []).filter((id) => eligible.has(id));+ a.sources = { order, eligibility };}this.deriveSupply(a);}}- /** §4.3 + §4.5 in miniature: capability (supplies the mapped id) split from+ /** §4.3 + §4.5 in miniature: capability (supplies the configured id) split from* runnability (not blocked), then the rollup over the resulting chain. */private deriveSupply(a: AgentSupply) {if (a.mode === 'direct') {@@ -463,14 +478,16 @@ class MockStore {return;}const byId = new Map(this.sources.map((s) => [s.id, s]));- const order = (a.sources?.order ?? []).map((id) => byId.get(id)).filter((s): s is Source => Boolean(s));- const target = (model: string) => {- const m = a.mappings?.find((x) => x.builtin_id === model && x.enabled && x.target_model_id);- return m ? m.target_model_id : model;- };- const chainFor = (model: string) => order.filter((s) => s.models.some((mm) => mm.id === target(model)));+ const routeFor = (model: string) => a.routes?.[model]?.hops ?? [];+ const chainFor = (model: string) => routeFor(model)+ .map((hop) => byId.get(hop.source_id))+ .filter((s): s is Source => Boolean(s));if (a.builtin_models) {- a.model_supply = a.builtin_models.map((m) => ({ model_id: m, chain_length: chainFor(m).length }));+ a.model_supply = a.builtin_models.map((m) => ({+ model_id: m,+ chain_length: routeFor(m).length,+ has_runnable_hop: chainFor(m).some(isRunnable),+ }));}const selected = a.selected_model_id ?? null;if (!selected) {@@ -497,62 +514,61 @@ class MockStore {return delay(structuredClone(this.sources));}- /**- * The `adopted_by` projection, derived the same way the server derives it:- * re-run the recommendation, then report where the new id actually landed.- *- * It is deliberately NOT a guess from the source's vendor — a `follow` backend- * adopts only what its eligibility admits, so the answer for one credential can- * be 「claude 第 2 位」 and nothing at all for opencode. Anything on `custom` is- * omitted by the contract; that omission is the signal the dialogs read.- */- private adoptionOf(sourceId: string): AdoptedBy[] {- this.syncAgents();- return this.agents- .filter((a) => a.mode === 'hub' && a.sources?.policy === 'follow')- .map((a) => ({ backend: a.backend, order: a.sources?.order ?? [] }))- .filter(({ order }) => order.includes(sourceId))- .map(({ backend, order }) => ({- backend,- policy: 'follow' as const,- position: order.indexOf(sourceId) + 1, // one-based, per api.md- }));- }-- /**- * The complement, derived the way `_skipped_by` derives it: ELIGIBLE for this- * backend, on a `custom` order, and not in it. The eligibility filter is what- * makes the two lists different from `MODEL_HUB_BACKENDS` minus `adopted_by` —- * a backend that could never use the credential belongs to neither.- */- private skippedOf(sourceId: string): SkippedBy[] {+ /** Materialize placement once, in the same transaction that creates a Source. */+ private placeNewSource(source: Source): Adoption {+ const added_to: AddedTo[] = [];+ const adopted_by: AdoptedBy[] = [];+ for (const agent of this.agents) {+ if (agent.mode !== 'hub') continue;+ const eligible = mockEligibility(this.sources, agent.backend).some(+ (entry) => entry.source_id === source.id && entry.eligible,+ );+ if (!eligible) continue;+ const order = agent.sources?.order ?? [];+ if (!order.includes(source.id)) order.push(source.id);+ agent.sources = { order, eligibility: agent.sources?.eligibility ?? null };+ for (const menuModel of listedModelIdsForPlacement(agent)) {+ const supplied = source.models.find((model) => model.id === menuModel);+ if (!supplied) continue;+ const hops = agent.routes?.[menuModel]?.hops ?? [];+ if (hops.some((hop) => hop.source_id === source.id)) continue;+ const next = [...hops, { source_id: source.id, model_id: supplied.id }];+ agent.routes = { ...(agent.routes ?? {}), [menuModel]: { hops: next } };+ added_to.push({+ backend: agent.backend,+ menu_model: menuModel,+ source_id: source.id,+ model_id: supplied.id,+ position: next.length,+ });+ adopted_by.push({ backend: agent.backend, menu_model: menuModel });+ }+ }this.syncAgents();- return this.agents- .filter(- (a) =>- a.mode === 'hub' &&- a.sources?.policy === 'custom' &&- !a.sources.order.includes(sourceId) &&- (a.sources.eligibility ?? []).some((e) => e.source_id === sourceId && e.eligible),- )- .map((a) => ({ backend: a.backend, reason: 'custom_order' as const }));- }-- /** Both creation routes answer with the same pair. */- private adoptionTail(sourceId: string) {- return { adopted_by: this.adoptionOf(sourceId), skipped_by: this.skippedOf(sourceId) };+ return { added_to, adopted_by };}createApiKeySource(draft: ApiKeySourceCreate) {+ const existing = draft.client_nonce+ ? this.sources.find((source) => source.client_nonce === draft.client_nonce)+ : undefined;+ if (existing) {+ return delay({+ source: structuredClone(existing),+ added_to: [],+ adopted_by: structuredClone(existing.adopted_by ?? []),+ });+ }const count = mockDiscoveredCount(draft.vendor);const source: Source = {id: rid('src'),+ client_nonce: draft.client_nonce ?? null,created_at: new Date().toISOString(),last_discovered_at: new Date().toISOString(),kind: 'api_key',vendor: draft.vendor,- display_name: draft.vendor === 'custom' ? hostLabel(draft.base_url) : vendorLabel(draft.vendor),- protocol: draft.vendor === 'anthropic' ? 'anthropic' : 'openai_chat',+ display_name: draft.display_name || (draft.vendor === 'custom' ? hostLabel(draft.base_url) : vendorLabel(draft.vendor)),+ protocol: draft.protocol_order?.[0] ?? (draft.vendor === 'anthropic' ? 'anthropic' : 'openai_chat'),base_url: draft.base_url ?? null,supply_channel: 'hub',billing: 'metered',@@ -564,14 +580,50 @@ class MockStore {models: Array.from({ length: count }, (_, i) => ({id: `${draft.vendor}-model-${i + 1}`,display_name: null,- provenance: 'discovered' as const,+ origin: 'discovered' as const,+ reasoning_efforts: [],discovered_at: new Date().toISOString(),})),credential_ref: rid('cred'),};this.sources.push(source);+ const placement = this.placeNewSource(source);+ source.adopted_by = placement.adopted_by;// simulate probe latency- return delay({ source: structuredClone(source), ...this.adoptionTail(source.id) }, 900);+ return delay({ source: structuredClone(source), ...placement }, 900);+ }++ observeApiKeySource(draft: ApiKeySourceObservation, signal?: AbortSignal) {+ const marker = `${draft.base_url ?? ''} ${draft.key}`.toLowerCase();+ const base = {+ contract_version: CONTRACT_VERSION,+ models: [] as string[],+ };+ let observation: SourceObservation;+ if (marker.includes('timeout')) {+ observation = { ...base, outcome: 'timeout', reachable: null, authenticated: 'unknown', protocol: null, discovery: 'not_attempted' };+ } else if (marker.includes('auth')) {+ observation = { ...base, outcome: 'authentication_failed', reachable: true, authenticated: 'rejected', protocol: null, discovery: 'not_attempted' };+ } else if (marker.includes('ambiguous')) {+ observation = { ...base, outcome: 'ambiguous', reachable: true, authenticated: 'authenticated', protocol: null, discovery: 'not_attempted' };+ } else if (marker.includes('inventory')) {+ observation = { ...base, outcome: 'observed', reachable: true, authenticated: 'authenticated', protocol: draft.protocol_order?.[0] ?? 'openai_chat', discovery: 'failed' };+ } else if (marker.includes('adapter')) {+ observation = { ...base, outcome: 'adapter_error', reachable: null, authenticated: 'unknown', protocol: null, discovery: 'not_attempted' };+ } else if (marker.includes('unreachable')) {+ observation = { ...base, outcome: 'unreachable', reachable: false, authenticated: 'unknown', protocol: null, discovery: 'not_attempted' };+ } else {+ observation = {+ ...base,+ outcome: 'observed',+ reachable: true,+ authenticated: 'authenticated',+ protocol: draft.protocol_order?.[0] ?? 'openai_chat',+ discovery: 'succeeded',+ models: ['model-1', 'model-2', 'model-3'],+ };+ }+ return delay(observation, 900, signal);}/**@@ -592,14 +644,10 @@ class MockStore {if (a.mode !== 'hub') continue;const model = a.selected_model_id;if (!model) continue;- const mapping = a.mappings?.find((x) => x.builtin_id === model && x.enabled && x.target_model_id);- const resolved = mapping ? mapping.target_model_id : model;- // A `follow` order only ever LOSES the removed id (the recommendation never- // gains a source from a write), so filtering the live order through the- // candidate set is the same answer refresh_follow_orders would give.- const survives = (a.sources?.order ?? [])- .map((id) => byId.get(id))- .some((s) => s !== undefined && s.models.some((mm) => mm.id === resolved) && isRunnable(s));+ const hops = a.routes?.[model]?.hops ?? [];+ const survives = hops+ .map((hop) => byId.get(hop.source_id))+ .some((s) => s !== undefined && isRunnable(s));if (survives) continue;gaps.push({backend: a.backend,@@ -712,22 +760,15 @@ class MockStore {putAgentSources(backend: AgentBackend, body: AgentSourcesPut) {const agent = this.agentOr404(backend);if (agent.mode === 'direct') throw new ApiCallError('direct_mode');- if (body.policy === 'follow') {- // 恢复推荐顺序 discards the frozen subset; the order comes back from §4.2.- agent.sources = { policy: 'follow', order: [], eligibility: null };- } else {- // §4.4's invariants, server-side: every id exists, is eligible here, and- // appears once. Omitting one is how the user says 未启用 — not an error.- const eligible = new Set(- mockEligibility(this.sources, backend).filter((e) => e.eligible).map((e) => e.source_id),- );- const seen = new Set<string>();- for (const id of body.order) {- if (!eligible.has(id) || seen.has(id)) throw new ApiCallError('invalid_source_order', id);- seen.add(id);- }- agent.sources = { policy: 'custom', order: [...body.order], eligibility: null };+ const eligible = new Set(+ mockEligibility(this.sources, backend).filter((e) => e.eligible).map((e) => e.source_id),+ );+ const seen = new Set<string>();+ for (const id of body.order) {+ if (!eligible.has(id) || seen.has(id)) throw new ApiCallError('invalid_source_order', id);+ seen.add(id);}+ agent.sources = { order: [...body.order], eligibility: null };this.syncAgents();return delay(structuredClone(agent), 380);}@@ -741,33 +782,36 @@ class MockStore {*/private chainFor(agent: AgentSupply, model: string) {const byId = new Map(this.sources.map((s) => [s.id, s]));- const mapping = agent.mappings?.find((x) => x.builtin_id === model && x.enabled && x.target_model_id);- const resolved = mapping ? mapping.target_model_id : model;- const chain: AgentChainLink[] = (agent.sources?.order ?? [])- .map((id) => byId.get(id))- .filter((s): s is Source => s !== undefined && s.models.some((mm) => mm.id === resolved))- .map((s) => ({- source_id: s.id,- channel: s.supply_channel,- via_mapping: Boolean(mapping),- resolved_model_id: mapping ? resolved : null,- health: chainHealth(s),- runnable: isRunnable(s),+ const hops = agent.routes?.[model]?.hops ?? [];+ const chain: AgentChainLink[] = hops+ .map((hop) => ({ hop, source: byId.get(hop.source_id) }))+ .map(({ hop, source }) => ({+ source_id: hop.source_id,+ model_id: hop.model_id,+ source,+ }))+ .map(({ source_id, model_id, source }) => ({+ source_id,+ model_id,+ channel: source?.supply_channel ?? 'hub',+ health: source ? chainHealth(source) : 'error',+ runnable: source ? isRunnable(source) : false,// v4: process availability is a fact about the serving process — which// native CLI it can launch under its own login — and a browser mock has// no way to observe it. So it stands in for a runtime where every// configured CLI is launchable, rather than inventing an outage. The// unavailable branch is asserted in the unit tests, which can state the// fact instead of guessing it.- reason: null,- retry_at: s.state.status === 'cooldown' ? s.state.retry_at ?? null : null,+ reason: source ? null : 'source_missing',+ retry_at: source?.state.status === 'cooldown' ? source.state.retry_at ?? null : null,}));const supply_state: AgentChain['supply_state'] = chain.some((l) => l.runnable)? 'ok': chain.length > 0 && chain.every((l) => l.health === 'cooldown' && l.reason === null)? 'waiting': 'interrupted';- return { chain, supply_state };+ const current = chain.find((link) => link.runnable);+ return { chain, current: current ? { source_id: current.source_id, model_id: current.model_id } : null, supply_state };}getAgentChain(backend: AgentBackend, model: string) {@@ -776,11 +820,12 @@ class MockStore {// AC-7: direct mode has no src_* identity to report, so the route refuses// rather than answering with an empty (falsely alarming) chain.if (agent.mode === 'direct') throw new ApiCallError('direct_mode');- const { chain, supply_state } = this.chainFor(agent, model);+ const { chain, current, supply_state } = this.chainFor(agent, model);return delay({contract_version: AGENT_CHAIN_CONTRACT_VERSION,backend,model_id: model,+ current,chain,supply_state,});@@ -813,11 +858,8 @@ class MockStore {channel: head.channel,reachable: true,source_id: head.source_id,- // The resolved id, mapping applied — what the server reports, and not the- // requested id it was rewritten from.- model_id: head.resolved_model_id ?? modelId,+ model_id: head.model_id,latency_ms: native ? null : 180 + Math.floor(Math.random() * 420),- via_mapping: head.via_mapping,error: null,};// A real upstream request takes a real moment; a local readiness check does not.@@ -828,9 +870,15 @@ class MockStore {const agent = this.agentOr404(backend);agent.mode = mode;if (mode === 'hub') {- // Rejoining the hub starts on the recommendation, and picks up whatever- // model selected for the Agent (first built-in / first supplied id in mock mode).- agent.sources = { policy: 'follow', order: [], eligibility: null };+ // Rejoining the gateway materializes one exact Route per matching menu model.+ const order = mockRecommendedOrder(this.sources, backend);+ agent.sources = { order, eligibility: null };+ agent.routes = Object.fromEntries(+ (agent.builtin_models ?? []).map((modelId) => [modelId, { hops: order+ .map((sourceId) => this.sources.find((source) => source.id === sourceId))+ .filter((source): source is Source => Boolean(source && source.models.some((model) => model.id === modelId)))+ .map((source) => ({ source_id: source.id, model_id: modelId })) }]),+ );agent.selected_model_id = agent.builtin_models?.[0] ?? this.sources[0]?.models[0]?.id ?? null;// The server's default comes from the STORED per-backend request, so a// non-null id here is explicit; nothing selected is the false case.@@ -844,66 +892,9 @@ class MockStore {return delay(structuredClone(agent));}- /**- * `_enroll_target_sources` in miniature (api.md → "Mapping and menu- * enrollment"): a target whose suppliers are all outside the order pulls in- * EXACTLY ONE — the first in the recommendation — and the order forks to- * `custom` only when something was actually appended.- *- * Modelled here rather than left as a no-op for the reason `oauthResult`- * documents: a mock that treats a mutation and its side effect as separate is- * a mock that cannot fail the way the product does, and the drawers' 完成- * notice exists only because of this side effect.- */- private enrollTargets(agent: AgentSupply, targetGroups: string[][]) {- const order = agent.sources?.order ?? [];- const enrolled = new Set(order);- const appended: string[] = [];- for (const group of targetGroups) {- if (group.length === 0 || group.some((id) => enrolled.has(id))) continue;- enrolled.add(group[0]);- appended.push(group[0]);- }- if (appended.length === 0) return;- agent.sources = { policy: 'custom', order: [...order, ...appended], eligibility: null };- }-- /** The suppliers of one target, in the recommendation's order — the list the- * server picks its single enrollee from. */- private suppliersOf(backend: AgentBackend, carries: (source: Source) => boolean): string[] {- const byId = new Map(this.sources.map((s) => [s.id, s]));- return mockRecommendedOrder(this.sources, backend).filter((id) => {- const source = byId.get(id);- return source ? carries(source) : false;- });- }-- putMappings(backend: AgentBackend, mappings: AgentMapping[]) {- const agent = this.agents.find((a) => a.backend === backend);- if (!agent) throw new ApiCallError('source_not_found');- this.enrollTargets(- agent,- mappings- .filter((m) => m.enabled)- .map((m) => this.suppliersOf(backend, (s) => s.models.some((mm) => mm.id === m.target_model_id))),- );- agent.mappings = mappings;- this.syncAgents();- return delay(structuredClone(agent));- }-putMenu(menu: AgentMenu) {const agent = this.agents.find((a) => a.backend === 'opencode');if (!agent) throw new ApiCallError('source_not_found');- const standardVendors = new Set(agent.standard_vendors ?? []);- this.enrollTargets(- agent,- menu.checked.map((identifier) =>- this.suppliersOf('opencode', (s) =>- s.models.some((mm) => buildIdentifier(s.vendor, mm.id, standardVendors) === identifier),- ),- ),- );agent.menu = menu;this.syncAgents();return delay(structuredClone(agent));@@ -915,13 +906,13 @@ class MockStore {const existing = source.models.find((m) => m.id === draft.model_id);if (existing) {existing.display_name = draft.display_name ?? existing.display_name;- existing.provenance = 'manual';+ existing.origin = 'manual';existing.reasoning_efforts = [...draft.reasoning_efforts];} else {source.models.push({id: draft.model_id,display_name: draft.display_name ?? null,- provenance: 'manual',+ origin: 'manual',reasoning_efforts: [...draft.reasoning_efforts],discovered_at: null,});@@ -933,15 +924,42 @@ class MockStore {const source = this.sources.find((s) => s.id === sourceId);if (!source) throw new ApiCallError('source_not_found');const model = source.models.find((item) => item.id === modelId);- if (!model) throw new ApiCallError('mapping_target_unavailable');+ if (!model) throw new ApiCallError('source_not_found');model.reasoning_efforts = [...reasoningEfforts];return delay(structuredClone(source));}- deleteCustomModel(sourceId: string, modelId: string) {+ deleteCustomModel(sourceId: string, modelId: string, confirmation?: GuardConfirmation) {const source = this.sources.find((s) => s.id === sourceId);if (!source) throw new ApiCallError('source_not_found');- source.models = source.models.filter((m) => !(m.id === modelId && m.provenance === 'manual'));+ const references: RouteHopRef[] = [];+ for (const agent of this.agents) {+ for (const [menuModel, route] of Object.entries(agent.routes ?? {})) {+ for (const [index, hop] of route.hops.entries()) {+ if (equalHopIdentity(hop, { source_id: sourceId, model_id: modelId })) {+ references.push({ backend: agent.backend, menu_model: menuModel, ...hop, position: index + 1 });+ }+ }+ }+ }+ const confirmed = confirmation !== undefined+ && JSON.stringify(confirmation.would_remove_hops) === JSON.stringify(references)+ && JSON.stringify(confirmation.would_interrupt) === JSON.stringify([]);+ if (references.length > 0 && !confirmed) {+ throw new ApiCallError('source_model_in_route_chain', undefined, true, [], [], references);+ }+ source.models = source.models.filter((m) => !(m.id === modelId && m.origin === 'manual'));+ if (confirmation) {+ for (const agent of this.agents) {+ agent.routes = Object.fromEntries(+ Object.entries(agent.routes ?? {}).map(([menuModel, route]) => [+ menuModel,+ { hops: route.hops.filter((hop) => !equalHopIdentity(hop, { source_id: sourceId, model_id: modelId })) },+ ]),+ );+ }+ }+ this.syncAgents();return delay(structuredClone(source));}@@ -971,14 +989,12 @@ class MockStore {protocol: item.backend === 'codex' ? 'openai_responses' : 'anthropic',base_url: null,supply_channel: channel,- // No hub-held subscription is created by migration, so never consented.- experimental_consent_at: null,billing: isKey ? 'metered' : 'monthly',state: { status: 'standby', retry_at: null, detail_key: null },usage: isKey ? { cycle_used_pct: null, month_spend_cents: 0, currency: 'USD' } : { cycle_used_pct: 0, month_spend_cents: null, currency: null },account_label: channel === 'native_cli' ? '[email protected]' : null,masked_credential: isKey ? 'sk-…dd3c' : null,- models: [{ id: item.backend === 'opencode' ? 'glm-5.2' : item.backend === 'codex' ? 'gpt-5.6' : 'claude-opus-4-6', display_name: null, provenance: 'discovered', discovered_at: new Date().toISOString() }],+ models: [{ id: item.backend === 'opencode' ? 'glm-5.2' : item.backend === 'codex' ? 'gpt-5.6' : 'claude-opus-4-6', display_name: null, origin: 'discovered', reasoning_efforts: [], discovered_at: new Date().toISOString() }],credential_ref: channel === 'hub' ? rid('cred') : null,});}@@ -1000,15 +1016,24 @@ class MockStore {return delay(structuredClone(this.runtime));}+ installRuntime() {+ this.runtime.status.health = 'installing';+ this.runtime.status.error_key = null;+ setTimeout(() => {+ this.runtime.status.installed_version = this.runtime.manifest.version;+ this.runtime.status.verified = true;+ this.runtime.status.health = 'not_started';+ }, 1200);+ return delay(structuredClone(this.runtime));+ }+startRuntime() {this.runtime.status.health = 'ok';this.runtime.status.listening = { host: '127.0.0.1', port: 15220 };return delay(structuredClone(this.runtime));}- startOAuth(vendor: string, channel: SupplyChannel, experimentalConsent?: boolean) {- // Mirror the server: a hub-held subscription connect requires recorded consent.- if (channel === 'hub' && !experimentalConsent) throw new ApiCallError('consent_required');+ startOAuth(vendor: string, channel: SupplyChannel) {const isDevice = vendor === 'openai';const flow: OAuthFlow = {flow_id: rid('oaf'),@@ -1096,7 +1121,8 @@ class MockStore {{id: isOpenai ? 'gpt-5.6' : 'claude-opus-4-6',display_name: isOpenai ? 'GPT-5.6' : 'Opus 4.6',- provenance: 'discovered',+ origin: 'discovered',+ reasoning_efforts: [],discovered_at: new Date().toISOString(),},];@@ -1106,7 +1132,7 @@ class MockStore {// Idempotent, like `_create_oauth_source(idempotent=True)`: re-polling a// completed flow re-echoes the same source instead of creating a second one.if (this.sources.some((s) => s.id === id)) return;- this.sources.push({+ const source: Source = {id,created_at: new Date().toISOString(),last_discovered_at: new Date().toISOString(),@@ -1116,19 +1142,20 @@ class MockStore {protocol: isOpenai ? 'openai_responses' : 'anthropic',base_url: null,supply_channel: flow.channel,- experimental_consent_at: flow.channel === 'hub' ? new Date().toISOString() : null,billing: 'monthly',state: { status: 'standby', retry_at: null, detail_key: null },usage: { cycle_used_pct: 0, month_spend_cents: null, currency: null },- // native_cli subscriptions surface the sanctioned CLI account; hub-held- // experimental sources may stay null until a later adapter rev (schema).+ // native_cli subscriptions surface the CLI account; gateway-held sources+ // may stay null until a later adapter revision publishes an account label.account_label: flow.channel === 'native_cli' ? '[email protected]' : null,masked_credential: null,models: isOpenai- ? [{ id: 'gpt-5.6', display_name: 'GPT-5.6', provenance: 'discovered', discovered_at: new Date().toISOString() }]- : [{ id: 'claude-opus-4-6', display_name: 'Opus 4.6', provenance: 'discovered', discovered_at: new Date().toISOString() }],+ ? [{ id: 'gpt-5.6', display_name: 'GPT-5.6', origin: 'discovered', reasoning_efforts: [], discovered_at: new Date().toISOString() }]+ : [{ id: 'claude-opus-4-6', display_name: 'Opus 4.6', origin: 'discovered', reasoning_efforts: [], discovered_at: new Date().toISOString() }],credential_ref: flow.channel === 'hub' ? rid('cred') : null,- });+ };+ this.sources.push(source);+ entry.placement = this.placeNewSource(source);}/**@@ -1158,7 +1185,10 @@ class MockStore {}return {flow,- created: { source: structuredClone(source), ...this.adoptionTail(source.id) },+ created: {+ source: structuredClone(source),+ ...(entry.placement ?? { added_to: [], adopted_by: [] }),+ },repaired: null,};}@@ -1171,7 +1201,7 @@ class MockStore {return delay(structuredClone(source), 300);}- refreshSource(id: string) {+ refreshSource(id: string, _confirmation?: GuardConfirmation) {const source = this.sources.find((s) => s.id === id);if (!source) throw new ApiCallError('source_not_found');// Native-CLI subscriptions can't be re-discovered (server rejects them);@@ -1226,9 +1256,10 @@ const mockStore = new MockStore();const mockApi: ModelsApi = {listSources: () => mockStore.listSources(),+ observeApiKeySource: (draft, signal) => mockStore.observeApiKeySource(draft, signal),createApiKeySource: (draft) => mockStore.createApiKeySource(draft),patchSource: (id, patch) => mockStore.patchSource(id, patch),- refreshSource: (id) => mockStore.refreshSource(id),+ refreshSource: (id, confirmation) => mockStore.refreshSource(id, confirmation),deleteSource: (id, force) => mockStore.deleteSource(id, force),replaceCredential: (id, body) => mockStore.replaceCredential(id, body),reauthSource: (id) => mockStore.reauthSource(id),@@ -1238,17 +1269,17 @@ const mockApi: ModelsApi = {getAgentChain: (backend, model) => mockStore.getAgentChain(backend, model),probeAgent: (backend, model) => mockStore.probeAgent(backend, model),setAgentMode: (backend, mode) => mockStore.setAgentMode(backend, mode),- putMappings: (backend, mappings) => mockStore.putMappings(backend, mappings),putMenu: (menu) => mockStore.putMenu(menu),addCustomModel: (sourceId, draft) => mockStore.addCustomModel(sourceId, draft),updateModelReasoningEfforts: (sourceId, modelId, reasoningEfforts) => mockStore.updateModelReasoningEfforts(sourceId, modelId, reasoningEfforts),- deleteCustomModel: (sourceId, modelId) => mockStore.deleteCustomModel(sourceId, modelId),+ deleteCustomModel: (sourceId, modelId, confirmation) => mockStore.deleteCustomModel(sourceId, modelId, confirmation),scanMigration: () => mockStore.scanMigration(),applyMigration: (itemIds) => mockStore.applyMigration(itemIds),listEvents: (limit, before) => mockStore.listEvents(limit, before),getRuntimeStatus: () => mockStore.getRuntimeStatus(),+ installRuntime: () => mockStore.installRuntime(),startRuntime: () => mockStore.startRuntime(),- startOAuth: (vendor, channel, experimentalConsent) => mockStore.startOAuth(vendor, channel, experimentalConsent),+ startOAuth: (vendor, channel) => mockStore.startOAuth(vendor, channel),getOAuthStatus: (flowId) => mockStore.getOAuthStatus(flowId),submitOAuth: (flowId, value) => mockStore.submitOAuth(flowId, value),cancelOAuth: (flowId) => mockStore.cancelOAuth(flowId),diff --git a/ui/src/components/settings/models/mutationConvergence.test.ts b/ui/src/components/settings/models/mutationConvergence.test.tsnew file mode 100644index 000000000..e46ac9a49--- /dev/null+++ b/ui/src/components/settings/models/mutationConvergence.test.ts@@ -0,0 +1,54 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it, vi } from 'vitest';++import { convergeMutation, createIntentAuthority } from './mutationConvergence';++describe('convergeMutation', () => {+ it('gives a newly injected mutation entity and intent before reconciliation', async () => {+ const order: string[] = [];+ let finishRead: (() => void) | undefined;+ const reconcile = vi.fn(() => new Promise<void>((resolve) => { finishRead = resolve; }));+ const authority = createIntentAuthority();++ const pending = convergeMutation({+ entity: { id: 'new-row' },+ applyEntity: ({ id }) => order.push(`entity:${id}`),+ intent: { authority, apply: () => order.push('intent:new-row') },+ reconcile,+ });++ expect(order).toEqual(['entity:new-row', 'intent:new-row']);+ expect(reconcile).toHaveBeenCalledOnce();+ authority.commit(() => order.push('intent:user-newer'));+ finishRead?.();++ await expect(pending).resolves.toBe('superseded');+ expect(order.at(-1)).toBe('intent:user-newer');+ });++ it('applies a reconciled entity even when no immediate UI intent exists', async () => {+ const apply = vi.fn();+ await expect(convergeMutation({+ entity: { id: 'reconciled-row' },+ applyEntity: apply,+ reconcile: vi.fn().mockResolvedValue(undefined),+ })).resolves.toBe('current');+ expect(apply).toHaveBeenCalledWith({ id: 'reconciled-row' });+ });++ it('owns Agent convergence and delegates Source convergence only through the per-Source settlement', () => {+ const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');+ const detail = readFileSync(join(__dirname, 'SourceDetailPanel.tsx'), 'utf8');+ const mutationOwners = [...page.matchAll(/const (\w+) = React\.useCallback\(async \([^)]*\) => \{\n\s+await convergeMutation\(\{/g)]+ .map((match) => match[1]);++ expect(mutationOwners).toEqual(expect.arrayContaining(['agentSaved']));+ expect(mutationOwners).not.toContain('sourceMutation');+ expect(page).toMatch(/const sourceAdded = async[\s\S]*?await convergeMutation\(\{[\s\S]*?intent:\s*\{[\s\S]*?reconcile: refresh/);+ expect(page).toMatch(/const trackSourceMutation[\s\S]*?sourceEntityAuthority\.current\(sourceId\)[\s\S]*?const settlement: SourceMutationSettlement/);+ expect(detail).toMatch(/reconcileRemoval[\s\S]*?await applyReconciliation\(sourceId, reconciliation\.value, settlement\)/);+ expect(detail).toMatch(/kind: 'gone'[\s\S]*?await settlement\.gone\(sourceId, value\)/);+ expect(detail).not.toMatch(/onSourceEcho|onChanged|onMutation|onGone/);+ });+});diff --git a/ui/src/components/settings/models/mutationConvergence.ts b/ui/src/components/settings/models/mutationConvergence.tsnew file mode 100644index 000000000..e515cfa13--- /dev/null+++ b/ui/src/components/settings/models/mutationConvergence.ts@@ -0,0 +1,44 @@+export type IntentAuthority = {+ commit: (apply: () => void) => number;+ isCurrent: (generation: number) => boolean;+};++/** Owns UI intent ordering separately from network ordering. A mutation may+ * finish reconciling after the user has navigated elsewhere; that older+ * continuation is then observably superseded and must not replay its intent. */+export const createIntentAuthority = (): IntentAuthority => {+ let generation = 0;+ return {+ commit: (apply) => {+ generation += 1;+ apply();+ return generation;+ },+ isCurrent: (candidate) => candidate === generation,+ };+};++export type MutationConvergence<T> = {+ entity?: T;+ applyEntity: (entity: T) => void;+ intent?: { authority: IntentAuthority; apply: () => void };+ reconcile: () => Promise<void>;+};++/** Every mutation converges in the same order: the server-owned entity first,+ * immediate UI intent before the first await, and then a latest-read+ * reconciliation. The returned generation verdict lets callers suppress any+ * optional post-read work without reconstructing intent ownership. */+export async function convergeMutation<T>({+ entity,+ applyEntity,+ intent,+ reconcile,+}: MutationConvergence<T>): Promise<'current' | 'superseded'> {+ if (entity !== undefined) applyEntity(entity);+ const generation = intent?.authority.commit(intent.apply);+ await reconcile();+ return generation === undefined || intent?.authority.isCurrent(generation)+ ? 'current'+ : 'superseded';+}diff --git a/ui/src/components/settings/models/mutationSettlement.test.ts b/ui/src/components/settings/models/mutationSettlement.test.tsnew file mode 100644index 000000000..a5aaf152b--- /dev/null+++ b/ui/src/components/settings/models/mutationSettlement.test.ts@@ -0,0 +1,46 @@+import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it, vi } from 'vitest';++import { createContinuationSettlement, createSourceCreatedDelivery } from './mutationSettlement';+import type { SourceCreated } from './modelsApi';++describe('mutation settlement fences', () => {+ it('atomically rejects every effect belonging to an invalidated attempt', () => {+ const authority = createContinuationSettlement();+ const attempt = authority.begin();+ const apply = vi.fn();+ authority.invalidate();++ expect(authority.settle(attempt, apply)).toBe('stale');+ expect(apply).not.toHaveBeenCalled();+ });++ it('keeps Source-created delivery behind the same attempt fence', () => {+ const authority = createContinuationSettlement();+ const delivery = createSourceCreatedDelivery();+ const onAdded = vi.fn();+ const onClose = vi.fn();+ const created = { source: { id: 'src_example00' }, added_to: [], adopted_by: [] } as unknown as SourceCreated;+ delivery.update(onAdded, onClose);+ const attempt = authority.begin();+ authority.invalidate();++ expect(delivery.settle(authority, attempt, created)).toBe('stale');+ expect(onAdded).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ });++ it('keeps child components from bypassing the settlement owners', () => {+ const here = dirname(fileURLToPath(import.meta.url));+ const addDialog = readFileSync(resolve(here, 'AddApiKeyDialog.tsx'), 'utf8');+ const detail = readFileSync(resolve(here, 'SourceDetailPanel.tsx'), 'utf8');+ expect(addDialog).not.toMatch(/onAddedRef|onCloseRef/);+ expect(addDialog).toContain('createdDelivery.settle');+ expect(detail).not.toMatch(/\bonMutation\b|\bonGone\b|beginSourceSnapshot/);+ expect(detail).toContain('settlement.source');+ expect(detail).toContain('settlement.gone');+ });+});diff --git a/ui/src/components/settings/models/mutationSettlement.ts b/ui/src/components/settings/models/mutationSettlement.tsnew file mode 100644index 000000000..d1a8fccc7--- /dev/null+++ b/ui/src/components/settings/models/mutationSettlement.ts@@ -0,0 +1,55 @@+import type { SourceCreated } from './modelsApi';+import type { Source } from './types';++export type ContinuationTicket = number & { readonly __continuationTicket: unique symbol };++/** The only place an awaited dialog continuation may decide whether to land effects. */+export const createContinuationSettlement = () => {+ let current = 0;+ return {+ begin: (): ContinuationTicket => (++current) as ContinuationTicket,+ invalidate: (): void => { current += 1; },+ settle: (ticket: ContinuationTicket, apply: () => void): 'landed' | 'stale' => {+ if (ticket !== current) return 'stale';+ apply();+ return 'landed';+ },+ };+};++export type ContinuationSettlement = ReturnType<typeof createContinuationSettlement>;++/** Keeps the dialog's mutation delivery private so callers cannot bypass its fence. */+export const createSourceCreatedDelivery = () => {+ let onAdded: (created: SourceCreated) => void = () => {};+ let onClose: () => void = () => {};+ return {+ update: (added: (created: SourceCreated) => void, close: () => void): void => {+ onAdded = added;+ onClose = close;+ },+ settle: (+ authority: ContinuationSettlement,+ ticket: ContinuationTicket,+ created: SourceCreated,+ ): 'landed' | 'stale' => authority.settle(ticket, () => {+ onAdded(created);+ onClose();+ }),+ close: (): void => onClose(),+ };+};++export type SourceInventorySnapshot = { snapshot: number; sources: Source[] };++export type SourceMutationSettlement = {+ source: (source: Source) => Promise<void>;+ gone: (sourceId: string, inventory?: SourceInventorySnapshot) => Promise<void>;+ unread: () => Promise<void>;+ release: () => void;+ readInventory: () => Promise<SourceInventorySnapshot>;+};++export type TrackSourceMutation = <T>(+ work: (source: Source, settlement: SourceMutationSettlement) => Promise<T>,+) => Promise<T>;diff --git a/ui/src/components/settings/models/oauthResult.test.ts b/ui/src/components/settings/models/oauthResult.test.tsindex 8493eef93..80b4c4d48 100644--- a/ui/src/components/settings/models/oauthResult.test.ts+++ b/ui/src/components/settings/models/oauthResult.test.ts@@ -1,135 +1,25 @@-// The OAuth terminal envelope (api.md → "OAuth completion").-//-// The regression these pin: the transport used to unwrap the response to `r.flow-// ?? r` and return the flow alone, so the `{source, adopted_by}` half the server-// puts beside it was discarded — and since the server materializes the Source-// inside the very call that first reports success (consuming the flow binding-// doing it), the dialog's follow-up POST /sources was then refused as-// `flow_not_found` on a connect that had in fact succeeded. Nothing in the mock-// caught it, because the mock had modelled completion and creation as separate.import { describe, expect, it } from 'vitest';import { oauthResult, type OAuthResultResponse } from './modelsApi';-import type { AdoptedBy, OAuthFlow, SkippedBy, Source } from './types';+import type { OAuthFlow, Source } from './types';-const flow = (over: Partial<OAuthFlow> = {}): OAuthFlow => ({- flow_id: 'oaf_1',- source_id: 'src_1',- vendor: 'anthropic',- channel: 'native_cli',- state: 'success',- presentation: { auth_url: null, device_code: null, expects: 'none', instructions_key: null },- error_key: null,- expires_at: null,- ...over,+const flow = (intent: 'create' | 'reauth' = 'create'): OAuthFlow => ({+ flow_id: 'oaf_1', intent, source_id: 'src_a', vendor: 'anthropic', channel: 'hub',+ state: 'success', presentation: { expects: 'none' }, error_key: null, expires_at: null,});--const source = { id: 'src_1', vendor: 'anthropic', kind: 'subscription' } as unknown as Source;-const adopted: AdoptedBy[] = [{ backend: 'claude', policy: 'follow', position: 1 }];-const skipped: SkippedBy[] = [{ backend: 'codex', reason: 'custom_order' }];+const source = { id: 'src_a', kind: 'api_key', vendor: 'anthropic' } as Source;describe('oauthResult', () => {- it('keeps the creation the terminal response reports', () => {- const r = { flow: flow(), source, adopted_by: adopted, skipped_by: skipped } as OAuthResultResponse;- expect(oauthResult(r)).toEqual({- flow: r.flow,- created: { source, adopted_by: adopted, skipped_by: skipped },- repaired: null,- });- });-- it('reads an absent adopted_by beside a source as nothing adopted it', () => {- // Distinct from a response that reports no creation at all: here the source- // exists, so 「没有 Agent 采用」 is a true statement and must be rendered.- const { created } = oauthResult({ flow: flow(), source } as OAuthResultResponse);- expect(created?.adopted_by).toEqual([]);- });-- it('reads an absent skipped_by the OTHER way, as a question left unanswered', () => {- // The two halves of the tail default in opposite directions, and this is the- // one the dialog's auto-close hangs on. `adopted_by` lists things that- // happened, so absent can only mean none did. `skipped_by` answers 「who was- // left out」, where `[]` is a positive claim of full coverage — a server that- // never sent the field has not made it, so silence stays null and `covered`- // stays out of reach.- const { created } = oauthResult({ flow: flow(), source, adopted_by: adopted } as OAuthResultResponse);- expect(created?.skipped_by).toBeNull();- });-- it('keeps an empty skipped_by as the claim it is', () => {- // The counterpart: `[]` here IS the server saying 「nobody was left out」, and- // collapsing it back to null would strand the one arrival that can settle.- const r = { flow: flow(), source, adopted_by: adopted, skipped_by: [] } as OAuthResultResponse;- expect(oauthResult(r).created?.skipped_by).toEqual([]);- });-- it('reports no creation while the flow is still running', () => {- expect(oauthResult({ flow: flow({ state: 'awaiting_action' }) } as OAuthResultResponse).created).toBeNull();- });-- it('reports no creation for a terminal reauth flow', () => {- // A reauth also terminates with a `source`, but its counterpart keys are- // `recovered` / `interrupted_pairs` — no order changed, so there is no- // adoption to report. Reading its payload as an adoption would state- // something about this connect that the server never said.- const r = { flow: flow({ intent: 'reauth' }), source } as OAuthResultResponse;- expect(oauthResult(r).created).toBeNull();- });-- it('keeps the repair tail a terminal reauth reports', () => {- // The other half of the same discrimination: dropping this is the L5 version- // of the bug above — the user re-authorizes, the server reports which Agents- // are still stranded, and the dialog would close saying nothing about them.- const gaps = [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['pm'] }];- const r = {- flow: flow({ intent: 'reauth' }),- source,- recovered: true,- interrupted_pairs: gaps,- } as OAuthResultResponse;- expect(oauthResult(r).repaired).toEqual({ source, recovered: true, interrupted_pairs: gaps });- });-- it('reads an absent recovered as "the server did not say so"', () => {- // Never as a client guess that it did: `recovered` drives 「已恢复」 copy, and- // claiming a recovery the server never reported is the one lie this tail can- // tell. An absent `interrupted_pairs` normalizes to [], which is the same- // statement the server makes by sending an empty array.- const r = { flow: flow({ intent: 'reauth' }), source } as OAuthResultResponse;- expect(oauthResult(r).repaired).toEqual({ source, recovered: false, interrupted_pairs: [] });- });-- it('fills a gap missing its agents rather than dropping the gap', () => {- // A gap with no nameable Agent is still a stranded model, and the confirm- // dialog was opened to report it. `agents: []` renders as 「无」; a dropped- // entry renders as 「nothing was stranded」, which is the opposite.- const r = {- flow: flow({ intent: 'reauth' }),- source,- interrupted_pairs: [{ backend: 'codex', model_id: 'gpt-5.6' }],- } as unknown as OAuthResultResponse;- expect(oauthResult(r).repaired?.interrupted_pairs).toEqual([- { backend: 'codex', model_id: 'gpt-5.6', agents: [] },- ]);- });-- it('reports no repair while a reauth flow is still running', () => {- const r = { flow: flow({ intent: 'reauth', state: 'awaiting_action' }) } as OAuthResultResponse;- expect(oauthResult(r).repaired).toBeNull();- });-- it('treats a flow without `intent` as a create flow', () => {- // The field postdates the first shipped payloads and the schema keeps it- // optional, so absent must not mean "unknown, report nothing".- expect(oauthResult({ flow: flow(), source } as OAuthResultResponse).created).not.toBeNull();+ it('keeps exact placement on a create terminal', () => {+ const added_to = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', source_id: 'src_a', model_id: 'claude-opus-4-6', position: 1 }];+ const adopted_by = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6' }];+ const result = oauthResult({ ...flow(), flow: flow(), source, added_to, adopted_by } as OAuthResultResponse);+ expect(result.created).toEqual({ source, added_to, adopted_by });});- it('tolerates a flat terminal payload', () => {- // Same tolerance every other write in this transport keeps: the flow may- // arrive un-nested, and the create half still has to survive.- const r = { ...flow(), source, adopted_by: adopted } as OAuthResultResponse;- const result = oauthResult(r);- expect(result.flow.flow_id).toBe('oaf_1');- expect(result.created?.adopted_by).toEqual(adopted);+ it('uses the repair tail for reauth', () => {+ const result = oauthResult({ ...flow('reauth'), flow: flow('reauth'), source, recovered: true, interrupted_pairs: [] } as OAuthResultResponse);+ expect(result.created).toBeNull();+ expect(result.repaired?.recovered).toBe(true);});});diff --git a/ui/src/components/settings/models/reconcileUnknownWrite.ts b/ui/src/components/settings/models/reconcileUnknownWrite.tsnew file mode 100644index 000000000..a2b15df14--- /dev/null+++ b/ui/src/components/settings/models/reconcileUnknownWrite.ts@@ -0,0 +1,21 @@+export type UnknownWriteReconciliation<T> =+ | { kind: 'committed'; value: T }+ | { kind: 'absent' }+ | { kind: 'unread' };++/**+ * A lost mutation response is not a failure verdict. Read the authoritative+ * collection and expose another write only after that read proves absence.+ */+export async function reconcileUnknownWrite<Collection, Value>(+ read: () => Promise<Collection>,+ committedValue: (collection: Collection) => Value | undefined,+): Promise<UnknownWriteReconciliation<Value>> {+ try {+ const collection = await read();+ const value = committedValue(collection);+ return value === undefined ? { kind: 'absent' } : { kind: 'committed', value };+ } catch {+ return { kind: 'unread' };+ }+}diff --git a/ui/src/components/settings/models/regionRead.test.ts b/ui/src/components/settings/models/regionRead.test.tsnew file mode 100644index 000000000..8782b784c--- /dev/null+++ b/ui/src/components/settings/models/regionRead.test.ts@@ -0,0 +1,124 @@+import { readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it, vi } from 'vitest';++import {+ beginRegionRead,+ foldRegionRead,+ failRegionRead,+ loadingRegion,+ readRegion,+ readyRegion,+ settleRegionRead,+ type RegionRead,+} from './regionRead';+import { FIRST_PAINT_REGION_WHITELIST, readFirstPaintRegions, type FirstPaintRegionReaders } from './firstPaintRegions';++const productFiles = (directory: string): string[] => readdirSync(directory, { withFileTypes: true })+ .flatMap((entry) => {+ const path = join(directory, entry.name);+ if (entry.isDirectory()) return productFiles(path);+ return /\.(?:ts|tsx)$/.test(entry.name) && !/\.test\.(?:ts|tsx)$/.test(entry.name) ? [path] : [];+ });++describe('RegionRead', () => {+ it('gives a newly injected region the same tagged lifecycle without domain fallbacks', async () => {+ type NewRegion = { rows: string[] };+ const read = vi.fn<() => Promise<NewRegion>>()+ .mockResolvedValueOnce({ rows: ['first'] })+ .mockRejectedValueOnce(new TypeError('unread'));++ const first = settleRegionRead(loadingRegion<NewRegion>(), await readRegion(read));+ expect(first).toEqual(readyRegion({ rows: ['first'] }));++ const pending = beginRegionRead(first);+ expect(pending).toMatchObject({ kind: 'degraded', cause: 'refreshing', retryable: false });++ const failed = settleRegionRead(pending, await readRegion(read));+ expect(failed).toMatchObject({ kind: 'degraded', cause: 'read_failed', retryable: true });+ expect(foldRegionRead(failed, {+ loading: () => null,+ ready: (data) => data,+ unread: () => null,+ degraded: (staleData) => staleData,+ })).toEqual({ rows: ['first'] });+ });++ it('marks a first failure unread instead of inventing a domain value', () => {+ expect(failRegionRead(loadingRegion<number>())).toEqual({ kind: 'unread', retryable: true });+ });++ it('makes unclassified data access impossible on the public union', () => {+ type ReadyRead = Extract<RegionRead<unknown>, { kind: 'ready' }>;+ type DegradedRead = Extract<RegionRead<unknown>, { kind: 'degraded' }>;+ type HasReadyPublicData = 'data' extends keyof ReadyRead ? true : false;+ type HasDegradedPublicData = 'data' extends keyof DegradedRead ? true : false;+ const hasPublicData: [HasReadyPublicData, HasDegradedPublicData] = [false, false];+ expect(hasPublicData).toEqual([false, false]);+ });++ it('keeps every landing region tagged instead of pairing nullable data with flags', () => {+ const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');+ const policy = readFileSync(join(__dirname, 'firstPaintRegions.ts'), 'utf8');++ expect(policy).toMatch(/export type SurfaceLanding = \{\s*\[K in keyof FirstPaintRegionValues\]: RegionRead<FirstPaintRegionValues\[K\]>;\s*\}/);+ expect(page).not.toMatch(/(?:sources|supply|runtime|events|chains)(?:State|Unread|Failed)\b/);+ });++ it('runs the first-paint barrier from its reasoned core-region whitelist only', async () => {+ const keys = Object.keys(FIRST_PAINT_REGION_WHITELIST);+ const called: string[] = [];+ const readers = Object.fromEntries(keys.map((key) => [key, async () => {+ called.push(key);+ return key;+ }])) as unknown as FirstPaintRegionReaders;++ const landing = await readFirstPaintRegions(readers);++ expect(called).toEqual(keys);+ expect(Object.keys(landing)).toEqual(keys);+ const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');+ const barrier = page.slice(page.indexOf('const readSurfaceLanding'), page.indexOf('\n\nconst surfaceLandingFailed'));+ expect(barrier).not.toMatch(/listEvents|events/);+ });++ it('allows RegionRead projection only through an exhaustive fold', () => {+ const violations = productFiles(__dirname).flatMap((path) => {+ if (path.endsWith('/regionRead.ts')) return [];+ const source = readFileSync(path, 'utf8');+ const importsRegionRead = /from ['"]\.\/(?:regionRead|modelRows)['"]/.test(source);+ const bypassesProjection = /\bfreshRegionData\b|\bregionData\s*\(|\b\w+\.data\b/.test(source);+ return importsRegionRead && bypassesProjection ? [path] : [];+ });++ expect(violations).toEqual([]);+ });++ it('keeps adoption decisions on the tagged runtime read', () => {+ const dialog = readFileSync(join(__dirname, 'EnableGatewayDialog.tsx'), 'utf8');++ expect(dialog).toMatch(/runtime: RegionRead<RuntimeDependency>/);+ expect(dialog).toMatch(/foldRegionRead<RuntimeDependency,[\s\S]*?degraded: \(\) => \(\{ kind: 'unavailable' \}\)/);+ expect(dialog).not.toMatch(/runtime: RuntimeDependency \| null/);+ });++ it('routes every per-model chain read through the per-backend latest authority', () => {+ const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');+ const definitionStart = page.indexOf('const readAgentChains');+ const definitionEnd = page.indexOf('\n\nconst settleAgentChainIndex');+ const withoutDefinition = `${page.slice(0, definitionStart)}${page.slice(definitionEnd)}`;+ const unownedCalls = [...withoutDefinition.matchAll(/\breadAgentChains\(/g)].flatMap((match) => {+ const before = withoutDefinition.slice(Math.max(0, (match.index ?? 0) - 240), match.index);+ return before.includes('chainReadAuthority.run') ? [] : [match.index];+ });+ const landing = page.slice(page.indexOf('const readSurfaceLanding'), page.indexOf('\n\nconst surfaceLandingFailed'));++ expect(definitionStart).toBeGreaterThanOrEqual(0);+ expect(definitionEnd).toBeGreaterThan(definitionStart);+ expect(withoutDefinition).not.toMatch(/modelsApi\.getAgentChain/);+ expect(unownedCalls).toEqual([]);+ expect(landing).not.toMatch(/readAgentChains|getAgentChain/);+ expect(page).not.toMatch(/\breadChains\b/);+ expect(page).toMatch(/chainReadAuthority\.invalidateExcept\(activeBackends\)/);+ });+});diff --git a/ui/src/components/settings/models/regionRead.ts b/ui/src/components/settings/models/regionRead.tsnew file mode 100644index 000000000..393feacd1--- /dev/null+++ b/ui/src/components/settings/models/regionRead.ts@@ -0,0 +1,86 @@+const REGION_VALUE: unique symbol = Symbol('model-hub-region-value');++export type RegionReadCause = 'refreshing' | 'read_failed';++export type RegionRead<T> =+ | { kind: 'loading' }+ | { kind: 'ready'; readonly [REGION_VALUE]: T }+ | { kind: 'unread'; retryable: boolean }+ | {+ kind: 'degraded';+ cause: RegionReadCause;+ retryable: boolean;+ readonly [REGION_VALUE]: T;+ };++type RegionReadFold<T, R> = {+ loading: () => R;+ ready: (data: T) => R;+ unread: (retryable: boolean) => R;+ degraded: (staleData: T, cause: RegionReadCause, retryable: boolean) => R;+};++export const loadingRegion = <T>(): RegionRead<T> => ({ kind: 'loading' });++export const readyRegion = <T>(data: T): RegionRead<T> => ({ kind: 'ready', [REGION_VALUE]: data });++export const unreadRegion = <T>(retryable = true): RegionRead<T> => ({ kind: 'unread', retryable });++export const degradedRegion = <T>(+ staleData: T,+ cause: RegionReadCause,+ retryable: boolean,+): RegionRead<T> => ({ kind: 'degraded', cause, retryable, [REGION_VALUE]: staleData });++/** The exhaustive projection path for consumers that intentionally render stale data. */+export const foldRegionRead = <T, R>(read: RegionRead<T>, cases: RegionReadFold<T, R>): R => {+ switch (read.kind) {+ case 'loading': return cases.loading();+ case 'ready': return cases.ready(read[REGION_VALUE]);+ case 'unread': return cases.unread(read.retryable);+ case 'degraded': return cases.degraded(read[REGION_VALUE], read.cause, read.retryable);+ }+};++/** A retry may keep the previous projection visible, but it never makes that+ * projection authoritative again. */+export const beginRegionRead = <T>(previous: RegionRead<T>): RegionRead<T> => {+ return foldRegionRead(previous, {+ loading: () => loadingRegion<T>(),+ ready: (data) => degradedRegion(data, 'refreshing', false),+ unread: () => loadingRegion<T>(),+ degraded: (data) => degradedRegion(data, 'refreshing', false),+ });+};++/** A failed first read is explicitly unread. A later failure retains the last+ * good projection under an error tag, so consumers cannot mistake it for a+ * fresh domain value. */+export const failRegionRead = <T>(previous: RegionRead<T>, retryable = true): RegionRead<T> => {+ return foldRegionRead(previous, {+ loading: () => unreadRegion<T>(retryable),+ ready: (data) => degradedRegion(data, 'read_failed', retryable),+ unread: () => unreadRegion<T>(retryable),+ degraded: (data) => degradedRegion(data, 'read_failed', retryable),+ });+};++export const settleRegionRead = <T>(+ previous: RegionRead<T>,+ next: RegionRead<T>,+): RegionRead<T> => next.kind === 'ready'+ ? next+ : next.kind === 'unread'+ ? failRegionRead(previous, next.retryable)+ : next;++export async function readRegion<T>(read: () => Promise<T>): Promise<RegionRead<T>> {+ try {+ return readyRegion(await read());+ } catch {+ return unreadRegion<T>();+ }+}++export const regionFailed = (read: RegionRead<unknown>): boolean =>+ read.kind === 'unread' || (read.kind === 'degraded' && read.cause === 'read_failed');diff --git a/ui/src/components/settings/models/reorder.test.ts b/ui/src/components/settings/models/reorder.test.tsindex d16b29a63..597ecc86a 100644--- a/ui/src/components/settings/models/reorder.test.ts+++ b/ui/src/components/settings/models/reorder.test.ts@@ -51,8 +51,7 @@ describe('sameIds', () => {expect(sameIds([], [])).toBe(true);});- // The composition that decides whether a `follow` backend gets forked to- // `custom`. `movedOrder` hands back a FRESH array at either boundary, so the+ // `movedOrder` hands back a FRESH array at either boundary, so the// commit path has to compare contents; on `!==` alone every ArrowUp on row 1// would silently cost the user their recommended order.it('sees a boundary move as no change at all', () => {diff --git a/ui/src/components/settings/models/reorder.ts b/ui/src/components/settings/models/reorder.tsindex 5c6dd0969..6676cb40c 100644--- a/ui/src/components/settings/models/reorder.ts+++ b/ui/src/components/settings/models/reorder.ts@@ -27,9 +27,8 @@ export function movedOrder(ids: readonly string[], index: number, delta: number)** It lives beside `movedOrder` because it is the other half of one rule: an arrow* key at either end, and a drag that lands back where it started, both produce a- * NEW array holding the old order. Whoever persists has to compare contents, and a- * `follow` backend forks to `custom` on the first write, so getting this wrong- * costs the user their recommendation for an input that did nothing.+ * NEW array holding the old order. Whoever persists has to compare contents so+ * an input that did nothing never creates a write.*/export const sameIds = (a: readonly string[], b: readonly string[]): boolean =>a.length === b.length && a.every((id, i) => id === b[i]);diff --git a/ui/src/components/settings/models/repair.test.ts b/ui/src/components/settings/models/repair.test.tsindex d12b59c16..461ee7e8b 100644--- a/ui/src/components/settings/models/repair.test.ts+++ b/ui/src/components/settings/models/repair.test.ts@@ -15,7 +15,6 @@ import en from '../../../i18n/en.json';import zh from '../../../i18n/zh.json';import {disprovedDrawnHead,- dryRunChainKey,dryRunOutcome,dryRunPlan,dryRunRowView,@@ -33,7 +32,7 @@ import {} from './repair';import type { RepairOutcome } from './repair';import { PROBE_RESULT_CONTRACT_VERSION } from './types';-import type { AgentSupply, ProbeResult, Source, SourceDetailKey, SourcePolicy, SupplyGap } from './types';+import type { AgentSupply, ProbeResult, Source, SourceDetailKey, SupplyGap } from './types';/** A healthy hub api_key with a credential to replace — the base every case* below narrows, so each test names only what it is actually about. */@@ -66,7 +65,7 @@ const translated = (bundle: unknown, key: string): unknown =>return (node as Record<string, unknown>)[part];}, bundle);-describe('repairAction — the one tap a stopped row offers (SourceRowMenu)', () => {+describe('repairAction — the one tap a stopped source offers', () => {it('offers nothing to a source that is running', () => {// Not a disabled button: a healthy row has no problem, and an affordance for// a problem it does not have is noise the V6 row has no slot for.@@ -161,21 +160,9 @@ 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 refreshSource = async \(source: Source\)[\s\S]*?modelsApi\.refreshSource\(source\.id\)/);- expect(page).toMatch(/onRetest=\{\(source\) => void refreshSource\(source\)\}/);- });-});--const gap = (backend: SupplyGap['backend'], model_id: string): SupplyGap => ({ backend, model_id });+const gap = (backend: SupplyGap['backend'], model_id: string): SupplyGap => ({ backend, model_id, agents: [] });-describe('repairOutcome — 「did that fix it?」 (OAuthConnectDialog, ReplaceKeyDialog)', () => {+describe('repairOutcome — 「did that fix it?」 (OAuthConnectDialog)', () => {it('reports a repair of a source that had been blocked', () => {expect(repairOutcome({ source: source(), recovered: true, interrupted_pairs: [] })).toEqual({ kind: 'repaired' });});@@ -339,9 +326,10 @@ describe('the copy each remedy names', () => {const agent = (over: Partial<AgentSupply> = {}): AgentSupply => ({backend: 'claude',+ cli_present: true,mode: 'hub',menu_kind: 'fixed',- sources: { policy: 'follow', order: ['src_a'] },+ sources: { order: ['src_a'] },supply_status: 'ok',...over,});@@ -357,215 +345,10 @@ const probe = (over: Partial<ProbeResult> = {}): ProbeResult => ({source_id: 'src_a',model_id: 'claude-opus-4-6',latency_ms: 412,- via_mapping: false,error: null,...over,});-describe('dryRunChainKey — which edits make a 试跑 report stop being about anything', () => {- const base = agent({- selected_model_id: 'claude-opus-4-6',- // What the server sends beside a non-null id on a fixed-menu backend: the hub- // path echoes the stored request, so an id there always had a request behind it.- selected_model_explicit: true,- mappings: [{ builtin_id: 'claude-opus-4-6', target_model_id: 'glm-5.2', enabled: true }],- menu: { view: 'featured', checked: ['zhipuai/glm-5.2'] },- });- const key = (- over: Partial<AgentSupply> = {},- policy: SourcePolicy = 'follow',- order = ['src_a'],- sources: Source[] = [source({ id: 'src_a', models: [{ id: 'glm-5.2', provenance: 'discovered' }] })],- ) => dryRunChainKey({ ...base, ...over }, policy, order, sources);-- it('moves for every surface the user selects the probed turn with', () => {- // The chain is not only its order: the probe takes no model, so the server- // resolves one from the same config the mapping drawer next door edits. Edit- // that and the sentence on screen is about a turn the button would no longer- // make.- const same = key();- expect(key()).toBe(same);- expect(key({}, 'custom')).not.toBe(same);- expect(key({}, 'follow', ['src_b', 'src_a'])).not.toBe(same);- expect(key({ selected_model_id: 'claude-sonnet-5' })).not.toBe(same);- expect(key({ mappings: [] })).not.toBe(same);- expect(key({ mappings: [{ builtin_id: 'claude-opus-4-6', target_model_id: 'glm-5.2', enabled: false }] })).not.toBe(- same,- );- expect(key({ menu: { view: 'featured', checked: [] } })).not.toBe(same);- });-- it('keys on the selected model only while the user is the one who asked for it', () => {- // Round 15 escalated this gap and #1110 closed it. `selected_model_id` is the- // resolver's ECHO: on opencode with no explicit request the resolver walks- // `checked` and returns the first identifier whose source is runnable, so- // keying on it would let a failing probe cool the head, move the pick, and- // erase the very report the click produced. `selected_model_explicit` is the- // config fact behind that echo, so the member is present for an explicit pick- // on ANY backend and absent for a resolved one — no backend special case left.- const opencode = {- backend: 'opencode',- menu_kind: 'open',- menu: { view: 'featured', checked: ['zhipuai/glm-5.2', 'anthropic/claude-opus-4-6'] },- } as const;- const resolved = key({ ...opencode, selected_model_id: 'zhipuai/glm-5.2', selected_model_explicit: false });- // A pick the resolver made is not a surface the user selected with: which of- // the two runnable identifiers came back cannot move this key.- expect(- key({ ...opencode, selected_model_id: 'anthropic/claude-opus-4-6', selected_model_explicit: false }),- ).toBe(resolved);- // The same identifier, this time because the user asked for it — a different- // configuration, and now a different key.- const asked = key({ ...opencode, selected_model_id: 'zhipuai/glm-5.2', selected_model_explicit: true });- expect(asked).not.toBe(resolved);- // And an explicit opencode selection moves the key when it changes, which is- // exactly what the old backend exclusion dropped.- expect(key({ ...opencode, selected_model_id: 'zhipuai/glm-5.3', selected_model_explicit: true })).not.toBe(asked);- });-- it('holds still for everything the server derives from those', () => {- // A failing 试跑 cools its own head down, moving the rollup and source health.- // Neither is a selection/config fact.- const same = key();- expect(key({ supply_status: 'interrupted' })).toBe(same);- expect(key({ supply_status: 'degraded' })).toBe(same);- });-- it('moves for an inventory the user never touched from this page', () => {- // Round 18. Everything else in this key is a surface of THIS drawer, so the- // key was blind to the one chain change that arrives from outside it: a- // discovery, a key replacement or a re-auth in another client changes what a- // source supplies, eligibility runs over that inventory, and membership moves- // with every surface here identical. The two lists above only notice it by- // being pruned — and an agent with neither has nothing inventory-derived left.- const withGlm = [source({ id: 'src_a', models: [{ id: 'glm-5.2', provenance: 'discovered' }] })];- const same = key({}, 'follow', ['src_a'], withGlm);- expect(key({}, 'follow', ['src_a'], withGlm)).toBe(same);- // Discovered a second model: same policy, order, model, mappings and menu.- expect(- key({}, 'follow', ['src_a'], [- source({- id: 'src_a',- models: [- { id: 'glm-5.2', provenance: 'discovered' },- { id: 'glm-5.3', provenance: 'discovered' },- ],- }),- ]),- ).not.toBe(same);- // Stripped back to nothing — what a fail-closed re-auth leaves behind.- expect(key({}, 'follow', ['src_a'], [source({ id: 'src_a', models: [] })])).not.toBe(same);- // A source that `order` does not name still counts, because under `follow`- // order is a recommendation and eligibility is what puts a source in the chain.- expect(- key({}, 'follow', ['src_a'], [...withGlm, source({ id: 'src_b', models: [{ id: 'gpt-6', provenance: 'discovered' }] })]),- ).not.toBe(same);- });-- it('holds still for a source whose health moved but whose inventory did not', () => {- // The reason the member above is safe to key on, and it is the same argument- // as the opencode exclusion read the other way: an inventory is not health.- // `_cooldown` and `_set_source_blocker` — the only two writers a failing 试跑- // reaches — assign `source.state` and nothing else. If this ever moved, the- // probe would erase its own answer.- const models = [{ id: 'glm-5.2', provenance: 'discovered' as const }];- const same = key({}, 'follow', ['src_a'], [source({ id: 'src_a', models })]);- expect(- key({}, 'follow', ['src_a'], [- source({ id: 'src_a', models, state: { status: 'cooldown', retry_at: '2026-07-30T13:00:00Z' } }),- ]),- ).toBe(same);- expect(- key({}, 'follow', ['src_a'], [- source({ id: 'src_a', models, state: { status: 'needs_action', detail_key: 'models.source.oauth_expired' } }),- ]),- ).toBe(same);- // Nor for the order the inventory happens to come back in.- expect(- key({}, 'follow', ['src_a'], [- source({- id: 'src_a',- models: [- { id: 'b', provenance: 'discovered' },- { id: 'a', provenance: 'discovered' },- ],- }),- ]),- ).toBe(- key({}, 'follow', ['src_a'], [- source({- id: 'src_a',- models: [- { id: 'a', provenance: 'discovered' },- { id: 'b', provenance: 'discovered' },- ],- }),- ]),- );- });-- it('falls back to the opencode selection surface when the resolver made the pick', () => {- // The other half of the rule above: with the model member gone, what the user- // selects with on an open menu is the checked list itself, and that still moves- // the key. Otherwise excluding a resolved pick would leave opencode with no- // selection member at all.- const oc = { backend: 'opencode' as const, menu_kind: 'open' as const, selected_model_explicit: false };- expect(key({ ...oc, menu: { view: 'full', checked: ['openai/gpt-6'] } })).not.toBe(key(oc));- });-- it('does not move for the order the mappings were written in', () => {- // `mappings` is a set the user edits by toggling; the API makes no ordering- // promise about it, and a re-read that returns the same overrides in another- // order would otherwise clear the report.- expect(- key({- mappings: [- { builtin_id: 'b', target_model_id: 'y', enabled: true },- { builtin_id: 'a', target_model_id: 'x', enabled: true },- ],- }),- ).toBe(- key({- mappings: [- { builtin_id: 'a', target_model_id: 'x', enabled: true },- { builtin_id: 'b', target_model_id: 'y', enabled: true },- ],- }),- );- });-- it('moves for the order menu.checked was written in, because there order IS the pick', () => {- // Round 19, and this test used to assert the opposite — `checked` was- // canonicalized beside `mappings` as though both were sets. On opencode with- // no explicit request the resolver walks `checked` and takes the FIRST- // identifier whose source is runnable (`resolver.py:171-182`), so [A, B] and- // [B, A] are different turns — different model, possibly different source —- // with identical membership. `selected_model_id` is excluded there, so this- // list is the only thing in the key that can carry the difference. Nothing on- // this page writes `checked`, so a re-order arrives the way an inventory- // change does: from another client. `savedMenuKey` reads it in order too.- const oc = { backend: 'opencode' as const, menu_kind: 'open' as const };- expect(key({ ...oc, menu: { view: 'full', checked: ['a', 'b'] } })).not.toBe(- key({ ...oc, menu: { view: 'full', checked: ['b', 'a'] } }),- );- // The fixed-menu backends resolve through `selected_model_id`, so the order- // decides nothing for them — this member stays sensitive anyway rather than- // branching per backend. The whole cost is a still-true report cleared by an- // edit that did not matter, and the user answers that by re-running; the other- // direction is a sentence about a chain that moved. Only one is a wrong answer.- expect(key({ menu: { view: 'featured', checked: ['a', 'b'] } })).not.toBe(- key({ menu: { view: 'featured', checked: ['b', 'a'] } }),- );- });-- it('keeps the parts apart', () => {- // A key is only as good as its separators: 「order a, model b」 and 「order a>b,- // no model」 are different chains and must not collide.- expect(key({ selected_model_id: 'src_b' }, 'follow', ['src_a'])).not.toBe(- key({ selected_model_id: '' }, 'follow', ['src_a', 'src_b']),- );- });-});describe('dryRunOutcome — what the per-model probe came back with', () => {it('names the source the server actually started from', () => {@@ -742,25 +525,13 @@ describe('probeArrival — an answer nobody wants can still be one the page owes);});- 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)), '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\) 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.- expect(drawer).toMatch(/serverNamed: failure\?\.serverNamed \?\? false/);- expect(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\);/);+ it('does not wire diagnostics into the model row or Frame 02', () => {+ const here = dirname(fileURLToPath(import.meta.url));+ const row = readFileSync(join(here, 'AgentCard.tsx'), 'utf8');+ const frame = readFileSync(join(here, 'RouteChainDialog.tsx'), 'utf8');++ expect(row).not.toMatch(/probeAgent|probeArrival/);+ expect(frame).not.toMatch(/probeAgent|probeArrival|modelsApi/);});});@@ -803,45 +574,10 @@ describe('mayHaveWritten — the same unknown, wherever it is caught', () => {expect(mayHaveWritten(null)).toBe(true);});- it('is what 更换 API Key re-reads on', () => {- // The write is atomic and re-discovers on commit, so a lost answer leaves the- // row showing the old key's state while 更换 would provision a second- // replacement. Reporting the error and re-reading the rows are not alternatives.- const dialog = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'ReplaceKeyDialog.tsx'), 'utf8');-- expect(dialog).toMatch(/if \(mayHaveWritten\(failure\)\) onReplaced\(\);\n\s*setPhase\('error'\);/);- // The named refusal above it still returns before this, and still writes nothing.- expect(dialog).toMatch(/failure\?\.code === 'source_last_supplier' && !force/);- });-- it('is one owner, not a predicate re-derived per caller', () => {+ it('is one owner, not a predicate re-derived in a component', () => {const here = dirname(fileURLToPath(import.meta.url));- for (const file of ['ReplaceKeyDialog.tsx', 'SourceOrderDrawer.tsx', 'SourceRowMenu.tsx']) {- expect(readFileSync(join(here, file), 'utf8')).not.toMatch(/!\(?failure\?\.serverNamed/);- }- });-- it('is not the question 删除 asks, so 删除 does not ask it', () => {- // Round 17's finding, and why it is answered without a gate rather than with- // this one. 更换 API Key asks 「did MY write land?」, because the cost of getting- // it wrong is provisioning a second replacement — `mayHaveWritten` is that- // question. A failed DELETE asks 「are the rows I am drawing still right?」, and- // the two come apart on both sides: a commit whose answer was lost is unknown- // AND stale, while `source_not_found` is server-NAMED, wrote nothing, and is- // news precisely because the row is already gone — the same shape- // `disprovedDrawnHead` above exists for. Gating on 「may it have written」 would- // leave that phantom row on screen until something else happened to refetch.- //- // So it re-reads either way, for the reason `releaseFlow` gives: a redundant- // re-read is inert, a missing one is the bug. The guarded refusal still leaves- // through the branch above this one, having provably written nothing.- const menu = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'SourceRowMenu.tsx'), 'utf8');-- expect(menu).not.toMatch(/mayHaveWritten/);- expect(menu).toMatch(/onChanged\(\);\n\s*showToast\(t\('settings\.models\.sourceActions\.deleteFailed'/);- // Both delete outcomes now reach the page: the refusal escalates to a second- // confirm, everything else closes and re-reads.- expect(menu).toMatch(/failure\?\.code === 'source_last_supplier' && !forceMode/);+ const components = readdirSync(here, { recursive: true, encoding: 'utf8' }).filter((file) => file.endsWith('.tsx'));+ expect(components.filter((file) => /!\(?failure\?\.serverNamed/.test(readFileSync(join(here, file), 'utf8')))).toEqual([]);});});@@ -911,7 +647,7 @@ describe('the class: no component decides a repair for itself', () => {it('sweeps a non-trivial file set', () => {// Without this the two rules below pass over an empty list after any move.expect(files.length).toBeGreaterThan(15);- expect(files).toContain('SourceRowMenu.tsx');+ expect(files).toContain('SettingsModelsPage.tsx');});/**@@ -962,8 +698,8 @@ describe('the class: no component decides a repair for itself', () => {/*** A hand-assembled 试跑 chain key. This is the class round 14 caught: the drawer- * built `${policy}|${order.join('>')}` inline, which is a complete statement of- * the chain only while nothing else selects the probed turn — and the model menu+ * built a Source-order signature inline, which is a complete statement of the+ * chain only while nothing else selects the probed turn — and the model menu* next door always did. Inline, the omission is invisible; behind* `dryRunChainKey` it is one function's business, and the test above says which* surfaces belong to it.@@ -973,7 +709,7 @@ 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('AgentCard.tsx')).toMatch(/modelsApi\.probeAgent\(agent\.backend, modelId\)/);+ expect(read('AgentCard.tsx')).not.toMatch(/probeAgent|dryRunChainKey/);expect(read('SourceOrderDrawer.tsx')).not.toMatch(/probeAgent|dryRunChainKey/);});@@ -989,12 +725,4 @@ describe('the class: no component decides a repair for itself', () => {expect(read(name)).not.toMatch(STORED_SENTENCE);});- it('keeps the dry-run failure as a reason, three states and all', () => {- 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(/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 da41428bb..bfa69e7ac 100644--- a/ui/src/components/settings/models/repair.ts+++ b/ui/src/components/settings/models/repair.ts@@ -15,7 +15,6 @@ import type {ProbeResult,Source,SourceDetailKey,- SourcePolicy,SourceRepaired,SourceState,SupplyChannel,@@ -221,10 +220,7 @@ export const repairOutcome = (tail: SourceRepaired): RepairOutcome =>* Whether the journey may close itself.** Provable from the tail alone: 「nothing was stranded, and the source came back- * working」 is two fields the server sends. The adoption auto-close next door now- * stands on the same footing — `covered` needs `skipped_by`, and that field has- * since landed — so the two differ in which fields they read, not in whether they- * can reach a verdict at all.+ * working」 is two fields the server sends.** An allowlist rather than `!== 'gaps'`: L4's rule is that the 1.4s dismissal is* for a plain success and 「every other verdict leaves an instruction on screen@@ -290,119 +286,6 @@ export function dryRunPlan(agent: AgentSupply): DryRunPlan {const nameOf = (sources: Source[], id: string): string =>sources.find((s) => s.id === id)?.display_name || id;-/**- * The identity of the chain a 试跑 report is ABOUT, so that a report outlives every- * refresh except the ones that make it answer for something else.- *- * The rule this obeys, and the reason it is not just 「everything on `agent`」: key- * on the surface the USER selects with, never on the pick the server RESOLVES from- * it. The probe deliberately sends no model, so the server resolves whichever- * selection is live at request time — which makes the selection part of the chain- * the report describes, not context around it. But resolution outputs move for a- * second reason: a failing probe cools its own head down, and keying on anything- * that moves for THAT reason erases the sentence the click just produced (the- * mistake this key was already once rebuilt to escape — see the reset effect in- * `SourceOrderDrawer.tsx`).- *- * So the members are the config-level ones, verified against the server rather than- * assumed:- *- * - `policy` / `order` as the USER currently has them, not as `agent.sources` holds- * them: a drag has already moved them before any PUT lands.- * - `mappings` — pruned only by `_available_model_ids`, which is- * `source_eligible_for_backend` over the inventory and reads no `state.status`- * and no cooldown. An inventory change is a real chain change; a cooldown cannot- * fake one.- * - `menu.checked` — same pruning via `_available_opencode_identifiers`, and for- * opencode this IS the selection surface. It goes in IN ORDER, unsorted, because- * on opencode the order is the selection: with no explicit request the resolver- * walks `checked` and takes the first identifier whose source is runnable- * (`resolver.py:171-182`), so `[A, B]` and `[B, A]` are different turns — a- * different model and possibly a different source — with the same membership.- * Nothing on this page writes `checked`, so a re-order arrives the way the- * inventory does, from another client; canonicalizing it here would hide exactly- * the change the member exists to catch. On the fixed-menu backends the order- * carries nothing, and the sensitivity costs at most a still-true report cleared- * by an edit that did not matter, which the user answers by re-running 一次试跑- * — the same asymmetry the inventory paragraph below settles the same way.- * `savedMenuKey` already reads this list in order for the drawer's own baseline.- * - `selected_model_id`, but only while `selected_model_explicit` says the user is- * the one who asked for it. One rule for every backend, because the flag states- * the rule the backends were a proxy for: it is a CONFIG fact, derived from the- * stored request before anything resolves (`service.py:2109` —- * `mode == "hub" and bool(requested_model)`), while `selected_model_id` is the- * resolver's echo of that same request. On the fixed-menu backends the two agree- * and the guard changes nothing: the hub path echoes `requested_model` back- * verbatim in every return (only `target_model` takes the mapping), so a- * non-null id there always had a request behind it, and an unset request stays- * empty through to a null id. On opencode it separates the two cases that used to- * be one — an explicit request comes back merely normalized and IS now keyed on,- * while an empty one sends the resolver walking `checked` for the first- * identifier whose source is runnable (`resolver.py:171-182`), a pick that- * `unavailable_source_ids` and cooldown gating decide and that `checked` above- * stands in for.- *- * Reading the flag is what makes the member health-free, and it is why this- * waited for the server instead of approximating. Both client-side stand-ins- * keyed on something the failing probe itself moves: on the VALUE, a- * single-source setup erases its own report, because the probe cools the only- * source the head model had and the pick moves; on `supply_status` (sound —- * the loop only ever returns a candidate WITH a source, so- * `waiting`/`interrupted` proves the request was explicit) the same erasure,- * through the guard rather than the value. `selected_model_explicit` moves only- * when the user edits the request, so the report survives its own failure.- *- * - the sources' model INVENTORIES, and this one is not the user's edit at all.- * Everything above is a surface the user changes from this page, and the- * paragraph on `mappings` claims 「an inventory change is a real chain change」- * while relying on the pruning of two lists to notice one. It does not always- * notice: an agent with no mappings and an empty `checked` has nothing- * inventory-derived in the key, and under the `follow` policy `order` is a- * recommendation rather than the membership — eligibility runs over the- * inventory (`source_eligible_for_backend`), so a discovery, a key replacement- * or a re-auth elsewhere can move a source in or out of the chain with every- * surface on this page untouched. Another client is enough; so is the same user- * in a second tab.- *- * Keying on it is safe for the reason the `selected_model_id` paragraph above is- * about, read the other way: an inventory is not health. The two writers a- * failing 试跑 reaches — `_cooldown` and `_set_source_blocker` — assign- * `source.state` and nothing else, so the probe cannot move this member and the- * self-erasing report that killed both remedies for the OpenCode gap cannot- * happen here. It is `models[].id` only: no `state`, no `usage`, no- * `retry_at`, no `provenance` (which changes without changing eligibility).- *- * Scope is every source, not the ones `order` names, precisely because of the- * `follow` case above — under that policy a source can join the chain without- * appearing in `order` first. The cost of being that broad is an unrelated- * source's discovery clearing a report that was still true, and the user re-runs- * 一次试跑; the cost of being narrow is a sentence that answers for a supplier- * chain that no longer exists. Only one of those two is a wrong answer.- *- * Excluded on purpose: resolved-head state and everything else about health. A- * head moving is what a failing report is for.- */-export const dryRunChainKey = (- agent: AgentSupply,- policy: SourcePolicy,- order: string[],- sources: Source[],-): string =>- [- policy,- order.join('>'),- agent.selected_model_explicit ? (agent.selected_model_id ?? '') : '',- (agent.mappings ?? [])- .map((m) => `${m.builtin_id}>${m.target_model_id}:${m.enabled ? 'on' : 'off'}`)- .sort()- .join(','),- (agent.menu?.checked ?? []).join(','),- sources- .map((s) => `${s.id}:${s.models.map((m) => m.id).sort().join('+')}`)- .sort()- .join(';'),- ].join('|');-/*** The probe's own verdict, named for copy. `reachable` is the discriminator the* contract pins (`error` is null iff reachable), so nothing else is consulted.diff --git a/ui/src/components/settings/models/runtimeLifecycle.ts b/ui/src/components/settings/models/runtimeLifecycle.tsindex a91fac3e7..48c6be5c8 100644--- a/ui/src/components/settings/models/runtimeLifecycle.ts+++ b/ui/src/components/settings/models/runtimeLifecycle.ts@@ -4,22 +4,148 @@// failed start. Pure of React so the contract is unit-testable// (see RuntimeNotStartedAction.test.tsx).import type { ModelsApi } from './modelsApi';-import type { RuntimeDependency } from './types';+import { foldRegionRead, type RegionRead } from './regionRead';+import type { AgentSupply, RuntimeDependency } from './types';++const FRESH_RUNTIME: unique symbol = Symbol('model-hub-fresh-runtime');++export type FreshRuntimeProjection = {+ readonly [FRESH_RUNTIME]: RuntimeDependency;+};++export const freshRuntimeProjection = (+ read: RegionRead<RuntimeDependency>,+): FreshRuntimeProjection | null => foldRegionRead(read, {+ loading: () => null,+ ready: (runtime) => ({ [FRESH_RUNTIME]: runtime }),+ unread: () => null,+ degraded: () => null,+});++const runtimeIsInstalled = (runtime: RuntimeDependency): boolean =>+ runtime.status.health !== 'not_installed' && runtime.status.health !== 'installing';++export const runtimeIsRunning = (runtime: RuntimeDependency): boolean =>+ runtime.status.health === 'ok' || runtime.status.health === 'degraded';++export type InstallAndStartStep = 'install' | 'start' | 'complete';++export const INSTALL_AND_START_STEP = {+ not_installed: 'install',+ installing: 'install',+ not_started: 'start',+ down: 'start',+ ok: 'complete',+ degraded: 'complete',+} as const satisfies Record<RuntimeDependency['status']['health'], InstallAndStartStep>;++export const installAndStartStep = (runtime: RuntimeDependency): InstallAndStartStep =>+ INSTALL_AND_START_STEP[runtime.status.health];++export const agentHasLiveChainProjection = (+ runtime: FreshRuntimeProjection | null,+ agent: AgentSupply,+): boolean => runtime !== null && runtimeIsRunning(runtime[FRESH_RUNTIME]) && agent.mode === 'hub';++export const runtimeHasInstallAsset = (runtime: RuntimeDependency): boolean => {+ const host = 'host_platform' in runtime && typeof runtime.host_platform === 'string'+ ? runtime.host_platform+ : null;+ return runtime.manifest.assets.some((asset) => host == null || asset.platform === host);+};++const waitForPoll = (intervalMs: number): Promise<void> => new Promise((resolve) => {+ globalThis.setTimeout(resolve, intervalMs);+});++export async function installRuntimeUntilSettled(+ api: Pick<ModelsApi, 'installRuntime' | 'getRuntimeStatus'>,+ onRuntime: (runtime: RuntimeDependency) => void = () => {},+ intervalMs = 2_000,+ initialRuntime?: RuntimeDependency,+): Promise<{ runtime: RuntimeDependency | null; failed: boolean }> {+ let runtime: RuntimeDependency | null = initialRuntime ?? null;+ if (!runtime) {+ try {+ runtime = await api.installRuntime();+ } catch {+ // The install request is not safe to repeat until supervisor state proves+ // it did not start. Reconcile the authoritative state first.+ runtime = await api.getRuntimeStatus().catch(() => null);+ }+ }++ if (!runtime) return { runtime: null, failed: true };+ onRuntime(runtime);+ while (runtime.status.health === 'installing') {+ await waitForPoll(intervalMs);+ runtime = await api.getRuntimeStatus().catch(() => null);+ if (!runtime) return { runtime: null, failed: true };+ onRuntime(runtime);+ }+ return { runtime, failed: !runtimeIsInstalled(runtime) };+}export async function startRuntimeWithStatusRefresh(api: Pick<ModelsApi, 'startRuntime' | 'getRuntimeStatus'>,-): Promise<{ runtime: RuntimeDependency | null; failed: boolean }> {+): Promise<{ runtime: RuntimeDependency | null; failed: boolean; error?: unknown }> {try {const runtime = await api.startRuntime();- return { runtime, failed: runtime.status.health !== 'ok' };- } catch {+ return {+ runtime,+ failed: runtime.status.health !== 'ok' && runtime.status.health !== 'degraded',+ };+ } catch (error) {// A failed start changes supervisor health. Read that authoritative state// back so the persistent page does not keep presenting lazy-start idleness.const runtime = await api.getRuntimeStatus().catch(() => null);- return { runtime, failed: runtime?.status.health !== 'ok' };+ return {+ runtime,+ failed: runtime?.status.health !== 'ok' && runtime?.status.health !== 'degraded',+ error,+ };}}+export type InstallAndStartResult = {+ runtime: RuntimeDependency | null;+ failedStep: 'install' | 'start' | null;+ error?: unknown;+};++/** Resume the held install-and-start promise at its first unproven step. */+export async function resumeInstallAndStartRuntime(+ api: Pick<ModelsApi, 'installRuntime' | 'startRuntime' | 'getRuntimeStatus'>,+ initialRuntime: RuntimeDependency,+ onRuntime: (runtime: RuntimeDependency) => void = () => {},+ installPollIntervalMs = 2_000,+): Promise<InstallAndStartResult> {+ let runtime = initialRuntime;+ if (installAndStartStep(runtime) === 'install') {+ const installed = await installRuntimeUntilSettled(+ api,+ onRuntime,+ installPollIntervalMs,+ runtime.status.health === 'installing' ? runtime : undefined,+ );+ if (!installed.runtime || installed.failed) {+ return { runtime: installed.runtime, failedStep: 'install' };+ }+ runtime = installed.runtime;+ }++ if (installAndStartStep(runtime) === 'start') {+ const started = await startRuntimeWithStatusRefresh(api);+ if (started.runtime) onRuntime(started.runtime);+ if (!started.runtime || started.failed) {+ return { runtime: started.runtime, failedStep: 'start', error: started.error };+ }+ runtime = started.runtime;+ }++ return { runtime, failedStep: null };+}+export function pollRuntimeStatus(api: Pick<ModelsApi, 'getRuntimeStatus'>,onRuntime: (runtime: RuntimeDependency) => void,diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.tsindex a5628ccbd..777f2564e 100644--- a/ui/src/components/settings/models/serverCopy.test.ts+++ b/ui/src/components/settings/models/serverCopy.test.ts@@ -67,13 +67,6 @@ describe('oauthFailureKey', () => {// POST /sources errors drift apart, which a shared constant cannot do.const MATERIALIZE = ['discovery_failed', 'migration_item_conflict'] as const;- it('keeps the consent remedy for both journeys', () => {- // consent_required is answered by a control the user can still reach, so its- // copy is the same instruction whichever journey asked.- expect(oauthFailureKey('consent_required', 'connect')).toBe('settings.models.oauth.error.consent');- expect(oauthFailureKey('consent_required', 'reauth')).toBe('settings.models.oauth.error.consent');- });-it.each(MATERIALIZE)('names the right object for %s', (code) => {// The whole reason the journey is a required argument: a connect has no// Source yet, a reauth has one the server just cleared and marked unavailable.@@ -105,7 +98,6 @@ describe('oauthFailureKey', () => {it.each(['zh', 'en'] as const)('resolves every key it can return in %s', (lng) => {const keys = [- oauthFailureKey('consent_required', 'connect'),oauthFailureKey('discovery_failed', 'connect'),oauthFailureKey('discovery_failed', 'reauth'),oauthFailureKey(undefined, 'connect'),diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.tsindex cb09a3c6e..f93d3d78b 100644--- a/ui/src/components/settings/models/serverCopy.ts+++ b/ui/src/components/settings/models/serverCopy.ts@@ -81,10 +81,8 @@ const MATERIALIZE_CODES = ['discovery_failed', 'migration_item_conflict'];* thing that just happened to the one they have.*/export const oauthFailureKey = (code: string | undefined, journey: OAuthJourney): string =>- code === 'consent_required'- ? 'settings.models.oauth.error.consent'- : code && MATERIALIZE_CODES.includes(code)- ? journey === 'reauth'- ? 'settings.models.oauth.error.finalizeReauth'- : 'settings.models.oauth.error.finalize'- : 'settings.models.oauth.error.generic';+ code && MATERIALIZE_CODES.includes(code)+ ? journey === 'reauth'+ ? 'settings.models.oauth.error.finalizeReauth'+ : 'settings.models.oauth.error.finalize'+ : 'settings.models.oauth.error.generic';diff --git a/ui/src/components/settings/models/sourceCreateContract.test.ts b/ui/src/components/settings/models/sourceCreateContract.test.tsnew file mode 100644index 000000000..d8717e6bb--- /dev/null+++ b/ui/src/components/settings/models/sourceCreateContract.test.ts@@ -0,0 +1,22 @@+import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import { SOURCE_DISPLAY_NAME_MAX_LENGTH } from './types';++const CONTRACT = resolve(+ dirname(fileURLToPath(import.meta.url)),+ '../../../../..',+ 'docs/plans/model-hub-contracts/source-create.schema.json',+);++describe('Source create contract projection', () => {+ it('takes the display-name limit from the authoritative schema', () => {+ const schema = JSON.parse(readFileSync(CONTRACT, 'utf8')) as {+ properties: { display_name: { maxLength: number } };+ };+ expect(SOURCE_DISPLAY_NAME_MAX_LENGTH).toBe(schema.properties.display_name.maxLength);+ });+});diff --git a/ui/src/components/settings/models/sourceModelContract.test.ts b/ui/src/components/settings/models/sourceModelContract.test.tsnew file mode 100644index 000000000..b32e82b99--- /dev/null+++ b/ui/src/components/settings/models/sourceModelContract.test.ts@@ -0,0 +1,34 @@+import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import { buildMockSources } from './mockData';++const SOURCE_SCHEMA = resolve(+ dirname(fileURLToPath(import.meta.url)),+ '../../../../..',+ 'docs/plans/model-hub-contracts/source.schema.json',+);++describe('Source model wire contract', () => {+ it('keeps typed fixtures aligned with every required model field and origin member', () => {+ const schema = JSON.parse(readFileSync(SOURCE_SCHEMA, 'utf8'));+ const modelSchema = schema.properties.models.items;+ const models = buildMockSources().flatMap((source) => source.models);+ const enumeratedFields = modelSchema.required.filter(+ (field: string) => Array.isArray(modelSchema.properties[field]?.enum),+ );+ const detail = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), 'SourceDetailPanel.tsx'), 'utf8');++ for (const model of models) {+ expect(modelSchema.required.every((field: string) => Object.hasOwn(model, field))).toBe(true);+ }+ for (const field of enumeratedFields) {+ expect(new Set(models.map((model) => model[field as keyof typeof model])))+ .toEqual(new Set(modelSchema.properties[field].enum));+ expect(detail).toContain(`model.${field}`);+ }+ });+});diff --git a/ui/src/components/settings/models/sourceOrderComposition.test.ts b/ui/src/components/settings/models/sourceOrderComposition.test.tsnew file mode 100644index 000000000..43b035df5--- /dev/null+++ b/ui/src/components/settings/models/sourceOrderComposition.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import { combineSourceOrderReads } from './sourceOrderComposition';+import type { AgentSupply, Source } from './types';++const source = (id: string): Source => ({+ id,+ last_discovered_at: null,+ kind: 'api_key',+ vendor: 'custom',+ display_name: id,+ protocol: 'openai_chat',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active', retry_at: null, detail_key: null },+ models: [],+});++const agent = (order: string[]): AgentSupply => ({+ backend: 'claude',+ cli_present: true,+ mode: 'hub',+ menu_kind: 'fixed',+ sources: { order, eligibility: order.map((sourceId) => ({ source_id: sourceId, eligible: true })) },+});++describe('combineSourceOrderReads', () => {+ it('detects an Agent projection newer than the Source inventory', () => {+ const composition = combineSourceOrderReads(agent(['src_a', 'src_new']), [source('src_a')]);++ expect(composition.missingOrderedIds).toEqual(['src_new']);+ expect(composition.missingInventoryIds).toEqual([]);+ expect(composition.hasHole).toBe(true);+ });++ it('detects a Source inventory newer than the Agent projection', () => {+ const composition = combineSourceOrderReads(agent(['src_a']), [source('src_a'), source('src_new')]);++ expect(composition.missingOrderedIds).toEqual([]);+ expect(composition.missingInventoryIds).toEqual(['src_new']);+ expect(composition.hasHole).toBe(true);+ });++ it('partitions a consistent eligible inventory without a hole', () => {+ const composition = combineSourceOrderReads(agent(['src_a']), [source('src_a')]);+ expect(composition.missingOrderedIds).toEqual([]);+ expect(composition.missingInventoryIds).toEqual([]);+ expect(composition.hasHole).toBe(false);+ expect(composition.available.map(({ id }) => id)).toEqual(['src_a']);+ });+});diff --git a/ui/src/components/settings/models/sourceOrderComposition.ts b/ui/src/components/settings/models/sourceOrderComposition.tsnew file mode 100644index 000000000..6e1904544--- /dev/null+++ b/ui/src/components/settings/models/sourceOrderComposition.ts@@ -0,0 +1,31 @@+import { eligibleSources } from './eligibility';+import type { AgentSupply, Source } from './types';++export type SourceOrderComposition = {+ available: Source[];+ missingOrderedIds: string[];+ missingInventoryIds: string[];+ hasHole: boolean;+};++/** A pair of individually authoritative reads may still describe different server moments. */+export const combineSourceOrderReads = (+ agent: AgentSupply,+ sources: Source[],+): SourceOrderComposition => {+ const inventoryIds = new Set(sources.map((source) => source.id));+ const projectedIds = new Set([+ ...(agent.sources?.order ?? []),+ ...(agent.sources?.eligibility ?? []).map((entry) => entry.source_id),+ ]);+ const missingOrderedIds = (agent.sources?.order ?? []).filter((sourceId) => !inventoryIds.has(sourceId));+ const missingInventoryIds = sources+ .map((source) => source.id)+ .filter((sourceId) => !projectedIds.has(sourceId));+ return {+ available: eligibleSources(sources, agent),+ missingOrderedIds,+ missingInventoryIds,+ hasHole: missingOrderedIds.length > 0 || missingInventoryIds.length > 0,+ };+};diff --git a/ui/src/components/settings/models/sourcePresentation.ts b/ui/src/components/settings/models/sourcePresentation.tsnew file mode 100644index 000000000..cb26bfd52--- /dev/null+++ b/ui/src/components/settings/models/sourcePresentation.ts@@ -0,0 +1,16 @@+import type { Source } from './types';++export const sourceDetail = (source: Source): string | null => {+ const parts: string[] = [];+ if (source.account_label) parts.push(source.account_label);+ if (source.base_url) {+ try {+ const url = new URL(source.base_url);+ parts.push(`${url.host}${url.pathname === '/' ? '' : url.pathname}`);+ } catch {+ parts.push(source.base_url);+ }+ }+ if (source.masked_credential) parts.push(source.masked_credential);+ return parts.length > 0 ? parts.join(' · ') : null;+};diff --git a/ui/src/components/settings/models/sourceStateClassification.test.ts b/ui/src/components/settings/models/sourceStateClassification.test.tsnew file mode 100644index 000000000..a7cd3aef2--- /dev/null+++ b/ui/src/components/settings/models/sourceStateClassification.test.ts@@ -0,0 +1,63 @@+import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import { classifyChainLink, SOURCE_STATE_CLASSIFICATION } from './sourceStateClassification';+import {+ CHAIN_HEALTHS,+ CHAIN_UNAVAILABLE_REASONS,+ SOURCE_STATUSES,+ type AgentChainLink,+} from './types';++const CONTRACTS = resolve(+ dirname(fileURLToPath(import.meta.url)),+ '../../../../..',+ 'docs/plans/model-hub-contracts',+);++describe('source state classification authority', () => {+ it('mirrors the closed Source and AgentChain vocabularies from their schemas', () => {+ const source = JSON.parse(readFileSync(resolve(CONTRACTS, 'source.schema.json'), 'utf8'));+ const chain = JSON.parse(readFileSync(resolve(CONTRACTS, 'agent-chain.schema.json'), 'utf8'));+ const link = chain.properties.chain.items.properties;+ const reasons = link.reason.anyOf.flatMap((branch: { const?: unknown; enum?: unknown[] }) => (+ branch.const === undefined ? branch.enum ?? [] : [branch.const]+ )).filter((value: unknown): value is string => typeof value === 'string');++ expect(new Set(SOURCE_STATUSES)).toEqual(new Set(source.properties.state.properties.status.enum));+ expect(new Set(CHAIN_HEALTHS)).toEqual(new Set(link.health.enum));+ expect(new Set(CHAIN_UNAVAILABLE_REASONS)).toEqual(new Set(reasons));+ expect(new Set(Object.keys(SOURCE_STATE_CLASSIFICATION.sourceStatus))).toEqual(new Set(SOURCE_STATUSES));+ expect(new Set(Object.keys(SOURCE_STATE_CLASSIFICATION.health))).toEqual(new Set(CHAIN_HEALTHS));+ expect(new Set(Object.keys(SOURCE_STATE_CLASSIFICATION.reason))).toEqual(new Set(CHAIN_UNAVAILABLE_REASONS));+ });++ it('separates timed recovery, process blockers, user action, and gone targets', () => {+ const link = (health: AgentChainLink['health'], reason: AgentChainLink['reason']): AgentChainLink => ({+ source_id: 'src_example00',+ model_id: 'model-a',+ channel: reason === 'native_cli_unavailable' ? 'native_cli' : 'hub',+ health,+ runnable: false,+ reason,+ retry_at: health === 'cooldown' || health === 'backoff' ? '2099-01-01T00:00:00Z' : null,+ });++ expect(classifyChainLink(link('cooldown', null))).toBe('self_healing');+ expect(classifyChainLink(link('backoff', 'models.source.backoff.connection_failed'))).toBe('self_healing');+ expect(classifyChainLink(link('backoff', 'native_cli_unavailable'))).toBe('process_blocked');+ expect(classifyChainLink(link('needs_action', 'models.source.needs_action.oauth_expired'))).toBe('needs_user');+ expect(classifyChainLink(link('healthy', 'source_missing'))).toBe('gone');+ });++ it('keeps takeover and relation projection as consumers, not competing tables', () => {+ const takeover = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), 'takeover.ts'), 'utf8');+ const relations = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), 'supplyRelations.ts'), 'utf8');+ expect(takeover).toContain('classifyChainLink(head)');+ expect(relations).toContain('classifyChainLink(link)');+ expect(`${takeover}\n${relations}`).not.toMatch(/SELF_HEALING_HEAD|RECOVERABLE_PROCESS_REASON/);+ });+});diff --git a/ui/src/components/settings/models/sourceStateClassification.ts b/ui/src/components/settings/models/sourceStateClassification.tsnew file mode 100644index 000000000..b5ce05872--- /dev/null+++ b/ui/src/components/settings/models/sourceStateClassification.ts@@ -0,0 +1,49 @@+import type {+ AgentChainLink,+ ChainHealth,+ ChainUnavailableReason,+ SourceStatus,+} from './types';++export type SourceStateClass = 'self_healing' | 'process_blocked' | 'needs_user' | 'gone';++/** One exhaustive state authority for persisted Source status and live chain blockers. */+export const SOURCE_STATE_CLASSIFICATION = {+ sourceStatus: {+ active: null,+ standby: null,+ cooldown: 'self_healing',+ needs_action: 'needs_user',+ error: 'needs_user',+ },+ health: {+ healthy: null,+ cooldown: 'self_healing',+ backoff: 'self_healing',+ needs_action: 'needs_user',+ error: 'needs_user',+ },+ reason: {+ native_cli_unavailable: 'process_blocked',+ 'models.source.backoff.connection_failed': 'self_healing',+ source_missing: 'gone',+ model_unsupported: 'gone',+ 'models.source.needs_action.oauth_expired': 'needs_user',+ 'models.source.needs_action.balance_exhausted': 'needs_user',+ 'models.source.needs_action.credential_revoked': 'needs_user',+ 'models.source.needs_action.account_banned': 'needs_user',+ 'models.source.error.unclassified': 'needs_user',+ },+} as const satisfies {+ sourceStatus: Readonly<Record<SourceStatus, SourceStateClass | null>>;+ health: Readonly<Record<ChainHealth, SourceStateClass | null>>;+ reason: Readonly<Record<ChainUnavailableReason, SourceStateClass>>;+};++export const classifySourceStatus = (status: SourceStatus): SourceStateClass | null =>+ SOURCE_STATE_CLASSIFICATION.sourceStatus[status];++export const classifyChainLink = (link: AgentChainLink): SourceStateClass | null =>+ link.reason === null+ ? SOURCE_STATE_CLASSIFICATION.health[link.health]+ : SOURCE_STATE_CLASSIFICATION.reason[link.reason];diff --git a/ui/src/components/settings/models/sourceStatePresentation.test.ts b/ui/src/components/settings/models/sourceStatePresentation.test.tsnew file mode 100644index 000000000..2ce462c7e--- /dev/null+++ b/ui/src/components/settings/models/sourceStatePresentation.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';++import { sourceStatePresentation } from './sourceStatePresentation';+import type { SourceState, SourceStatus } from './types';++const state = (status: SourceStatus, over: Partial<SourceState> = {}): SourceState => ({+ status,+ retry_at: null,+ detail_key: null,+ ...over,+});++describe('sourceStatePresentation', () => {+ it('omits attribution when the source projection does not carry it', () => {+ expect(sourceStatePresentation(state('active'), 'card', 'en', 0).key).toBeNull();+ expect(sourceStatePresentation(state('active'), 'detail', 'en', 0).key).toBeNull();+ expect(sourceStatePresentation(state('active'), 'card', 'en', 0, {+ known: true,+ backends: [],+ native: false,+ }).key).toBe('settings.models.upstream.state.standby');+ });++ it('uses a creation response adoption without reconstructing it from chains', () => {+ expect(sourceStatePresentation(state('active'), 'card', 'en', 0, {+ known: true,+ backends: ['Claude Code', 'Codex'],+ native: false,+ })).toMatchObject({+ key: 'settings.models.upstream.state.supplying',+ values: { backends: 'Claude Code, Codex' },+ dotClass: 'bg-mint',+ });+ expect(sourceStatePresentation(state('active'), 'detail', 'en', 0, {+ known: true,+ backends: ['Claude Code'],+ native: true,+ })).toMatchObject({ key: 'settings.models.sourceDetail.status.inUse', dotClass: 'bg-mint' });+ });++ it('renders a future cooldown as a localized duration', () => {+ const view = sourceStatePresentation(+ state('cooldown', { retry_at: '2026-08-11T10:05:00Z' }),+ 'detail',+ 'en',+ Date.parse('2026-08-11T10:00:00Z'),+ );+ expect(view).toMatchObject({+ key: 'settings.models.upstream.state.unavailableRetry',+ values: { delay: '5 minutes' },+ });+ });++ it('does not imply another request ran after a cooldown deadline passed', () => {+ expect(sourceStatePresentation(+ state('cooldown', { retry_at: '2026-08-11T09:59:00Z' }),+ 'detail',+ 'en',+ Date.parse('2026-08-11T10:00:00Z'),+ ).key).toBe('settings.models.upstream.state.unavailableDue');+ });++ it('maps each needs-action cause to the copy register', () => {+ expect(sourceStatePresentation(state('needs_action', {+ detail_key: 'models.source.needs_action.balance_exhausted',+ }), 'detail', 'en', 0).key).toBe('settings.models.sourceDetail.status.needsAction.balanceExhausted');+ });+});diff --git a/ui/src/components/settings/models/sourceStatePresentation.ts b/ui/src/components/settings/models/sourceStatePresentation.tsnew file mode 100644index 000000000..d55167c25--- /dev/null+++ b/ui/src/components/settings/models/sourceStatePresentation.ts@@ -0,0 +1,95 @@+import type { NeedsActionDetailKey, SourceState, SourceStatus } from './types';++export type SourceStateSurface = 'card' | 'detail';++export type SourceStatePresentation = {+ key: string | null;+ values?: Record<string, string>;+ textClass: string;+ dotClass: string;+};++const NEEDS_ACTION_KEY: Readonly<Record<NeedsActionDetailKey, string>> = {+ 'models.source.needs_action.oauth_expired': 'settings.models.sourceDetail.status.needsAction.oauthExpired',+ 'models.source.needs_action.balance_exhausted': 'settings.models.sourceDetail.status.needsAction.balanceExhausted',+ 'models.source.needs_action.credential_revoked': 'settings.models.sourceDetail.status.needsAction.credentialRevoked',+ 'models.source.needs_action.account_banned': 'settings.models.sourceDetail.status.needsAction.accountBanned',+};++type Rule = (state: SourceState, surface: SourceStateSurface, locale: string, now: number) => SourceStatePresentation;++const STATUS_RULES: Readonly<Record<SourceStatus, Rule>> = {+ active: () => ({+ key: 'settings.models.upstream.state.standby',+ textClass: 'text-muted',+ dotClass: 'bg-muted',+ }),+ standby: () => ({+ key: 'settings.models.upstream.state.standby',+ textClass: 'text-muted',+ dotClass: 'bg-muted',+ }),+ cooldown: (state, _surface, locale, now) => {+ const retryAt = state.retry_at ? new Date(state.retry_at).getTime() : Number.NaN;+ const remainingMinutes = Math.ceil((retryAt - now) / 60_000);+ if (!Number.isFinite(retryAt) || remainingMinutes <= 0) {+ return {+ key: 'settings.models.upstream.state.unavailableDue',+ textClass: 'model-hub-ink-gold',+ dotClass: 'bg-gold',+ };+ }+ return {+ key: 'settings.models.upstream.state.unavailableRetry',+ values: {+ delay: new Intl.NumberFormat(locale, { style: 'unit', unit: 'minute', unitDisplay: 'long' }).format(remainingMinutes),+ },+ textClass: 'model-hub-ink-gold',+ dotClass: 'bg-gold',+ };+ },+ needs_action: (state) => ({+ key: state.detail_key+ ? NEEDS_ACTION_KEY[state.detail_key as NeedsActionDetailKey] ?? state.detail_key+ : 'settings.models.state.needs_action',+ textClass: 'text-destructive',+ dotClass: 'bg-destructive',+ }),+ error: () => ({+ key: 'settings.models.sourceDetail.status.error',+ textClass: 'text-destructive',+ dotClass: 'bg-destructive',+ }),+};++export const sourceStatePresentation = (+ state: SourceState,+ surface: SourceStateSurface,+ locale: string,+ now: number = Date.now(),+ adoption: { known: boolean; backends: string[]; native: boolean } = { known: false, backends: [], native: false },+): SourceStatePresentation => {+ if (state.status === 'active' && !adoption.known) {+ return { key: null, textClass: 'text-muted', dotClass: 'bg-muted' };+ }+ if (state.status === 'active' && adoption.backends.length > 0) {+ if (surface === 'detail') {+ return {+ key: 'settings.models.sourceDetail.status.inUse',+ textClass: 'model-hub-ink-mint',+ dotClass: 'bg-mint',+ };+ }+ return {+ key: adoption.native+ ? 'settings.models.upstream.state.supplyingNative'+ : 'settings.models.upstream.state.supplying',+ values: adoption.native+ ? { backend: adoption.backends[0] }+ : { backends: adoption.backends.join(locale.startsWith('zh') ? '、' : ', ') },+ textClass: adoption.native ? 'text-cyan' : 'model-hub-ink-mint',+ dotClass: adoption.native ? 'bg-cyan' : 'bg-mint',+ };+ }+ return STATUS_RULES[state.status](state, surface, locale, now);+};diff --git a/ui/src/components/settings/models/subscriptionOptions.ts b/ui/src/components/settings/models/subscriptionOptions.tsnew file mode 100644index 000000000..74e5ca1f2--- /dev/null+++ b/ui/src/components/settings/models/subscriptionOptions.ts@@ -0,0 +1,25 @@+import type { Source, SupplyChannel } from './types';++export type SubscriptionVendorCopy = 'claude' | 'chatgpt';++export const subscriptionVendorCopy = (vendor: string): SubscriptionVendorCopy =>+ vendor === 'openai' ? 'chatgpt' : 'claude';++export const nativeSubscriptionSlotTaken = (vendor: string, sources: Source[]): boolean =>+ sources.some(+ (source) =>+ source.kind === 'subscription'+ && source.supply_channel === 'native_cli'+ && source.vendor === vendor,+ );++export const recommendedSubscriptionChannel = (vendor: string): SupplyChannel =>+ vendor === 'openai' ? 'hub' : 'native_cli';++export const initialSubscriptionChannel = (vendor: string, sources: Source[]): SupplyChannel =>+ nativeSubscriptionSlotTaken(vendor, sources) ? 'hub' : recommendedSubscriptionChannel(vendor);++export const subscriptionOptionOrder = (vendor: string): SupplyChannel[] =>+ recommendedSubscriptionChannel(vendor) === 'hub'+ ? ['hub', 'native_cli']+ : ['native_cli', 'hub'];diff --git a/ui/src/components/settings/models/sufficiency.test.ts b/ui/src/components/settings/models/sufficiency.test.tsindex d8fceb5df..e50905752 100644--- a/ui/src/components/settings/models/sufficiency.test.ts+++ b/ui/src/components/settings/models/sufficiency.test.ts@@ -1,384 +1,27 @@-// Tests for the one owner of 「will the next turn actually run?」.-//-// Written test-first, one block per consuming site, because the class this module-// closes was five sites each answering that question with a `.length` — and the-// review had named only two of them. The last block is the grep guard that makes a-// sixth site impossible to add quietly.-import { readFileSync, readdirSync } from 'node:fs';-import { dirname, join } from 'node:path';-import { fileURLToPath } from 'node:url';-import { describe, expect, it } from 'vitest';-import {- SUPPLY_WARNINGS,- adoptionVerdict,- connectOutcome,- isSupplyWarning,- orderSufficiency,-} from './sufficiency';-import type { AdoptedBy, AgentSupply, Source, SourceEligibility, SourceState, SourceStatus } from './types';--const source = (id: string, status: SourceStatus): Source => ({- id,- kind: 'api_key',- vendor: 'anthropic',- display_name: id,- protocol: 'anthropic',- supply_channel: 'hub',- billing: 'metered',- state: { status, ...(status === 'cooldown' ? { retry_at: '2030-01-01T00:00:00Z' } : {}) } as SourceState,- last_discovered_at: null,- models: [],-});--/** Sources the server says this Agent's machine cannot launch — healthy, eligible,- * and still unable to take the turn. The rows carry `eligible: true` on purpose:- * the two questions are independent, and this one has to bite on its own. */-const unlaunchable = (ids: readonly string[]): SourceEligibility[] =>- ids.map((id) => ({ source_id: id, eligible: true, process_availability_reason: 'native_cli_unavailable' }));--/** The Agent-grain facts `orderSufficiency` hangs off. Its `order` is deliberately- * the WRONG list — the ids under test come in as the first argument. */-const facts = (...cannotLaunch: string[]): Pick<AgentSupply, 'sources'> => ({- sources: { policy: 'follow', order: ['not-the-list-under-test'], eligibility: unlaunchable(cannotLaunch) },-});--/** Direct mode, and every payload that omits the optional field: nothing claimed. */-const NO_FACTS: Pick<AgentSupply, 'sources'> = { sources: null };+import { connectOutcome, orderSufficiency } from './sufficiency';+import type { AgentSupply, Source } from './types';-const hub = (- order: string[],- supply_status: AgentSupply['supply_status'] = null,- cannotLaunch: string[] = [],-): AgentSupply => ({- backend: 'claude',- mode: 'hub',- menu_kind: 'fixed',- sources: { policy: 'follow', order, eligibility: unlaunchable(cannotLaunch) },- supply_status,+const source = (status: Source['state']['status']): Source => ({+ id: 'src_a', last_discovered_at: null, kind: 'api_key', vendor: 'anthropic', display_name: 'A', protocol: 'anthropic',+ supply_channel: 'hub', billing: 'metered', state: { status, retry_at: status === 'cooldown' ? '2099-01-01T00:00:00Z' : null, detail_key: status === 'needs_action' ? 'models.source.needs_action.oauth_expired' : null }, models: [],});--const adopted = (backend: AdoptedBy['backend'], position: number): AdoptedBy => ({- backend,- policy: 'follow',- position,-});--describe('adoptionVerdict — the creation dialogs (AdoptionNote, AddApiKeyDialog, OAuthConnectDialog)', () => {- it('reports an empty adopter list as adopted_none, which IS provable', () => {- // The server sent the array and it is empty: nobody took the source. That is a- // closed fact, not an absence of information.- expect(adoptionVerdict([])).toEqual({ kind: 'adopted_none' });- });-- it('refuses to call a non-empty adopter list covered while skipped_by is missing', () => {- // The honesty rule. `_adopted_by` filters `policy == "follow"`, so a `custom`- // backend that skipped the source is ABSENT — indistinguishable in this payload- // from a backend that was never eligible. Non-empty proves someone took it; it- // proves nothing about who did not.- expect(adoptionVerdict([adopted('claude', 1)])).toEqual({ kind: 'indeterminate' });- });-- it('has no verdict at all when the creation result never arrived', () => {- expect(adoptionVerdict(null)).toEqual({ kind: 'indeterminate' });- });-- // The two branches the server half unlocks. Reachable today only through the- // parameter, so the wiring is proved before the field exists rather than after.- it('is covered once the server states that nothing eligible was skipped', () => {- expect(adoptionVerdict([adopted('claude', 1)], [])).toEqual({ kind: 'covered' });- });-- it('names the skipped backends when the server states them', () => {- const verdict = adoptionVerdict(- [adopted('claude', 1)],- [{ backend: 'codex', reason: 'custom_order' }],- );- expect(verdict).toEqual({ kind: 'partly_skipped', backends: ['codex'] });- });-- it('names the orders when nobody adopted it and the server said who left it out', () => {- // Not a corner case: this is the normal shape of an install where every eligible- // backend keeps a hand-picked order, and it is the case `skipped_by` was added- // for. The remedy matches `adopted_none`, and the difference is the whole value —- // 「go add it somewhere」 vs. 「go add it in these two」.- expect(adoptionVerdict([], [{ backend: 'codex', reason: 'custom_order' }])).toEqual({- kind: 'skipped_all',- backends: ['codex'],- });- });-- it('stays at adopted_none when an empty adopter list is all the server sent', () => {- // Nothing to name, from either direction: no complement at all, and a complement- // that is itself empty (nothing eligible was left out either).- expect(adoptionVerdict([], null)).toEqual({ kind: 'adopted_none' });- expect(adoptionVerdict([], [])).toEqual({ kind: 'adopted_none' });- });+const agent = (supply_status: AgentSupply['supply_status']): AgentSupply => ({+ backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed', sources: { order: ['src_a'], eligibility: [{ source_id: 'src_a', eligible: true, in_current_model_chain: true, process_availability_reason: null }] },+ routes: {}, supply_status, model_supply: [], named_agents: [], builtin_models: [], menu: null,});-describe('orderSufficiency — the drawer (SourceOrderDrawer) and the connect toasts', () => {- it('separates 「nothing enabled」 from 「nothing works」, because the remedies differ', () => {- expect(orderSufficiency([], [source('a', 'active')], NO_FACTS)).toEqual({ kind: 'adopted_none' });- expect(orderSufficiency(['a'], [source('a', 'needs_action')], NO_FACTS)).toEqual({ kind: 'nothing_runnable' });- });-- it('is covered when any enabled source can serve, not when the list is non-empty', () => {- expect(orderSufficiency(['a', 'b'], [source('a', 'error'), source('b', 'standby')], NO_FACTS)).toEqual({- kind: 'covered',- });- });-- it('counts a cooling source as unable to serve right now', () => {- // `cooldown` heals itself, but the turn taken during it still fails, and this- // verdict answers 「the NEXT turn」.- expect(orderSufficiency(['a'], [source('a', 'cooldown')], NO_FACTS)).toEqual({ kind: 'nothing_runnable' });- });-- it('will not claim nothing runs when an enabled id is missing from the inventory', () => {- // The two reads can disagree; an id we cannot resolve is unknown, not broken.- expect(orderSufficiency(['a', 'ghost'], [source('a', 'error')], NO_FACTS)).toEqual({ kind: 'indeterminate' });- });-- it('is indeterminate where the source inventory is not loaded', () => {- expect(orderSufficiency(['a'], null, NO_FACTS)).toEqual({ kind: 'indeterminate' });- expect(orderSufficiency(null, [source('a', 'active')], NO_FACTS)).toEqual({ kind: 'indeterminate' });- });-- // The v4 caveat this closes: a `native_cli` source whose CLI is not usable on this- // machine reports itself perfectly healthy, because the credential IS fine.- it('counts a healthy source this machine cannot launch as unable to serve', () => {- expect(orderSufficiency(['a'], [source('a', 'active')], facts('a'))).toEqual({ kind: 'nothing_runnable' });- });-- it('needs BOTH halves before it says covered', () => {- // One reachable-and-launchable source is enough; neither half alone is.- expect(orderSufficiency(['a', 'b'], [source('a', 'active'), source('b', 'active')], facts('a'))).toEqual({- kind: 'covered',- });- expect(orderSufficiency(['a', 'b'], [source('a', 'active'), source('b', 'cooldown')], facts('a'))).toEqual({- kind: 'nothing_runnable',- });- });-- it('reads silence as runnable rather than inventing an outage', () => {- // Direct mode, a server that omits the optional field, and a source with no row- // all mean 「nothing claimed」 — the weaker claim, never the false alarm.- expect(orderSufficiency(['a'], [source('a', 'active')], NO_FACTS)).toEqual({ kind: 'covered' });- expect(orderSufficiency(['a'], [source('a', 'active')], facts())).toEqual({ kind: 'covered' });- expect(orderSufficiency(['a'], [source('a', 'active')], facts('b'))).toEqual({ kind: 'covered' });- });-- it('grades the ids it was handed, never the order saved on the Agent', () => {- // The drawer asks about the list the user is CURRENTLY editing. `facts()` carries- // a decoy order for exactly this: the Agent comes along for the server facts that- // hang off it, and for nothing else.- expect(orderSufficiency(['a'], [source('a', 'active')], facts())).toEqual({ kind: 'covered' });+describe('orderSufficiency', () => {+ it('distinguishes empty configuration from configured-but-blocked supply', () => {+ expect(orderSufficiency([], [], agent(null))).toEqual({ kind: 'adopted_none' });+ expect(orderSufficiency(['src_a'], [source('needs_action')], agent('interrupted'))).toEqual({ kind: 'nothing_runnable' });});});-/** The same Agent-grain facts with the route gate's two inputs made explicit: the- * order the server's answer was ABOUT, and per-source membership in the selected- * model's chain. An id left out of `membership` has no eligibility row at all —- * the payload that never mentions it. */-const routed = (- savedOrder: readonly string[],- membership: Record<string, boolean | null>,- cannotLaunch: readonly string[] = [],-): Pick<AgentSupply, 'sources'> => ({- sources: {- policy: 'custom',- order: [...savedOrder],- eligibility: Object.entries(membership).map(([id, inChain]) => ({- source_id: id,- eligible: true,- in_current_model_chain: inChain,- process_availability_reason: cannotLaunch.includes(id) ? 'native_cli_unavailable' : null,- })),- },-});--describe('orderSufficiency — of the sources the selected model can actually reach', () => {- it('stops a source that cannot serve THIS turn from answering for it', () => {- // The finding. Enabled: a healthy metered key that does not stock the selected- // model, and the one source that does — a native CLI this machine cannot launch.- // A rollup over 「can any of these serve something」 says 「fine」 about a turn that- // has already been decided to fail.- expect(- orderSufficiency(- ['a', 'b'],- [source('a', 'active'), source('b', 'active')],- routed(['a', 'b'], { a: false, b: true }, ['b']),- ),- ).toEqual({ kind: 'nothing_runnable' });- });-- it('still lets an on-route source answer for it', () => {- // The other side of the same gate: dropping the off-route ones may not turn a- // working order into a warning.- expect(- orderSufficiency(- ['a', 'b'],- [source('a', 'active'), source('b', 'active')],- routed(['a', 'b'], { a: false, b: true }),- ),- ).toEqual({ kind: 'covered' });- });-- it('warns when the route is empty because nothing enabled stocks the model', () => {- // Not 「everything is down」 — everything here is healthy and launchable, and the- // next turn still has no supplier. One verdict, because the warning offers both- // remedies and the user has to do one of them either way.- expect(- orderSufficiency(- ['a', 'b'],- [source('a', 'active'), source('b', 'active')],- routed(['a', 'b'], { a: false, b: false }),- ),- ).toEqual({ kind: 'nothing_runnable' });- });-- it('does not apply the answer to an id the answer was not about', () => {- // The false alarm this gate has to not become. `in_current_model_chain` is- // computed by walking `config.effective_source_order(backend)` — the very list- // the payload reports as `sources.order` — so a source the user has just enabled- // in the drawer and not yet saved reads `false` because it was outside that walk,- // for a reason about the ORDER and not about the model. Gated on that, the drawer- // would say 「下一个回合会失败,再启用一个」 at the exact moment the user enabled- // the one that fixes it.- expect(- orderSufficiency(- ['a', 'b'],- [source('a', 'active'), source('b', 'active')],- routed(['b'], { a: false, b: true }, ['b']),- ),- ).toEqual({ kind: 'covered' });- });-- it('reads a null or absent membership as the silence it is', () => {- // `null` is what every row carries while no model is selected: there is no route,- // so there is nothing to be off. An absent row is a payload that never spoke.- expect(- orderSufficiency(- ['a', 'b'],- [source('a', 'active'), source('b', 'active')],- routed(['a', 'b'], { a: null, b: true }, ['b']),- ),- ).toEqual({ kind: 'covered' });- expect(- orderSufficiency(- ['a', 'b'],- [source('a', 'active'), source('b', 'active')],- routed(['a', 'b'], { b: true }, ['b']),- ),- ).toEqual({ kind: 'covered' });- });-- it('keeps 「unknown id」 ahead of the route gate', () => {- // An id the inventory cannot resolve is still unknown, not broken — even when- // everything the gate DID resolve is off the route.- expect(- orderSufficiency(['a', 'ghost'], [source('a', 'active')], routed(['a', 'ghost'], { a: false })),- ).toEqual({ kind: 'indeterminate' });- });-});--describe('connectOutcome — the two mode-switch toasts', () => {- it('reports a switch that did not take', () => {- expect(connectOutcome({ ...hub([]), mode: 'direct' }, [])).toBe('failed');- });-- it('keeps the server word whenever the server graded the supply', () => {- for (const status of ['degraded', 'waiting', 'interrupted'] as const) {- expect(connectOutcome(hub(['a'], status), [source('a', 'active')])).toBe(status);- }- expect(connectOutcome(hub(['a'], 'ok'), [source('a', 'active')])).toBe('connected');- });-- it('warns about an empty order before consulting the grade', () => {- expect(connectOutcome(hub([], 'ok'), [])).toBe('noSources');- });-- it('no longer reads a null grade as success', () => {- // The finding. `supply_status: null` means the server had no model to resolve- // (`_requested_model` returned nothing) — it is silence about the order, and the- // old code answered it with the order's length.- expect(connectOutcome(hub(['a']), [source('a', 'needs_action')])).toBe('nothingRunnable');- expect(connectOutcome(hub(['a']), [source('a', 'active')])).toBe('connected');- });-- it('warns about an order it cannot launch, even though every source reads healthy', () => {- // The switch just took, the server has no model to resolve yet, and the only- // enabled source is a native CLI this machine cannot run. Health alone would- // call this connected.- expect(connectOutcome(hub(['a'], null, ['a']), [source('a', 'active')])).toBe('nothingRunnable');- });-- it('still defers to the grade the server did give', () => {- // `supply_status` is the server's own answer about the resolved model, computed- // where this fact came from. Our inventory read does not get to overrule it.- expect(connectOutcome(hub(['a'], 'ok', ['a']), [source('a', 'active')])).toBe('connected');- });-- it('is never reached by the route gate, because the two states cannot coexist', () => {- // The verdict's route gate only bites where a model is selected, and this caller- // only consults the verdict where `supply_status` is null — which is the server- // saying it had no model to resolve, the same condition that makes- // `in_current_model_chain` null for every row. So the narrowing has nothing to- // say here, and a payload that somehow carried both would still be answered by- // the membership rather than by the grade's absence.- const noSelection = { ...hub(['a', 'b']), sources: routed(['a', 'b'], { a: null, b: null }).sources };- expect(connectOutcome(noSelection, [source('a', 'active'), source('b', 'active')])).toBe('connected');- });-- it('says 「I did not check」 rather than 「fine」 where the inventory is absent', () => {- // BackendSupplyModeCard holds no source list. Its toast states the mode change,- // which is a fact it owns; it must not upgrade that into a supply claim.- expect(connectOutcome(hub(['a']), null)).toBe('indeterminate');- expect(isSupplyWarning('indeterminate')).toBe(false);- });-- it('routes exactly the warning outcomes through the warning copy family', () => {- expect([...SUPPLY_WARNINGS].sort()).toEqual(- ['degraded', 'interrupted', 'noSources', 'nothingRunnable', 'waiting'].sort(),- );- expect(isSupplyWarning('connected')).toBe(false);- expect(isSupplyWarning('failed')).toBe(false);- });-});--describe('the class: no site answers sufficiency with an emptiness test', () => {- const here = dirname(fileURLToPath(import.meta.url));- const files = readdirSync(here, { recursive: true, encoding: 'utf8' })- .filter((f) => /\.tsx?$/.test(f) && !/\.test\.tsx?$/.test(f) && f !== 'sufficiency.ts');-- /**- * The identifiers that carry the question, used as a BOOLEAN. A count is fine- * (`{ count: enabledIds.length }` renders a group header and claims nothing), so- * the operator is what the rule keys on — which is why it needs no allowance list.- */- const PROXY = /\b(?:adopted_by|adoptedBy|order|enabledIds)\.length\s*(?:[=!<>]=|[<>]|\?|\)|&&|\|\|)/;-- it('sweeps a non-trivial file set', () => {- // Without this the rule below passes over an empty list after any move.- expect(files.length).toBeGreaterThan(15);- expect(files).toContain('AdoptionNote.tsx');- });-- it.each([- 'AdoptionNote.tsx',- 'AddApiKeyDialog.tsx',- 'OAuthConnectDialog.tsx',- 'SourceOrderDrawer.tsx',- 'supply.ts',- ])('%s asks the owner instead of keeping its own proxy', (name) => {- // supply.ts is on the list because `connectOutcome` MOVED out of it: the module- // that used to own the wrong answer must not grow a replacement.- expect(readFileSync(join(here, name), 'utf8')).not.toMatch(PROXY);- });-- it('holds for every other module on the page too', () => {- const offenders = files.filter((f) => PROXY.test(readFileSync(join(here, f), 'utf8')));- expect(offenders).toEqual([]);+describe('connectOutcome', () => {+ it('uses the server rollup rather than recomputing routing', () => {+ expect(connectOutcome(agent('degraded'), [source('active')])).toBe('degraded');+ expect(connectOutcome(agent('waiting'), [source('cooldown')])).toBe('waiting');});});diff --git a/ui/src/components/settings/models/sufficiency.ts b/ui/src/components/settings/models/sufficiency.tsindex 78541292a..7ff382fb0 100644--- a/ui/src/components/settings/models/sufficiency.ts+++ b/ui/src/components/settings/models/sufficiency.ts@@ -1,83 +1,18 @@-// One owner for the question five surfaces were each answering on their own:-// 「will the next turn actually run?」-//-// The class this closes is an EMPTINESS test standing in for an ADEQUACY test. Five-// sites asked `collection.length === 0` and read a non-empty collection as success —-// AdoptionNote, both creation dialogs' auto-close timers, the order drawer's warning,-// and `connectOutcome`. Three different arrays, one question, five answers, and the-// review had named two of them. So the remedy is not five guards: it is one function-// that returns a CLOSED verdict, and no caller left holding a length.-//-// The honesty rule that shapes the union: what the payload cannot prove is-// `indeterminate`, never optimistic. Two server facts were missing when this module-// was written, and both have since landed — `skipped_by` beside `adopted_by` (the-// eligible-but-skipped complement, which `_adopted_by` filters out server-side) and-// `process_availability_reason` on `sources.eligibility` (whether the local machine-// can launch a source at all, at per-(source, backend) grain). Each is now read by-// the function that was already shaped to take it: `adoptionVerdict` takes the-// complement, `orderSufficiency` asks its predicates per source — of the sources-// the selected model's route can actually reach, which `in_current_model_chain`,-// arriving alongside, is what let it narrow to.-//-// The rule outlives them, because the arrival is what proves it was right: neither-// function grew a branch to accommodate the field, and a payload that still omits-// one keeps returning the same weaker verdict it always did. Silence stays-// `indeterminate` or the weaker claim, never a false alarm and never a guess.+// One owner for the question several surfaces ask: will the next turn run?import { offCurrentModelChain, processAvailabilityOf } from './eligibility';import { isUnhealthy } from './supply';-import type { AdoptedBy, AgentBackend, AgentSupply, SkippedBy, Source } from './types';+import type { AgentSupply, Source } from './types';/**- * The closed verdict. Not every grain can produce every member — each function- * documents its own subset — but there is exactly one vocabulary.- *- * `adopted_none` is the empty-membership case at either grain: no backend adopted the- * source, or no source is enabled for the backend. It is deliberately distinct from+ * `adopted_none` is the empty-membership case. It is deliberately distinct from* `nothing_runnable`, because the remedy is 「add one」 rather than 「fix one」.- *- * `skipped_all` is that same 「add one」 remedy with the orders NAMED. It is a separate- * member rather than a field on `adopted_none` because only one grain can ever reach- * it: `orderSufficiency` has no complement to read.*/export type Sufficiency =| { kind: 'covered' }- | { kind: 'partly_skipped'; backends: AgentBackend[] }- | { kind: 'skipped_all'; backends: AgentBackend[] }| { kind: 'nothing_runnable' }| { kind: 'adopted_none' }| { kind: 'indeterminate' };-/**- * Did the new source actually reach everyone it should have?- *- * Returns `adopted_none` | `skipped_all` | `partly_skipped` | `covered` |- * `indeterminate`.- *- * `adopted_by.length` decides how much of the answer is good news, and NOTHING else:- * that array never says who was left out, at any length. So the complement is read on- * both sides of the branch. Zero adopters with a non-empty complement is not a corner- * case but the normal shape of an install where every eligible backend keeps a- * hand-picked order — the exact case the field was added for, and the one where- * naming the orders saves the most work. Deciding it from `adopted_by` alone would be- * this module's own header defect, an emptiness test standing in for an adequacy one.- */-export function adoptionVerdict(- adoptedBy: readonly AdoptedBy[] | null | undefined,- skippedBy?: readonly SkippedBy[] | null,-): Sufficiency {- if (!adoptedBy) return { kind: 'indeterminate' };- const skipped = skippedBy?.map((s) => s.backend) ?? [];- // Empty is a closed fact — the server sent the list and nobody is on it. What it- // is NOT is a reason to stop reading: 「nobody took it」 and 「these three orders- // left it out」 share one remedy and differ entirely in where to go do it.- if (adoptedBy.length === 0) {- return skipped.length > 0 ? { kind: 'skipped_all', backends: skipped } : { kind: 'adopted_none' };- }- // Non-empty proves someone took it and nothing about who did not.- if (!skippedBy) return { kind: 'indeterminate' };- return skipped.length === 0 ? { kind: 'covered' } : { kind: 'partly_skipped', backends: skipped };-}-/*** Can this backend's enabled order serve the next turn?*diff --git a/ui/src/components/settings/models/supply.test.ts b/ui/src/components/settings/models/supply.test.tsindex 73ee6b94e..08c940750 100644--- a/ui/src/components/settings/models/supply.test.ts+++ b/ui/src/components/settings/models/supply.test.ts@@ -35,7 +35,7 @@ const STANDBY: SourceState = { status: 'standby', retry_at: null, detail_key: nuconst COOLING: SourceState = {status: 'cooldown',retry_at: '2026-07-30T09:00:00Z',- detail_key: 'models.source.cooldown.timeout',+ detail_key: 'models.source.cooldown.server_error',};const EXHAUSTED: SourceState = {status: 'cooldown',@@ -50,16 +50,16 @@ const DEAD: SourceState = {const hubAgent = (over: Partial<AgentSupply> = {}): AgentSupply => ({backend: 'claude',+ cli_present: true,mode: 'hub',menu_kind: 'fixed',selected_by_agent: 'claude',selected_model_id: 'claude-opus-4-6',selected_model_explicit: true,- sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility: [] },+ sources: { order: ['src_a', 'src_b'], eligibility: [] },supply_status: 'ok',model_supply: [],named_agents: [],- mappings: [],menu: null,builtin_models: [],standard_vendors: null,@@ -113,7 +113,7 @@ describe('needsAttention', () => {describe('healthyButUnrunnable', () => {const agentWith = (eligibility: NonNullable<AgentSupply['sources']>['eligibility']) =>- hubAgent({ sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility } });+ hubAgent({ sources: { order: ['src_a', 'src_b'], eligibility } });it('retracts a healthy row promise this machine cannot keep', () => {expect(healthyButUnrunnable(agentWith(cannotLaunch('src_b')), nativeSource('src_b', ACTIVE))).toBe(true);@@ -158,8 +158,8 @@ describe('attribution (AC-9)', () => {const agent = hubAgent({named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' }],model_supply: [- { model_id: 'claude-opus-4-6', chain_length: 2 },- { model_id: 'claude-haiku-4-5', chain_length: 0 },+ { model_id: 'claude-opus-4-6', chain_length: 2, has_runnable_hop: true },+ { model_id: 'claude-haiku-4-5', chain_length: 0, has_runnable_hop: false },],});expect(attribution(agent)).toEqual({@@ -172,7 +172,7 @@ describe('attribution (AC-9)', () => {it('never double-counts a model an Agent runs', () => {const agent = hubAgent({named_agents: [{ name: 'claude', effective_model_id: 'claude-haiku-4-5', supply_status: 'interrupted' }],- model_supply: [{ model_id: 'claude-haiku-4-5', chain_length: 0 }],+ model_supply: [{ model_id: 'claude-haiku-4-5', chain_length: 0, has_runnable_hop: false }],});expect(attribution(agent)).toEqual({ interrupted: ['claude'], waiting: [], unassignedModels: [] });});diff --git a/ui/src/components/settings/models/supplyCopyRedline.test.ts b/ui/src/components/settings/models/supplyCopyRedline.test.tsindex 191d18236..a775ba07a 100644--- a/ui/src/components/settings/models/supplyCopyRedline.test.ts+++ b/ui/src/components/settings/models/supplyCopyRedline.test.ts@@ -5,7 +5,7 @@// fix had been applied to the strings that were reported rather than to the class.// `model_hub.resolve()` returns a Direct launch only when the backend's own mode is// direct; past a switch to Hub an empty or blocked order raises-// `mapping_target_unavailable` and the turn FAILS. So any copy telling a Hub user+// `route_unconfigured` and the turn FAILS. So any copy telling a Hub user// that Direct will cover them is false, wherever it lives.//// The check is deliberately TOTAL rather than a list of known-bad keys: it walks@@ -21,7 +21,7 @@ import { SUPPLY_WARNINGS } from './sufficiency';const BUNDLES = { zh, en } as const;-const DIRECT = /直连|direct/i;+const DIRECT = /直连|\bdirect\b/i;/** Verbs that turn a mention of Direct into a claim about falling back to it. */const FALLBACK = /回退|切回|退回|改用|回到|继续用|fall ?back|revert|switch(?:es|ed)? back|stays? on/i;@@ -32,11 +32,12 @@ const FALLBACK = /回退|切回|退回|改用|回到|继续用|fall ?back|revert* and rewriting that sentence into a promise should re-trip the check.*/const CLASSIFIED: Record<string, string> = {- 'order.enabledEmpty': 'States the opposite — 「中枢不会替它回退到直连」 is the correction itself.',+ 'direct.note.perBackend': 'The user is choosing one backend at a time on the all-direct screen.',+ 'gateway.fail.switchToDirect': 'Reports a failed user-triggered switch; it does not promise an automatic fallback.',+ 'adopt.undo.1': 'Names the manual, user-triggered undo promised by the adoption dialog.',+ 'adopt.undo.2': 'Names the exact location of that manual undo control.','migration.nonDestructive':'Describes a manual switch the user may make on the Backends page, not something the Hub does on their behalf.',- 'consent.points.2':- 'ToS advice: recommends the user choose Direct mode for subscriptions themselves. The subject is the user, not the Hub, and it is offered before enabling rather than after supply runs out.',};type Leaf = { key: string; text: string };@@ -73,8 +74,8 @@ describe('Direct-fallback redline over settings.models copy', () => {// Guards the walk itself: a renamed namespace would otherwise make every// assertion below pass over an empty list.const all = leaves(BUNDLES[lng]);- expect(all.length).toBeGreaterThan(100);- expect(all.map((l) => l.key)).toContain('supply.interrupted');+ expect(all.some((leaf) => DIRECT.test(leaf.text))).toBe(true);+ expect(all.some((leaf) => FALLBACK.test(leaf.text))).toBe(true);});it.each(['zh', 'en'] as const)('classifies every Direct-fallback sentence in %s', (lng) => {@@ -110,7 +111,7 @@ describe('Direct-fallback redline over settings.models copy', () => {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) => {+ it.each(['zh', 'en'] as const)('keeps Source order out of exact Route copy in %s', (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 [@@ -121,7 +122,7 @@ describe('Direct-fallback redline over settings.models copy', () => {'routes.orderDecidesSource','routes.openMenuGlobal',]) {- expect(lookup(BUNDLES[lng], key), `${key} does not name its backend in ${lng}`).toContain('{{backend}}');+ expect(lookup(BUNDLES[lng], key), `${key} is retired in ${lng}`).toBeUndefined();}});});diff --git a/ui/src/components/settings/models/supplyRelations.ts b/ui/src/components/settings/models/supplyRelations.tsnew file mode 100644index 000000000..4c9417afd--- /dev/null+++ b/ui/src/components/settings/models/supplyRelations.ts@@ -0,0 +1,70 @@+import { modelChainKey, type ModelChainIndex } from './modelRows';+import { equalHopIdentity, hopBelongsToSource } from './hopIdentity';+import { foldRegionRead } from './regionRead';+import { agentHasLiveChainProjection, type FreshRuntimeProjection } from './runtimeLifecycle';+import { classifyChainLink, classifySourceStatus } from './sourceStateClassification';+import { isTakeoverChain } from './takeover';+import type { AgentBackend, AgentSupply, Source } from './types';++export type SupplyRelationKind = 'native' | 'gateway' | 'connected_unused' | 'takeover' | 'unavailable';++export type SupplyRelation = {+ sourceId: string;+ backend: AgentBackend;+ kind: SupplyRelationKind;+};++const relationKind = (+ source: Source,+ agent: AgentSupply,+ chains: ModelChainIndex,+): SupplyRelationKind => {+ let isCurrent = false;+ let isTakeover = false;+ let isUnavailable = false;+ let hasRunnableLink = false;+ for (const modelId of Object.keys(agent.routes ?? {})) {+ const read = chains[modelChainKey(agent.backend, modelId)];+ const chain = read ? foldRegionRead(read, {+ loading: () => null,+ ready: (value) => value,+ unread: () => null,+ degraded: () => null,+ }) : null;+ if (!chain) continue;+ for (const link of chain.chain.filter((candidate) => hopBelongsToSource(candidate, source.id))) {+ hasRunnableLink ||= link.runnable;+ if (!link.runnable && classifyChainLink(link) !== null) isUnavailable = true;+ if (equalHopIdentity(chain.current, link)) {+ isCurrent = true;+ isTakeover ||= isTakeoverChain(chain);+ }+ }+ }+ if (isTakeover) return 'takeover';+ if (isCurrent) return source.supply_channel === 'native_cli' ? 'native' : 'gateway';+ if ((!hasRunnableLink && isUnavailable) || classifySourceStatus(source.state.status) !== null) return 'unavailable';+ return 'connected_unused';+};++export function buildSupplyRelations(+ agents: AgentSupply[],+ sources: Source[],+ chains: ModelChainIndex,+ runtime: FreshRuntimeProjection | null,+): SupplyRelation[] {+ const sourceById = new Map(sources.map((source) => [source.id, source]));+ const relations: SupplyRelation[] = [];+ for (const agent of agents) {+ if (!agentHasLiveChainProjection(runtime, agent)) continue;+ const sourceIds = new Set(+ Object.values(agent.routes ?? {}).flatMap((route) => route.hops.map((hop) => hop.source_id)),+ );+ for (const source of sources) {+ if (!sourceIds.has(source.id)) continue;+ const canonical = sourceById.get(source.id);+ if (canonical) relations.push({ sourceId: source.id, backend: agent.backend, kind: relationKind(canonical, agent, chains) });+ }+ }+ return relations;+}diff --git a/ui/src/components/settings/models/takeover.ts b/ui/src/components/settings/models/takeover.tsnew file mode 100644index 000000000..0e7c313a8--- /dev/null+++ b/ui/src/components/settings/models/takeover.ts@@ -0,0 +1,16 @@+import { classifyChainLink } from './sourceStateClassification';+import { equalHopIdentity } from './hopIdentity';+import type { AgentChain, AgentChainLink } from './types';++export const currentChainLink = (chain: AgentChain): AgentChainLink | null => {+ if (!chain.current) return null;+ return chain.chain.find((link) => equalHopIdentity(link, chain.current)) ?? null;+};++export const isTakeoverChain = (chain: AgentChain): boolean => {+ const current = currentChainLink(chain);+ const head = chain.chain[0];+ if (!current || !head) return false;+ const advanced = !equalHopIdentity(current, head);+ return advanced && !head.runnable && classifyChainLink(head) === 'self_healing';+};diff --git a/ui/src/components/settings/models/tierMutation.test.ts b/ui/src/components/settings/models/tierMutation.test.tsnew file mode 100644index 000000000..d9ff6b287--- /dev/null+++ b/ui/src/components/settings/models/tierMutation.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';++import { createPendingWrites } from './asyncLifetime';+import { tierMutationPayload, type TierMutationIntent } from './tierMutation';+import type { Source } from './types';++const source = (tiers: string[]): Source => ({+ id: 'source-a',+ last_discovered_at: null,+ kind: 'api_key',+ vendor: 'anthropic',+ display_name: 'Source A',+ protocol: 'anthropic',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active', retry_at: null, detail_key: null },+ models: [{ id: 'model-a', display_name: null, origin: 'manual', reasoning_efforts: tiers }],+});++describe('queued tier mutation payloads', () => {+ it('builds each full-list payload from the latest Source after dequeue', async () => {+ let latest = source(['high', 'medium', 'low']);+ const sent: string[][] = [];+ const writes = createPendingWrites(() => {});+ const enqueue = (intent: TierMutationIntent) => writes.track(latest.id, async () => {+ const payload = tierMutationPayload(latest, 'model-a', intent);+ if (!payload) throw new Error('missing model');+ sent.push(payload.next);+ latest = source(payload.next);+ });++ await Promise.all([+ enqueue({ kind: 'remove', tier: 'high' }),+ enqueue({ kind: 'remove', tier: 'low' }),+ ]);++ expect(sent).toEqual([+ ['medium', 'low'],+ ['medium'],+ ]);+ });+});diff --git a/ui/src/components/settings/models/tierMutation.ts b/ui/src/components/settings/models/tierMutation.tsnew file mode 100644index 000000000..b7cb28485--- /dev/null+++ b/ui/src/components/settings/models/tierMutation.ts@@ -0,0 +1,25 @@+import type { Source } from './types';++export type TierMutationIntent = Readonly<{+ kind: 'add' | 'remove';+ tier: string;+}>;++export type TierMutationPayload = Readonly<{+ previous: string[];+ next: string[];+}>;++export const tierMutationPayload = (+ source: Source,+ modelId: string,+ intent: TierMutationIntent,+): TierMutationPayload | null => {+ const model = source.models.find((candidate) => candidate.id === modelId);+ if (!model) return null;+ const previous = [...model.reasoning_efforts];+ const next = intent.kind === 'add'+ ? previous.includes(intent.tier) ? previous : [...previous, intent.tier]+ : previous.filter((tier) => tier !== intent.tier);+ return { previous, next };+};diff --git a/ui/src/components/settings/models/tsconfig.tests.json b/ui/src/components/settings/models/tsconfig.tests.jsonnew file mode 100644index 000000000..721948207--- /dev/null+++ b/ui/src/components/settings/models/tsconfig.tests.json@@ -0,0 +1,10 @@+{+ "extends": "../../../../tsconfig.app.json",+ "compilerOptions": {+ "composite": false,+ "noEmit": true,+ "tsBuildInfoFile": "../../../../node_modules/.tmp/model-hub-tests.tsbuildinfo"+ },+ "include": ["./**/*.ts", "./**/*.tsx"],+ "exclude": []+}diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 7bb28aa2e..ece91a181 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -3,50 +3,55 @@// (case included); the UI consumes these types and never edits the schemas.//// Contract versions are PER OBJECT, not per file. `_model_hub_success` stamps-// the envelope and nests the payload, so one response carries both numbers: the-// envelope is still v3 while the two payload schemas below moved to v4. Mirrored-// under the backend's own constant names (`core/handlers/model_hub/service.py`-// spells them CONTRACT_VERSION / AGENT_CHAIN_CONTRACT_VERSION /-// PROBE_RESULT_CONTRACT_VERSION) so a bump is greppable across the boundary.-// Never bump one of these to cover another: a shared constant would claim v4-// for every route that did not move. This file changes in lockstep with the-// schemas — never ahead of them.+// the envelope and nests the payload, so one response carries both numbers.+// Mirror the backend's own constant names so a bump is greppable across the+// boundary; never bump one object to cover another. When a frozen contract PR+// is staged ahead of this UI's merge base, optional members stay presence-gated+// and the PR records the server implementation and feature-flag activation+// edge. The client never synthesizes a fallback payload shape.export const CONTRACT_VERSION = 5 as const;-export const AGENT_CHAIN_CONTRACT_VERSION = 5 as const;-export const PROBE_RESULT_CONTRACT_VERSION = 5 as const;+export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;+export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;// ── source.schema.json ──────────────────────────────────────────────────export type SourceKind = 'subscription' | 'api_key';-export type SourceProtocol =- | 'anthropic'- | 'openai_responses'- | 'openai_chat';+export const SOURCE_PROTOCOLS = [+ 'anthropic',+ 'openai_responses',+ 'openai_chat',+] as const;+export type SourceProtocol = (typeof SOURCE_PROTOCOLS)[number];+export const SOURCE_DISPLAY_NAME_MAX_LENGTH = 64 as const;export type SupplyChannel = 'native_cli' | 'hub';/** v3 (§4.5): classified by whether the state heals itself. cooldown carries a* `retry_at` and clears on its own; needs_action never recovers unattended;* error is an unclassified failure and equally a blocker. */-export type SourceStatus = 'active' | 'standby' | 'cooldown' | 'needs_action' | 'error';-export type ModelProvenance = 'discovered' | 'manual';+export const SOURCE_STATUSES = ['active', 'standby', 'cooldown', 'needs_action', 'error'] as const;+export type SourceStatus = (typeof SOURCE_STATUSES)[number];+export type ModelOrigin = 'discovered' | 'manual';/** Optional cause of a self-healing cooldown. A closed vocabulary, not a* prefix: the key is rendered through i18n, never as raw upstream text. */-export type CooldownDetailKey =- | 'models.source.cooldown.network'- | 'models.source.cooldown.timeout'- | 'models.source.cooldown.rate_limited'- | 'models.source.cooldown.quota_exhausted'- | 'models.source.cooldown.server_error';+export const COOLDOWN_DETAIL_KEYS = [+ 'models.source.cooldown.rate_limited',+ 'models.source.cooldown.quota_exhausted',+ 'models.source.cooldown.server_error',+] as const;+export type CooldownDetailKey = (typeof COOLDOWN_DETAIL_KEYS)[number];/** Required on `needs_action`: the state's whole point is that the user must* act, which is unrenderable without naming the action. */-export type NeedsActionDetailKey =- | 'models.source.needs_action.oauth_expired'- | 'models.source.needs_action.balance_exhausted'- | 'models.source.needs_action.credential_revoked'- | 'models.source.needs_action.account_banned';+export const NEEDS_ACTION_DETAIL_KEYS = [+ 'models.source.needs_action.oauth_expired',+ 'models.source.needs_action.balance_exhausted',+ 'models.source.needs_action.credential_revoked',+ 'models.source.needs_action.account_banned',+] as const;+export type NeedsActionDetailKey = (typeof NEEDS_ACTION_DETAIL_KEYS)[number];-export type ErrorDetailKey = 'models.source.error.unclassified';+export const ERROR_DETAIL_KEYS = ['models.source.error.unclassified'] as const;+export type ErrorDetailKey = (typeof ERROR_DETAIL_KEYS)[number];/** The complete set `state.detail_key` (and `ProbeResult.error`) can hold. */export type SourceDetailKey = CooldownDetailKey | NeedsActionDetailKey | ErrorDetailKey;@@ -75,13 +80,15 @@ export type SuppliedModel = {/** Bare model id (no provider prefix). */id: string;display_name?: string | null;- provenance: ModelProvenance;- reasoning_efforts?: string[];+ origin: ModelOrigin;+ reasoning_efforts: string[];discovered_at?: string | null;};export type Source = {id: string;+ /** Exact optional create correlation used only for lost-response recovery. */+ client_nonce?: string | null;/** Source creation time; ordinary audit/display metadata only. */created_at?: string | null;/** Latest successful full model discovery for this source. null means the@@ -95,8 +102,6 @@ export type Source = {/** api_key kind only. null = vendor official default. */base_url?: string | null;supply_channel: SupplyChannel;- /** Set iff a hub-held subscription the user explicitly consented to. */- experimental_consent_at?: string | null;billing: 'monthly' | 'metered';state: SourceState;usage?: SourceUsage;@@ -110,6 +115,8 @@ export type Source = {models: SuppliedModel[];/** Opaque handle. Secret material NEVER appears here. */credential_ref?: string | null;+ /** Server-derived persisted Route-reference projection. */+ adopted_by?: AdoptedBy[];};// `priority.schema.json` does not exist in v3: there is no global source order,@@ -121,24 +128,12 @@ export type AgentBackend = 'claude' | 'codex' | 'opencode';export type AgentMode = 'hub' | 'direct';export type MenuKind = 'fixed' | 'open';-export type AgentMapping = {- /** real built-in model id, e.g. claude-opus-4-6. */- builtin_id: string;- target_model_id: string;- enabled: boolean;-};-export type AgentMenu = {view: 'featured' | 'full';/** prefixed identifiers, e.g. zhipuai/glm-5.2. */checked: string[];};-/** Whether the per-backend order is server-recommended or user-owned. `follow`- * recomputes on every read, so a newly eligible source joins automatically;- * `custom` is a frozen subset the server never reorders and never extends. */-export type SourcePolicy = 'follow' | 'custom';-/** Why a source cannot serve this backend at all. A closed vocabulary — a new* cause ships its enum member and its locale copy in the same change. */export type EligibilityReasonKey =@@ -166,7 +161,6 @@ export type SourceEligibility = {};export type AgentSources = {- policy: SourcePolicy;/** Enabled source ids for THIS backend, position 0 = tried first. A subset:* ids absent from it are not enabled here, not merely lower-priority. */order: string[];@@ -175,6 +169,22 @@ export type AgentSources = {eligibility?: SourceEligibility[] | null;};+export type RouteHop = {+ source_id: string;+ model_id: string;+};++export type RouteHopRef = RouteHop & {+ backend: AgentBackend;+ menu_model: string;+ /** One-based position in the Route before the guarded mutation. */+ position: number;+};++export type AgentRoute = {+ hops: RouteHop[];+};+/** Agent-level supply rollup (§4.5). `waiting` = every enabled source is* cooling and one will come back; `interrupted` = nothing can serve the* selection without the user acting. */@@ -196,10 +206,13 @@ export type NamedAgentSupply = {export type ModelSupply = {model_id: string;chain_length: number;+ has_runnable_hop: boolean;};export type AgentSupply = {backend: AgentBackend;+ /** Server-authoritative CLI installation fact for this backend. */+ cli_present: boolean;mode: AgentMode;menu_kind: MenuKind;/** The named Agent whose explicit selection `selected_model_id` came from.@@ -211,8 +224,10 @@ export type AgentSupply = {/** TRUE iff `selected_model_id` originates from the Agent's explicit* configuration. FALSE covers a resolver-picked value. */selected_model_explicit?: boolean;- /** Per-backend enabled subset + order + policy. null when mode=direct. */+ /** Per-backend enabled subset + order. null when mode=direct. */sources?: AgentSources | null;+ /** Exact configured Route for each menu model. Runtime reads this verbatim. */+ routes?: Record<string, AgentRoute> | null;/** Rollup over `sources.order` for the current selection. null in direct mode* and whenever `selected_model_id` is null. */supply_status?: SupplyStatus | null;@@ -221,11 +236,10 @@ export type AgentSupply = {/** AC-9 attribution source. Always present; every entry's `supply_status` is* null in direct mode. */named_agents?: NamedAgentSupply[];- mappings?: AgentMapping[];menu?: AgentMenu | null;/** v1.2 read-only projection: fixed-menu backends only — the backend's real* built-in model ids (from vibe/backend_model_catalog.py). null for open-menu- * backends. The mapping drawer renders these; the UI never hardcodes menus. */+ * backends. The route editor renders these; the UI never hardcodes menus. */builtin_models?: string[] | null;/** v1.2 read-only projection: opencode only — server mirror of* STANDARD_OPENCODE_VENDOR_IDS, so the UI never hand-mirrors vendor prefixes.@@ -235,9 +249,8 @@ export type AgentSupply = {// ── migration-scan.schema.json ──────────────────────────────────────────export type MigrationKind = 'api_key' | 'oauth_native' | 'opencode_provider';-/** Option 1 (spec v1.1): Claude oauth_native → keep_native (sanctioned as-is);- * Codex auth.json → controlled_import behind the consent-gated flag, else- * keep_native; keys / base URLs → import. */+/** Native OAuth remains native; controlled_import is reserved and not+ * applicable in v3. Keys and base URLs may be imported. */export type MigrationAction = 'import' | 'controlled_import' | 'keep_native' | 'reauth';export type MigrationItem = {@@ -260,7 +273,6 @@ export type ResolutionEventKind =| 'cooldown'| 'recover'| 'skip'- | 'mapping_applied'| 'channel_switch'/** v3: a source stopped in a way that will never heal unattended. */| 'needs_action'@@ -273,17 +285,17 @@ export type ResolutionReason =| 'network'| 'recovery'| 'manual'- | 'mapping'- // v3 — the five non-self-healing causes, a bijection with the needs_action /- // error detail keys above.+ // Non-self-healing causes mirror the source-state detail vocabulary.| 'credential_expired'| 'credential_revoked'| 'balance_exhausted'| 'account_banned'+ | 'permission_denied'| 'unclassified_error'- // v3 — supply exhaustion causes.| 'no_enabled_source'| 'no_eligible_source'+ | 'route_unconfigured'+ | 'source_missing'| 'model_unsupported';export type BillingNote = null | 'entered_metered' | 'left_metered';/** v3: `action_required` on needs_action / supply_interrupted, `info` on the six@@ -310,23 +322,27 @@ export type ResolutionEvent = {};// ── agent-chain.schema.json ─────────────────────────────────────────────-export type ChainHealth = 'healthy' | 'cooldown' | 'needs_action' | 'error';--/** v4: the only process-unavailability state in v2. `chain[].reason` is its- * VOCABULARY HOME; `ProbeResult.error` carries the i18n spelling of the same- * fact (`models.probe.native_cli_unavailable`), a mapping registered as M8 in- * mirror-registry.json. */-export type ChainUnavailableReason = 'native_cli_unavailable';+export const CHAIN_HEALTHS = ['healthy', 'cooldown', 'backoff', 'needs_action', 'error'] as const;+export type ChainHealth = (typeof CHAIN_HEALTHS)[number];++/** Closed runtime-unavailability vocabulary shared by chain and probe results. */+export const CHAIN_UNAVAILABLE_REASONS = [+ 'native_cli_unavailable',+ 'models.source.backoff.connection_failed',+ 'source_missing',+ 'model_unsupported',+ ...NEEDS_ACTION_DETAIL_KEYS,+ ...ERROR_DETAIL_KEYS,+] as const;+export type ChainUnavailableReason = (typeof CHAIN_UNAVAILABLE_REASONS)[number];export type AgentChainLink = {source_id: string;+ model_id: string;/** v4: the source's serving channel, mirroring `Source.supply_channel`. `hub`* is definitionally process-available; `native_cli` is additionally gated by* whether this process can launch the sanctioned CLI under its own login. */channel: SupplyChannel;- via_mapping: boolean;- /** The id actually sent upstream. Non-null whenever `via_mapping` is true. */- resolved_model_id: string | null;health: ChainHealth;/** Health permits the turn AND this process can serve the channel. Always* false for needs_action / error, and whenever `reason` is non-null; true for@@ -349,6 +365,7 @@ export type AgentChain = {contract_version: typeof AGENT_CHAIN_CONTRACT_VERSION;backend: AgentBackend;model_id: string;+ current: RouteHop | null;chain: AgentChainLink[];/** v4 pins this to the array it summarises: `ok` iff some member is runnable,* the two blocked values iff none is. */@@ -358,7 +375,10 @@ export type AgentChain = {// ── probe-result.schema.json ────────────────────────────────────────────/** v4 widened this beyond `state.detail_key`: the native_cli branch reports* process unavailability, which no source-state key can express. */-export type ProbeErrorKey = SourceDetailKey | 'models.probe.native_cli_unavailable';+export type ProbeErrorKey =+ | SourceDetailKey+ | 'models.source.backoff.connection_failed'+ | 'models.probe.native_cli_unavailable';/** POST /api/models/agents/<backend>/probe — hub mode only, same reason as the* chain route: there is no `src_*` identity to report in direct mode. */@@ -379,37 +399,25 @@ export type ProbeResult = {* because nothing upstream is timed — a local number would impersonate* completion evidence. */latency_ms: number | null;- via_mapping: boolean;/** Closed vocabulary, null on every reachable result. hub: the ten* `state.detail_key` values. native_cli: only the unavailability key. */error: ProbeErrorKey | null;};-/** api.md — returned by the source-creation routes: which backends adopted the- * new source into their order, and where. `position` is ONE-based. A `custom`- * backend is absent (the UI hints 「有新来源未启用」 instead). */-export type AdoptedBy = {+/** api.md — the exact Route hops materialized by Add Source. */+export type AddedTo = {backend: AgentBackend;- policy: SourcePolicy;+ menu_model: string;+ source_id: string;+ model_id: string;+ /** One-based position in the persisted Route chain. */position: number;};-/**- * api.md — the eligible-but-skipped complement of `adopted_by`, returned beside it- * by both creation routes.- *- * It exists because absence in `adopted_by` says two different things: a backend- * that could never use this source, and one that could and was left out. Only the- * second is worth telling the user about, and only the server can tell them apart —- * `_skipped_by` filters on `_eligible_for_agent` before reporting a `custom` order- * that omits the id.- */-export type SkippedBy = {+/** api.md — stable Source-card projection of persisted Route references. */+export type AdoptedBy = {backend: AgentBackend;- /** v2's only cause: the backend keeps a `custom` order, which the server never- * extends on its own. An INELIGIBLE backend is not 「skipped」 — it was never a- * candidate, and it appears in neither list. */- reason: 'custom_order';+ menu_model: string;};// ── oauth-flow.schema.json ──────────────────────────────────────────────@@ -457,10 +465,12 @@ export type OAuthFlow = {};// ── runtime-dependency.schema.json ──────────────────────────────────────-export type RuntimeHealth = 'ok' | 'degraded' | 'down' | 'not_started' | 'not_installed';+export type RuntimeHealth = 'ok' | 'degraded' | 'down' | 'not_started' | 'not_installed' | 'installing';export type RuntimeDependency = {contract_version: typeof CONTRACT_VERSION;+ /** Server host platform, never the browser platform. */+ host_platform?: string;manifest: {name: 'cliproxyapi';version: string;@@ -478,6 +488,7 @@ export type RuntimeDependency = {listening?: { host: '127.0.0.1'; port: number } | null;health: RuntimeHealth;last_check?: string | null;+ error_key?: 'settings.models.install.fail.detail' | null;};};@@ -502,12 +513,48 @@ export type SupplyGap = {agents: string[];};-/** POST /api/models/sources — api_key create validates + discovers models. */+// ── observation-result.schema.json ─────────────────────────────────────+export type ObservationOutcome =+ | 'observed'+ | 'ambiguous'+ | 'unreachable'+ | 'authentication_failed'+ | 'adapter_error'+ | 'timeout';++export type ObservationAuthentication = 'authenticated' | 'rejected' | 'unknown';+export type ObservationDiscovery = 'succeeded' | 'failed' | 'not_attempted';++export type SourceObservation = {+ contract_version: typeof CONTRACT_VERSION;+ outcome: ObservationOutcome;+ reachable: boolean | null;+ authenticated: ObservationAuthentication;+ protocol: SourceProtocol | null;+ discovery: ObservationDiscovery;+ models: string[];+};++/** POST /api/models/sources/observe — never persists a Source. */+export type ApiKeySourceObservation = {+ vendor: string;+ base_url?: string | null;+ key: string;+ /** Probe order only. Every member occurs exactly once. */+ protocol_order?: SourceProtocol[];+};++/** POST /api/models/sources — api_key create observes again before persisting. */export type ApiKeySourceCreate = {kind: 'api_key';vendor: string;+ display_name?: string;base_url?: string | null;key: string;+ /** Stable across a create retry; persisted only when the Source commits. */+ client_nonce?: string;+ /** Probe order only; the client never sends a protocol conclusion. */+ protocol_order?: SourceProtocol[];};/**@@ -526,7 +573,6 @@ export type OAuthSourceCreate = {oauth_flow_ref: string;supply_channel: SupplyChannel;display_name?: string;- experimental_consent?: boolean;};/** PATCH /api/models/sources/<id> — display_name and/or base_url only@@ -536,11 +582,10 @@ export type SourcePatch = {base_url?: string | null;};-/** PUT /api/models/agents/<backend>/sources — a TOTAL body: `follow` hands the- * order back to the server, `custom` freezes exactly the ids sent. The route- * rejects unknown keys, so `contract_version` is deliberately NOT part of it. */-export type AgentSourcesPut = { policy: 'follow' } | { policy: 'custom'; order: string[] };+/** PUT /api/models/agents/<backend>/sources — replaces the complete order. */+export type AgentSourcesPut = { order: string[] };+/** PUT /api/models/agents/<backend>/chain?model=<id> — replaces exact hops. *//*** PUT /api/models/sources/<id>/credential — hub-channel api_key sources only.* Also a TOTAL body that rejects unknown keys (`contract_version` included), sodiff --git a/ui/src/components/settings/models/useDeadlineClock.ts b/ui/src/components/settings/models/useDeadlineClock.tsnew file mode 100644index 000000000..ab4e0a2df--- /dev/null+++ b/ui/src/components/settings/models/useDeadlineClock.ts@@ -0,0 +1,26 @@+import * as React from 'react';++const CLOCK_TICK_MS = 60_000;++export const useDeadlineClock = (deadlineValue?: string | null): number => {+ const [now, setNow] = React.useState(() => Date.now());+ const deadline = deadlineValue ? Date.parse(deadlineValue) : Number.NaN;++ React.useEffect(() => {+ let timer: ReturnType<typeof setTimeout> | null = null;+ const tick = () => {+ const current = Date.now();+ setNow(current);+ if (Number.isFinite(deadline) && current < deadline) {+ timer = setTimeout(tick, Math.min(CLOCK_TICK_MS, deadline - current));+ }+ };++ tick();+ return () => {+ if (timer !== null) clearTimeout(timer);+ };+ }, [deadline]);++ return now;+};diff --git a/ui/src/components/settings/models/validation.test.ts b/ui/src/components/settings/models/validation.test.tsnew file mode 100644index 000000000..13b6ef501--- /dev/null+++ b/ui/src/components/settings/models/validation.test.ts@@ -0,0 +1,11 @@+import { describe, expect, it } from 'vitest';++import { optionalTrimmedTextWithin, unicodeCodePointLength } from './validation';++describe('contract text validation', () => {+ it('counts Unicode code points rather than UTF-16 code units', () => {+ expect(unicodeCodePointLength('😀')).toBe(1);+ expect(optionalTrimmedTextWithin('😀'.repeat(64), 64)).toBe(true);+ expect(optionalTrimmedTextWithin('😀'.repeat(65), 64)).toBe(false);+ });+});diff --git a/ui/src/components/settings/models/validation.ts b/ui/src/components/settings/models/validation.tsnew file mode 100644index 000000000..9f983f170--- /dev/null+++ b/ui/src/components/settings/models/validation.ts@@ -0,0 +1,7 @@+export const unicodeCodePointLength = (value: string): number => Array.from(value).length;++export const optionalTrimmedTextWithin = (value: string, maxLength: number): boolean => {+ if (value.length === 0) return true;+ const trimmed = value.trim();+ return trimmed.length > 0 && unicodeCodePointLength(trimmed) <= maxLength;+};diff --git a/ui/src/components/settings/models/vendorMeta.test.ts b/ui/src/components/settings/models/vendorMeta.test.tsnew file mode 100644index 000000000..86a145485--- /dev/null+++ b/ui/src/components/settings/models/vendorMeta.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest';++import {+ BACKEND_IDENTITY_ACCENT,+ backendVisual,+ SOURCE_IDENTITY_ACCENT,+ sourceAccent,+} from './vendorMeta';++describe('Model Hub semantic identity palette', () => {+ it('keeps every source authority row connected to the source consumer', () => {+ for (const [identity, accent] of Object.entries(SOURCE_IDENTITY_ACCENT)) {+ const source = identity === 'native_cli'+ ? { kind: 'subscription' as const, supply_channel: 'native_cli' as const }+ : { kind: identity as 'subscription' | 'api_key', supply_channel: 'hub' as const };+ expect(sourceAccent(source)).toBe(accent);+ }+ });++ it('keeps every backend authority row connected to the backend consumer', () => {+ for (const [backend, accent] of Object.entries(BACKEND_IDENTITY_ACCENT)) {+ expect(backendVisual(backend as keyof typeof BACKEND_IDENTITY_ACCENT).accent).toBe(accent);+ }+ });+});diff --git a/ui/src/components/settings/models/vendorMeta.ts b/ui/src/components/settings/models/vendorMeta.tsindex 2625ef306..378ec3f4a 100644--- a/ui/src/components/settings/models/vendorMeta.ts+++ b/ui/src/components/settings/models/vendorMeta.ts@@ -1,32 +1,28 @@-// Visual + vendor metadata for the Model Hub surfaces. Colors follow the V4-// design (design.pen `产品改造 V4 01r/06r/07`): subscriptions carry the brand-// sparkle accent (Claude→mint, ChatGPT→gold); API keys carry a per-vendor key-// accent (Anthropic→violet, 智谱→cyan, custom/relay→gold). Only the icon-// component is reused from `lib/agentBackends`; the V4 accents differ from the-// older backends page on purpose, so they live here as data.+// Model Hub identity colors are semantic, not vendor branding: channel/kind+// owns source color, while backend identity owns Agent color.import type React from 'react';import { Bot, KeyRound, Sparkles, Terminal } from 'lucide-react';-import type { AgentBackend, Source, SourceProtocol } from './types';+import type { AgentBackend, Source } from './types';export type Accent = 'mint' | 'gold' | 'cyan' | 'violet' | 'muted';// Soft-tinted tile + matching icon/dot color per accent. Uses the theme tokens// (mint/gold/cyan/violet + *-soft) so it tracks Light/Dark automatically.export const ACCENT_TILE: Record<Accent, string> = {- mint: 'bg-mint-soft',- gold: 'bg-gold/15',- cyan: 'bg-cyan-soft',- violet: 'bg-violet-soft',- muted: 'bg-surface-2',+ mint: 'model-hub-accent-tile--mint',+ gold: 'model-hub-accent-tile--gold',+ cyan: 'model-hub-accent-tile--cyan',+ violet: 'model-hub-accent-tile--violet',+ muted: 'model-hub-accent-tile--neutral',};export const ACCENT_ICON: Record<Accent, string> = {- mint: 'text-mint',- gold: 'text-gold',- cyan: 'text-cyan',- violet: 'text-violet',- muted: 'text-muted',+ mint: 'model-hub-accent-ink--mint',+ gold: 'model-hub-accent-ink--gold',+ cyan: 'model-hub-accent-ink--cyan',+ violet: 'model-hub-accent-ink--violet',+ muted: 'model-hub-accent-ink--neutral',};// Status dot fill (composite pill · recent-switch list). Gold reserved for the@@ -39,30 +35,31 @@ export const ACCENT_DOT: Record<Accent, string> = {muted: 'bg-muted',};+export const ACCENT_PILL: Record<Accent, string> = {+ mint: 'model-hub-accent-pill--mint',+ gold: 'model-hub-accent-pill--gold',+ cyan: 'model-hub-accent-pill--cyan',+ violet: 'model-hub-accent-pill--violet',+ muted: 'model-hub-accent-pill--neutral',+};+type IconType = React.ComponentType<{ size?: number; className?: string }>;-// api_key accent by vendor id. Unknown vendors fall back to violet (the generic-// "key" accent used by the add-source menu).-const API_KEY_ACCENT: Record<string, Accent> = {- anthropic: 'violet',- openai: 'gold',- zhipuai: 'cyan',- kimi: 'cyan',- xai: 'muted',- custom: 'gold',-};+export const SOURCE_IDENTITY_ACCENT = {+ native_cli: 'cyan',+ subscription: 'mint',+ api_key: 'muted',+} as const satisfies Record<'native_cli' | Source['kind'], Accent>;-export function sourceAccent(source: Pick<Source, 'kind' | 'vendor'>): Accent {- if (source.kind === 'subscription') {- if (source.vendor === 'openai') return 'gold';- return 'mint'; // anthropic + any other subscription- }- return API_KEY_ACCENT[source.vendor] ?? 'violet';+export function sourceAccent(source: Pick<Source, 'kind' | 'supply_channel'>): Accent {+ return source.supply_channel === 'native_cli'+ ? SOURCE_IDENTITY_ACCENT.native_cli+ : SOURCE_IDENTITY_ACCENT[source.kind];}export type SourceVisual = { Icon: IconType; accent: Accent };-export function sourceVisual(source: Pick<Source, 'kind' | 'vendor'>): SourceVisual {+export function sourceVisual(source: Pick<Source, 'kind' | 'supply_channel'>): SourceVisual {return {Icon: source.kind === 'subscription' ? Sparkles : KeyRound,accent: sourceAccent(source),@@ -72,44 +69,50 @@ export function sourceVisual(source: Pick<Source, 'kind' | 'vendor'>): SourceVis// ── Agent backends (Agent card rows) ────────────────────────────────────export type BackendVisual = { Icon: IconType; accent: Accent };+export const BACKEND_IDENTITY_ACCENT = {+ claude: 'cyan',+ codex: 'mint',+ opencode: 'violet',+} as const satisfies Record<AgentBackend, Accent>;++export const BACKEND_ADOPTION_VENDOR_KEY = {+ claude: 'claude',+ codex: 'chatgpt',+ opencode: 'chatgpt',+} as const satisfies Record<AgentBackend, string>;++const BACKEND_ICON: Record<AgentBackend, IconType> = {+ claude: Sparkles,+ codex: Bot,+ opencode: Terminal,+};+const BACKEND_VISUAL: Record<AgentBackend, BackendVisual> = {- claude: { Icon: Sparkles, accent: 'mint' },- codex: { Icon: Bot, accent: 'gold' },- opencode: { Icon: Terminal, accent: 'violet' },+ claude: { Icon: BACKEND_ICON.claude, accent: BACKEND_IDENTITY_ACCENT.claude },+ codex: { Icon: BACKEND_ICON.codex, accent: BACKEND_IDENTITY_ACCENT.codex },+ opencode: { Icon: BACKEND_ICON.opencode, accent: BACKEND_IDENTITY_ACCENT.opencode },};export function backendVisual(backend: AgentBackend): BackendVisual {return BACKEND_VISUAL[backend] ?? { Icon: Bot, accent: 'muted' };}-// ── API-key vendor picker (frame 06r) ───────────────────────────────────-// value = standard vendor id; labelKey → i18n; base_url prefilled for official-// vendors (editable), null for 自定义. Probe order is only a hint; the server-// still requires upstream response evidence before it stores a protocol.-export type VendorOption = {- value: string;- labelKey: string;- base_url: string | null;- probe_order: SourceProtocol[];+// Official endpoints are used only to classify an existing Source as custom.+// Add API key accepts a Base URL directly and intentionally has no vendor picker.+const OFFICIAL_BASE_URLS: Record<string, string> = {+ anthropic: 'https://api.anthropic.com/v1',+ openai: 'https://api.openai.com/v1',+ zhipuai: 'https://open.bigmodel.cn/api/paas/v4',+ kimi: 'https://api.moonshot.cn/v1',+ xai: 'https://api.x.ai/v1',};-export const VENDOR_OPTIONS: VendorOption[] = [- { value: 'custom', labelKey: 'settings.models.addKey.vendors.custom', base_url: null, probe_order: ['openai_responses', 'openai_chat', 'anthropic'] },- { value: 'anthropic', labelKey: 'settings.models.addKey.vendors.anthropic', base_url: 'https://api.anthropic.com/v1', probe_order: ['anthropic', 'openai_responses', 'openai_chat'] },- { value: 'openai', labelKey: 'settings.models.addKey.vendors.openai', base_url: 'https://api.openai.com/v1', probe_order: ['openai_responses', 'openai_chat', 'anthropic'] },- { value: 'zhipuai', labelKey: 'settings.models.addKey.vendors.zhipuai', base_url: 'https://open.bigmodel.cn/api/paas/v4', probe_order: ['openai_responses', 'openai_chat', 'anthropic'] },- { value: 'kimi', labelKey: 'settings.models.addKey.vendors.kimi', base_url: 'https://api.moonshot.cn/v1', probe_order: ['openai_responses', 'openai_chat', 'anthropic'] },- { value: 'xai', labelKey: 'settings.models.addKey.vendors.xai', base_url: 'https://api.x.ai/v1', probe_order: ['openai_responses', 'openai_chat', 'anthropic'] },-];--export const DEFAULT_VENDOR = VENDOR_OPTIONS[0];-// An api_key points at a custom endpoint when its base URL is set and differs// from the vendor's official one — covers both vendor='custom' (official = null)// and an official vendor whose prefilled Base URL was edited to a relay. Shared// by the 来源 list (SourceRow) and the custom-model source picker.export function isCustomEndpoint(source: Pick<Source, 'vendor' | 'base_url'>): boolean {if (!source.base_url) return false;- const official = VENDOR_OPTIONS.find((v) => v.value === source.vendor)?.base_url ?? null;+ const official = OFFICIAL_BASE_URLS[source.vendor] ?? null;return source.base_url !== official;}diff --git a/ui/src/components/settings/models/vocabulary.test.ts b/ui/src/components/settings/models/vocabulary.test.tsindex 4942032b2..f01b5cd61 100644--- a/ui/src/components/settings/models/vocabulary.test.ts+++ b/ui/src/components/settings/models/vocabulary.test.ts@@ -13,13 +13,14 @@ const leaves = (node: unknown): string[] =>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(copy).not.toMatch(/菜单固定|跟随推荐|中枢 Hub|按量\s*\$|映射|供给引擎|自定义顺序|已改为手动|恢复默认/);expect(copy).not.toMatch(/按量(?!付费)/);expect(zh.settings.models.billing.monthly).toBe('订阅');expect(zh.settings.models.billing.metered).toBe('按量付费');expect(en.settings.models.billing.monthly).toBe('Subscription');expect(en.settings.models.billing.metered).toBe('Pay as you go');- expect(zh.settings.models.order.customized).toBe('已改为手动');- expect(zh.settings.models.order.restore).toBe('恢复默认');+ expect(zh.settings.models.order.subtitle).toContain('不会改动任何已配置的路由链');+ expect(en.settings.models.order.subtitle).toContain('changes no configured Route chain');+ expect('policy' in zh.settings.models.agents).toBe(false);});});diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 9ee312175..d025645da 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -629,26 +629,246 @@"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}}",+ "tabs": {+ "sources": "Sources & gateway",+ "usage": "Usage & quota"+ },+ "sourceKind": {+ "api_key": "API key",+ "subscription": "Subscription"+ },+ "shell": {+ "title": "Models",+ "running": "Gateway running",+ "stopped": "Gateway stopped · click to start",+ "degraded": "Gateway running degraded",+ "unread": "Gateway status unavailable",+ "notStarted": "Gateway not started · click to start",+ "notInstalled": "Gateway component not installed · click to install",+ "allDirect_one": "The only backend is direct",+ "allDirect_other": "All {{count}} backends are direct",+ "starting": "Starting…",+ "unsupported": "No gateway component for this platform yet",+ "gatewayInfo": {+ "label": "What the gateway is",+ "body": "The gateway is a dispatch layer on this machine: it holds the sources you add and supplies them to your Agents in the order you configure."+ },+ "tab": {+ "hub": "Sources & gateway",+ "usage": "Usage & quota"+ }+ },+ "direct": {+ "card": {+ "current": "Currently: direct",+ "current.sub": "Each agent backend uses its own login and connects to the vendor directly."+ },+ "pill": {+ "direct": "Direct"+ },+ "backend": {+ "claude": { "detail": "Uses its own Claude login" },+ "codex": { "detail": "Uses its own ChatGPT login" },+ "opencode": { "detail": "Uses its own model configuration" }+ },+ "action": {+ "switchToGateway": "Switch to gateway"+ },+ "benefits": {+ "title": "Switch to the gateway and you gain three things",+ "1": "Your session survives a quota running out",+ "1.detail": "When your Claude subscription is exhausted, it moves to the next source you added and the conversation continues.",+ "2": "One key supplies several backends",+ "2.detail": "The same API key can serve Claude Code, Codex and OpenCode at once.",+ "3": "Decide per backend and per model",+ "3.detail": "You can specify which source each model on each backend uses."+ },+ "note": {+ "perBackend": "Switch one backend at a time — the others stay direct. You can switch back at any time."+ },+ "empty": {+ "title": "No agent backend was found on this machine",+ "body": "Install Claude Code, Codex or OpenCode, come back to this page, and they will appear here.",+ "install": "Install a backend CLI, then reload this page."+ }+ },+ "adopt": {+ "title": "Switch {{backend}} to the gateway",+ "subtitle": "Affects {{backend}} only; the other backends are unchanged.",+ "vendor": {+ "claude": "Claude",+ "chatgpt": "ChatGPT"+ },+ "section": {+ "effects": "What will happen",+ "undo": "You can undo this"+ },+ "effects": {+ "1": "Your current {{vendor}} login becomes the first source and keeps priority",+ "2": "Once you add other sources, it moves to them when this login is exhausted",+ "1.opencode": "OpenCode's own model configuration is kept as it is; this switch does not change it",+ "2.opencode": "Its models are supplied from the sources on this page; if there are none yet, add one first",+ "3": "The model menu does not change",+ "4": "Conversations in progress are unaffected; the change applies from the next request",+ "install": "The gateway component ({{component}}, about {{duration}}) is installed first, then the switch happens"+ },+ "undo": {+ "1": "You can switch back to direct at any time",+ "2": "Where to undo: the {{backend}} card on this page → Switch to direct",+ "3": "If you switch back, the sources you added stay; they just stop supplying {{backend}}"+ },+ "cancel": "Cancel",+ "confirm": "Switch to gateway",+ "confirm.install": "Install and switch",+ "fail": {+ "title": "The switch to the gateway did not go through",+ "detail": "{{request}} · {{status}} · {{reason}}",+ "reason": {+ "transport": "The gateway could not be reached",+ "refused": "The gateway did not accept the switch",+ "notReady": "The gateway started but did not become ready",+ "unknown": "No reason was given"+ }+ }+ },+ "install": {+ "duration": "1 minute",+ "title": "Install the gateway component",+ "subtitle": "Installs the component only; the backends keep working the way they do now",+ "section": {+ "effects": "What will happen"+ },+ "effects": {+ "1": "{{component}} is downloaded and installed, about {{duration}}",+ "2": "The gateway starts automatically once it is installed",+ "3": "No backend is switched and the model menu does not change"+ },+ "confirm": "Install and start",+ "cancel": "Cancel",+ "progress": "Installing…",+ "fail": {+ "title": "The install did not finish",+ "detail": "The install did not finish, and the component may be left incomplete. Retrying installs it again from scratch."+ },+ "retry": "Try again"+ },+ "gateway": {+ "heading": "Gateway",+ "sourceOrder": "Source order",+ "switchToGateway": "Switch to gateway",+ "switchToDirect": "Switch to direct",+ "fail": {+ "switchToDirect": "The switch back to direct did not go through"+ },+ "modelCount_one": "{{count}} model",+ "modelCount_other": "{{count}} models",+ "moreModels_one": "{{count}} more model",+ "moreModels_other": "{{count}} more models",+ "collapse_one": "{{count}} more model",+ "collapse_other": "{{count}} more models",+ "retry": "Retry",+ "supply": {+ "none": "No usable source",+ "unread": "Could not read this backend's supply · the gateway itself is fine"+ },+ "row": {+ "current": "Now: {{source}}",+ "currentTakeover": "Now: {{source}} (takeover)"+ },+ "group": {+ "subtitle": {+ "direct": "{{mode}}",+ "gateway": "{{mode}} · {{health}}"+ },+ "mode": {+ "direct": "Direct",+ "gateway": "Gateway"+ },+ "status": {+ "ok": "Healthy",+ "degraded": "Degraded",+ "waiting": "All sources are cooling down",+ "interrupted": "No source is available",+ "noSelection": "No model selected"+ },+ "emptyModels": "This backend has no models"+ }+ },+ "takeover": {+ "pill_one": "{{count}} takeover active",+ "pill_other": "{{count}} takeovers active",+ "chip": "Taken over"+ },+ "legend": {+ "native": "Native",+ "viaGateway": "Gateway supply",+ "connectedUnused": "Enabled · not currently used",+ "takeover": "Taken over · temporarily rerouted",+ "unavailable": "Supply paused",+ "note": "Route chains are each backend's configured source order."+ },+ "usageTab": {+ "title": "Usage and quota",+ "detail": "Usage appears after a gateway source serves a request."+ },"status": {"allHealthy": "All healthy",- "needsAction": "{{count}} model(s) need attention",+ "needsAction_one": "{{count}} model needs attention",+ "needsAction_other": "{{count}} models need attention","noIssues": "No models need attention"},"statusPill": {- "ok": "All good · {{count}} on the Hub",- "none": "No agent is on the Hub yet",- "engineDown": "Supply engine isn't ready · the Hub can't serve",- "interrupted": "{{count}} with no supply · needs attention",- "waiting": "{{count}} awaiting source recovery",+ "ok_one": "All good · {{count}} on the gateway",+ "ok_other": "All good · {{count}} on the gateway",+ "none": "No Agent is using the gateway yet",+ "engineDown": "The gateway isn't ready to serve",+ "interrupted_one": "{{count}} with no supply · needs attention",+ "interrupted_other": "{{count}} with no supply · needs attention",+ "waiting_one": "{{count}} awaiting source recovery",+ "waiting_other": "{{count}} awaiting source recovery","needsAction": "{{source}} — {{detail}}","cooldown": "{{source}} — {{detail}} · switched over, will switch back",- "andMore": "{{count}} more"+ "andMore_one": "{{count}} more",+ "andMore_other": "{{count}} more"+ },+ "upstream": {+ "heading": "Sources",+ "count_one": "{{count}} source",+ "count_other": "{{count}} sources",+ "group": {+ "native": "Native · on this machine",+ "hub": "Held by the gateway"+ },+ "kind": {+ "nativeCredential": "Native · local credential",+ "subscription": "Subscription",+ "apiKey": "API key"+ },+ "empty": "No sources yet. Add a subscription or an API key first.",+ "unread": "Could not read the source list · the gateway itself is fine",+ "retry": "Retry",+ "addSubscription": "Add subscription",+ "addApiKey": "Add API key",+ "state": {+ "supplyingNative": "Supplying {{backend}} (native)",+ "supplying": "Supplying {{backends}}",+ "standby": "Standby",+ "unavailableRetry": "Unavailable · retrying automatically after {{delay}}",+ "unavailableDue": "Unavailable · the retry is due"+ }},"sources": {"title": "Sources",+ "info": "Accounts and credentials available to gateway routes",+ "count_one": "{{count}} source",+ "count_other": "{{count}} sources",+ "group": {+ "native": "Native · on this machine",+ "hub": "Held by the gateway"+ },"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)",+ "modelCount_one": "{{count}} model",+ "modelCount_other": "{{count}} models","lastDiscovery": "Last fetched {{time}}","neverDiscovered": "Not fetched yet","addModel": "Add model",@@ -657,7 +877,7 @@},"source": {"nativeSupply": "Native supply",- "hubHosted": "Hub-hosted",+ "hubHosted": "Gateway-held","officialEndpoint": "Official endpoint","customEndpoint": "Custom endpoint","retryIn": "retry in {{minutes}} min",@@ -665,20 +885,36 @@"oauthSignedOut": "CLI subscription is signed out"},"order": {- "title": "Source order · {{backend}}",- "subtitle": "Used top to bottom; a failure switches to the next one and switches back once it recovers. This order only affects {{backend}}.",- "subtitleShort": "Used top to bottom; failures switch over and back. Affects {{backend}} only.",- "groupEnabled": "Enabled · {{count}}",- "groupDisabled": "Not enabled · {{count}}",- "groupIneligible": "Not applicable · {{count}}",- "customized": "Changed manually",- "restore": "Restore default",- "enable": "Enable",- "enableAria": "Enable {{name}}",- "disable": "Disable",- "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"+ "title": "{{backend}} · Source order",+ "subtitle": "The Source order this backend stores. Changing it changes no configured Route chain.",+ "reorder": "Reorder source",+ "section": {+ "ordered": "In this order",+ "ordered.note": "Drag to reorder",+ "heldOut": "Not in this order"+ },+ "action": {+ "include": "Add to order",+ "exclude": "Remove from order"+ },+ "empty": {+ "noEligible": "No source is available to this backend yet.",+ "ordered": "This order is empty. Add a source from below."+ },+ "cancel": "Cancel",+ "save": "Save order",+ "fail": {+ "read": "The source list could not be read",+ "save": "The order was not saved"+ },+ "retry": "Retry",+ "grabbed_one": "Grabbed {{source}}, position {{position}} of {{count}}.",+ "grabbed_other": "Grabbed {{source}}, position {{position}} of {{count}}.",+ "moved_one": "Moved {{source}} to position {{position}} of {{count}}.",+ "moved_other": "Moved {{source}} to position {{position}} of {{count}}.",+ "dropped_one": "Dropped {{source}} at position {{position}} of {{count}}.",+ "dropped_other": "Dropped {{source}} at position {{position}} of {{count}}.",+ "grabCancelled": "Cancelled moving {{source}} and restored its original position."},"billing": {"monthly": "Subscription",@@ -698,7 +934,7 @@"label": "Supplies: "},"mode": {- "hub": "Hub",+ "hub": "Gateway","direct": "Direct"},"errors": {@@ -710,22 +946,19 @@"startNow": "Start now","starting": "Starting"},- "install": {- "fail": {- "detail": "The install did not finish, and the component may be left incomplete. Retrying installs it again from scratch."- }- },"experimental": "Experimental","agents": {"title": "Agent","subtitle": "Each agent picks its own sources and order; a failure moves to the next one","backendSettings": "Backend settings",- "connectHub": "Connect to Hub",- "modelCount": "{{count}} model(s)",- "hubNoSupply": "On Hub · no source enabled, the next turn will fail",- "directNote": "Still supplied by the CLI's own config — not connected to the Hub",+ "connectHub": "Switch to gateway",+ "modelCount_one": "{{count}} model",+ "modelCount_other": "{{count}} models",+ "hubNoSupply": "On the gateway · no source enabled, the next turn will fail",+ "directNote": "Uses the CLI's native configuration","sourceOrder": "Source order",- "modelListCount": "{{count}} model(s)",+ "modelListCount_one": "{{count}} model",+ "modelListCount_other": "{{count}} models","enableManaged": "Manage centrally","emptyModels": "This agent has no models yet.","manageModels": "Manage models",@@ -733,10 +966,6 @@"fixed": "Fixed menu","open": "Open menu"},- "policy": {- "follow": "Recommended",- "custom": "Custom"- },"attribution": {"interrupted": "No supply for {{names}}","waiting": "Awaiting source recovery for {{names}}",@@ -753,41 +982,22 @@"blocked": "Current source unavailable","currentSwitched": "Currently switched to {{source}}","currentSource": "Currently served by {{source}}",+ "takeover": "Now: {{source}} (takeover)",+ "waiting": "Waiting for a source to recover","source": "Served by {{source}}","unknown": "Unable to confirm","retry": "Retry","runtime": "Model service is not ready","runtimeAction": "Resolve"},- "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"+ "routeDialog": {+ "title": "{{model}} · Route chain",+ "open": "Open {{model}} route chain",+ "label": "Route chain for this model",+ "removeHop": "Remove hop",+ "addHop": "Add a hop",+ "reseed": "Reorder by source order",+ "hint": "This chain is stored configuration. Later source-order changes do not change it."},"recent": {"title": "Recent switches",@@ -805,54 +1015,108 @@"detail": "Cross-vendor auto-substitution (off) · Request log · Diagnostics","comingSoon": "Advanced settings are coming soon"},- "addMenu": {- "claude": {- "title": "Connect Claude subscription",- "subtitle": "Pro / Max · browser sign-in"+ "addKey": {+ "title": "Add API key",+ "subtitle": "Add connects once: it identifies the interface and fetches the model list",+ "field": {+ "name": "Name (optional)",+ "baseUrl": "Base URL",+ "baseUrl.hint": "Paste any relay, aggregator or self-hosted address — Avibe identifies the interface itself",+ "apiKey": "API key",+ "apiKey.reveal": "Show API key",+ "apiKey.conceal": "Hide API key"},- "chatgpt": {- "title": "Connect ChatGPT subscription",- "subtitle": "Plus / Pro · browser sign-in"+ "test": "Fetch models",+ "test.hint": "Optional · Add fetches once anyway",+ "pull": {+ "result_one": "Fetched {{count}} model",+ "result_other": "Fetched {{count}} models",+ "empty": "Connected, but this source lists no models"},- "apiKey": {- "title": "Add API Key…",- "subtitle": "Any vendor or compatible service, editable URL"+ "submit": "Add",+ "adding": "Connecting…",+ "adding.detail": "Connect, identify the interface, fetch the model list · usually 1–3s",+ "fail": {+ "subtitle": "Identifying the interface is a precondition of Add · fix what the line below names, then retry",+ "auth": "Authentication failed: 401 Unauthorized",+ "auth.detail": "Check whether the API key is valid",+ "address": "Wrong address: 404 Not Found",+ "network": "Could not connect to this address (unreachable or timed out)",+ "unclassified": "It did not connect, and the cause could not be identified",+ "engineDown": "The gateway is not responding — try again",+ "save": "The source is not confirmed saved"},- "sheetTitle": "Add source",- "sheetSubtitle": "There are only two kinds: a subscription account, or a key. A relay is just a key with a different URL.",- "vendorTitle": "Connect a subscription",- "vendorSubtitle": "Uses the CLI's own sign-in; the credential stays on this machine.",- "apiKeySheetSubtitle": "Official or third-party URLs both work; filling in a custom URL makes it a relay.",- "subscription": {- "title": "Subscription account",- "subtitle": "Claude Pro, ChatGPT Plus and the like. Uses the CLI's own sign-in; the credential stays in the local CLI.",- "recommended": "Recommended"- }- },- "addKey": {- "title": "Add API Key",- "subtitle": "Any vendor or compatible service; connect once, shared by every agent.",- "vendorLabel": "Vendor",- "vendorHint": "Choosing Anthropic / OpenAI / Zhipu / Kimi etc. prefills the official URL.",- "keyLabel": "API KEY",- "baseUrlLabel": "SERVICE URL (BASE URL)",- "baseUrlHint": "Official vendors are prefilled and editable; for a compatible service (relay, self-hosted gateway) enter the URL it gives you.",- "discovered": "Connected · discovered {{count}} model(s), added to the supply list",- "failed": "Connection failed: {{detail}}",- "testing": "Connecting…",- "vendors": {- "custom": "Custom · OpenAI / Anthropic compatible",- "anthropic": "Anthropic",- "openai": "OpenAI",- "zhipuai": "Zhipu",- "kimi": "Kimi",- "xai": "xAI"- }+ "retry": "Retry",+ "undetermined": {+ "title": "Connected and authenticated — but we cannot tell which interface it speaks",+ "detail": "The response shape matches no interface we know",+ "label": "Interface type · you hint it this once",+ "hint": "The hint only reorders the probe · it still has to really connect before anything is saved, and it cannot be changed afterwards"+ },+ "protocol": {+ "anthropicMessages": "Anthropic Messages",+ "openaiResponses": "OpenAI Responses",+ "openaiChatCompletions": "OpenAI Chat Completions"+ },+ "inventory": {+ "title": "The interface is identified — but its model list did not come back this time"+ },+ "addAnyway": "Add anyway",+ "success": {+ "title": "Done → the dialog closes and you land on Source details · Models",+ "detail": "The model list, refetch and reasoning tiers are all maintained there"+ },+ "cancel": "Cancel"},"field": {"apiKeyPlaceholder": "sk-…","baseUrlPlaceholder": "https://api.example.com/v1"},+ "addSub": {+ "title": "Add {{vendor}} subscription",+ "subtitle": {+ "claude": "claude.ai / Max · Pro",+ "chatgpt": "chatgpt.com / Plus · Pro"+ },+ "opt": {+ "added": "Already added",+ "native": {+ "label": "Use natively",+ "desc": {+ "claude": "Claude Code uses this subscription directly; the credential stays on this machine.",+ "chatgpt": "Codex signs in with this ChatGPT account directly."+ }+ },+ "hub": {+ "label": "Sign in as a gateway source",+ "desc": {+ "claude": "Hand this subscription to the gateway so it can supply Codex, OpenCode and other Agents.",+ "chatgpt": "The gateway supplies it to Codex and other Agents, with usage, quota and takeover all visible."+ }+ }+ },+ "badge": {+ "recommended": "Recommended",+ "secondary": "Second choice",+ "supportedNotRecommended": "Supported, not recommended"+ },+ "tos": {+ "claude": "The subscription terms authorize only you, inside Claude's official clients. Supplying it to other Agents is out-of-scope use and the account may be restricted."+ },+ "hint": {+ "claude": "You can have both — add them one at a time.",+ "chatgpt": "Nothing takes over when the quota runs out, and usage stays invisible."+ },+ "signIn": "Sign in",+ "cancel": "Cancel",+ "retry": "Retry",+ "error": {+ "oauthFailed": "Sign-in did not complete. You can retry.",+ "startFailed": "Could not confirm the sign-in started — you can retry",+ "engineDown": "The gateway is not responding. Please retry.",+ "alreadyBound": "This backend's native login slot is already taken. Add it as a gateway-held source instead."+ }+ },"oauth": {"title": {"anthropic": "Connect Claude subscription",@@ -886,142 +1150,70 @@"timeout": "Authorization timed out, please reconnect","generic": "Connection failed, please retry","finalize": "Authorized, but couldn't create the source — please retry",- "finalizeReauth": "Signed in, but this source still isn't working — please retry",- "consent": "A hub-hosted subscription needs experimental consent — restart the connect and enable the hub option."- },- "hubOption": {- "title": "Let the Hub hold this subscription (experimental)",- "subtitle": "The Hub stores and forwards the credential; may violate vendor terms",- "on": "On",- "off": "Off"+ "finalizeReauth": "Signed in, but this source still isn't working — please retry"}},- "consent": {- "title": "Hub-held subscription · risk notice",- "subtitle": "Please confirm you understand the risks before enabling.",- "points": [- "This source uses your own subscription login. Vendor terms generally intend a subscription for personal use inside the official client; routing it through the hub proxy is an unofficial use that may violate those terms.",- "There is a real risk of rate-limiting, review, or account suspension (Claude subscriptions used via proxies have been auto-disabled). Enabling this is your choice and at your own risk.",- "For the safest setup, use Direct mode for subscriptions (official client, direct connection), or add an API Key source instead — vendors explicitly permit programmatic / proxied use of API keys."- ],- "confirm": "I understand the risks, continue"- },"toast": {"reorderFailed": "Couldn't save the new order",- "connected": "Connected to the Hub",+ "connected": "Connected to the gateway","connectFailed": "Couldn't connect, please retry","refreshFailed": "Couldn't refresh, please retry"},"supply": {- "degraded": "On the Hub · a source is down, already switched to the next one",- "waiting": "On the Hub · every source is cooling down; turns fail until one recovers",- "interrupted": "On the Hub · supply interrupted, the next turn will fail",- "noSources": "On the Hub · no source enabled yet, the next turn will fail",- "nothingRunnable": "On the Hub · no enabled source can serve right now, the next turn will fail"+ "degraded": "On the gateway · a source is down, already switched to the next one",+ "waiting": "On the gateway · every source is cooling down; turns fail until one recovers",+ "interrupted": "On the gateway · supply interrupted, the next turn will fail",+ "noSources": "On the gateway · no source enabled yet, the next turn will fail",+ "nothingRunnable": "On the gateway · no enabled source can serve right now, the next turn will fail"},"adoption": {- "enabled": "Added to the source order of {{list}}",- "entry": "{{name}} (#{{position}})",- "none": "No agent has enabled it yet · add it to an agent's source order for it to be used",- "noneSkipped": "No agent has enabled it yet · skipped for {{skipped}} (hand-picked order) — add it there to use it",- "partlySkipped": "Added to the source order of {{list}} · skipped for {{skipped}} (hand-picked order) — add it there to use it"- },- "menus": {- "done": "Done",- "resetAll": "Reset all to default",- "saveFailed": "Couldn't save your changes, please retry",- "enrolled": "Added {{sources}} to {{backend}}’s source order so your selection has a supplier",- "mapping": {- "title": "{{backend}} · Model menu",- "subtitle": "Fixed menu: {{backend}} only recognizes these built-in model IDs. Each ID can be redirected to another model — this affects {{backend}} only.",- "builtinCol": "Built-in model ID",- "supplyCol": "Actual supply",- "followNative": "Follow native · supply by source order",- "candidates": "Source order · {{sources}}",- "candidatesUnavailable": "No source can supply this model yet",- "warning": "Reasoning, cache and tool semantics aren't fully equivalent after remapping",- "resetRow": "Reset to default",- "footnote": "Remapping affects only this ID in {{backend}}; the Hub converts protocols automatically."- },- "opencode": {- "title": "OpenCode · Model menu",- "subtitle": "Open menu: grouped by provider prefix. Prefix + model ID = the full identifier, identical to native OpenCode. Checked = shown in the model picker.",- "viewLabel": "Menu scope",- "featured": "Featured · {{count}}",- "full": "All · {{count}}",- "addCustom": "Custom model",- "empty": "No models here yet.",- "footnote": "Prefix = the standard vendor ID (identical to native OpenCode; unrecognized vendors fall under custom/). Switching Hub/Direct never changes the identifier; dots = supplying sources.",- "customBadge": "Custom",- "provider": {- "anthropic": "Anthropic protocol · Claude family",- "openai": "OpenAI protocol · GPT family",- "zhipuai": "OpenAI-compatible · GLM family",- "custom": "Custom endpoints"- }- },- "custom": {- "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",- "displayNameLabel": "Display name (optional)",- "displayNamePlaceholder": "GLM 5.2 Air",- "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 model",- "failed": "Couldn't add the model, please retry",- "delete": "Remove model",- "deleteConfirmTitle": "Remove custom model?",- "deleteConfirmBody": "This removes {{model}} from “{{source}}”.",- "deleted": "Custom model removed",- "deleteFailed": "Couldn't remove the model, please retry",- "deleteInUse": "This model is still selected by an agent — unselect it in that menu/mapping first."- }+ "enabled": "Added to {{list}}",+ "route": "{{backend}} · {{model}} · hop {{position}}",+ "none": "Connected. Add it to a model's route when you want to use it."},"supplyMode": {"title": "Supply mode",- "currentHub": "Current: Hub",+ "currentHub": "Current: Gateway","currentDirect": "Current: Direct",- "switchedHub": "Switched to Hub",+ "switchedHub": "Switched to Gateway","switchedDirect": "Switched to Direct","switchFailed": "Couldn't switch mode, please retry","hub": {- "title": "Hub mode",+ "title": "Gateway mode","recommended": "Recommended · default","openModels": "Open Models page",- "description": "Model tokens are supplied from Settings → Models: sign-ins, API keys, source order and mappings all live there. {{backend}}'s native config is left untouched, and you can switch away anytime."+ "description": "Sign-ins, API keys and per-model Routes are managed in Settings → Models. {{backend}}'s native config is left untouched, and you can switch away anytime."},"direct": {"title": "Direct mode","description": "{{backend}} uses its own native config (settings.json / CLI sign-in); Avibe only launches the process and doesn't manage models. Good for troubleshooting or fully self-managed setups.",- "detected": "Existing direct config detected: {{detail}} — import it into the Hub in one click",- "import": "Import to Hub…"+ "detected": "Existing direct config detected: {{detail}} — import it into the gateway in one click",+ "import": "Import to gateway…"},"fixHint": "Add or enable a source on the Models page to bring it back."},"migration": {- "title": "Connect to the Model Hub",- "subtitle": "Move your existing sign-ins and API keys into the Models Hub in one pass — each agent then picks its own sources and their order.",+ "title": "Connect to the model gateway",+ "subtitle": "Move your existing sign-ins and API keys into the gateway in one pass — each Agent then keeps its own sources and order.","empty": "No native configuration detected to migrate.","scanFailed": "Couldn't scan native configs, please retry","applyFailed": "Import failed, please retry",- "applied": "Imported {{count}} item(s)",+ "applied_one": "Imported {{count}} item",+ "applied_other": "Imported {{count}} items","later": "Maybe later",- "apply": "Import {{count}} & enable Hub",+ "apply_one": "Import {{count}} item and enable the gateway",+ "apply_other": "Import {{count}} items and enable the gateway","nonDestructive": "Non-destructive: native configs are never changed or deleted — importing only copies them; you can switch back to Direct on the Backends page anytime.","action": {"import": "Import as source",- "controlledImport": "Controlled import · experimental",+ "controlledImport": "Controlled import · reserved","keepNative": "Keep native","reauth": "Re-authorize · one-click in browser"},"notes": {"customBaseUrl": "Includes a custom Base URL","keepNativeSanctioned": "Stays in the CLI's own store (sanctioned)",- "keepNativeReauthHint": "Kept native; re-authorize inside the hub to make it hub-held (experimental)",+ "keepNativeReauthHint": "Kept native; add a separate gateway-held subscription explicitly","fromOpencode": "From the opencode config"}},@@ -1030,33 +1222,85 @@"codex": "Codex","opencode": "OpenCode"},- "sourceActions": {- "more": "More actions",- "rename": "Rename",- "refresh": "Refresh models",- "refreshing": "Refreshing models",- "reauth": "Sign in again",- "replaceKey": "Replace API key",- "delete": "Delete source",- "renameTitle": "Rename source",- "renameLabel": "Display name",- "renamePlaceholder": "e.g. Production key",- "renamed": "Renamed",- "renameFailed": "Couldn't rename, please retry",- "refreshed": "Updated {{count}} model(s)",- "refreshFailed": "Couldn't fetch the latest models. The last successful list is still shown.",- "deleteTitle": "Delete source?",- "deleteBody": "This removes “{{name}}” from the Hub and revokes its credential. This can't be undone.",- "deleteConfirm": "Delete",- "deleteForceTitle": "Delete this source anyway?",- "deleteForceBody": "“{{name}}” is the only supplier of a selected model; deleting it leaves that agent with no source. Force delete?",- "deleteForceConfirm": "Force delete",- "deleted": "Source deleted",- "deleteFailed": "Couldn't delete, please retry",- "renameHint": "Changes the display name only — the credential is untouched",- "deleteHint": "You'll be asked to confirm first",- "reauthHint": "The old sign-in stops working right away",- "replaceKeyHint": "Enter a new key — the endpoint and name stay"+ "sourceDetail": {+ "back": "Back to sources",+ "status": {+ "inUse": "In use",+ "needsAction": {+ "oauthExpired": "Sign in again",+ "balanceExhausted": "Out of balance",+ "credentialRevoked": "Credential revoked",+ "accountBanned": "Account restricted"+ },+ "error": "Error",+ "listUpdated": "· model list updated {{time}}"+ },+ "summary_one": "{{host}} · {{count}} model",+ "summary_other": "{{host}} · {{count}} models",+ "action": {+ "refetch": "Refetch",+ "addModel": "Add model"+ },+ "refetch": {+ "added": "New",+ "removed_one": "This fetch removed {{count}} model: {{models}}",+ "removed_other": "This fetch removed {{count}} models: {{models}}",+ "unchangedOnly": "Nothing changed in this fetch"+ },+ "row": { "remove": "Remove" },+ "fail": {+ "refetch": "The fetch did not come back. The list below is the last one this page actually read",+ "tier": "The tier was not saved",+ "addModel": "The model was not added",+ "removeModel": "The model was not removed"+ },+ "retry": "Try again",+ "search": "Search model IDs",+ "col": {+ "id": "Model ID",+ "entry": "Entry",+ "tiers": "Reasoning tiers"+ },+ "entry": { "auto": "Auto-fetched", "manual": "Added manually" },+ "tiers": {+ "empty": "No tiers set",+ "addFirst": "+ Add tier",+ "add": "+ Tier",+ "inputHint": "Enter to add · any text",+ "remove": "Remove {{tier}}"+ },+ "addRow": { "hint": "Use this when a model is not discoverable, or when you only want one of them" },+ "empty": "This source returned no models. Add one by hand, or refetch.",+ "emptyNeverFetched": "This source's model list has never come back. Deal with the status above, fetch again, or add a model by hand.",+ "footnote": "This page answers only \"which models does this source have\". Which routing chain a model takes is set in the gateway module. Tiers are yours to type, the same for both entry kinds. The interface type is identified when the source is added and fixed there — it is neither shown on this page nor editable."+ },+ "guard": {+ "label": "Hops that will be removed",+ "count_one": "{{count}} hop",+ "count_other": "{{count}} hops",+ "hop": { "position": "Order #{{n}}" },+ "hint": {+ "safe": "These models still have another source available.",+ "interrupt": "Some models will be left with no usable source."+ },+ "gap": {+ "label": "Models that will be left with no source",+ "subject": "{{backend}} · {{menuModel}}",+ "agents": "Agents pinned to it: {{agents}}"+ },+ "cancel": "Cancel",+ "title": {+ "refetch": "Refetch models from {{source}}",+ "removeModel": "Remove {{model}} from {{source}}"+ },+ "subtitle": {+ "refetch": "This refetch drops models from this source's inventory.",+ "removeModel": "This model disappears from this source's inventory."+ },+ "confirm": {+ "refetch": "Refetch anyway",+ "removeModel": "Remove anyway"+ }},"repair": {"reauth": "Sign in",@@ -1084,19 +1328,11 @@"unresolved": "Still not working","failed": "Couldn't do that, please retry"},- "dryRun": {- "action": "Run a test turn",- "running": "Testing…",- "ok": "{{name}} is reachable · {{ms}} ms",- "okNoLatency": "{{name}} is reachable",- "failed": "{{name}} didn't go through · {{detail}}",- "failedUnknown": "{{name}} didn't go through",- "error": "Couldn't run the test, please retry"- },"migrationBanner": {"title": "Native configs ready to import",- "body": "Found {{count}} native sign-in(s) / API key(s) you can move into the Hub — each agent then picks its own sources and their order.",- "import": "Import to Hub",+ "body_one": "Found {{count}} native sign-in or API key you can move into the gateway.",+ "body_other": "Found {{count}} native sign-ins or API keys you can move into the gateway.",+ "import": "Import to gateway","dismiss": "Dismiss"}}@@ -1225,8 +1461,6 @@},"source": {"cooldown": {- "network": "Network unreachable",- "timeout": "Repeated timeouts","rate_limited": "Rate limited","quota_exhausted": "Cycle quota used up","server_error": "Upstream server error"diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 2dc8edc6f..4c1579253 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -629,26 +629,246 @@"subtitle": "按 Agent 查看每个型号现在能否运行、由谁供给;需要时可为单个型号指定路由。","addSource": "添加来源","loadError": "加载失败:{{detail}}",+ "tabs": {+ "sources": "来源与网关",+ "usage": "用量与额度"+ },+ "sourceKind": {+ "api_key": "API Key",+ "subscription": "订阅"+ },+ "shell": {+ "title": "模型",+ "running": "网关运行中",+ "stopped": "网关已停止 · 点击启动",+ "degraded": "网关降级运行",+ "unread": "网关状态未读到",+ "notStarted": "网关未启动 · 点击启动",+ "notInstalled": "网关组件未安装 · 点击安装",+ "allDirect_one": "{{count}} 个后端都在直连",+ "allDirect_other": "{{count}} 个后端都在直连",+ "starting": "正在启动…",+ "unsupported": "这个平台还没有网关组件",+ "gatewayInfo": {+ "label": "什么是网关",+ "body": "网关是本机的一层调度:它持有你添加的来源,按你配置的顺序供给各个 Agent。"+ },+ "tab": {+ "hub": "来源与网关",+ "usage": "用量与额度"+ }+ },+ "direct": {+ "card": {+ "current": "当前:直连",+ "current.sub": "每个 Agent 后端各自用自己的登录,直接连厂商。"+ },+ "pill": {+ "direct": "直连"+ },+ "backend": {+ "claude": { "detail": "走它自己的 Claude 登录" },+ "codex": { "detail": "走它自己的 ChatGPT 登录" },+ "opencode": { "detail": "用它自己的模型配置" }+ },+ "action": {+ "switchToGateway": "切换到网关"+ },+ "benefits": {+ "title": "切换到网关,你会多出三件事",+ "1": "额度用尽不断线",+ "1.detail": "Claude 订阅用满时,自动换到你添加的下一个来源,对话继续。",+ "2": "一个 Key 供给多个后端",+ "2.detail": "同一个 API Key 可以同时给 Claude Code、Codex、OpenCode 用。",+ "3": "按后端、按型号自己定",+ "3.detail": "哪个后端的哪个型号走哪个来源,都可以逐条指定。"+ },+ "note": {+ "perBackend": "逐个后端切换,互不影响——其余后端保持直连。切换后随时可以切换回直连。"+ },+ "empty": {+ "title": "这台机器上没有找到 Agent 后端",+ "body": "装好 Claude Code、Codex 或 OpenCode 之后,回到这一页,它们会出现在这里。",+ "install": "安装一个后端 CLI,然后重新加载这一页。"+ }+ },+ "adopt": {+ "title": "把 {{backend}} 切换到网关",+ "subtitle": "只影响 {{backend}},其余后端保持原样。",+ "vendor": {+ "claude": "Claude",+ "chatgpt": "ChatGPT"+ },+ "section": {+ "effects": "会发生什么",+ "undo": "可以撤回"+ },+ "effects": {+ "1": "你现在的 {{vendor}} 登录成为第一个来源,继续优先使用",+ "2": "等你添加了别的来源,这个登录用满时会自动换过去",+ "1.opencode": "OpenCode 自己的模型配置原样保留,这次切换不改动它",+ "2.opencode": "它的型号从此由这一页上的来源供给;还没有来源时,先添加一个",+ "3": "型号菜单不变",+ "4": "正在进行的对话不受影响,下一次请求开始生效",+ "install": "先安装网关组件({{component}},约 {{duration}}),再切换"+ },+ "undo": {+ "1": "随时可以切换回直连",+ "2": "回退入口:这一页的 {{backend}} 卡片 → 切换到直连",+ "3": "切回后,你添加的来源会留着,只是不再供给 {{backend}}"+ },+ "cancel": "取消",+ "confirm": "切换到网关",+ "confirm.install": "安装并切换",+ "fail": {+ "title": "没能切换到网关",+ "detail": "{{request}} · {{status}} · {{reason}}",+ "reason": {+ "transport": "没能连上网关",+ "refused": "网关没有接受这次切换",+ "notReady": "网关起来了,但没有就绪",+ "unknown": "没有给出原因"+ }+ }+ },+ "install": {+ "duration": "1 分钟",+ "title": "安装网关组件",+ "subtitle": "只安装组件,后端保持现在的方式",+ "section": {+ "effects": "会发生什么"+ },+ "effects": {+ "1": "下载并安装 {{component}},约 {{duration}}",+ "2": "装好后网关自动启动",+ "3": "没有后端会被切换,型号菜单不变"+ },+ "confirm": "安装并启动",+ "cancel": "取消",+ "progress": "正在安装…",+ "fail": {+ "title": "安装没有完成",+ "detail": "这次安装没有完成,组件可能处于未完成状态。重试会重新装一遍。"+ },+ "retry": "重试"+ },+ "gateway": {+ "heading": "网关",+ "sourceOrder": "来源顺序",+ "switchToGateway": "切换到网关",+ "switchToDirect": "切换到直连",+ "fail": {+ "switchToDirect": "没能切回直连"+ },+ "modelCount_one": "{{count}} 个型号",+ "modelCount_other": "{{count}} 个型号",+ "moreModels_one": "还有 {{count}} 个型号",+ "moreModels_other": "还有 {{count}} 个型号",+ "collapse_one": "还有 {{count}} 个型号",+ "collapse_other": "还有 {{count}} 个型号",+ "retry": "重试",+ "supply": {+ "none": "没有可用来源",+ "unread": "后端供给情况没读到 · 网关本身正常"+ },+ "row": {+ "current": "当前 {{source}}",+ "currentTakeover": "当前 {{source}}(接管)"+ },+ "group": {+ "subtitle": {+ "direct": "{{mode}}",+ "gateway": "{{mode}} · {{health}}"+ },+ "mode": {+ "direct": "直连",+ "gateway": "网关"+ },+ "status": {+ "ok": "正常",+ "degraded": "降级",+ "waiting": "暂时全部在冷却",+ "interrupted": "无可用来源",+ "noSelection": "未选型号"+ },+ "emptyModels": "这个后端没有可用型号"+ }+ },+ "takeover": {+ "pill_one": "{{count}} 处接管中",+ "pill_other": "{{count}} 处接管中",+ "chip": "接管中"+ },+ "legend": {+ "native": "原生",+ "viaGateway": "网关供给",+ "connectedUnused": "已启用 · 当前未被使用",+ "takeover": "接管中 · 临时改走",+ "unavailable": "供给已暂停",+ "note": "路由链就是各后端配置的来源顺序。"+ },+ "usageTab": {+ "title": "用量与额度",+ "detail": "网关来源完成请求后,用量会显示在这里。"+ },"status": {"allHealthy": "全部正常",- "needsAction": "{{count}} 个模型需要处理",+ "needsAction_one": "{{count}} 个模型需要处理",+ "needsAction_other": "{{count}} 个模型需要处理","noIssues": "没有需要处理的模型"},"statusPill": {- "ok": "一切正常 · {{count}} 个 Agent 已接入中枢",- "none": "还没有 Agent 接入中枢",+ "ok_one": "一切正常 · {{count}} 个 Agent 已接入网关",+ "ok_other": "一切正常 · {{count}} 个 Agent 已接入网关",+ "none": "还没有 Agent 使用网关","engineDown": "模型服务未就绪 · 暂时无法供给",- "interrupted": "{{count}} 个 Agent 供给中断 · 需要处理",- "waiting": "{{count}} 个 Agent 正在等待来源恢复",+ "interrupted_one": "{{count}} 个 Agent 供给中断 · 需要处理",+ "interrupted_other": "{{count}} 个 Agent 供给中断 · 需要处理",+ "waiting_one": "{{count}} 个 Agent 正在等待来源恢复",+ "waiting_other": "{{count}} 个 Agent 正在等待来源恢复","needsAction": "{{source}} {{detail}}","cooldown": "{{source}} {{detail}} · 已自动切换,恢复后切回",- "andMore": "另有 {{count}} 个来源"+ "andMore_one": "另有 {{count}} 个来源",+ "andMore_other": "另有 {{count}} 个来源"+ },+ "upstream": {+ "heading": "来源",+ "count_one": "{{count}} 个",+ "count_other": "{{count}} 个",+ "group": {+ "native": "本机原生",+ "hub": "网关持有"+ },+ "kind": {+ "nativeCredential": "原生 · 本机凭据",+ "subscription": "订阅",+ "apiKey": "API Key"+ },+ "empty": "还没有来源。先添加一个订阅或 API Key。",+ "unread": "来源列表没读到 · 网关本身正常",+ "retry": "重试",+ "addSubscription": "添加订阅",+ "addApiKey": "添加 API Key",+ "state": {+ "supplyingNative": "正在供给 {{backend}}(原生)",+ "supplying": "正在供给 {{backends}}",+ "standby": "备用",+ "unavailableRetry": "暂不可用 · {{delay}} 后自动重试",+ "unavailableDue": "暂不可用 · 已到重试时间"+ }},"sources": {"title": "来源",+ "info": "可用于网关路由的账号与凭据",+ "count_one": "{{count}} 个",+ "count_other": "{{count}} 个",+ "group": {+ "native": "本机原生",+ "hub": "网关持有"+ },"subtitle": "管理全局共用的账号和型号清单;来源顺序在各 Agent 卡片中调整",- "empty": "还没有来源,点“添加来源”连接订阅或 API Key。",- "modelCount": "{{count}} 个型号",+ "modelCount_one": "{{count}} 个型号",+ "modelCount_other": "{{count}} 个型号","lastDiscovery": "上次自动获取 {{time}}","neverDiscovered": "尚未自动获取","addModel": "添加型号",@@ -657,7 +877,7 @@},"source": {"nativeSupply": "原生供给",- "hubHosted": "中枢托管",+ "hubHosted": "网关托管","officialEndpoint": "官方地址","customEndpoint": "自定义地址","retryIn": "{{minutes}} 分后重试",@@ -665,20 +885,36 @@"oauthSignedOut": "CLI 订阅未登录"},"order": {- "title": "来源顺序 · {{backend}}",- "subtitle": "从上到下依次使用;失败自动切到下一个,恢复后自动切回。这里的顺序只影响 {{backend}}。",- "subtitleShort": "从上到下依次使用;失败自动切到下一个,恢复后自动切回。只影响 {{backend}}。",- "groupEnabled": "启用 · {{count}} 个来源",- "groupDisabled": "未启用 · {{count}}",- "groupIneligible": "不适用 · {{count}}",- "customized": "已改为手动",- "restore": "恢复默认",- "enable": "启用",- "enableAria": "启用 {{name}}",- "disable": "取消启用",- "enabledEmpty": "{{backend}} 没有启用任何来源,下一个回合会失败。请从下方启用一个来源。",- "ineligibleUnknown": "不能供 {{backend}} 使用",- "ineligibleClientUnknown": "{{vendor}} 订阅只能供它自己的官方客户端使用"+ "title": "{{backend}} · 来源顺序",+ "subtitle": "这个后端存下来的来源顺序。改动它不会改动任何已配置的路由链。",+ "reorder": "调整来源顺序",+ "section": {+ "ordered": "排在这条顺序里",+ "ordered.note": "拖动排序",+ "heldOut": "未排入这条顺序"+ },+ "action": {+ "include": "排进来",+ "exclude": "移出"+ },+ "empty": {+ "noEligible": "这个后端还没有可用来源。",+ "ordered": "这条顺序现在是空的。把下面的来源排进来。"+ },+ "cancel": "取消",+ "save": "保存顺序",+ "fail": {+ "read": "来源列表没读到",+ "save": "顺序没保存上"+ },+ "retry": "重试",+ "grabbed_one": "已抓取 {{source}},当前位置 {{position}} / {{count}}。",+ "grabbed_other": "已抓取 {{source}},当前位置 {{position}} / {{count}}。",+ "moved_one": "已将 {{source}} 移到第 {{position}} 位,共 {{count}} 位。",+ "moved_other": "已将 {{source}} 移到第 {{position}} 位,共 {{count}} 位。",+ "dropped_one": "已将 {{source}} 放在第 {{position}} 位,共 {{count}} 位。",+ "dropped_other": "已将 {{source}} 放在第 {{position}} 位,共 {{count}} 位。",+ "grabCancelled": "已取消移动 {{source}},并恢复原来的位置。"},"billing": {"monthly": "订阅",@@ -710,22 +946,19 @@"startNow": "立即启动","starting": "正在启动"},- "install": {- "fail": {- "detail": "这次安装没有完成,组件可能处于未完成状态。重试会重新装一遍。"- }- },"experimental": "实验","agents": {"title": "Agent","subtitle": "各自选用来源、各自排序;失败自动切到下一个","backendSettings": "后端设置",- "connectHub": "接入中枢",- "modelCount": "{{count}} 个模型",- "hubNoSupply": "已接入中枢 · 没有启用任何来源,下一个回合会失败",- "directNote": "仍在用 CLI 原生配置供给,未接入中枢",+ "connectHub": "切换到网关",+ "modelCount_one": "{{count}} 个模型",+ "modelCount_other": "{{count}} 个模型",+ "hubNoSupply": "已使用网关 · 没有启用任何来源,下一个回合会失败",+ "directNote": "使用 CLI 原生配置供给","sourceOrder": "来源顺序",- "modelListCount": "{{count}} 个型号",+ "modelListCount_one": "{{count}} 个型号",+ "modelListCount_other": "{{count}} 个型号","enableManaged": "统一管理","emptyModels": "这个 Agent 还没有型号。","manageModels": "管理型号",@@ -733,10 +966,6 @@"fixed": "内置型号","open": "菜单开放"},- "policy": {- "follow": "默认顺序",- "custom": "自定义"- },"attribution": {"interrupted": "{{names}} 供给中断","waiting": "{{names}} 正在等待来源恢复",@@ -753,41 +982,22 @@"blocked": "当前来源不可用","currentSwitched": "当前已自动换到 {{source}}","currentSource": "当前由 {{source}} 供给",+ "takeover": "当前 {{source}}(接管)",+ "waiting": "正在等待来源恢复","source": "由 {{source}} 供给","unknown": "暂时无法确认","retry": "重试","runtime": "模型服务未就绪","runtimeAction": "去处理"},- "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": "测试失败,请重试"+ "routeDialog": {+ "title": "{{model}} · 路由链",+ "open": "打开 {{model}} 的路由链",+ "label": "这个型号的路由链",+ "removeHop": "移除这一跳",+ "addHop": "添加一跳",+ "reseed": "按来源顺序重排",+ "hint": "这条链是写下来的配置。以后来源顺序怎么变,它都不变。"},"recent": {"title": "最近切换",@@ -805,54 +1015,108 @@"detail": "跨厂商自动顶替(默认关)· 请求日志 · 诊断","comingSoon": "高级设置即将上线"},- "addMenu": {- "claude": {- "title": "连接 Claude 订阅",- "subtitle": "Pro / Max · 浏览器登录"+ "addKey": {+ "title": "添加 API Key",+ "subtitle": "「添加」时自动连一次:认出接口 + 拉取型号列表",+ "field": {+ "name": "名称(可选)",+ "baseUrl": "Base URL",+ "baseUrl.hint": "粘贴任何中转 / 聚合 / 自建服务的地址即可,Avibe 会自己认出接口",+ "apiKey": "API Key",+ "apiKey.reveal": "显示 API Key",+ "apiKey.conceal": "隐藏 API Key"},- "chatgpt": {- "title": "连接 ChatGPT 订阅",- "subtitle": "Plus / Pro · 浏览器登录"+ "test": "拉取型号",+ "test.hint": "可选 ·「添加」时会自动拉一次",+ "pull": {+ "result_one": "拉到 {{count}} 个型号",+ "result_other": "拉到 {{count}} 个型号",+ "empty": "连上了,但这个来源没有可用型号"},- "apiKey": {- "title": "添加 API Key…",- "subtitle": "任何厂商或兼容服务,可改地址"+ "submit": "添加",+ "adding": "连接中…",+ "adding.detail": "连上 + 认出接口 + 首次拉取型号列表 · 通常 1–3 秒",+ "fail": {+ "subtitle": "认出接口是「添加」的前置条件 · 先按下面这条修,再重试",+ "auth": "鉴权失败:401 Unauthorized",+ "auth.detail": "检查 API Key 是否有效",+ "address": "地址不对:404 Not Found",+ "network": "无法连接到该地址(不可达或超时)",+ "unclassified": "没连成,原因认不出来",+ "engineDown": "网关没有响应,请重试",+ "save": "没能确认这个来源已经保存"},- "sheetTitle": "添加来源",- "sheetSubtitle": "来源只有两类:订阅账号,或一把 Key。中转站 = 改了地址的 Key。",- "vendorTitle": "连接订阅账号",- "vendorSubtitle": "走 CLI 原生登录,凭证留在本机。",- "apiKeySheetSubtitle": "官方或第三方地址都行;填了自定义地址就是「中转站」。",- "subscription": {- "title": "订阅账号",- "subtitle": "Claude Pro / ChatGPT Plus 等。走 CLI 原生登录,凭证留在本机 CLI 里。",- "recommended": "推荐"- }- },- "addKey": {- "title": "添加 API Key",- "subtitle": "任何厂商或兼容服务;连接一次,所有 Agent 共用。",- "vendorLabel": "服务商",- "vendorHint": "选择 Anthropic / OpenAI / 智谱 / Kimi 等厂商时,自动填官方地址。",- "keyLabel": "API KEY",- "baseUrlLabel": "服务地址(BASE URL)",- "baseUrlHint": "官方厂商已预填,可改;使用兼容服务(如中转、自建网关)时填它提供的地址。",- "discovered": "连接成功 · 发现 {{count}} 个可用模型,已加入供应清单",- "failed": "连接失败:{{detail}}",- "testing": "连接中…",- "vendors": {- "custom": "自定义 · OpenAI / Anthropic 兼容",- "anthropic": "Anthropic",- "openai": "OpenAI",- "zhipuai": "智谱",- "kimi": "Kimi",- "xai": "xAI"- }+ "retry": "重试",+ "undetermined": {+ "title": "连上了、也通过了鉴权 —— 但认不出它说哪种接口",+ "detail": "返回结构对不上任何一种已知接口",+ "label": "接口类型 · 这一次由你提示",+ "hint": "提示只改探测顺序 · 仍要真的连上才会保存;保存后不可更改"+ },+ "protocol": {+ "anthropicMessages": "Anthropic Messages",+ "openaiResponses": "OpenAI Responses",+ "openaiChatCompletions": "OpenAI Chat Completions"+ },+ "inventory": {+ "title": "接口已经认出来了 —— 但这次没拿到它的型号清单"+ },+ "addAnyway": "仍要添加",+ "success": {+ "title": "成功 → 弹窗关闭,直接进入「来源详情 · 型号管理」",+ "detail": "型号列表、重新拉取、推理强度档位都在那里维护"+ },+ "cancel": "取消"},"field": {"apiKeyPlaceholder": "sk-…","baseUrlPlaceholder": "https://api.example.com/v1"},+ "addSub": {+ "title": "添加 {{vendor}} 订阅",+ "subtitle": {+ "claude": "claude.ai / Max · Pro",+ "chatgpt": "chatgpt.com / Plus · Pro"+ },+ "opt": {+ "added": "已添加",+ "native": {+ "label": "原生使用",+ "desc": {+ "claude": "Claude Code 直接用这个订阅,凭据只留在本机。",+ "chatgpt": "Codex 直接用这个 ChatGPT 账号登录。"+ }+ },+ "hub": {+ "label": "登录为网关来源",+ "desc": {+ "claude": "把这个订阅交给网关,供给 Codex、OpenCode 等其他 Agent。",+ "chatgpt": "网关把它供给 Codex 和其他 Agent,用量、额度、接管都能看到。"+ }+ }+ },+ "badge": {+ "recommended": "推荐",+ "secondary": "次选",+ "supportedNotRecommended": "支持,不推荐"+ },+ "tos": {+ "claude": "订阅条款只授权你本人在 Claude 官方客户端里使用。转供其他 Agent 属于超范围使用,账号可能被限制。"+ },+ "hint": {+ "claude": "两条都要也可以,分两次添加。",+ "chatgpt": "额度用完不会自动接管,也看不到用量。"+ },+ "signIn": "去登录",+ "cancel": "取消",+ "retry": "重试",+ "error": {+ "oauthFailed": "登录没有完成。可以重试。",+ "startFailed": "没能确认登录已经开始,可以重试",+ "engineDown": "网关没有响应,请重试",+ "alreadyBound": "这个后端的原生登录位已经被占用了。改用网关托管添加。"+ }+ },"oauth": {"title": {"anthropic": "连接 Claude 订阅",@@ -886,100 +1150,26 @@"timeout": "授权超时,请重新连接","generic": "连接失败,请重试","finalize": "已完成授权,但创建来源失败,请重试",- "finalizeReauth": "已重新登录,但这个来源还是不可用,请重试",- "consent": "连接中枢托管订阅需先同意实验条款;请重新发起连接并在弹窗中开启「中枢托管」选项。"- },- "hubOption": {- "title": "由中枢托管此订阅(实验)",- "subtitle": "凭据由中枢保存并转发,可能违反厂商条款",- "on": "已开启",- "off": "关"+ "finalizeReauth": "已重新登录,但这个来源还是不可用,请重试"}},- "consent": {- "title": "由中枢托管订阅 · 风险提示",- "subtitle": "启用前请确认你已了解以下风险。",- "points": [- "该来源使用你本人订阅的登录凭据;厂商条款通常要求订阅仅供个人在官方客户端内使用,经由中枢代理转发属于非官方用法,可能违反其服务条款。",- "存在账号被风控、限流或封禁的真实风险(已有 Claude 订阅经代理使用被自动封号的先例);是否启用由你自行决定并承担后果。",- "追求最稳妥时,请对订阅使用直连模式(官方客户端直接连接),或改用 API Key 来源(厂商明确允许程序化 / 代理调用)。"- ],- "confirm": "我已了解风险,继续"- },"toast": {"reorderFailed": "顺序保存失败",- "connected": "已接入中枢",+ "connected": "已接入网关","connectFailed": "接入失败,请重试","refreshFailed": "刷新失败,请重试"},"supply": {- "degraded": "已接入中枢 · 有来源不可用,已自动切到下一个",- "waiting": "已接入中枢 · 来源都在冷却中,恢复前的回合会失败",- "interrupted": "已接入中枢 · 供给中断,下一个回合会失败",- "noSources": "已接入中枢 · 还没有启用任何来源,下一个回合会失败",- "nothingRunnable": "已接入中枢 · 已启用的来源当前都无法供给,下一个回合会失败"+ "degraded": "已接入网关 · 有来源不可用,已自动切到下一个",+ "waiting": "已接入网关 · 来源都在冷却中,恢复前的回合会失败",+ "interrupted": "已接入网关 · 供给中断,下一个回合会失败",+ "noSources": "已接入网关 · 还没有启用任何来源,下一个回合会失败",+ "nothingRunnable": "已接入网关 · 已启用的来源当前都无法供给,下一个回合会失败"},"adoption": {- "enabled": "已自动加入 {{list}} 的来源顺序",- "entry": "{{name}}(第 {{position}} 位)",- "none": "还没有 Agent 启用它 · 到各 Agent 的「来源顺序」里加进来才会被使用",- "noneSkipped": "还没有 Agent 启用它 · {{skipped}} 已改为手动,未加入——到那里手动加进来才会被使用",- "partlySkipped": "已自动加入 {{list}} 的来源顺序 · {{skipped}} 已改为手动,未加入——到那里手动加进来才会被使用"- },- "menus": {- "done": "完成",- "resetAll": "恢复全部默认",- "saveFailed": "保存失败,请重试",- "enrolled": "已自动把「{{sources}}」加入 {{backend}} 的来源顺序,你选的模型才有来源可用",- "mapping": {- "title": "{{backend}} · 模型菜单",- "subtitle": "{{backend}} 只认这些内置 model ID;每个 ID 可指定其他型号供给,只影响 {{backend}}。",- "builtinCol": "内置 MODEL ID",- "supplyCol": "实际供给",- "followNative": "跟随原生 · 按来源顺序供给",- "candidates": "来源顺序 · {{sources}}",- "candidatesUnavailable": "暂无来源可供给此模型",- "warning": "改写后思维链、缓存与工具语义与原生不完全等价",- "resetRow": "恢复默认",- "footnote": "改写只影响 {{backend}} 的这个 ID;协议转换由中枢自动完成。"- },- "opencode": {- "title": "OpenCode · 模型菜单",- "subtitle": "菜单开放:按 provider 前缀分组,前缀 + 模型 ID = 完整标识,与 OpenCode 原生写法一致。勾选 = 出现在模型选择里。",- "viewLabel": "菜单范围",- "featured": "精选 · {{count}}",- "full": "全量 · {{count}}",- "addCustom": "自定义模型",- "empty": "这里还没有模型。",- "footnote": "前缀 = 厂商标准 ID(与 OpenCode 原生一致,识别不了归 custom/);中枢 / 直连切换不改变标识;圆点 = 可供来源。",- "customBadge": "自定义",- "provider": {- "anthropic": "Anthropic 协议 · Claude 系",- "openai": "OpenAI 协议 · GPT 系",- "zhipuai": "OpenAI 兼容 · GLM 系",- "custom": "自定义端点"- }- },- "custom": {- "title": "手动添加型号",- "subtitle": "补登这个来源清单里没有的型号,可用于型号选择和指定路由。",- "sourceLabel": "来源(它能供应这个模型)",- "modelIdLabel": "模型 ID",- "modelIdPlaceholder": "glm-5.2-air",- "displayNameLabel": "显示名(可选)",- "displayNamePlaceholder": "GLM 5.2 Air",- "previewLabel": "OPENCODE 标识 · 自动生成",- "previewEmpty": "填入模型 ID 后预览",- "previewHint": "provider 段自动选:可识别厂商用标准 ID(与 OpenCode 原生一致),识别不了归 custom/;来源增减、模式切换都不影响标识。",- "add": "添加型号",- "failed": "添加失败,请重试",- "delete": "删除模型",- "deleteConfirmTitle": "移除自定义模型?",- "deleteConfirmBody": "将从「{{source}}」的清单移除 {{model}}。",- "deleted": "已移除自定义模型",- "deleteFailed": "移除失败,请重试",- "deleteInUse": "该模型仍被某个 Agent 选用,请先在其菜单或指定路由里取消后再删除。"- }+ "enabled": "已加入 {{list}}",+ "route": "{{backend}} · {{model}} · 第 {{position}} 跳",+ "none": "已连接。需要使用时,把它加到对应型号的路由中。"},"supplyMode": {"title": "供给方式",@@ -989,39 +1179,41 @@"switchedDirect": "已切换到直连 Direct","switchFailed": "切换失败,请重试","hub": {- "title": "中枢模式 · Hub",+ "title": "网关模式 · Gateway","recommended": "推荐 · 默认","openModels": "打开模型页",- "description": "模型 token 由「设置 → 模型」统一供给:登录、API Key、来源顺序、指定路由都在那里管理。不改动 {{backend}} 的原生配置,随时可切走。"+ "description": "登录、API Key 和逐型号路由都在「设置 → 模型」中管理。不改动 {{backend}} 的原生配置,随时可切走。"},"direct": {"title": "直连模式 · Direct","description": "{{backend}} 使用自己的原生配置(settings.json / CLI 登录),Avibe 仅负责启动进程、不代管模型。适合排查问题,或想完全自管配置的用户。",- "detected": "检测到既有直连配置:{{detail}} —— 可一键搬进中枢",- "import": "导入中枢…"+ "detected": "检测到既有直连配置:{{detail}} —— 可一键导入网关",+ "import": "导入网关…"},"fixHint": "去「模型」页添加或启用来源即可恢复。"},"migration": {- "title": "接入模型中枢",- "subtitle": "把现有的登录和 API Key 一次搬进「模型」中枢;导入后每个 Agent 各自选用来源、各自排序。",+ "title": "接入模型网关",+ "subtitle": "把现有的登录和 API Key 一次导入网关;导入后每个 Agent 各自选用来源、各自排序。","empty": "没有检测到可迁移的原生配置。","scanFailed": "扫描原生配置失败,请重试","applyFailed": "导入失败,请重试",- "applied": "已导入 {{count}} 项",+ "applied_one": "已导入 {{count}} 项",+ "applied_other": "已导入 {{count}} 项","later": "稍后再说",- "apply": "导入 {{count}} 项并启用中枢",+ "apply_one": "导入 {{count}} 项并启用网关",+ "apply_other": "导入 {{count}} 项并启用网关","nonDestructive": "非破坏迁移:原生配置不改动、不删除,导入只是复制;随时可在「后端」页切回直连。","action": {"import": "导入为来源",- "controlledImport": "受控导入 · 实验",+ "controlledImport": "受控导入 · 预留","keepNative": "保留原生","reauth": "需重新授权 · 浏览器一键"},"notes": {"customBaseUrl": "含自定义 Base URL","keepNativeSanctioned": "保留在 CLI 自己的凭据库(受官方认可)",- "keepNativeReauthHint": "保持原生;可在中枢内重新授权以托管(实验)",+ "keepNativeReauthHint": "保持原生;需要网关托管时另行添加订阅","fromOpencode": "来自 opencode 配置"}},@@ -1030,33 +1222,85 @@"codex": "Codex","opencode": "OpenCode"},- "sourceActions": {- "more": "更多操作",- "rename": "重命名",- "refresh": "刷新模型",- "refreshing": "正在刷新模型",- "reauth": "重新登录",- "replaceKey": "更换 API Key",- "delete": "删除来源",- "renameTitle": "重命名来源",- "renameLabel": "显示名",- "renamePlaceholder": "例如 生产环境 Key",- "renamed": "已重命名",- "renameFailed": "重命名失败,请重试",- "refreshed": "已更新 {{count}} 个模型",- "refreshFailed": "未能获取最新模型,仍显示上次成功获取的清单。",- "deleteTitle": "删除来源?",- "deleteBody": "将从中枢移除「{{name}}」并撤销其凭证,此操作不可撤销。",- "deleteConfirm": "删除",- "deleteForceTitle": "仍要删除该来源?",- "deleteForceBody": "「{{name}}」是某个已选模型的唯一供给,删除后相关 Agent 将无来源可用。确认强制删除?",- "deleteForceConfirm": "强制删除",- "deleted": "已删除来源",- "deleteFailed": "删除失败,请重试",- "renameHint": "只改显示名,不动凭证",- "deleteHint": "删除前会再确认一次",- "reauthHint": "旧登录立即失效",- "replaceKeyHint": "填入新 Key,地址与显示名不变"+ "sourceDetail": {+ "back": "返回来源列表",+ "status": {+ "inUse": "使用中",+ "needsAction": {+ "oauthExpired": "需要重新登录",+ "balanceExhausted": "余额用完",+ "credentialRevoked": "凭据被吊销",+ "accountBanned": "账号被限制"+ },+ "error": "异常",+ "listUpdated": "· 型号列表更新于 {{time}}"+ },+ "summary_one": "{{host}} · {{count}} 个型号",+ "summary_other": "{{host}} · {{count}} 个型号",+ "action": {+ "refetch": "重新拉取",+ "addModel": "添加模型"+ },+ "refetch": {+ "added": "新增",+ "removed_one": "本次拉取移除了 {{count}} 个型号:{{models}}",+ "removed_other": "本次拉取移除了 {{count}} 个型号:{{models}}",+ "unchangedOnly": "本次拉取没有变化"+ },+ "row": { "remove": "移除" },+ "fail": {+ "refetch": "拉取没有回来,下面是这一页最后一次真的读到的列表",+ "tier": "档位没保存上",+ "addModel": "这个型号没添加上",+ "removeModel": "这个型号没移除掉"+ },+ "retry": "重试",+ "search": "搜索型号 ID",+ "col": {+ "id": "型号 ID",+ "entry": "录入",+ "tiers": "推理强度"+ },+ "entry": { "auto": "自动拉取", "manual": "手动添加" },+ "tiers": {+ "empty": "未设置档位",+ "addFirst": "+ 添加档位",+ "add": "+ 档位",+ "inputHint": "回车添加 · 任意文本",+ "remove": "移除 {{tier}}"+ },+ "addRow": { "hint": "拉取不到、或只想接入其中一个时用" },+ "empty": "这个来源没有返回型号。可以手动添加,或重新拉取。",+ "emptyNeverFetched": "还没有成功拉取过这个来源的型号列表。先处理上面的状态,再拉一次,或者手动添加一个型号。",+ "footnote": "这里只管「这个来源有哪些型号」。型号走哪条路由链,在网关模块里改。档位自己填,两种录入方式都一样。接口类型在添加时认出并固定,页面上不显示、也不能改。"+ },+ "guard": {+ "label": "会被移除的跳",+ "count_one": "{{count}} 跳",+ "count_other": "{{count}} 跳",+ "hop": { "position": "顺序 #{{n}}" },+ "hint": {+ "safe": "这些型号还有别的来源可用。",+ "interrupt": "有型号会因此没有可用来源。"+ },+ "gap": {+ "label": "会失去可用来源的型号",+ "subject": "{{backend}} · {{menuModel}}",+ "agents": "已指定它的 Agent:{{agents}}"+ },+ "cancel": "取消",+ "title": {+ "refetch": "重新拉取 {{source}} 的型号",+ "removeModel": "从 {{source}} 移除 {{model}}"+ },+ "subtitle": {+ "refetch": "这次拉取会让部分型号从这个来源的清单里消失。",+ "removeModel": "这个型号会从这个来源的清单里消失。"+ },+ "confirm": {+ "refetch": "仍要拉取",+ "removeModel": "仍要移除"+ }},"repair": {"reauth": "重新登录",@@ -1084,19 +1328,11 @@"unresolved": "仍然不可用","failed": "没能处理,请重试"},- "dryRun": {- "action": "试跑一次",- "running": "试跑中…",- "ok": "{{name}} 可用 · {{ms}} ms",- "okNoLatency": "{{name}} 可用",- "failed": "{{name}} 没跑通 · {{detail}}",- "failedUnknown": "{{name}} 没跑通",- "error": "试跑没能进行,请重试"- },"migrationBanner": {- "title": "发现可导入中枢的原生配置",- "body": "检测到 {{count}} 项原生登录 / API Key 可搬进中枢;导入后每个 Agent 各自选用来源、各自排序。",- "import": "导入中枢",+ "title": "发现可导入网关的原生配置",+ "body_one": "检测到 {{count}} 项原生登录 / API Key 可搬进网关。",+ "body_other": "检测到 {{count}} 项原生登录 / API Key 可搬进网关。",+ "import": "导入网关","dismiss": "忽略"}}@@ -1225,8 +1461,6 @@},"source": {"cooldown": {- "network": "网络不通",- "timeout": "连续超时","rate_limited": "触发限流","quota_exhausted": "本周期额度用完","server_error": "上游服务异常"diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 6807f6303..23369aacd 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -720,11 +720,9 @@"flow_expired": "Authorization flow expired.","discovery_failed": "Could not validate or discover this source.","invalid_source_order": "The source order contains an unavailable, ineligible, or duplicate source.",- "mapping_target_unavailable": "The selected model is unavailable for this backend.","mode_switch_blocked": "This operation is blocked by the current supply mode or selection.",- "engine_down": "The local Model Hub runtime is unavailable.",- "consent_required": "Explicit consent is required for experimental subscription routing.",- "migration_item_conflict": "This migration item conflicts with current Model Hub state.",+ "engine_down": "The local model gateway is unavailable.",+ "migration_item_conflict": "This migration item conflicts with the current model gateway state.","stream_interrupted": "The upstream stream was interrupted.","upstream_protocol_error": "The upstream response did not match the expected protocol.","upstream_request_invalid": "The upstream service rejected the request.",@@ -737,7 +735,6 @@"cooldown": "{from_source}: {reason}; cooling down","recover": "{to_source}: recovered and available","skip": "{from_source}: {reason}; skipped",- "mapping_applied": "{from_source} -> {model}: model mapping applied","channel_switch": "{from_source}: supply channel changed","needs_action": "{from_source}: {reason}; action required","supply_interrupted": "{model}: {reason}; model supply interrupted",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex d27d465a0..eb9ef5b6c 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -720,11 +720,9 @@"flow_expired": "授权流程已过期。","discovery_failed": "无法验证或发现此来源。","invalid_source_order": "来源顺序包含不可用、不适用或重复的来源。",- "mapping_target_unavailable": "所选模型无法用于此后端。","mode_switch_blocked": "当前供给模式或选择阻止了此操作。",- "engine_down": "本地模型中枢运行时不可用。",- "consent_required": "实验性订阅路由需要明确同意。",- "migration_item_conflict": "此迁移项与当前模型中枢状态冲突。",+ "engine_down": "本地模型网关不可用。",+ "migration_item_conflict": "此迁移项与当前模型网关状态冲突。","stream_interrupted": "上游流已中断。","upstream_protocol_error": "上游响应不符合预期协议。","upstream_request_invalid": "上游服务拒绝了请求。",@@ -737,7 +735,6 @@"cooldown": "{from_source}:{reason},暂时冷却","recover": "{to_source}:已恢复可用","skip": "{from_source}:{reason},已跳过",- "mapping_applied": "{from_source} -> {model}:已应用模型映射","channel_switch": "{from_source}:供给通道已切换","needs_action": "{from_source}:{reason},需要处理","supply_interrupted": "{model}:{reason},模型供给已中断",