Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(ui-design): Model Hub baseline frames (sources and routing) (#3137)
Call White50da23056969
diff --git a/ui/design/Canvas.tsx b/ui/design/Canvas.tsxindex 4742c7dd0..981e225c5 100644--- a/ui/design/Canvas.tsx+++ b/ui/design/Canvas.tsx@@ -34,7 +34,11 @@ function Single({ frame, theme }: { frame: Frame; theme: DesignTheme }) {.then(() => designNetwork.quiet()).then(() => (frame.wait ? new Promise((resolve) => setTimeout(resolve, frame.wait)).then(() => designNetwork.quiet()) : undefined)).then(() => {- if (!cancelled) document.body.dataset.designReady = 'true';+ if (cancelled) return;+ // A dialog moves focus into itself as it opens. A person who opened it with the+ // pointer sees no focus ring there, but a document nobody has touched draws one.+ if (document.activeElement instanceof HTMLElement && document.activeElement !== document.body) document.activeElement.blur();+ document.body.dataset.designReady = 'true';});return () => {cancelled = true;diff --git a/ui/design/frames/models/add-provider.design.tsx b/ui/design/frames/models/add-provider.design.tsxnew file mode 100644index 000000000..e9156fa07--- /dev/null+++ b/ui/design/frames/models/add-provider.design.tsx@@ -0,0 +1,119 @@+// Adding a provider from 模型供应商: the shipped API key dialog (添加供应商 → API Key) and the+// subscription dialog (添加订阅 → a vendor), each in the state it opens in.+import { AddApiKeyDialog } from '@/components/settings/models/AddApiKeyDialog';+import { createSourceCollectionReadAuthority } from '@/components/settings/models/collectionReadAuthority';+import { OAuthConnectDialog } from '@/components/settings/models/OAuthConnectDialog';+import type { OAuthFlow, Source } from '@/components/settings/models/types';++import { frames } from '../../frame';+import { at, baseApi, chatgptPro, demoSources, ok } from './fixtures';++const sourceReads = createSourceCollectionReadAuthority();+const addApiKey = () => <AddApiKeyDialog open sourceReads={sourceReads} onClose={() => {}} onAdded={() => {}} />;++const subscription = (vendor: string, reauth: Source | null = null) => () => (+ <OAuthConnectDialog open vendor={vendor} reauth={reauth} sources={demoSources} onClose={() => {}} onConnected={() => {}} />+);++/** The flow `/api/models/oauth/start` answers with, and the status every poll reads back. */+const flowApi = (flow: Partial<OAuthFlow> & Pick<OAuthFlow, 'vendor' | 'channel' | 'presentation'>) => {+ const full: OAuthFlow = { flow_id: 'flow_design', state: 'awaiting_action', expires_at: at(9), intent: 'create', ...flow };+ return {+ ...baseApi,+ '/api/models/oauth/start': ok({ flow: full }),+ '/api/models/oauth/status/flow_design': ok({ flow: full }),+ // A re-login starts from the Source rather than from the vendor.+ ...(flow.source_id ? { [`/api/models/sources/${flow.source_id}/reauth`]: ok({ flow: full }) } : {}),+ };+};++const chatgptExpired: Source = { ...chatgptPro, state: { status: 'needs_action', retry_at: null, detail_key: 'models.source.needs_action.oauth_expired' } };++const designFrames = frames([+ {+ name: 'api-key',+ title: '添加 API Key',+ width: 1000,+ height: 760,+ status: 'shipped',+ fixtures: { api: baseApi },+ render: addApiKey,+ },+ {+ name: 'api-key-phone',+ title: '添加 API Key · 手机',+ width: 390,+ height: 844,+ status: 'shipped',+ fixtures: { api: baseApi },+ render: addApiKey,+ },+ {+ name: 'claude',+ title: '添加订阅 · Claude(选择接入方式)',+ width: 1000,+ height: 720,+ status: 'shipped',+ fixtures: { api: baseApi },+ render: subscription('anthropic'),+ },+ {+ name: 'claude-phone',+ title: '添加订阅 · Claude · 手机',+ width: 390,+ height: 844,+ status: 'shipped',+ fixtures: { api: baseApi },+ render: subscription('anthropic'),+ },+ {+ name: 'chatgpt',+ title: '添加订阅 · ChatGPT(选择接入方式)',+ width: 1000,+ height: 720,+ status: 'shipped',+ fixtures: { api: baseApi },+ render: subscription('openai'),+ },+ {+ name: 'kimi-device',+ title: '添加订阅 · Kimi(设备码登录)',+ width: 1000,+ height: 720,+ status: 'shipped',+ fixtures: {+ api: flowApi({ vendor: 'kimi', channel: 'hub', presentation: { auth_url: 'https://www.kimi.com/device', device_code: 'WXKP-7QJM', expects: 'none', instructions_key: null } }),+ },+ render: subscription('kimi'),+ },+ {+ name: 'reauth-callback',+ title: '重新登录 · ChatGPT Pro(粘贴回调地址)',+ width: 1000,+ height: 720,+ status: 'shipped',+ fixtures: {+ api: flowApi({+ vendor: 'openai',+ channel: 'hub',+ intent: 'reauth',+ source_id: chatgptPro.id,+ presentation: { auth_url: 'https://auth.openai.com/oauth/authorize?client_id=app_design&state=design', device_code: null, expects: 'paste_callback_url', instructions_key: null },+ }),+ },+ render: subscription('openai', chatgptExpired),+ },+ {+ name: 'failed',+ title: '添加订阅 · 登录失败',+ width: 1000,+ height: 720,+ status: 'shipped',+ fixtures: {+ api: flowApi({ vendor: 'kimi', channel: 'hub', state: 'failed', error_key: 'models.oauth.provider_denied', error_detail: 'access_denied: user cancelled the consent screen', presentation: { expects: 'none' } }),+ },+ render: subscription('kimi'),+ },+]);++export default designFrames;diff --git a/ui/design/frames/models/fixtures.ts b/ui/design/frames/models/fixtures.tsnew file mode 100644index 000000000..094ae4793--- /dev/null+++ b/ui/design/frames/models/fixtures.ts@@ -0,0 +1,443 @@+// Fixture builders for the Model Hub (Settings · Models) frames: the `/api/models/*`+// reads the shipped page makes, served through the design network stub.+import type {+ AgentBackend,+ AgentChain,+ AgentChainLink,+ AgentSupply,+ BackendModel,+ ChainHealth,+ HostedToolsStatus,+ MigrationItem,+ ModelSupply,+ RouteOrigin,+ RuntimeDependency,+ RuntimeHealth,+ Source,+ SourceState,+ SuppliedModel,+ UsageBucket,+ UsageBucketEntry,+ UsageBucketRow,+ UsageCounters,+ UsageReport,+ UsageWindowKey,+} from '@/components/settings/models/types';++import { DESIGN_NOW } from '../../shell/clock';++export const at = (minutesFromNow: number) => new Date(DESIGN_NOW + minutesFromNow * 60_000).toISOString();++/** A successful `/api/models/*` envelope. */+export const ok = <T extends object>(body: T) => ({ ok: true, contract_version: 23, ...body });++// ── Sources ─────────────────────────────────────────────────────────────++const models = (ids: string[], efforts: string[] = ['low', 'medium', 'high']): SuppliedModel[] =>+ ids.map((id) => ({ id, origin: 'discovered', reasoning_efforts: efforts, reasoning_efforts_source: 'catalog', discovered_at: at(-180) }));++const ACTIVE: SourceState = { status: 'active', retry_at: null, detail_key: null };+const STANDBY: SourceState = { status: 'standby', retry_at: null, detail_key: null };++export const source = (id: string, extra: Partial<Source> & Pick<Source, 'display_name' | 'vendor' | 'protocol'>): Source => ({+ id,+ created_at: at(-60 * 24 * 20),+ last_discovered_at: at(-180),+ kind: 'api_key',+ supply_channel: 'hub',+ billing: 'metered',+ state: STANDBY,+ base_url: null,+ account_label: null,+ masked_credential: null,+ credential_ref: `cred_${id}`,+ models: [],+ ...extra,+});++export const claudeMax = source('src_claudemax', {+ kind: 'subscription',+ vendor: 'anthropic',+ display_name: 'Claude Max',+ protocol: 'anthropic',+ supply_channel: 'native_cli',+ billing: 'monthly',+ state: ACTIVE,+ account_label: '[email protected]',+ credential_ref: null,+ models: models(['claude-opus-5', 'claude-sonnet-5', 'claude-haiku-5'], ['low', 'medium', 'high', 'max']),+ adopted_by: [{ backend: 'claude', menu_model: 'claude-opus-5' }],+});++export const chatgptPro = source('src_chatgptpro', {+ kind: 'subscription',+ vendor: 'openai',+ display_name: 'ChatGPT Pro',+ protocol: 'openai_responses',+ supply_channel: 'hub',+ billing: 'monthly',+ state: ACTIVE,+ account_label: '[email protected]',+ credential_ref: null,+ models: models(['gpt-6-astra', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.5'], ['minimal', 'low', 'medium', 'high', 'xhigh']),+ adopted_by: [{ backend: 'codex', menu_model: 'gpt-6-astra' }, { backend: 'vibey', menu_model: 'gpt-6-astra' }],+});++export const relayClaude = source('src_relayclaude', {+ vendor: 'custom',+ display_name: 'ai-relay-claude',+ protocol: 'anthropic',+ base_url: 'https://ai-relay.chainbot.io/v1',+ masked_credential: 'sk-9c5…738a',+ models: models(['claude-opus-5', 'claude-sonnet-5', 'claude-haiku-5', 'claude-opus-4-8']),+ adopted_by: [{ backend: 'claude', menu_model: 'claude-sonnet-5' }, { backend: 'opencode', menu_model: 'claude-sonnet-5' }],+});++export const relayGpt = source('src_relaygpt', {+ vendor: 'custom',+ display_name: 'ai-relay-gpt',+ protocol: 'openai_responses',+ base_url: 'https://ai-relay.chainbot.io/v1',+ masked_credential: 'sk-29d…de81',+ models: models(['gpt-6-astra', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4']),+ adopted_by: [{ backend: 'codex', menu_model: 'gpt-5.6-sol' }],+});++export const deepseek = source('src_deepseek', {+ vendor: 'deepseek',+ display_name: 'DeepSeek',+ protocol: 'openai_chat',+ base_url: 'https://api.deepseek.com/v1',+ masked_credential: 'sk-4f1…a09c',+ models: models(['deepseek-v4', 'deepseek-v4-reasoner'], []),+ adopted_by: [{ backend: 'opencode', menu_model: 'deepseek-v4' }],+});++export const tavily = source('src_tavily', {+ vendor: 'tavily',+ display_name: 'Tavily',+ protocol: 'search',+ masked_credential: 'tvly-…3k9Q',+ models: [],+});++export const demoSources: Source[] = [claudeMax, chatgptPro, relayClaude, relayGpt, deepseek, tavily];++// ── Agents (backends) and their routes ──────────────────────────────────++export const backendModel = (id: string, extra: Partial<BackendModel> = {}): BackendModel => ({+ id,+ display_name: null,+ origin: 'builtin',+ models_dev_id: null,+ context_window: null,+ max_output_tokens: null,+ input_modalities: ['text', 'image'],+ output_modalities: ['text'],+ supports_tools: null,+ supports_reasoning: null,+ reasoning_efforts: [],+ locked: false,+ routeable: true,+ ...extra,+});++export type RouteSpec = {+ /** The hops a turn would try, in order: `[source, upstream model]`. */+ hops: [Source, string][];+ origin?: RouteOrigin;+ /** Hop health by Source id; healthy otherwise. */+ health?: Record<string, ChainHealth>;+};++export type AgentSpec = {+ backend: AgentBackend;+ mode?: 'hub' | 'direct';+ cliPresent?: boolean;+ menuKind?: 'fixed' | 'open';+ order?: Source[];+ routes?: Record<string, RouteSpec>;+ catalog?: BackendModel[];+ namedAgents?: AgentSupply['named_agents'];+};++const runnable = (health: ChainHealth) => health === 'healthy';++/** Which Sources may serve a backend, as the server decides (`ModelHubConfig.source_eligible_for_backend`):+ * never a search service; any gateway-held Source; a native login only for its own CLI. */+const NATIVE_CLIENT: Record<string, AgentBackend> = { anthropic: 'claude', openai: 'codex' };+export const eligible = (src: Source, backend: AgentBackend): boolean =>+ src.protocol !== 'search'+ && (src.supply_channel === 'hub' || (src.kind === 'subscription' && NATIVE_CLIENT[src.vendor] === backend));++const modelSupply = (modelId: string, route: RouteSpec | undefined): ModelSupply => ({+ model_id: modelId,+ route_origin: route?.origin ?? (route ? 'automatic' : null),+ chain_length: route?.hops.length ?? 0,+ has_runnable_hop: (route?.hops ?? []).some(([hop]) => runnable(route?.health?.[hop.id] ?? 'healthy')),+});++export const agent = ({ backend, mode = 'hub', cliPresent = true, menuKind, order = [], routes = {}, catalog, namedAgents = [] }: AgentSpec): AgentSupply => {+ const catalogModels = catalog ?? Object.keys(routes).map((id) => backendModel(id, backend === 'opencode' ? { origin: 'provider', native_protocol: 'openai_responses' } : {}));+ return {+ backend,+ cli_present: cliPresent,+ mode,+ menu_kind: menuKind ?? (backend === 'opencode' ? 'open' : 'fixed'),+ sources: mode === 'hub'+ ? {+ order: order.map((s) => s.id),+ eligibility: demoSources.map((s) => eligible(s, backend)+ ? { source_id: s.id, eligible: true, reason_key: null }+ : { source_id: s.id, eligible: false, reason_key: 'models.eligibility.subscription_wrong_client' }),+ }+ : null,+ model_supply: mode === 'hub' ? catalogModels.filter((m) => m.routeable).map((m) => modelSupply(m.id, routes[m.id])) : null,+ named_agents: namedAgents,+ catalog_models: catalogModels,+ };+};++export const chain = (backend: AgentBackend, modelId: string, route: RouteSpec | undefined): AgentChain => {+ const links: AgentChainLink[] = (route?.hops ?? []).map(([hop, upstream]) => {+ const health = route?.health?.[hop.id] ?? 'healthy';+ return {+ source_id: hop.id,+ model_id: upstream,+ channel: hop.supply_channel,+ health,+ runnable: runnable(health),+ reason: health === 'needs_action' ? 'models.source.needs_action.oauth_expired' : null,+ retry_at: health === 'cooldown' ? at(42) : null,+ };+ });+ const first = links.find((link) => link.runnable) ?? null;+ const origin = route?.origin ?? 'automatic';+ return {+ contract_version: 23,+ backend,+ model_id: modelId,+ manual_override: origin === 'manual' ? { hops: links.map(({ source_id, model_id }) => ({ source_id, model_id })) } : null,+ route_origin: route ? origin : null,+ current: first ? { source_id: first.source_id, model_id: first.model_id } : null,+ chain: links,+ supply_state: first ? 'ok' : links.length ? 'waiting' : 'interrupted',+ };+};++// ── Gateway runtime ─────────────────────────────────────────────────────++export const runtime = (health: RuntimeHealth = 'ok', enabled = true): RuntimeDependency => ({+ contract_version: 23,+ enabled,+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '6.9.2', source_sha: 'a'.repeat(40), assets: [] },+ status: {+ installed_version: health === 'not_installed' ? null : '6.9.2',+ verified: health !== 'not_installed',+ listening: health === 'ok' ? { host: '127.0.0.1', port: 40121 } : null,+ health,+ last_check: at(-1),+ },+});++// ── Hosted tools ────────────────────────────────────────────────────────++const searchPrice = (usd: number) => ({ unit: 'search' as const, usd_per_1k: usd, extra: [], as_of: '2026-10-24', url: 'https://avibe.bot' });++export const hostedTools = (): HostedToolsStatus => ({+ tools: [+ {+ name: 'web_search',+ enabled: true,+ prefer_native: true,+ services: {},+ service_order: [tavily.id],+ executor_order: null,+ effective_order: [tavily.id, 'src_exakeyless', relayClaude.id],+ status: { latest_ok: null, verified: [], refused: [] },+ executor_candidates: [+ { kind: 'service', source_id: tavily.id, model_id: 'tavily/search', billing: 'metered', relay: false, price: searchPrice(8), settings: { results: 5, enabled: true }, state: STANDBY, trial_pending: false, cooldown_until: null },+ { kind: 'service', source_id: 'src_exakeyless', model_id: 'exa/mcp', billing: 'metered', relay: false, price: searchPrice(0), settings: { results: 5, enabled: true }, state: ACTIVE, trial_pending: false, cooldown_until: null },+ { kind: 'model', source_id: relayClaude.id, model_id: 'claude-haiku-5', billing: 'metered', relay: true, price: { ...searchPrice(10), unit: 'call' } },+ ],+ service_vendors: [+ { id: 'tavily', name: 'Tavily', results_max: 20, price: searchPrice(8), free_tier: null, source_ids: [tavily.id], facts: { tool_only: true, auto_enroll: false, free_check: true } },+ { id: 'exa', name: 'Exa', results_max: 10, price: searchPrice(7), free_tier: null, source_ids: [], facts: { tool_only: true, auto_enroll: false, free_check: false } },+ { id: 'exa-mcp', name: 'Exa (free)', results_max: 100, price: searchPrice(0), free_tier: 'Free; IP rate-limited', source_ids: ['src_exakeyless'], facts: { tool_only: true, auto_enroll: false, free_check: false, built_in: true, requires_setup: false } },+ ],+ },+ ],+});++// ── Usage ──++const HOUR = 60;+const usageCounters = (requests: number, cost: number): UsageCounters => ({+ requests,+ token_reports: requests,+ input_tokens: requests * 18_400,+ cached_input_tokens: requests * 61_000,+ output_tokens: requests * 2_300,+ api_cost_usd: cost,+ excluded_tokens: 0,+ api_cost_lower_bound: false,+});++/** Who metered what, as shares of a window: [source, model, share of requests]. */+const USAGE_MIX: [Source, string, number][] = [+ [chatgptPro, 'gpt-6-astra', 0.34],+ [relayClaude, 'claude-opus-5', 0.22],+ [relayGpt, 'gpt-5.6-sol', 0.18],+ [claudeMax, 'claude-sonnet-5', 0.14],+ [deepseek, 'deepseek-v4', 0.12],+];+const COST_PER_REQUEST: Record<string, number> = { 'gpt-6-astra': 0.11, 'claude-opus-5': 0.19, 'gpt-5.6-sol': 0.06, 'claude-sonnet-5': 0.08, 'deepseek-v4': 0.004 };++/** A usage report over a trailing window, with a working-hours curve and one search service. */+export function usageReport(windowKey: UsageWindowKey = '24h'): UsageReport {+ const hourly = windowKey === '24h';+ const count = hourly ? 24 : Number(windowKey.slice(0, -1));+ const step = hourly ? HOUR : 24 * HOUR;+ const buckets: UsageBucket[] = Array.from({ length: count }, (_, index) => {+ const start = -(count - index) * step;+ // Busier in working hours and on recent days.+ const load = hourly ? [2, 1, 0, 0, 0, 0, 1, 3, 9, 14, 17, 15, 9, 13, 18, 16, 12, 8, 6, 7, 9, 6, 4, 3][index] : 20 + ((index * 37) % 23) + index;+ const rows: UsageBucketEntry[] = USAGE_MIX.flatMap(([src, model, share]) => {+ const requests = Math.round(load * share * (hourly ? 1 : 6));+ return requests > 0 ? [{ source_id: src.id, model_id: model, ...usageCounters(requests, requests * COST_PER_REQUEST[model]) }] : [];+ });+ if (load > 8) rows.push({ kind: 'service', source_id: tavily.id, service_id: 'tavily/search', tool: 'web_search', requests: 2, billable_requests: 2, uncertain_requests: 0, reported_requests: 0, api_cost_usd: 0.016, reported_usd: 0, api_cost_lower_bound: false });+ return { key: at(start).slice(0, hourly ? 13 : 10), start_at: at(start), end_at: at(start + step), history_complete: index < count - 1, rows };+ });+ const modelRows = buckets.flatMap((bucket) => bucket.rows).filter((row): row is UsageBucketRow => row.kind !== 'service');+ const sum = (rows: UsageBucketRow[]) => {+ const requests = rows.reduce((total, row) => total + row.requests, 0);+ return usageCounters(requests, Math.round(rows.reduce((total, row) => total + (row.api_cost_usd ?? 0), 0) * 100) / 100);+ };+ const searches = buckets.flatMap((bucket) => bucket.rows).filter((row) => row.kind === 'service').length * 2;+ return {+ window_key: windowKey,+ window_days: hourly ? 1 : count,+ granularity: hourly ? 'hour' : 'day',+ from_day: at(-count * step).slice(0, 10),+ to_day: at(0).slice(0, 10),+ from_at: at(-count * step),+ to_at: at(0),+ totals: sum(modelRows),+ sources: [...new Set(USAGE_MIX.map(([src]) => src))].map((src) => ({+ source_id: src.id,+ label: src.display_name,+ last_metered_at: at(-12),+ ...sum(modelRows.filter((row) => row.source_id === src.id)),+ models: USAGE_MIX.filter(([s]) => s === src).map(([, model]) => ({ model_id: model, label: null, ...sum(modelRows.filter((row) => row.model_id === model && row.source_id === src.id)) })),+ })),+ services: [{ source_id: tavily.id, service_id: 'tavily/search', tool: 'web_search', label: 'Tavily', service_label: 'Tavily Search', last_metered_at: at(-40), requests: searches, billable_requests: searches, uncertain_requests: 0, reported_requests: 0, api_cost_usd: searches * 0.008, reported_usd: 0, api_cost_lower_bound: false, priced: true }],+ days: [],+ buckets,+ pricing: { currency: 'USD', price_table_date: '2026-10-30' },+ };+}++// ── The page's reads ────────────────────────────────────────────────────++export type HubSpec = {+ sources?: Source[];+ agents?: AgentSpec[];+ runtime?: RuntimeDependency;+ tools?: HostedToolsStatus;+ /** Native logins the gateway could import (shows 迁移配置). */+ migration?: MigrationItem[];+};++/** Reads every frame's providers make: the Bots provider, and the CSRF token a write (or the migration scan) asks for. */+export const baseApi: Record<string, unknown> = {+ '/api/bots': { ok: true, bots: [] },+ '/api/csrf-token': { csrf_token: 'design' },+};++/** The usage read a search service's detail makes for its monthly line. */+export const usageApi = (windowKey: UsageWindowKey = '60d') => ({ '/api/models/usage': ok({ usage: usageReport(windowKey) }) });++/** An API error envelope, for a read that failed. */+export const failed = (error = 'internal_error') => ({ ok: false, contract_version: 23, error });++/** Every `/api/models/*` read the Models page makes on open, from one description of the Hub. */+export function hubApi({ sources = demoSources, agents = [], runtime: rt = runtime(), tools = hostedTools(), migration = [] }: HubSpec): Record<string, unknown> {+ const api: Record<string, unknown> = {+ ...baseApi,+ '/api/models/sources': ok({ sources }),+ '/api/models/agents': ok({ agents: agents.map(agent) }),+ '/api/models/runtime/status': ok({ runtime: rt }),+ '/api/models/hosted-tools': ok({ hosted_tools: tools }),+ '/api/models/migration/scan': ok({ scan: { items: migration } }),+ '/api/models/events': ok({ events: [] }),+ ...usageApi(),+ };+ for (const spec of agents) {+ if ((spec.mode ?? 'hub') !== 'hub') continue;+ const chains = Object.entries(spec.routes ?? {}).map(([modelId, route]) => chain(spec.backend, modelId, route));+ api[`/api/models/agents/${spec.backend}/chains`] = ok({ chains });+ api[`/api/models/agents/${spec.backend}/provenance`] = ok({ provenance: null });+ for (const read of chains) api[`/api/models/agents/${spec.backend}/chain?model=${encodeURIComponent(read.model_id)}`] = ok({ chain: read });+ // The model menu dialog and the default-route drawer read the backend's own supply.+ api[`/api/models/agents/${spec.backend}/sources`] = ok({ agent: agent(spec) });+ }+ return api;+}++/** One backend's supply as the page reads it, by spec. */+export const agentOf = (backend: AgentBackend, specs: AgentSpec[] = demoAgents): AgentSupply =>+ agent(specs.find((spec) => spec.backend === backend)!);++/** One model's route as the page reads it, by spec. */+export const chainOf = (backend: AgentBackend, modelId: string, specs: AgentSpec[] = demoAgents): AgentChain =>+ chain(backend, modelId, specs.find((spec) => spec.backend === backend)?.routes?.[modelId]);++/** The populated Hub: four backends on the gateway, each with its own routes. */+export const demoAgents: AgentSpec[] = [+ {+ backend: 'claude',+ order: [claudeMax, relayClaude],+ routes: {+ 'claude-opus-5': { hops: [[claudeMax, 'claude-opus-5'], [relayClaude, 'claude-opus-5']] },+ 'claude-sonnet-5': { hops: [[claudeMax, 'claude-sonnet-5'], [relayClaude, 'claude-sonnet-5']] },+ 'claude-haiku-5': { hops: [[relayClaude, 'claude-haiku-5']], origin: 'manual' },+ 'claude-opus-4-8': { hops: [[relayClaude, 'claude-opus-4-8']] },+ },+ },+ {+ backend: 'codex',+ order: [chatgptPro, relayGpt],+ routes: {+ 'gpt-6-astra': { hops: [[chatgptPro, 'gpt-6-astra'], [relayGpt, 'gpt-6-astra']] },+ 'gpt-5.6-sol': { hops: [[chatgptPro, 'gpt-5.6-sol'], [relayGpt, 'gpt-5.6-sol']] },+ 'gpt-5.6-terra': { hops: [[relayGpt, 'gpt-5.6-terra']], origin: 'manual' },+ 'gpt-5.6-luna': { hops: [[relayGpt, 'gpt-5.6-luna']], origin: 'passthrough' },+ 'gpt-5.5': { hops: [[chatgptPro, 'gpt-5.5'], [relayGpt, 'gpt-5.5']] },+ 'gpt-5.4': { hops: [[relayGpt, 'gpt-5.4']] },+ 'gpt-5.4-mini': { hops: [[relayGpt, 'gpt-5.4-mini']] },+ },+ },+ {+ backend: 'opencode',+ order: [deepseek, relayGpt, relayClaude],+ routes: {+ 'deepseek-v4': { hops: [[deepseek, 'deepseek-v4']] },+ 'deepseek-v4-reasoner': { hops: [[deepseek, 'deepseek-v4-reasoner']] },+ 'claude-sonnet-5': { hops: [[relayClaude, 'claude-sonnet-5']] },+ 'gpt-5.6-sol': { hops: [[relayGpt, 'gpt-5.6-sol']] },+ },+ },+ {+ backend: 'vibey',+ cliPresent: false,+ order: [chatgptPro, relayGpt, relayClaude],+ routes: {+ 'gpt-6-astra': { hops: [[chatgptPro, 'gpt-6-astra'], [relayGpt, 'gpt-6-astra']] },+ 'claude-opus-5': { hops: [[relayClaude, 'claude-opus-5']] },+ },+ },+];++/** The Settings route pane the Models page renders in (SettingsLayout's content column). */+export const settingsPaneClass = 'w-full min-h-full px-4 pb-5 pt-5 md:px-8 md:pb-7 md:pt-7';diff --git a/ui/design/frames/models/migration.design.tsx b/ui/design/frames/models/migration.design.tsxnew file mode 100644index 000000000..9a754e25d--- /dev/null+++ b/ui/design/frames/models/migration.design.tsx@@ -0,0 +1,47 @@+// 迁移配置: the shipped MigrationDialog, listing the native logins and keys it found on this+// machine that the gateway can take over.+import { MigrationDialog } from '@/components/settings/models/MigrationDialog';+import type { MigrationItem } from '@/components/settings/models/types';++import { frames } from '../../frame';+import { baseApi, ok } from './fixtures';++const items: MigrationItem[] = [+ {+ id: 'mig_claude_oauth', backend: 'claude', kind: 'oauth_native', masked_detail: 'Claude 本机登录 · [email protected]', proposed_action: 'keep_native',+ selected: true, notes_key: null, vendor: 'anthropic', display_name: 'Anthropic', masked_credential: null, source_paths: ['~/.claude/.credentials.json'],+ },+ {+ id: 'mig_codex_key', backend: 'codex', kind: 'api_key', masked_detail: 'sk-proj…7Fq2 + 自定义 Base URL', proposed_action: 'import',+ selected: true, notes_key: null, vendor: 'openai', display_name: 'OpenAI', masked_credential: 'sk-proj…7Fq2', source_paths: ['~/.codex/config.toml'], may_hold_api_key: true,+ },+ {+ id: 'mig_opencode_deepseek', backend: 'opencode', kind: 'opencode_provider', masked_detail: 'deepseek · sk-4f1…a09c', proposed_action: 'import',+ selected: true, notes_key: null, vendor: 'deepseek', display_name: 'deepseek', masked_credential: 'sk-4f1…a09c', source_paths: ['~/.config/opencode/opencode.json'], may_hold_api_key: true,+ },+];++const migration = () => <MigrationDialog open onClose={() => {}} />;++const designFrames = frames([+ {+ name: 'found',+ title: '迁移配置 · 发现本机配置',+ width: 1000,+ height: 820,+ status: 'shipped',+ fixtures: { api: { ...baseApi, '/api/models/migration/scan': ok({ scan: { items } }) } },+ render: migration,+ },+ {+ name: 'phone',+ title: '迁移配置 · 手机',+ width: 390,+ height: 844,+ status: 'shipped',+ fixtures: { api: { ...baseApi, '/api/models/migration/scan': ok({ scan: { items } }) } },+ render: migration,+ },+]);++export default designFrames;diff --git a/ui/design/frames/models/model-menu.design.tsx b/ui/design/frames/models/model-menu.design.tsxnew file mode 100644index 000000000..4c1514d5d--- /dev/null+++ b/ui/design/frames/models/model-menu.design.tsx@@ -0,0 +1,160 @@+// A backend's model menu (管理模型): the shipped BackendModelCatalogDialog, its picker for adding+// models providers supply, and its editor for one model.+import { BackendModelCatalogDialog } from '@/components/settings/models/BackendModelCatalogDialog';+import { BackendModelEditorDialog } from '@/components/settings/models/BackendModelEditorDialog';+import { BackendModelPickerDialog } from '@/components/settings/models/BackendModelPickerDialog';+import type { AgentBackend, Source } from '@/components/settings/models/types';++import { frames } from '../../frame';+import { backendModel, deepseek, demoAgents, demoSources, hubApi, ok, relayClaude, relayGpt, type AgentSpec } from './fixtures';++const sourceNames = Object.fromEntries(demoSources.map((s) => [s.id, s.display_name]));++const catalogWrite = { pending: false, track: () => new Promise<void>(() => {}) };+const catalog = (backend: AgentBackend) => () => (+ <BackendModelCatalogDialog+ open+ backend={backend}+ canReadSources+ sourceNames={sourceNames}+ onClose={() => {}}+ onSaved={() => {}}+ onObserved={() => {}}+ catalogWrite={catalogWrite}+ />+);++// Claude Code's menu: the built-in models with their reasoning efforts, plus one a provider added.+const claudeEfforts = ['low', 'medium', 'high', 'max'];+const menuAgents: AgentSpec[] = demoAgents.map((spec) => spec.backend !== 'claude' ? spec : {+ ...spec,+ catalog: [+ backendModel('default', { display_name: 'Default', locked: true, routeable: false }),+ backendModel('claude-opus-5', { display_name: 'Opus 5', reasoning_efforts: claudeEfforts, supports_reasoning: true, context_window: 1_000_000, max_output_tokens: 128_000 }),+ backendModel('claude-sonnet-5', { display_name: 'Sonnet 5', reasoning_efforts: claudeEfforts, supports_reasoning: true, context_window: 1_000_000, max_output_tokens: 64_000 }),+ backendModel('claude-haiku-5', { display_name: 'Haiku 5', reasoning_efforts: ['low', 'medium', 'high'], supports_reasoning: true, context_window: 200_000 }),+ backendModel('claude-opus-4-8', { origin: 'provider', reasoning_efforts: claudeEfforts, supports_reasoning: true }),+ ],+});++const supplier = (source: Source, model: string) => ({ source_id: source.id, source_name: source.display_name, model_id: model });+const candidate = (id: string, suppliers: ReturnType<typeof supplier>[], protocol: 'openai_responses' | 'anthropic' = 'openai_responses') => ({+ id, display_name: null, reasoning_efforts: [], suppliers, origin: 'provider', native_protocol: protocol,+});++/** What the picker offers OpenCode: models its providers supply that the menu does not hold yet. */+const opencodeCandidates = ok({+ candidates: {+ builtin: [],+ providers: [+ candidate('claude-opus-5', [supplier(relayClaude, 'claude-opus-5')], 'anthropic'),+ candidate('claude-haiku-5', [supplier(relayClaude, 'claude-haiku-5')], 'anthropic'),+ candidate('claude-opus-4-8', [supplier(relayClaude, 'claude-opus-4-8')], 'anthropic'),+ candidate('gpt-6-astra', [supplier(relayGpt, 'gpt-6-astra')]),+ candidate('gpt-5.6-terra', [supplier(relayGpt, 'gpt-5.6-terra')]),+ candidate('gpt-5.6-luna', [supplier(relayGpt, 'gpt-5.6-luna')]),+ candidate('gpt-5.5', [supplier(relayGpt, 'gpt-5.5')]),+ ],+ in_list: [+ candidate('deepseek-v4', [supplier(deepseek, 'deepseek-v4')]),+ candidate('deepseek-v4-reasoner', [supplier(deepseek, 'deepseek-v4-reasoner')]),+ candidate('claude-sonnet-5', [supplier(relayClaude, 'claude-sonnet-5')], 'anthropic'),+ candidate('gpt-5.6-sol', [supplier(relayGpt, 'gpt-5.6-sol')]),+ ],+ },+});++const api = { ...hubApi({ agents: menuAgents }), '/api/models/agents/opencode/models/candidates': opencodeCandidates };++const editing = backendModel('claude-opus-4-8', { origin: 'provider', reasoning_efforts: claudeEfforts, supports_reasoning: true, supports_tools: true, context_window: 1_000_000, max_output_tokens: 128_000 });++const opencodeListed = new Set(['deepseek-v4', 'deepseek-v4-reasoner', 'claude-sonnet-5', 'gpt-5.6-sol']);+const claudeTaken = new Set(['claude-opus-5', 'claude-sonnet-5', 'claude-haiku-5']);++const designFrames = frames([+ {+ name: 'claude',+ title: '管理模型 · Claude Code',+ width: 1000,+ height: 820,+ status: 'shipped',+ fixtures: { api },+ render: catalog('claude'),+ },+ {+ name: 'opencode',+ title: '管理模型 · OpenCode',+ width: 1000,+ height: 820,+ status: 'shipped',+ fixtures: { api },+ render: catalog('opencode'),+ },+ {+ name: 'phone',+ title: '管理模型 · 手机',+ width: 390,+ height: 844,+ status: 'shipped',+ fixtures: { api },+ render: catalog('codex'),+ },+ {+ name: 'add-models',+ title: '添加模型 · 从供应商选择(OpenCode)',+ width: 1000,+ height: 820,+ status: 'shipped',+ fixtures: { api },+ render: () => (+ <BackendModelPickerDialog+ open+ backend="opencode"+ listedIds={opencodeListed}+ onCancel={() => {}}+ onAdd={() => {}}+ onCustom={() => {}}+ />+ ),+ },+ {+ name: 'edit-model',+ title: '编辑模型 · claude-opus-4-8',+ width: 1000,+ height: 900,+ status: 'shipped',+ fixtures: { api },+ render: () => (+ <BackendModelEditorDialog+ open+ backend="claude"+ model={editing}+ takenIds={claudeTaken}+ effortSuggestions={claudeEfforts}+ onCancel={() => {}}+ onCommit={() => {}}+ />+ ),+ },+ {+ name: 'custom-model',+ title: '添加自定义模型(OpenCode)',+ width: 1000,+ height: 900,+ status: 'shipped',+ fixtures: { api },+ render: () => (+ <BackendModelEditorDialog+ open+ backend="opencode"+ model={null}+ takenIds={opencodeListed}+ effortSuggestions={['low', 'medium', 'high']}+ onCancel={() => {}}+ onCommit={() => {}}+ />+ ),+ },+]);++export default designFrames;diff --git a/ui/design/frames/models/page.design.tsx b/ui/design/frames/models/page.design.tsxnew file mode 100644index 000000000..f277c66ca--- /dev/null+++ b/ui/design/frames/models/page.design.tsx@@ -0,0 +1,146 @@+// Settings · Models (the Model Hub): the shipped page on its 供应商与路由 tab, rendered from+// `/api/models/*` fixtures. Providers on the left, each backend's model routes on the right.+import { SettingsModelsPage } from '@/components/settings/models/SettingsModelsPage';++import { frames } from '../../frame';+import {+ chatgptPro,+ claudeMax,+ demoAgents,+ demoSources,+ failed,+ hubApi,+ runtime,+ settingsPaneClass,+ type AgentSpec,+} from './fixtures';++const page = () => (+ <div className={settingsPaneClass}>+ <SettingsModelsPage />+ </div>+);++// Claude Max ran out of its 5-hour quota: Claude Code's routes moved to the relay until it returns.+const claudeCooling = { ...claudeMax, state: { status: 'cooldown' as const, retry_at: '2026-11-01T08:42:00Z', detail_key: 'models.source.cooldown.quota_exhausted' as const } };+const takeoverAgents: AgentSpec[] = demoAgents.map((spec) => spec.backend !== 'claude' ? spec : {+ ...spec,+ routes: Object.fromEntries(Object.entries(spec.routes ?? {}).map(([id, route]) => [id, { ...route, health: { [claudeMax.id]: 'cooldown' } }])),+});++// The ChatGPT login expired: Codex and Vibey fall back to the relay, and the row asks to sign in again.+const chatgptExpired = { ...chatgptPro, state: { status: 'needs_action' as const, retry_at: null, detail_key: 'models.source.needs_action.oauth_expired' as const } };+const expiredAgents: AgentSpec[] = demoAgents.map((spec) => ({+ ...spec,+ routes: Object.fromEntries(Object.entries(spec.routes ?? {}).map(([id, route]) => [id, { ...route, health: { [chatgptPro.id]: 'needs_action' } }])),+}));++// A fresh switch to the gateway: no provider yet, so every model waits for one.+const unsuppliedAgents: AgentSpec[] = [+ { backend: 'claude', routes: { 'claude-opus-5': { hops: [] }, 'claude-sonnet-5': { hops: [] }, 'claude-haiku-5': { hops: [] } } },+ { backend: 'codex', routes: { 'gpt-6-astra': { hops: [] }, 'gpt-5.6-sol': { hops: [] }, 'gpt-5.5': { hops: [] } } },+];++const directAgents: AgentSpec[] = [{ backend: 'claude', mode: 'direct' }, { backend: 'codex', mode: 'direct' }, { backend: 'opencode', mode: 'direct' }];++const designFrames = frames([+ {+ name: 'overview',+ title: '模型网关 · 供应商与路由',+ width: 1280,+ height: 1720,+ status: 'shipped',+ fixtures: { api: hubApi({ agents: demoAgents }) },+ render: page,+ },+ {+ name: 'overview-phone',+ title: '模型网关 · 供应商与路由 · 手机',+ width: 390,+ height: 1800,+ status: 'shipped',+ fixtures: { api: hubApi({ agents: demoAgents }) },+ render: page,+ },+ {+ name: 'origin-help',+ title: '模型网关 · 路由标签说明(悬停)',+ width: 1280,+ height: 900,+ status: 'shipped',+ fixtures: { api: hubApi({ agents: demoAgents }) },+ hover: '[data-route-backend="claude"][data-route-model="claude-haiku-5"] span.relative > button',+ render: page,+ },+ {+ name: 'takeover',+ title: '模型网关 · 已自动切换(Claude Max 额度用完)',+ width: 1280,+ height: 1100,+ status: 'shipped',+ fixtures: { api: hubApi({ sources: demoSources.map((s) => (s.id === claudeMax.id ? claudeCooling : s)), agents: takeoverAgents }) },+ render: page,+ },+ {+ name: 'needs-action',+ title: '模型网关 · 供应商需要处理(ChatGPT 登录过期)',+ width: 1280,+ height: 1100,+ status: 'shipped',+ fixtures: { api: hubApi({ sources: demoSources.map((s) => (s.id === chatgptPro.id ? chatgptExpired : s)), agents: expiredAgents }) },+ render: page,+ },+ {+ name: 'no-providers',+ title: '模型网关 · 已切到网关、还没有供应商',+ width: 1280,+ height: 900,+ status: 'shipped',+ fixtures: { api: hubApi({ sources: [], agents: unsuppliedAgents }) },+ render: page,+ },+ {+ name: 'direct',+ title: '模型网关 · 全部直连(升级后第一屏)',+ width: 1280,+ height: 760,+ status: 'shipped',+ fixtures: {+ api: hubApi({+ sources: [],+ agents: directAgents,+ migration: [{ id: 'mig_claude', backend: 'claude', kind: 'oauth_native', masked_detail: 'Claude 本机登录', proposed_action: 'import', selected: true, notes_key: null, vendor: 'anthropic', display_name: 'Anthropic' }],+ }),+ },+ render: page,+ },+ {+ name: 'runtime-off',+ title: '模型网关 · 暂不可用(运行时已停止)',+ width: 1280,+ height: 600,+ status: 'shipped',+ fixtures: { api: hubApi({ agents: demoAgents, runtime: runtime('down', false) }) },+ render: page,+ },+ {+ name: 'runtime-not-installed',+ title: '模型网关 · 组件未安装',+ width: 1280,+ height: 600,+ status: 'shipped',+ fixtures: { api: hubApi({ agents: demoAgents, runtime: runtime('not_installed', false) }) },+ render: page,+ },+ {+ name: 'read-failed',+ title: '模型网关 · 读取失败',+ width: 1280,+ height: 760,+ status: 'shipped',+ fixtures: { api: { ...hubApi({ agents: demoAgents }), '/api/models/sources': failed(), '/api/models/agents': failed() } },+ render: page,+ },+]);++export default designFrames;diff --git a/ui/design/frames/models/routing.design.tsx b/ui/design/frames/models/routing.design.tsxnew file mode 100644index 000000000..6da78bee9--- /dev/null+++ b/ui/design/frames/models/routing.design.tsx@@ -0,0 +1,160 @@+// Routing a backend's models: 默认路由 (the shipped SourceOrderDrawer, the order every automatic+// route follows) and one model's route (the shipped RouteChainDialog, opened from a model row).+import { createSourceCollectionReadAuthority } from '@/components/settings/models/collectionReadAuthority';+import { readyRegion } from '@/components/settings/models/regionRead';+import { RouteChainDialog } from '@/components/settings/models/RouteChainDialog';+import { SourceOrderDrawer } from '@/components/settings/models/SourceOrderDrawer';+import type { AgentBackend, AgentSupply, Source, TurnProvenance } from '@/components/settings/models/types';++import { frames } from '../../frame';+import { AfterMount } from '../../shell/AfterMount';+import { agent, agentOf, at, chainOf, claudeMax, demoAgents, demoSources, hubApi, ok, relayClaude, type AgentSpec } from './fixtures';++const order = (backend: AgentBackend) => {+ const supply = agentOf(backend);+ const sourceReads = createSourceCollectionReadAuthority();+ const orderWrite = { pending: false, track: () => new Promise<void>(() => {}) };+ return () => (+ <SourceOrderDrawer open agent={supply} sources={demoSources} sourceReads={sourceReads} onClose={() => {}} onSaved={() => {}} orderWrite={orderWrite} />+ );+};++/** One model's route dialog, opened after mount as the page does. The selection is built once: the dialog re-reads the route whenever it changes. */+const route = (backend: AgentBackend, modelId: string, specs: AgentSpec[] = demoAgents, sources: Source[] = demoSources) => {+ const supply: AgentSupply = agent(specs.find((spec) => spec.backend === backend)!);+ const selection = { agent: supply, modelId, read: readyRegion(chainOf(backend, modelId, specs)) };+ const readAgents = async () => ({ value: [supply], install: () => {} });+ const readSources = async () => ({ value: sources, install: () => {} });+ return () => (+ <AfterMount>+ {(open) => (+ <RouteChainDialog+ selection={open ? selection : null}+ sources={sources}+ onClose={() => {}}+ readAgents={readAgents}+ readSources={readSources}+ onOpenDefaults={() => {}}+ onManageModel={() => {}}+ />+ )}+ </AfterMount>+ );+};++// The last turn on claude-opus-5 ended in an upstream error on its second hop.+const upstreamError: TurnProvenance = {+ contract_version: 23,+ turn_id: 'turn_design',+ ts: at(-6),+ agent: 'claude',+ requested_model_id: 'claude-opus-5',+ outcome: 'failed_terminal',+ failed_attempts: [],+ served: null,+ canceled_attempt: null,+ terminal_error: {+ source_id: relayClaude.id,+ configured_model_id: 'claude-opus-5',+ channel: 'hub',+ reason: 'invalid_parameter',+ stream_started: false,+ http_status: 400,+ upstream_error_code: 'invalid_request_error',+ upstream_detail: 'max_tokens: 200000 > 128000, which is the maximum allowed number of output tokens for claude-opus-5',+ response_correlation_ids: [{ header: 'request-id', value: 'req_011CUf3kR8ZqBvN7xDesign' }],+ },+ model_supply_state: null,+ blockers: [],+};+const relayFirstAgents: AgentSpec[] = demoAgents.map((spec) => spec.backend !== 'claude' ? spec : {+ ...spec,+ routes: { ...spec.routes, 'claude-opus-5': { hops: [[relayClaude, 'claude-opus-5'], [claudeMax, 'claude-opus-5']], origin: 'manual' } },+});++// A model added to the menu that no provider serves yet.+const unroutedAgents: AgentSpec[] = demoAgents.map((spec) => spec.backend !== 'opencode' ? spec : {+ ...spec,+ routes: { ...spec.routes, 'kimi-k3': { hops: [] } },+});++const api = hubApi({ agents: demoAgents });++const designFrames = frames([+ {+ name: 'default-order',+ title: '默认路由 · Codex(供应商顺序)',+ width: 1280,+ height: 800,+ status: 'shipped',+ fixtures: { api },+ render: order('codex'),+ },+ {+ name: 'default-order-phone',+ title: '默认路由 · 手机',+ width: 390,+ height: 844,+ status: 'shipped',+ fixtures: { api },+ render: order('opencode'),+ },+ {+ name: 'route-automatic',+ title: '模型路由 · 自动(按默认路由)',+ width: 1000,+ height: 760,+ status: 'shipped',+ fixtures: { api },+ render: route('codex', 'gpt-5.6-sol'),+ },+ {+ name: 'route-manual',+ title: '模型路由 · 手动',+ width: 1000,+ height: 760,+ status: 'shipped',+ fixtures: { api },+ render: route('codex', 'gpt-5.6-terra'),+ },+ {+ name: 'route-passthrough',+ title: '模型路由 · 透传',+ width: 1000,+ height: 760,+ status: 'shipped',+ fixtures: { api },+ render: route('codex', 'gpt-5.6-luna'),+ },+ {+ name: 'route-upstream-error',+ title: '模型路由 · 最近一轮上游报错',+ width: 1000,+ height: 760,+ status: 'shipped',+ fixtures: {+ api: { ...hubApi({ agents: relayFirstAgents }), '/api/models/agents/claude/provenance?model=claude-opus-5': ok({ provenance: upstreamError }) },+ },+ render: route('claude', 'claude-opus-5', relayFirstAgents),+ },+ {+ name: 'route-empty',+ title: '模型路由 · 还没有供应商提供',+ width: 1000,+ height: 760,+ status: 'shipped',+ fixtures: { api: hubApi({ agents: unroutedAgents }) },+ render: route('opencode', 'kimi-k3', unroutedAgents),+ },+ {+ name: 'route-phone',+ title: '模型路由 · 手机',+ width: 390,+ height: 844,+ status: 'shipped',+ fixtures: { api },+ render: route('claude', 'claude-opus-5'),+ },+]);++export default designFrames;diff --git a/ui/design/frames/models/source-detail.design.tsx b/ui/design/frames/models/source-detail.design.tsxnew file mode 100644index 000000000..ebc13ba53--- /dev/null+++ b/ui/design/frames/models/source-detail.design.tsx@@ -0,0 +1,104 @@+// A provider's detail: the shipped SourceDetailPanel, opened from a row of 模型供应商, and its+// 测试 dialog.+import { SourceDetailPanel } from '@/components/settings/models/SourceDetailPanel';+import { SourceTestDialog } from '@/components/settings/models/SourceTestDialog';+import type { TrackSourceMutation } from '@/components/settings/models/mutationSettlement';+import { readyRegion } from '@/components/settings/models/regionRead';+import type { Source } from '@/components/settings/models/types';++import { frames } from '../../frame';+import { baseApi, chatgptPro, claudeMax, hostedTools, relayGpt, tavily, usageApi } from './fixtures';++const pending: TrackSourceMutation = () => new Promise(() => {});+const tools = readyRegion(hostedTools());+const gatewayBackends = new Set(['claude', 'codex', 'opencode', 'vibey'] as const);+const noPending = new Set<never>();++/**+ * The shipped panel at the size the Models page's provider dialog gives it (720 × 624; a tall+ * sheet on a phone). The dialog itself is inline in SettingsModelsPage and opens from page+ * state, so these frames draw the panel without it.+ */+const detail = (source: Source, serviceView = false) => () => (+ <div className="flex h-full flex-col">+ <SourceDetailPanel+ source={source}+ serviceView={serviceView}+ hostedTools={tools}+ hostedPending={noPending}+ onRetryHostedTools={() => {}}+ onClearHostedRefusal={() => {}}+ onSaveSearch={() => {}}+ onSaveFetch={() => {}}+ onRetryService={() => {}}+ onRetryFetch={() => {}}+ onManageSource={() => {}}+ onOpenUsage={() => {}}+ activeBackends={gatewayBackends}+ trackMutation={pending}+ onReauth={() => {}}+ onMutationCommitted={async () => {}}+ />+ </div>+);++const chatgptExpired: Source = { ...chatgptPro, state: { status: 'needs_action', retry_at: null, detail_key: 'models.source.needs_action.oauth_expired' } };++const designFrames = frames([+ {+ name: 'api-key',+ title: '供应商详情 · API Key(ai-relay-gpt)',+ width: 720,+ height: 624,+ status: 'shipped',+ fixtures: { api: baseApi },+ render: detail(relayGpt),+ },+ {+ name: 'subscription',+ title: '供应商详情 · 本机订阅(Claude Max)',+ width: 720,+ height: 624,+ status: 'shipped',+ fixtures: { api: baseApi },+ render: detail(claudeMax),+ },+ {+ name: 'needs-action',+ title: '供应商详情 · 需要重新登录(ChatGPT Pro)',+ width: 720,+ height: 624,+ status: 'shipped',+ fixtures: { api: baseApi },+ render: detail(chatgptExpired),+ },+ {+ name: 'search-service',+ title: '供应商详情 · 搜索服务(Tavily)',+ width: 720,+ height: 624,+ status: 'shipped',+ fixtures: { api: { ...baseApi, ...usageApi() } },+ render: detail(tavily, true),+ },+ {+ name: 'test',+ title: '测试供应商(ai-relay-gpt)',+ width: 1000,+ height: 600,+ status: 'shipped',+ fixtures: { api: baseApi },+ render: () => <SourceTestDialog source={relayGpt} onClose={() => {}} trackMutation={pending} />,+ },+ {+ name: 'phone',+ title: '供应商详情 · 手机',+ width: 390,+ height: 760,+ status: 'shipped',+ fixtures: { api: baseApi },+ render: detail(relayGpt),+ },+]);++export default designFrames;diff --git a/ui/design/shell/AfterMount.tsx b/ui/design/shell/AfterMount.tsxnew file mode 100644index 000000000..4526b777c--- /dev/null+++ b/ui/design/shell/AfterMount.tsx@@ -0,0 +1,22 @@+import { useEffect, useState, type ReactNode } from 'react';++/**+ * Renders `children(false)` first and `children(true)` once mounted. Some product dialogs stay+ * mounted and open later (the Model Hub route dialog gets its `selection` after mount); one that+ * mounts already open starts a read during StrictMode's remount and then drops it, so a frame+ * opens such a dialog the way the product does: closed first, open right after.+ */+export function AfterMount({ children }: { children: (mounted: boolean) => ReactNode }) {+ const [mounted, setMounted] = useState(false);+ useEffect(() => {+ // After the commit, so StrictMode's remount of the children has already run.+ let live = true;+ queueMicrotask(() => {+ if (live) setMounted(true);+ });+ return () => {+ live = false;+ };+ }, []);+ return <>{children(mounted)}</>;+}diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsxindex 6cdae6e90..00cc31e18 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx@@ -1,4 +1,4 @@-// Add-subscription dialog (frame 04). RENDERS DECLARATIVELY from the runtime-declared+// Add-subscription dialog (ui/design: models/add-provider/claude). 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 / OAuthDeviceCodeRowdiff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex ae41f29e4..8180016e2 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -96,7 +96,7 @@ type RouteTarget = {modelId: string;opener: HTMLElement | null;};-// Frame 13's rows, derived from the one subscription-vendor vocabulary rather+// The 添加订阅 menu's rows, derived from the one subscription-vendor vocabulary rather// than restated here. `subscriptionOptions.ts` owns which vendors are offered and// what custody each has, so this menu cannot drift out of the same order the// dialog's chooser reads.@@ -1606,8 +1606,8 @@ export const SettingsModelsPage: React.FC = () => {{/* The tab strip belongs to the Hub, not to the sourceinventory. Usage and switch history both outlive the Sourcesthey name, so deleting the last Source may not remove the only- route to either record. Frame 09 predates these tabs; it still- owns the direct-only body of `sources`. */}+ route to either record. The direct-only body of `sources` is+ DirectHome (ui/design: models/page/direct). */}<HubTabs tab={tab} onChange={setTab} />{tab === 'quota' ? <QuotaTabquota={quotaRead}diff --git a/ui/src/components/settings/models/chips.tsx b/ui/src/components/settings/models/chips.tsxindex 2893f3a20..5eb063f4f 100644--- a/ui/src/components/settings/models/chips.tsx+++ b/ui/src/components/settings/models/chips.tsx@@ -1,7 +1,7 @@// Small shared chips for the Model Hub rows — all built on the ui/Badge// primitive (reuse ladder) with size/width overrides. Kept in one place so the// 来源 and Agent bands stay visually consistent and the fixed-width chip-// columns (frame 01r) align across rows.+// columns (ui/design: models/page/overview) align across rows.import * as React from 'react';import { Hourglass, TriangleAlert, Unplug, Zap } from 'lucide-react';@@ -19,7 +19,7 @@ export const Dot: React.FC<{ accent: Accent; className?: string }> = ({ accent,/*** Source-row chip metrics. On phones the row's second tier has to fit billing +- * state + usage on ONE line (design.pen M01 m01SrcL2), so the chips shrink to+ * state + usage on ONE line (ui/design: models/page/overview-phone), so the chips shrink to* content-width pills — the desktop frame's fixed-width columns are what made* that line overflow. From sm+ the fixed widths come back so the chip columns* still align down the list, which is the whole point of them on a wide screen.@@ -53,8 +53,8 @@ export const BillingChip: React.FC<{* 暂不可用 / 需要处理 / 不可用 — nothing at all while the source is healthy.** A source that is serving normally (active / standby) draws NO chip in V6:- * health surfaces as an exception, not as a per-row label (design.pen 「产品改造- * V6 01」 — only the cooling relay carries one). Callers that reserve an aligned+ * health surfaces as an exception, not as a per-row label (ui/design:+ * models/page/takeover — only the cooling source carries one). Callers that reserve an aligned* column ask `isUnhealthy(state)` (supply.ts) to tell an empty cell from a* missing one.*/@@ -91,7 +91,7 @@ export const StateChip: React.FC<{ state: SourceState }> = ({ state }) => {/*** Managed / Direct — a fixed 104px column on desktop so the pills line up- * down the Agent list (V6 01), content-width beside the name on a phone (M01).+ * down the Agent list (ui/design: models/page/overview), content-width beside the name on a phone (models/page/overview-phone).** Direct carries the `unplug` glyph on mobile only: the desktop frame drops it* because the pill sits in a labelled column, while the mobile row has it inlinediff --git a/ui/src/components/settings/models/menus/MenuDrawer.tsx b/ui/src/components/settings/models/menus/MenuDrawer.tsxindex 15f1d91c8..47154d402 100644--- a/ui/src/components/settings/models/menus/MenuDrawer.tsx+++ b/ui/src/components/settings/models/menus/MenuDrawer.tsx@@ -1,11 +1,11 @@-// Shared sheet shell for the 模型菜单 drawers (frames 04 / 05r).+// Shared sheet shell for the 模型菜单 drawers.// Built directly on the Radix dialog primitive (already a dependency) rather// than the centered `ui/dialog` Dialog, because these surfaces need a custom// header (tinted icon tile + title + subtitle + close), a scrollable body, and a// sticky footer action bar.//// Desktop: slides in from the right edge, full height. Phones: a bottom sheet at-// ~91dvh (design.pen M03 m03Sheet, 730 of an 800 tall frame) — a right-edge+// ~91dvh (730 of an 800 tall phone) — a right-edge// drawer on a phone is a full-screen takeover that hides where you came from,// and the sheet keeps the page visible behind it.//diff --git a/ui/src/components/settings/models/modelHubStylePolicy.test.ts b/ui/src/components/settings/models/modelHubStylePolicy.test.tsindex 66a2daad3..03be6efe9 100644--- a/ui/src/components/settings/models/modelHubStylePolicy.test.ts+++ b/ui/src/components/settings/models/modelHubStylePolicy.test.ts@@ -204,12 +204,11 @@ describe('Model Hub visual token policy', () => {expect(literals).toEqual([]);});- // Every modal in `design.pen` whose frame carries an explicit height sits at- // exactly (viewport - dialog) / 2. This one is the file's single hug-height- // frame, so its 300px `y` is a round stand-in for the 332.5px its own- // head/body/foot measure to — and read as a literal `top` it held at the- // 1100px artboard and nowhere else, which is how the dialog came to sit near- // the bottom of an ordinary laptop viewport.+ // A modal with an explicit height sits at exactly (viewport - dialog) / 2.+ // The route dialog hugs its content, so a fixed 300px `y` was a round+ // stand-in for the 332.5px its own head/body/foot measure to — and read as a+ // literal `top` it held at an 1100px viewport and nowhere else, which is how+ // the dialog came to sit near the bottom of an ordinary laptop viewport.it('centres the route dialog and leaves it the room a centred box has', () => {const dialog = surfaceCssBody.match(/\.model-hub-route-dialog\s*\{([^}]*)\}/)?.[1] ?? '';const body = surfaceCssBody.match(/\.model-hub-route-body\s*\{([^}]*)\}/)?.[1] ?? '';diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex e5078fc1b..182418764 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -2,7 +2,7 @@** Every color resolves through a theme token, so the surface follows the app's* light/dark switch instead of assuming the dark frame it was drawn on. The base- * block carries design.pen's dark values; the two light blocks below mirror the+ * block carries the dark values; the two light blocks below mirror the* structure index.css uses ([data-theme="light"] for the explicit pick, the media* query for "system") and re-state only what cannot simply flip channel.*@@ -13,7 +13,7 @@* --muted, whose light value is already contrast-matched to its dark one.** Accent washes need no light branch: color-mix over --gold / --violet / --mint /- * --cyan / --destructive lands on design.pen's dark hex in dark mode and follows+ * --cyan / --destructive lands on the dark accent hex in dark mode and follows* the light accents on its own. Accent *inks* do need one, because an accent* dimmed toward transparency reads as "quiet" over black and "washed out" over* white; light re-anchors those on the full ink.@@ -85,7 +85,7 @@/* Danger and success roles, shared by the key dialog and the adopt drawer.* The danger ink mixes toward --foreground rather than transparency: that is- * what lifts dark --destructive-ink to design.pen's #ff8a8a and deepens the+ * what lifts dark --destructive-ink to #ff8a8a and deepens the* light one instead of fading it into the surface. */--model-hub-danger-ink: color-mix(in srgb, var(--destructive-ink) 80%, var(--foreground));--model-hub-danger-fill: color-mix(in srgb, var(--destructive) 7.8%, transparent);@@ -3893,7 +3893,7 @@ a.model-hub-order-price:hover { text-decoration: underline; }}.model-hub-picker-row--suppliers {- /* What a stacked row measures (frame B‴): the strip sits 4px under the name+ /* What a stacked row measures: the strip sits 4px under the name* it belongs to. The indent is not a length — the strip starts where the* entry does, which is already past the checkbox. */--model-hub-picker-stack-gap: 4px;diff --git a/ui/src/components/settings/models/modelHubSurfaceState.ts b/ui/src/components/settings/models/modelHubSurfaceState.tsindex 982f4a075..8609201d8 100644--- a/ui/src/components/settings/models/modelHubSurfaceState.ts+++ b/ui/src/components/settings/models/modelHubSurfaceState.ts@@ -15,7 +15,7 @@ export const modelsSurfaceKind = (agents: AgentSupply[], sources: Source[]): Mod? 'direct_empty': 'gateway';-/** Frame 09 has no region failure surface, so only two fresh reads may select it. */+/** The direct-only home (ui/design: models/page/direct) has no region failure surface, so only two fresh reads may select it. */export const modelsSurfaceKindFromReads = (agentsRead: RegionRead<AgentSupply[]>,sourcesRead: RegionRead<Source[]>,diff --git a/ui/src/components/settings/models/subscriptionOptions.ts b/ui/src/components/settings/models/subscriptionOptions.tsindex 23af0b1f1..e10fed685 100644--- a/ui/src/components/settings/models/subscriptionOptions.ts+++ b/ui/src/components/settings/models/subscriptionOptions.ts@@ -18,9 +18,9 @@// meant to need a decision here rather than to inherit one.import type { Source, SupplyChannel } from './types';-/** Menu order is frame 13's order: the two subscriptions the chooser has a+/** Menu order is the 添加订阅 menu's order: the two subscriptions the chooser has a* recommendation for, then the hub-held ones. It is not the engine table's order- * and not the API-key catalog's A–Z — nothing here sorts, the frame ranked them. */+ * and not the API-key catalog's A–Z — nothing here sorts, the menu ranks them. */export const SUBSCRIPTION_VENDORS = ['anthropic', 'openai', 'gemini', 'kimi', 'xai'] as const;export type SubscriptionVendor = (typeof SUBSCRIPTION_VENDORS)[number];@@ -41,7 +41,7 @@ const SUBSCRIPTION_CHOOSER = {openai: { copy: 'chatgpt', brand: 'ChatGPT' },} as const satisfies Record<string, { copy: SubscriptionVendorCopy; brand: string }>;-/** The copy family frame 04's chooser is written in, and the brand name its title+/** The copy family the chooser (ui/design: models/add-provider/claude) is written in, and the brand name its title* interpolates. `null` is the answer for a hub-held vendor, and it is the reason* this returns one: every line the chooser renders names a plan, a consequence of* a channel, or a ToS note, and a chooser rendered for a vendor with none of them@@ -89,8 +89,8 @@ export const subscriptionOptionOrder = (vendor: string): SupplyChannel[] =>/** Which channel the menu recommends, or `null` when the vendor has no native* channel to recommend against. A hub-held row carries no badge: 网关推荐 over the- * only custody there is recommends nothing, and frame 13 draws a badge because- * both of its rows had a choice to rank. */+ * only custody there is recommends nothing, and the menu draws a badge only where+ * a row has a choice to rank. */export const subscriptionMenuRecommendation = (vendor: SubscriptionVendor,): 'native' | 'gateway' | null => {diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex feb78a9e1..1846c54a6 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -1468,7 +1468,7 @@ export type SourceRepaired = {};/** POST /api/models/sources/<source_id>/models — appends a user-authored model- * entry to a Source inventory (frame 08). */+ * entry to a Source inventory. */export type CustomModelCreate = {model_id: string;display_name?: string | null;