Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(ui): Model Hub — Models settings page, sources & OAuth connect (L4) (#966)

Call White5bd5152f6f1d
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 5609813d2..67697d7e2 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -68,6 +68,12 @@ const LibraryAppBody = lazy(() => import('./apps/LibraryApp').then((m) => ({ def
const ShowPageRoute = lazy(() =>
import('./components/apps/ShowPageRoute').then((m) => ({ default: m.ShowPageRoute })),
);
+// Settings → Models (Model Hub, L4). Lazy so its code + framer-motion Reorder
+// stay out of the main entry — the surface is nav-gated until its backend
+// dependencies land (see models/featureFlags.ts).
+const SettingsModelsPage = lazy(() =>
+ import('./components/settings/models/SettingsModelsPage').then((m) => ({ default: m.SettingsModelsPage })),
+);
import { hasConfiguredPlatformCredentials } from './lib/platforms';
import { isIosDevice, isStandalonePwa } from './lib/platform';
import {
@@ -585,6 +591,14 @@ const router = createBrowserRouter(
<Route path="/admin/settings/backends/opencode" element={<SettingsOpencodeProviderPage />} />
<Route path="/admin/settings/backends/claude" element={<SettingsClaudeProviderPage />} />
<Route path="/admin/settings/backends/codex" element={<SettingsCodexProviderPage />} />
+ <Route
+ path="/admin/settings/models"
+ element={
+ <Suspense fallback={<AppsRouteFallback />}>
+ <SettingsModelsPage />
+ </Suspense>
+ }
+ />
<Route path="/admin/settings/dependencies" element={<SettingsDependenciesPage />} />
<Route path="/admin/settings/messaging" element={<SettingsMessagingPage />} />
<Route path="/admin/settings/diagnostics" element={<SettingsDiagnosticsPage />} />
@@ -608,6 +622,7 @@ const router = createBrowserRouter(
<Route path="/settings/backends/opencode" element={<Navigate to="/admin/settings/backends/opencode" replace />} />
<Route path="/settings/backends/claude" element={<Navigate to="/admin/settings/backends/claude" replace />} />
<Route path="/settings/backends/codex" element={<Navigate to="/admin/settings/backends/codex" replace />} />
+ <Route path="/settings/models" element={<Navigate to="/admin/settings/models" replace />} />
<Route path="/settings/dependencies" element={<Navigate to="/admin/settings/dependencies" replace />} />
<Route path="/settings/messaging" element={<Navigate to="/admin/settings/messaging" replace />} />
<Route path="/settings/diagnostics" element={<Navigate to="/admin/settings/diagnostics" replace />} />
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 633f68658..5fb254aea 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -1,9 +1,10 @@
import React, { useEffect, useState } from 'react';
import { Link, NavLink, Outlet, useLocation } from 'react-router-dom';
-import { ArrowLeft, Bot, ChevronDown, FolderTree, Globe, Grid2x2, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, PlugZap, Plus, Settings, Sparkles, X } from 'lucide-react';
+import { ArrowLeft, Bot, ChevronDown, Cpu, FolderTree, Globe, Grid2x2, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, PlugZap, Plus, Settings, Sparkles, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
+import { MODEL_HUB_NAV_ENABLED } from './settings/models/featureFlags';
import { useApi } from '../context/ApiContext';
import { useStatus } from '../context/StatusContext';
import { useWorkbenchInbox } from '../context/WorkbenchInboxContext';
@@ -298,6 +299,19 @@ export const AppShell: React.FC = () => {
{ to: '/admin/users', label: t('nav.users'), icon: MessageCircle },
],
},
+ // 模型 (Model Hub, L4): sits between 通讯平台 and 后端. Nav-gated until its
+ // backend dependencies land (MODEL_HUB_NAV_ENABLED); the route is always
+ // registered for direct access + review.
+ ...(MODEL_HUB_NAV_ENABLED
+ ? [
+ {
+ to: '/admin/settings/models',
+ label: t('nav.models'),
+ icon: Cpu,
+ match: (p: string) => p.startsWith('/admin/settings/models'),
+ },
+ ]
+ : []),
{
to: '/admin/settings/backends',
label: t('nav.backends'),
@@ -314,7 +328,8 @@ export const AppShell: React.FC = () => {
match: (p) =>
p.startsWith('/admin/settings') &&
!p.startsWith('/admin/settings/platforms') &&
- !p.startsWith('/admin/settings/backends'),
+ !p.startsWith('/admin/settings/backends') &&
+ !p.startsWith('/admin/settings/models'),
},
];
@@ -336,7 +351,8 @@ export const AppShell: React.FC = () => {
match: (p) =>
p.startsWith('/admin/settings') &&
!p.startsWith('/admin/settings/platforms') &&
- !p.startsWith('/admin/settings/backends'),
+ !p.startsWith('/admin/settings/backends') &&
+ !p.startsWith('/admin/settings/models'),
},
];
// The 更多 sheet shows the OVERFLOW — admin sections not already on the bottom
diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsx
index 07667e407..63822e0d5 100644
--- a/ui/src/components/settings/BackendOAuthPanel.tsx
+++ b/ui/src/components/settings/BackendOAuthPanel.tsx
@@ -1,11 +1,10 @@
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { AlertTriangle, CheckCircle2, Copy, ExternalLink, LogIn, Trash2, X } from 'lucide-react';
-import clsx from 'clsx';
+import { AlertTriangle, CheckCircle2, LogIn, Trash2, X } from 'lucide-react';
import { Button } from '../ui/button';
-import { Input } from '../ui/input';
import { Label } from '../ui/label';
+import { OAuthDeviceCodeRow, OAuthLinkRow, OAuthSubmitRow } from './oauth/OAuthFlowParts';
import { useApi } from '@/context/ApiContext';
import type { OAuthWebState } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
@@ -424,25 +423,11 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
<Label className="text-[11px] font-medium uppercase tracking-wide text-muted">
{t('settings.backends.oauthAuthUrlLabel')}
</Label>
- <div className="flex flex-wrap items-center gap-2">
- <a
- href={url}
- target="_blank"
- rel="noopener noreferrer"
- className={clsx(
- 'inline-flex max-w-full items-center gap-1.5 break-all rounded-md',
- 'bg-cyan-soft/40 px-2 py-1 font-mono text-[12px] text-cyan',
- 'transition-colors hover:bg-cyan-soft hover:text-cyan',
- )}
- >
- <ExternalLink className="size-3 shrink-0" />
- <span className="break-all">{url}</span>
- </a>
- <Button type="button" variant="secondary" size="xs" onClick={(e) => void copyUrl(e)}>
- <Copy className="size-3" />
- {t('common.copy')}
- </Button>
- </div>
+ <OAuthLinkRow
+ url={url}
+ onCopy={(e) => void copyUrl(e)}
+ copyLabel={t('common.copy') as string}
+ />
</div>
)}
@@ -451,15 +436,11 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
<Label className="text-[11px] font-medium uppercase tracking-wide text-muted">
{t('settings.backends.codexDeviceCodeLabel')}
</Label>
- <div className="flex flex-wrap items-center gap-2">
- <code className="rounded-md bg-cyan-soft/40 px-2.5 py-1 font-mono text-[14px] font-semibold tracking-[0.18em] text-cyan">
- {deviceCode}
- </code>
- <Button type="button" variant="secondary" size="xs" onClick={(e) => void copyDeviceCode(e)}>
- <Copy className="size-3" />
- {t('common.copy')}
- </Button>
- </div>
+ <OAuthDeviceCodeRow
+ code={deviceCode ?? ''}
+ onCopy={(e) => void copyDeviceCode(e)}
+ copyLabel={t('common.copy') as string}
+ />
<p className="text-[12px] leading-relaxed text-muted">
{t('settings.backends.codexDeviceInstructions')}
</p>
@@ -471,28 +452,16 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
<Label htmlFor={`oauth-code-${backend}`} className="text-xs font-medium uppercase text-muted">
{t('settings.backends.claudeCallbackCodeLabel')}
</Label>
- <div className="flex gap-2">
- <Input
- id={`oauth-code-${backend}`}
- type="text"
- autoComplete="off"
- spellCheck={false}
- placeholder={t('settings.backends.claudeCallbackCodePlaceholder') as string}
- value={code}
- onChange={(e) => setCode(e.target.value)}
- className="font-mono"
- disabled={submitting}
- />
- <Button
- type="button"
- variant="brand"
- size="sm"
- onClick={() => void submitCallback()}
- disabled={submitting || !code.trim()}
- >
- {submitting ? t('common.submitting') : t('common.submit')}
- </Button>
- </div>
+ <OAuthSubmitRow
+ id={`oauth-code-${backend}`}
+ value={code}
+ onChange={setCode}
+ onSubmit={() => void submitCallback()}
+ submitting={submitting}
+ placeholder={t('settings.backends.claudeCallbackCodePlaceholder') as string}
+ submitLabel={t('common.submit') as string}
+ submittingLabel={t('common.submitting') as string}
+ />
<p className="text-[12px] leading-relaxed text-muted">
{t('settings.backends.claudeCallbackCodeHint')}
</p>
@@ -504,28 +473,16 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
<Label htmlFor={`oauth-code-${backend}`} className="text-xs font-medium uppercase text-muted">
{t('settings.backends.opencodeCallbackUrlLabel')}
</Label>
- <div className="flex gap-2">
- <Input
- id={`oauth-code-${backend}`}
- type="text"
- autoComplete="off"
- spellCheck={false}
- placeholder="http://127.0.0.1:..../callback?code=..."
- value={code}
- onChange={(e) => setCode(e.target.value)}
- className="font-mono"
- disabled={submitting}
- />
- <Button
- type="button"
- variant="brand"
- size="sm"
- onClick={() => void submitCallback()}
- disabled={submitting || !code.trim()}
- >
- {submitting ? t('common.submitting') : t('common.submit')}
- </Button>
- </div>
+ <OAuthSubmitRow
+ id={`oauth-code-${backend}`}
+ value={code}
+ onChange={setCode}
+ onSubmit={() => void submitCallback()}
+ submitting={submitting}
+ placeholder="http://127.0.0.1:..../callback?code=..."
+ submitLabel={t('common.submit') as string}
+ submittingLabel={t('common.submitting') as string}
+ />
<p className="text-[12px] leading-relaxed text-muted">
{t('settings.backends.opencodeCallbackUrlHint')}
</p>
diff --git a/ui/src/components/settings/SettingsPageShell.tsx b/ui/src/components/settings/SettingsPageShell.tsx
index ed6f601ca..807390a32 100644
--- a/ui/src/components/settings/SettingsPageShell.tsx
+++ b/ui/src/components/settings/SettingsPageShell.tsx
@@ -9,7 +9,7 @@ import {
Stethoscope,
} from 'lucide-react';
-type SettingsTab = 'service' | 'platforms' | 'backends' | 'dependencies' | 'messaging' | 'diagnostics';
+type SettingsTab = 'service' | 'platforms' | 'backends' | 'models' | 'dependencies' | 'messaging' | 'diagnostics';
const TABS: Array<{
key: SettingsTab;
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsx
new file mode 100644
index 000000000..bdb747f04
--- /dev/null
+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx
@@ -0,0 +1,206 @@
+// 添加 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, Shield, 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 { Select } from '@/components/ui/select';
+import { cn } from '@/lib/utils';
+import { modelsApi } from './modelsApi';
+import { DEFAULT_VENDOR, VENDOR_OPTIONS } from './vendorMeta';
+import type { Source } from './types';
+
+type Phase = 'edit' | 'submitting' | 'done' | 'error';
+
+const FieldLabel: React.FC<{ mono?: boolean; children: React.ReactNode }> = ({ mono, children }) => (
+ <label
+ className={cn(
+ 'text-muted',
+ mono
+ ? 'font-mono text-[11px] font-medium uppercase tracking-wide'
+ : 'text-[12px] font-semibold text-foreground',
+ )}
+ >
+ {children}
+ </label>
+);
+
+const IconField: React.FC<{
+ icon: React.ComponentType<{ className?: string }>;
+ children: React.ReactNode;
+}> = ({ icon: Icon, children }) => (
+ <div className="relative">
+ <Icon className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />
+ {children}
+ </div>
+);
+
+export const AddApiKeyDialog: React.FC<{
+ open: boolean;
+ onClose: () => void;
+ onAdded: (source: Source) => void;
+}> = ({ open, onClose, onAdded }) => {
+ const { t } = useTranslation();
+ const [vendor, setVendor] = React.useState(DEFAULT_VENDOR.value);
+ const [apiKey, setApiKey] = React.useState('');
+ const [baseUrl, setBaseUrl] = React.useState('');
+ const [phase, setPhase] = React.useState<Phase>('edit');
+ const [discovered, setDiscovered] = React.useState(0);
+ 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.
+ React.useEffect(() => {
+ submitSeq.current += 1;
+ if (open) {
+ setVendor(DEFAULT_VENDOR.value);
+ setApiKey('');
+ setBaseUrl(DEFAULT_VENDOR.base_url ?? '');
+ setPhase('edit');
+ setDiscovered(0);
+ setError(null);
+ }
+ 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 ?? '');
+ };
+
+ const submit = async () => {
+ if (!apiKey.trim()) return;
+ const seq = submitSeq.current;
+ setPhase('submitting');
+ setError(null);
+ try {
+ const source = await modelsApi.createApiKeySource({
+ kind: 'api_key',
+ vendor,
+ base_url: baseUrl.trim() || null,
+ key: apiKey.trim(),
+ });
+ if (submitSeq.current !== seq) return; // dialog closed/reopened mid-request
+ setDiscovered(source.models.length);
+ setPhase('done');
+ onAdded(source);
+ closeTimer.current = window.setTimeout(onClose, 1500);
+ } catch (e: any) {
+ if (submitSeq.current !== seq) return;
+ setError(e?.code || e?.message || 'discovery_failed');
+ setPhase('error');
+ }
+ };
+
+ 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>
+
+ <div className="flex flex-col gap-2">
+ <FieldLabel>{t('settings.models.addKey.vendorLabel')}</FieldLabel>
+ <Select value={vendor} onChange={(e) => onVendorChange(e.target.value)} className="h-11 text-[14px]">
+ {VENDOR_OPTIONS.map((v) => (
+ <option key={v.value} value={v.value}>
+ {t(v.labelKey)}
+ </option>
+ ))}
+ </Select>
+ <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.addKey.vendorHint')}</p>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <FieldLabel mono>{t('settings.models.addKey.keyLabel')}</FieldLabel>
+ <IconField icon={KeyRound}>
+ <Input
+ type="password"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder="sk-…"
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ className="h-11 pl-9 font-mono text-[14px]"
+ disabled={phase === 'submitting' || phase === 'done'}
+ />
+ </IconField>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <FieldLabel mono>{t('settings.models.addKey.baseUrlLabel')}</FieldLabel>
+ <IconField icon={Globe}>
+ <Input
+ type="text"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder="https://api.example.com/v1"
+ value={baseUrl}
+ onChange={(e) => setBaseUrl(e.target.value)}
+ className="h-11 pl-9 font-mono text-[14px]"
+ disabled={phase === 'submitting' || phase === 'done'}
+ />
+ </IconField>
+ <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.addKey.baseUrlHint')}</p>
+ </div>
+
+ {phase === 'done' && (
+ <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">
+ <CheckCircle2 className="size-4 shrink-0" />
+ <span>{t('settings.models.addKey.discovered', { count: discovered })}</span>
+ </div>
+ )}
+ {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>
+ </div>
+ )}
+
+ <DialogFooter className="items-center sm:justify-between">
+ <span className="flex items-center gap-1.5 text-[12px] text-mint">
+ <Shield className="size-3.5" />
+ {t('settings.models.addKey.vaultNote')}
+ </span>
+ <div className="flex items-center gap-2">
+ <Button variant="outline" size="sm" onClick={onClose} disabled={phase === 'submitting'}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ variant="brand"
+ size="sm"
+ onClick={() => void submit()}
+ disabled={phase === 'submitting' || phase === 'done' || !apiKey.trim()}
+ >
+ <Plus className="size-4" />
+ {phase === 'submitting' ? t('settings.models.addKey.testing') : t('settings.models.addSource')}
+ </Button>
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/ui/src/components/settings/models/AddSourceMenu.tsx b/ui/src/components/settings/models/AddSourceMenu.tsx
new file mode 100644
index 000000000..1a1ac2278
--- /dev/null
+++ b/ui/src/components/settings/models/AddSourceMenu.tsx
@@ -0,0 +1,96 @@
+// 添加来源 dropdown (frame 07): three entries — connect Claude / ChatGPT
+// subscription (→ OAuth connect dialog) and add API Key (→ form dialog). No
+// type-chooser dialog; the menu IS the chooser.
+import * as React from 'react';
+import { ChevronRight, ExternalLink, KeyRound, Plus, Sparkles } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { cn } from '@/lib/utils';
+import { ACCENT_ICON, ACCENT_TILE } from './vendorMeta';
+
+type MenuItemProps = {
+ Icon: React.ComponentType<{ size?: number; className?: string }>;
+ accentTile: string;
+ accentIcon: string;
+ title: string;
+ subtitle: string;
+ Trailing: React.ComponentType<{ className?: string }>;
+ onClick: () => void;
+};
+
+const MenuItem: React.FC<MenuItemProps> = ({ Icon, accentTile, accentIcon, title, subtitle, Trailing, onClick }) => (
+ <button
+ type="button"
+ onClick={onClick}
+ className="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"
+ >
+ <span className={cn('flex size-10 shrink-0 items-center justify-center rounded-[10px]', accentTile)}>
+ <Icon size={20} className={accentIcon} />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-[14px] font-semibold text-foreground">{title}</span>
+ <span className="truncate text-[12px] text-muted">{subtitle}</span>
+ </span>
+ <Trailing className="size-4 shrink-0 text-muted" />
+ </button>
+);
+
+export const AddSourceMenu: React.FC<{
+ onConnectClaude: () => void;
+ onConnectChatGPT: () => void;
+ onAddApiKey: () => void;
+}> = ({ onConnectClaude, onConnectChatGPT, onAddApiKey }) => {
+ const { t } = useTranslation();
+ const [open, setOpen] = React.useState(false);
+
+ const pick = (fn: () => void) => () => {
+ setOpen(false);
+ fn();
+ };
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button variant="outline" size="sm" className="border-mint/40 bg-mint-soft/50 text-mint hover:bg-mint-soft">
+ <Plus className="size-4" />
+ {t('settings.models.addSource')}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="end"
+ sideOffset={8}
+ className="w-[360px] overflow-hidden border-border bg-card p-0 text-foreground shadow-lg"
+ >
+ <MenuItem
+ Icon={Sparkles}
+ accentTile={ACCENT_TILE.mint}
+ accentIcon={ACCENT_ICON.mint}
+ title={t('settings.models.addMenu.claude.title')}
+ subtitle={t('settings.models.addMenu.claude.subtitle')}
+ Trailing={ExternalLink}
+ onClick={pick(onConnectClaude)}
+ />
+ <MenuItem
+ Icon={Sparkles}
+ accentTile={ACCENT_TILE.gold}
+ accentIcon={ACCENT_ICON.gold}
+ title={t('settings.models.addMenu.chatgpt.title')}
+ subtitle={t('settings.models.addMenu.chatgpt.subtitle')}
+ Trailing={ExternalLink}
+ onClick={pick(onConnectChatGPT)}
+ />
+ <MenuItem
+ Icon={KeyRound}
+ accentTile={ACCENT_TILE.violet}
+ accentIcon={ACCENT_ICON.violet}
+ title={t('settings.models.addMenu.apiKey.title')}
+ subtitle={t('settings.models.addMenu.apiKey.subtitle')}
+ Trailing={ChevronRight}
+ onClick={pick(onAddApiKey)}
+ />
+ </PopoverContent>
+ </Popover>
+ );
+};
diff --git a/ui/src/components/settings/models/AdvancedRow.tsx b/ui/src/components/settings/models/AdvancedRow.tsx
new file mode 100644
index 000000000..2af84beab
--- /dev/null
+++ b/ui/src/components/settings/models/AdvancedRow.tsx
@@ -0,0 +1,28 @@
+// The single 高级 placeholder row (frame 01r): cross-vendor auto-substitution
+// (default-off) · request log · diagnostics. The detail surfaces are future
+// work; the row explains itself until they land.
+import * as React from 'react';
+import { ChevronRight, SlidersHorizontal } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { useToast } from '@/context/ToastContext';
+
+export const AdvancedRow: React.FC = () => {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+
+ return (
+ <button
+ type="button"
+ onClick={() => showToast(t('settings.models.advanced.comingSoon') as string, 'warning')}
+ className="flex w-full items-center gap-3 rounded-xl border border-border bg-background px-5 py-4 text-left transition-colors hover:border-border-strong"
+ >
+ <SlidersHorizontal className="size-4 shrink-0 text-muted" />
+ <span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5">
+ <span className="text-[14px] font-medium text-foreground">{t('settings.models.advanced.title')}</span>
+ <span className="text-[12px] text-muted">{t('settings.models.advanced.detail')}</span>
+ </span>
+ <ChevronRight className="size-4 shrink-0 text-muted" />
+ </button>
+ );
+};
diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsx
new file mode 100644
index 000000000..cfbdcc98f
--- /dev/null
+++ b/ui/src/components/settings/models/AgentCard.tsx
@@ -0,0 +1,133 @@
+// The Agent band (frame 01r): one row per backend — icon + name + menu-kind
+// badge, the current supply as a composite pill (hub only), the supply-mode
+// chip, and the row action (模型菜单 for hub / 接入中枢 for direct). 模型菜单
+// links into L5's drawers; until L5 lands (MODEL_MENUS_ENABLED) it explains
+// itself rather than opening a missing surface.
+import * as React from 'react';
+import { Link } from 'react-router-dom';
+import { ArrowDownToLine, ArrowRight, ChevronRight } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { cn } from '@/lib/utils';
+import { useToast } from '@/context/ToastContext';
+import { CompositePill, MenuKindBadge, ModeChip } from './chips';
+import { ACCENT_ICON, ACCENT_TILE, backendVisual, sourceAccent } from './vendorMeta';
+import { friendlyModelName } from './format';
+import { MODEL_MENUS_ENABLED } from './featureFlags';
+import type { AgentSupply, Source } from './types';
+
+const AgentRow: React.FC<{
+ agent: AgentSupply;
+ sources: Source[];
+ onConnectHub: (agent: AgentSupply) => void;
+ connecting: boolean;
+}> = ({ agent, sources, onConnectHub, connecting }) => {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+ const { Icon, accent } = backendVisual(agent.backend);
+
+ const openMenu = () => {
+ if (!MODEL_MENUS_ENABLED) {
+ showToast(t('settings.models.agents.menuComingSoon') as string, 'warning');
+ return;
+ }
+ // L5 owns the mapping / menu drawers; wired when MODEL_MENUS_ENABLED flips.
+ };
+
+ // Composite pill content. Fixed-menu → model | source; open-menu → count |
+ // multi-source (+ custom count).
+ let pill: React.ReactNode = null;
+ if (agent.mode === 'hub' && agent.current) {
+ if (agent.menu_kind === 'open' && agent.menu) {
+ const customCount = sources.reduce(
+ (n, s) => n + s.models.filter((m) => m.provenance === 'manual').length,
+ 0,
+ );
+ const right =
+ customCount > 0
+ ? (t('settings.models.agents.multiSourceCustom', { count: customCount }) as string)
+ : (t('settings.models.agents.multiSource') as string);
+ pill = <CompositePill left={t('settings.models.agents.modelCount', { count: agent.menu.checked.length }) as string} dot={accent} right={right} />;
+ } else {
+ const source = sources.find((s) => s.id === agent.current?.source_id);
+ pill = (
+ <CompositePill
+ left={friendlyModelName(agent, sources)}
+ dot={source ? sourceAccent(source) : accent}
+ right={source?.display_name ?? agent.current.source_id}
+ />
+ );
+ }
+ }
+
+ return (
+ <div className="flex items-center gap-4 border-b border-border px-5 py-4 last:border-b-0">
+ <span className={cn('flex size-11 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>
+ <Icon size={22} className={ACCENT_ICON[accent]} />
+ </span>
+
+ <div className="flex min-w-0 flex-1 flex-col items-start gap-2">
+ <div className="flex items-center gap-2">
+ <span className="text-[15px] font-semibold text-foreground">
+ {t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}
+ </span>
+ <MenuKindBadge kind={agent.menu_kind} />
+ </div>
+ {pill}
+ </div>
+
+ <div className="flex shrink-0 items-center gap-2.5">
+ <ModeChip mode={agent.mode} />
+ {agent.mode === 'hub' ? (
+ <Button variant="secondary" size="sm" onClick={openMenu}>
+ {t('settings.models.agents.modelMenu')}
+ <ChevronRight className="size-3.5" />
+ </Button>
+ ) : (
+ <Button variant="brand" size="sm" onClick={() => onConnectHub(agent)} disabled={connecting}>
+ <ArrowDownToLine className="size-3.5" />
+ {t('settings.models.agents.connectHub')}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export const AgentCard: React.FC<{
+ agents: AgentSupply[];
+ sources: Source[];
+ onConnectHub: (agent: AgentSupply) => void;
+ connectingBackend: string | null;
+}> = ({ agents, sources, onConnectHub, connectingBackend }) => {
+ const { t } = useTranslation();
+ return (
+ <section className="rounded-xl border border-border bg-background">
+ <div className="flex items-start justify-between gap-4 border-b border-border px-5 py-4">
+ <div className="flex min-w-0 flex-col gap-1">
+ <h2 className="text-[15px] font-semibold text-foreground">{t('settings.models.agents.title')}</h2>
+ <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.agents.subtitle')}</p>
+ </div>
+ <Link
+ to="/admin/settings/backends"
+ className="inline-flex shrink-0 items-center gap-1 text-[13px] font-medium text-mint transition-colors hover:text-mint/80"
+ >
+ {t('settings.models.agents.backendSettings')}
+ <ArrowRight className="size-3.5" />
+ </Link>
+ </div>
+ <div className="flex flex-col">
+ {agents.map((agent) => (
+ <AgentRow
+ key={agent.backend}
+ agent={agent}
+ sources={sources}
+ onConnectHub={onConnectHub}
+ connecting={connectingBackend === agent.backend}
+ />
+ ))}
+ </div>
+ </section>
+ );
+};
diff --git a/ui/src/components/settings/models/ExperimentalConsentDialog.tsx b/ui/src/components/settings/models/ExperimentalConsentDialog.tsx
new file mode 100644
index 000000000..4b2fef971
--- /dev/null
+++ b/ui/src/components/settings/models/ExperimentalConsentDialog.tsx
@@ -0,0 +1,61 @@
+// 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/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsx
new file mode 100644
index 000000000..cde36fa1b
--- /dev/null
+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx
@@ -0,0 +1,337 @@
+// 连接订阅 dialog (frame 09). 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
+// / OAuthSubmitRow) so it matches the Backends OAuth panel. State machine
+// mirrors BackendOAuthPanel: start → 2s poll → verifying → success, 15-min
+// timeout, cancel.
+import * as React from 'react';
+import { CheckCircle2, Sparkles, TriangleAlert } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
+import { cn } from '@/lib/utils';
+import { useToast } from '@/context/ToastContext';
+import { OAuthDeviceCodeRow, OAuthLinkRow, OAuthSubmitRow } from '../oauth/OAuthFlowParts';
+import { ExperimentalConsentDialog } from './ExperimentalConsentDialog';
+import { SUBSCRIPTION_HUB_EXPERIMENTAL } from './featureFlags';
+import { modelsApi } from './modelsApi';
+import { ACCENT_ICON, ACCENT_TILE } from './vendorMeta';
+import type { OAuthFlow, SupplyChannel } from './types';
+
+const POLL_MS = 2000;
+const DEADLINE_MS = 16 * 60 * 1000;
+const TERMINAL = ['success', 'failed', 'cancelled'];
+
+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">
+ <span className="font-mono text-muted">{n} · </span>
+ {label}
+ </span>
+ {children}
+ </div>
+);
+
+export const OAuthConnectDialog: React.FC<{
+ open: boolean;
+ /** 'anthropic' (Claude) | 'openai' (ChatGPT) | any future subscription vendor. */
+ vendor: string;
+ onClose: () => void;
+ onConnected: () => void;
+}> = ({ open, vendor, onClose, onConnected }) => {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+
+ const [flow, setFlow] = React.useState<OAuthFlow | null>(null);
+ const [code, setCode] = React.useState('');
+ const [submitting, setSubmitting] = React.useState(false);
+ const [errorKey, setErrorKey] = React.useState<string | null>(null);
+ const [channel, setChannel] = React.useState<SupplyChannel>('native_cli');
+ const [consentOpen, setConsentOpen] = React.useState(false);
+ const [, tick] = React.useReducer((x) => x + 1, 0);
+
+ const flowRef = React.useRef<OAuthFlow | null>(null);
+ const successTimer = React.useRef<number | null>(null);
+ const onConnectedRef = React.useRef(onConnected);
+ onConnectedRef.current = onConnected;
+ const onCloseRef = React.useRef(onClose);
+ onCloseRef.current = onClose;
+
+ const accent = vendor === 'openai' ? 'gold' : 'mint';
+
+ const copy = (text: string | null | undefined) => (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (!text) return;
+ // navigator.clipboard is undefined in non-secure contexts / older browsers;
+ // touching .writeText there throws synchronously, not as a rejected promise.
+ if (!navigator.clipboard?.writeText) {
+ showToast(t('common.copyFailed') as string, 'error');
+ return;
+ }
+ navigator.clipboard
+ .writeText(text)
+ .then(() => showToast(t('common.copied') as string, 'success'))
+ .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).
+ React.useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ let pollTimer: number | null = null;
+ let deadline = Date.now() + DEADLINE_MS;
+
+ const stop = () => {
+ if (pollTimer !== null) window.clearTimeout(pollTimer);
+ pollTimer = null;
+ };
+ const apply = (f: OAuthFlow | null) => {
+ flowRef.current = f;
+ setFlow(f);
+ };
+
+ const poll = async (flowId: string) => {
+ if (cancelled) return;
+ if (Date.now() > deadline) {
+ setErrorKey('settings.models.oauth.error.timeout');
+ if (flowRef.current) apply({ ...flowRef.current, state: 'failed' });
+ return;
+ }
+ try {
+ const next = await modelsApi.getOAuthStatus(flowId);
+ if (cancelled) return;
+ apply(next);
+ if (next.state === 'success') {
+ showToast(t('settings.models.oauth.status.success') as string, 'success');
+ onConnectedRef.current();
+ successTimer.current = window.setTimeout(() => onCloseRef.current(), 1400);
+ return;
+ }
+ if (next.state === 'failed' || next.state === 'cancelled') {
+ setErrorKey(next.error_key ?? 'settings.models.oauth.error.generic');
+ return;
+ }
+ pollTimer = window.setTimeout(() => void poll(flowId), POLL_MS);
+ } catch {
+ if (!cancelled) setErrorKey('settings.models.oauth.error.generic');
+ }
+ };
+
+ // Clear any stale flow from a prior open so the previous success/failure
+ // isn't shown while the new startOAuth request is in flight.
+ apply(null);
+ setErrorKey(null);
+ setCode('');
+ setSubmitting(false);
+ void (async () => {
+ try {
+ const started = await modelsApi.startOAuth(vendor, channel);
+ if (cancelled) return;
+ apply(started);
+ if (started.expires_at) deadline = new Date(started.expires_at).getTime() + 60_000;
+ pollTimer = window.setTimeout(() => void poll(started.flow_id), POLL_MS);
+ } catch {
+ if (!cancelled) setErrorKey('settings.models.oauth.error.start');
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ stop();
+ if (successTimer.current !== null) window.clearTimeout(successTimer.current);
+ const cur = flowRef.current;
+ if (cur && !TERMINAL.includes(cur.state)) modelsApi.cancelOAuth(cur.flow_id).catch(() => {});
+ flowRef.current = null;
+ };
+ }, [open, vendor, channel, t, showToast]);
+
+ // 1-second ticker so the paste-flow countdown updates.
+ React.useEffect(() => {
+ if (!open) return;
+ const id = window.setInterval(() => tick(), 1000);
+ 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 cur = flowRef.current;
+ if (!cur || !code.trim()) return;
+ setSubmitting(true);
+ try {
+ const next = await modelsApi.submitOAuth(cur.flow_id, code.trim());
+ // Drop the response if the dialog closed or a new flow started meanwhile.
+ if (flowRef.current?.flow_id !== cur.flow_id) return;
+ flowRef.current = next;
+ setFlow(next);
+ } catch {
+ if (flowRef.current?.flow_id !== cur.flow_id) return;
+ setErrorKey('settings.models.oauth.error.generic');
+ } finally {
+ if (flowRef.current?.flow_id === cur.flow_id) setSubmitting(false);
+ }
+ };
+
+ const presentation = flow?.presentation;
+ const expects = presentation?.expects;
+ const isDevice = expects === 'none';
+ const state = flow?.state;
+ const success = state === 'success';
+ const failed = state === 'failed' || state === 'cancelled' || Boolean(errorKey);
+ const active = !success && !failed;
+
+ const remainingMs = flow?.expires_at ? Math.max(0, new Date(flow.expires_at).getTime() - Date.now()) : null;
+ const mmss =
+ remainingMs !== null
+ ? `${String(Math.floor(remainingMs / 60000)).padStart(2, '0')}:${String(Math.floor((remainingMs % 60000) / 1000)).padStart(2, '0')}`
+ : '';
+
+ const step2Label = presentation?.instructions_key
+ ? (t(presentation.instructions_key) as string)
+ : isDevice
+ ? (t('settings.models.oauth.deviceCode.hint') as string)
+ : expects === 'paste_callback_url'
+ ? (t('settings.models.oauth.callback.hint') as string)
+ : (t('settings.models.oauth.pasteCode.hint') as string);
+
+ return (
+ <>
+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
+ <DialogContent className="max-w-[520px] gap-5">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2.5 text-[17px] font-bold">
+ <span className={cn('grid size-8 shrink-0 place-items-center rounded-lg', ACCENT_TILE[accent])}>
+ <Sparkles className={cn('size-4', ACCENT_ICON[accent])} />
+ </span>
+ {t(`settings.models.oauth.title.${vendor}`, {
+ defaultValue: t('settings.models.oauth.title.generic') as string,
+ })}
+ </DialogTitle>
+ </DialogHeader>
+
+ {failed && (
+ <div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive">
+ <TriangleAlert className="mt-0.5 size-4 shrink-0" />
+ <span>{t(errorKey ?? 'settings.models.oauth.error.generic')}</span>
+ </div>
+ )}
+
+ {success ? (
+ <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">
+ <CheckCircle2 className="size-4 shrink-0" />
+ {t('settings.models.oauth.connected')}
+ </div>
+ ) : (
+ active && (
+ <div className="flex flex-col gap-3">
+ <Step
+ n={1}
+ label={
+ isDevice
+ ? (t('settings.models.oauth.step1.devicePage') as string)
+ : (t('settings.models.oauth.step1.authLink') as string)
+ }
+ >
+ {presentation?.auth_url ? (
+ <OAuthLinkRow
+ url={presentation.auth_url}
+ onCopy={copy(presentation.auth_url)}
+ copyLabel={t('common.copy') as string}
+ />
+ ) : (
+ <p className="text-[12px] text-muted">{t('settings.models.oauth.starting')}</p>
+ )}
+ </Step>
+
+ <Step n={2} label={step2Label}>
+ {isDevice ? (
+ <OAuthDeviceCodeRow
+ code={presentation?.device_code ?? ''}
+ onCopy={copy(presentation?.device_code)}
+ copyLabel={t('common.copy') as string}
+ />
+ ) : (
+ <OAuthSubmitRow
+ value={code}
+ onChange={setCode}
+ onSubmit={() => void submit()}
+ submitting={submitting || state === 'verifying'}
+ placeholder={
+ expects === 'paste_callback_url' ? 'http://127.0.0.1:.../callback?code=…' : 'ac_…#st_…'
+ }
+ submitLabel={t('common.submit') as string}
+ submittingLabel={t('common.submitting') as string}
+ />
+ )}
+ </Step>
+
+ {SUBSCRIPTION_HUB_EXPERIMENTAL && (
+ <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>
+ )
+ )}
+
+ <div className="flex items-center justify-between gap-3 border-t border-border pt-4">
+ {active ? (
+ <span className="flex items-center gap-2 text-[12px] text-muted">
+ <span className="size-2 shrink-0 rounded-full bg-gold" aria-hidden />
+ {state === 'verifying'
+ ? t('settings.models.oauth.status.verifying')
+ : isDevice
+ ? t('settings.models.oauth.status.awaitingDevice')
+ : t('settings.models.oauth.status.awaitingPaste', { time: mmss })}
+ </span>
+ ) : (
+ <span />
+ )}
+ <Button variant={active ? 'ghost' : 'outline'} size="sm" onClick={onClose}>
+ {active ? t('common.cancel') : t('common.close')}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ <ExperimentalConsentDialog
+ open={consentOpen}
+ onConsent={() => {
+ setConsentOpen(false);
+ setChannel('hub');
+ }}
+ onCancel={() => setConsentOpen(false)}
+ />
+ </>
+ );
+};
diff --git a/ui/src/components/settings/models/RecentSwitchesCard.tsx b/ui/src/components/settings/models/RecentSwitchesCard.tsx
new file mode 100644
index 000000000..523099ac7
--- /dev/null
+++ b/ui/src/components/settings/models/RecentSwitchesCard.tsx
@@ -0,0 +1,78 @@
+// 最近切换 — the human-readable resolution-event feed (frame 01r). Shows the
+// three most recent by default; 查看全部 expands to the full fetched set. Text
+// uses the locale-matched human_zh / human_en the adapter already produced.
+import * as React from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { Dot } from './chips';
+import type { Accent } from './vendorMeta';
+import type { ResolutionEvent } from './types';
+
+const COLLAPSED = 3;
+
+function eventAccent(e: ResolutionEvent): Accent {
+ if (e.billing_note === 'entered_metered') return 'gold';
+ if (e.kind === 'recover' || e.reason === 'recovery') return 'mint';
+ if (e.kind === 'cooldown' || e.kind === 'skip') return 'muted';
+ return 'cyan';
+}
+
+function useEventTime() {
+ const { t } = useTranslation();
+ return (ts: string): string => {
+ const d = new Date(ts);
+ 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);
+ 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;
+ 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 }) => {
+ const { t, i18n } = useTranslation();
+ const [expanded, setExpanded] = React.useState(false);
+ const formatTime = useEventTime();
+ const zh = i18n.language.startsWith('zh');
+
+ const shown = expanded ? events : events.slice(0, COLLAPSED);
+ const canExpand = events.length > COLLAPSED;
+
+ return (
+ <section className="rounded-xl border border-border bg-background">
+ <div className="flex items-center justify-between gap-4 border-b border-border px-5 py-4">
+ <h2 className="text-[15px] font-semibold text-foreground">{t('settings.models.recent.title')}</h2>
+ {canExpand && (
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ className="text-[13px] font-medium text-mint transition-colors hover:text-mint/80"
+ >
+ {expanded ? t('settings.models.recent.collapse') : t('settings.models.recent.viewAll')}
+ </button>
+ )}
+ </div>
+ {shown.length === 0 ? (
+ <div className="px-5 py-8 text-center text-[13px] text-muted">{t('settings.models.recent.empty')}</div>
+ ) : (
+ <div className="flex flex-col">
+ {shown.map((event) => (
+ <div key={event.id} className="flex items-start gap-3 border-b border-border px-5 py-3 last:border-b-0">
+ <span className="w-[92px] shrink-0 pt-0.5 font-mono text-[12px] text-muted">{formatTime(event.ts)}</span>
+ <Dot accent={eventAccent(event)} className="mt-[7px]" />
+ <span className="min-w-0 flex-1 text-[13px] leading-relaxed text-foreground">
+ {zh ? event.human_zh : event.human_en}
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+ );
+};
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
new file mode 100644
index 000000000..477f1843d
--- /dev/null
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -0,0 +1,189 @@
+// 设置 · 模型 — the Model Hub main page (design.pen 产品改造 V4 01r). Owns data
+// fetching + the ordered source list; composes the 来源 band, Agent band,
+// 最近切换 feed, and the 高级 row, plus the add-source dialogs. Talks to the hub
+// through modelsApi (mock fixtures until L2's REST API is live — see
+// featureFlags.ts).
+import * as React from 'react';
+import { CheckCircle2, TriangleAlert } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Badge } from '@/components/ui/badge';
+import { useToast } from '@/context/ToastContext';
+import { SettingsPageShell } from '../SettingsPageShell';
+import { SourcesCard } from './SourcesCard';
+import { AgentCard } from './AgentCard';
+import { RecentSwitchesCard } from './RecentSwitchesCard';
+import { AdvancedRow } from './AdvancedRow';
+import { AddApiKeyDialog } from './AddApiKeyDialog';
+import { OAuthConnectDialog } from './OAuthConnectDialog';
+import { modelsApi } from './modelsApi';
+import type { AgentSupply, ResolutionEvent, RuntimeDependency, Source } from './types';
+
+const StatusPill: React.FC<{ healthy: boolean; hubCount: number }> = ({ healthy, hubCount }) => {
+ const { t } = useTranslation();
+ return healthy ? (
+ <Badge variant="success" className="gap-1.5 rounded-full px-3 py-1.5 text-[12px]">
+ <CheckCircle2 className="size-3.5" />
+ {t('settings.models.statusPill.ok', { count: hubCount })}
+ </Badge>
+ ) : (
+ <Badge variant="warning" className="gap-1.5 rounded-full px-3 py-1.5 text-[12px]">
+ <TriangleAlert className="size-3.5" />
+ {t('settings.models.statusPill.degraded', { count: hubCount })}
+ </Badge>
+ );
+};
+
+export const SettingsModelsPage: React.FC = () => {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+
+ const [sources, setSources] = React.useState<Source[]>([]);
+ const [agents, setAgents] = React.useState<AgentSupply[]>([]);
+ const [events, setEvents] = React.useState<ResolutionEvent[]>([]);
+ const [runtime, setRuntime] = React.useState<RuntimeDependency | null>(null);
+ const [loading, setLoading] = React.useState(true);
+ const [loadError, setLoadError] = React.useState<string | null>(null);
+ const [connecting, setConnecting] = React.useState<string | null>(null);
+
+ const [apiKeyOpen, setApiKeyOpen] = React.useState(false);
+ const [oauthVendor, setOauthVendor] = React.useState<string | null>(null);
+
+ // Mirror the latest ordered sources for reorder-commit (drag end reads the
+ // freshest order without threading it through the framer callback).
+ const sourcesRef = React.useRef<Source[]>(sources);
+ sourcesRef.current = sources;
+ // Bumped per reorder-commit so an out-of-order PUT /priority response from a
+ // superseded drag can't overwrite the newest order.
+ const reorderSeq = React.useRef(0);
+ // Guards event-handler async writes (refresh / connect) from landing after
+ // the page unmounts — the whole class of stale-async writes the review flagged.
+ const aliveRef = React.useRef(true);
+ React.useEffect(() => () => {
+ aliveRef.current = false;
+ }, []);
+
+ React.useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ Promise.all([modelsApi.listSources(), modelsApi.listAgents(), modelsApi.listEvents(20), modelsApi.getRuntimeStatus()])
+ .then(([s, a, e, r]) => {
+ if (cancelled) return;
+ setSources(s);
+ setAgents(a);
+ setEvents(e);
+ setRuntime(r);
+ setLoading(false);
+ })
+ .catch((err) => {
+ if (cancelled) return;
+ setLoadError(err?.code || err?.message || 'load_failed');
+ setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const refreshSourcesAgents = React.useCallback(async () => {
+ try {
+ const [s, a] = await Promise.all([modelsApi.listSources(), modelsApi.listAgents()]);
+ if (!aliveRef.current) return;
+ setSources(s);
+ setAgents(a);
+ } catch {
+ // A mutation may have succeeded server-side but the re-read failed — tell
+ // the user the view might be stale rather than silently swallowing it.
+ if (aliveRef.current) showToast(t('settings.models.toast.refreshFailed') as string, 'error');
+ }
+ }, [showToast, t]);
+
+ const reorderPreview = (ids: string[]) => {
+ setSources((prev) => {
+ const byId = new Map(prev.map((s) => [s.id, s]));
+ return ids.map((id) => byId.get(id)).filter((s): s is Source => Boolean(s));
+ });
+ };
+
+ const reorderCommit = () => {
+ const seq = ++reorderSeq.current;
+ const order = sourcesRef.current.map((s) => s.id);
+ modelsApi
+ .putPriority(order)
+ .then((priority) => {
+ if (reorderSeq.current !== seq) return; // superseded by a newer reorder
+ // Re-echo the server's authoritative order.
+ setSources((prev) => {
+ const byId = new Map(prev.map((s) => [s.id, s]));
+ return priority.order.map((id) => byId.get(id)).filter((s): s is Source => Boolean(s));
+ });
+ })
+ .catch(() => {
+ if (reorderSeq.current !== seq) return;
+ showToast(t('settings.models.toast.reorderFailed') as string, 'error');
+ // The optimistic preview order diverged from the server; re-fetch so the
+ // list reflects the persisted (unchanged) order rather than a phantom one.
+ void refreshSourcesAgents();
+ });
+ };
+
+ const connectHub = async (agent: AgentSupply) => {
+ setConnecting(agent.backend);
+ try {
+ await modelsApi.setAgentMode(agent.backend, 'hub');
+ await refreshSourcesAgents();
+ if (aliveRef.current) 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 hubCount = agents.filter((a) => a.mode === 'hub').length;
+ // Only a fully-ok runtime + no errored source is "一切正常"; degraded / down /
+ // not_installed / unknown all warrant the warning pill.
+ const healthy = runtime?.status.health === 'ok' && !sources.some((s) => s.state.status === 'error');
+
+ return (
+ <SettingsPageShell
+ activeTab="models"
+ title={t('settings.models.title')}
+ subtitle={t('settings.models.subtitle')}
+ actions={!loading && !loadError ? <StatusPill healthy={healthy} hubCount={hubCount} /> : 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">
+ <SourcesCard
+ sources={sources}
+ onReorderPreview={reorderPreview}
+ onReorderCommit={reorderCommit}
+ onConnectClaude={() => setOauthVendor('anthropic')}
+ onConnectChatGPT={() => setOauthVendor('openai')}
+ onAddApiKey={() => setApiKeyOpen(true)}
+ />
+ <AgentCard agents={agents} sources={sources} onConnectHub={connectHub} connectingBackend={connecting} />
+ <RecentSwitchesCard events={events} />
+ <AdvancedRow />
+ </div>
+ )}
+
+ <AddApiKeyDialog open={apiKeyOpen} onClose={() => setApiKeyOpen(false)} onAdded={() => void refreshSourcesAgents()} />
+ <OAuthConnectDialog
+ open={oauthVendor !== null}
+ vendor={oauthVendor ?? 'anthropic'}
+ onClose={() => setOauthVendor(null)}
+ onConnected={() => void refreshSourcesAgents()}
+ />
+ </SettingsPageShell>
+ );
+};
+
+export default SettingsModelsPage;
diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsx
new file mode 100644
index 000000000..c4f082829
--- /dev/null
+++ b/ui/src/components/settings/models/SourceRow.tsx
@@ -0,0 +1,118 @@
+// One row of the 来源 list (frame 01r): drag handle · priority number · icon +
+// name/mono-sub (supply tooltip on hover) · fixed-width usage column · billing
+// chip · state chip. Presentation-only; drag + reorder live in SourcesCard.
+import * as React from 'react';
+import { GripVertical } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { cn } from '@/lib/utils';
+import { BillingChip, ExperimentalChip, StateChip } from './chips';
+import { SupplyTooltip } from './SupplyTooltip';
+import { ACCENT_ICON, ACCENT_TILE, VENDOR_OPTIONS, sourceVisual } from './vendorMeta';
+import { cooldownEtaMinutes, formatSpend } from './format';
+import type { Source } from './types';
+
+// 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.
+function isCustomEndpoint(source: Source): boolean {
+ if (!source.base_url) return false;
+ const official = VENDOR_OPTIONS.find((v) => v.value === source.vendor)?.base_url ?? null;
+ return source.base_url !== official;
+}
+
+// The mono sub-line shows the source identity: account_label (subscriptions)
+// or masked_credential (api keys) — both server-provided display data (contract
+// v1.1, 07-23, from the L4 finding). Falls back to the supply channel / endpoint
+// (原生供给 / 中枢托管 / 官方地址 / 自定义地址) when neither is set, e.g. hub-held
+// experimental sources before a later adapter rev. Cooldown ETA is appended.
+function useSubline(source: Source): string {
+ const { t } = useTranslation();
+
+ const fallback =
+ source.kind === 'subscription'
+ ? source.supply_channel === 'native_cli'
+ ? (t('settings.models.source.nativeSupply') as string)
+ : (t('settings.models.source.hubHosted') as string)
+ : isCustomEndpoint(source)
+ ? (t('settings.models.source.customEndpoint') as string)
+ : (t('settings.models.source.officialEndpoint') as string);
+
+ const parts = [source.account_label ?? source.masked_credential ?? fallback];
+ if (source.state.status === 'cooldown') {
+ parts.push(t('settings.models.source.retryIn', { minutes: cooldownEtaMinutes(source.state.retry_at) }) as string);
+ }
+ return parts.join(' · ');
+}
+
+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') {
+ return (
+ <div className="flex w-[150px] shrink-0 items-center justify-end gap-2">
+ <div className="h-1.5 w-[92px] overflow-hidden rounded-full bg-border">
+ <div className="h-full rounded-full bg-mint" style={{ width: `${Math.min(100, Math.max(0, pct))}%` }} />
+ </div>
+ <span className="w-9 text-right font-mono text-[12px] text-muted">{Math.round(pct)}%</span>
+ </div>
+ );
+ }
+ if (typeof spend === 'number') {
+ return (
+ <div className="w-[150px] shrink-0 text-right text-[12px] text-muted">
+ {t('settings.models.usage.monthSpend', { amount: formatSpend(spend, source.usage?.currency) })}
+ </div>
+ );
+ }
+ return <div className="w-[150px] shrink-0" />;
+};
+
+export const SourceRow: React.FC<{
+ source: Source;
+ priority: number;
+ onDragHandlePointerDown: (e: React.PointerEvent) => void;
+}> = ({ source, priority, onDragHandlePointerDown }) => {
+ const { t } = useTranslation();
+ const { Icon, accent } = sourceVisual(source);
+ const subline = useSubline(source);
+ const isExperimental = source.kind === 'subscription' && source.supply_channel === 'hub';
+
+ return (
+ <div className="flex items-center gap-3 border-b border-border px-5 py-3.5 last:border-b-0">
+ <button
+ type="button"
+ aria-label={t('settings.models.source.reorder') as string}
+ onPointerDown={onDragHandlePointerDown}
+ className="flex size-6 shrink-0 cursor-grab touch-none items-center justify-center rounded text-muted/50 transition-colors hover:text-muted active:cursor-grabbing"
+ >
+ <GripVertical className="size-4" />
+ </button>
+
+ <span className="grid size-7 shrink-0 place-items-center rounded-md border border-border bg-surface font-mono text-[13px] text-muted">
+ {priority}
+ </span>
+
+ <SupplyTooltip models={source.models} className="flex min-w-0 flex-1 items-center gap-3">
+ <span className={cn('flex size-11 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>
+ <Icon size={22} className={ACCENT_ICON[accent]} />
+ </span>
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <span className="flex items-center gap-2">
+ <span className="truncate text-[15px] font-semibold text-foreground">{source.display_name}</span>
+ {isExperimental && <ExperimentalChip />}
+ </span>
+ <span className="truncate font-mono text-[12px] text-muted">{subline}</span>
+ </span>
+ </SupplyTooltip>
+
+ <div className="flex shrink-0 items-center gap-4">
+ <UsageCell source={source} />
+ <BillingChip billing={source.billing} />
+ <StateChip state={source.state} />
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsx
new file mode 100644
index 000000000..07a50617d
--- /dev/null
+++ b/ui/src/components/settings/models/SourcesCard.tsx
@@ -0,0 +1,75 @@
+// The 来源 band (frame 01r): header (policy sub-line + 添加来源 menu) over a
+// drag-to-reorder priority list. Fully controlled — the ordered `sources` and
+// the reorder handlers live in the page, so this card holds no derived state.
+// Drag is restricted to each row's handle via framer-motion drag controls.
+import * as React from 'react';
+import { Reorder, useDragControls } from 'framer-motion';
+import { useTranslation } from 'react-i18next';
+
+import { AddSourceMenu } from './AddSourceMenu';
+import { SourceRow } from './SourceRow';
+import type { Source } from './types';
+
+const SourceReorderItem: React.FC<{ source: Source; priority: number; onCommit: () => void }> = ({
+ source,
+ priority,
+ onCommit,
+}) => {
+ const controls = useDragControls();
+ return (
+ <Reorder.Item
+ value={source.id}
+ dragListener={false}
+ dragControls={controls}
+ onDragEnd={onCommit}
+ className="list-none bg-background"
+ >
+ <SourceRow
+ source={source}
+ priority={priority}
+ onDragHandlePointerDown={(e) => controls.start(e)}
+ />
+ </Reorder.Item>
+ );
+};
+
+export const SourcesCard: React.FC<{
+ sources: Source[];
+ /** Fires continuously during drag with the new id order (visual only). */
+ onReorderPreview: (orderedIds: string[]) => void;
+ /** Fires on drag end — persist the current order. */
+ onReorderCommit: () => void;
+ onConnectClaude: () => void;
+ onConnectChatGPT: () => void;
+ onAddApiKey: () => void;
+}> = ({ sources, onReorderPreview, onReorderCommit, onConnectClaude, onConnectChatGPT, onAddApiKey }) => {
+ const { t } = useTranslation();
+ const ids = sources.map((s) => s.id);
+
+ 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 items-start justify-between gap-4 border-b border-border px-5 py-4">
+ <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}
+ />
+ </div>
+
+ {ids.length === 0 ? (
+ <div className="px-5 py-12 text-center text-[13px] text-muted">{t('settings.models.sources.empty')}</div>
+ ) : (
+ <Reorder.Group axis="y" values={ids} onReorder={onReorderPreview} className="flex flex-col">
+ {sources.map((source, index) => (
+ <SourceReorderItem key={source.id} source={source} priority={index + 1} onCommit={onReorderCommit} />
+ ))}
+ </Reorder.Group>
+ )}
+ </section>
+ );
+};
diff --git a/ui/src/components/settings/models/SupplyTooltip.tsx b/ui/src/components/settings/models/SupplyTooltip.tsx
new file mode 100644
index 000000000..ca81f851a
--- /dev/null
+++ b/ui/src/components/settings/models/SupplyTooltip.tsx
@@ -0,0 +1,48 @@
+// 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/chips.tsx b/ui/src/components/settings/models/chips.tsx
new file mode 100644
index 000000000..631a232d0
--- /dev/null
+++ b/ui/src/components/settings/models/chips.tsx
@@ -0,0 +1,119 @@
+// 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.
+import * as React from 'react';
+import { FlaskConical, Hourglass, Zap } from 'lucide-react';
+
+import { Badge } from '@/components/ui/badge';
+import { cn } from '@/lib/utils';
+import { useTranslation } from 'react-i18next';
+
+import { ACCENT_DOT, type Accent } from './vendorMeta';
+import type { AgentMode, SourceState } from './types';
+
+/** Status dot used in the composite pill and the 最近切换 list. */
+export const Dot: React.FC<{ accent: Accent; className?: string }> = ({ accent, className }) => (
+ <span className={cn('inline-block size-1.5 shrink-0 rounded-full', ACCENT_DOT[accent], className)} aria-hidden />
+);
+
+/** 包月 / 按量 ¥ — fixed-width so the column aligns down the source list. */
+export const BillingChip: React.FC<{ billing: 'monthly' | 'metered' }> = ({ billing }) => {
+ const { t } = useTranslation();
+ return billing === 'monthly' ? (
+ <Badge variant="secondary" className="w-16 justify-center rounded-md py-1 font-medium">
+ {t('settings.models.billing.monthly')}
+ </Badge>
+ ) : (
+ <Badge variant="warning" className="w-16 justify-center rounded-md py-1 font-medium">
+ {t('settings.models.billing.metered')}
+ </Badge>
+ );
+};
+
+/** 使用中 / 备用 / 暂不可用 / 不可用 — fixed-width aligned column. */
+export const StateChip: React.FC<{ state: SourceState }> = ({ state }) => {
+ const { t } = useTranslation();
+ const base = 'w-[86px] justify-center rounded-full py-1';
+ switch (state.status) {
+ case 'active':
+ return (
+ <Badge variant="success" className={base}>
+ <Dot accent="mint" />
+ {t('settings.models.state.active')}
+ </Badge>
+ );
+ case 'cooldown':
+ return (
+ <Badge variant="warning" className={base}>
+ <Hourglass className="size-3" />
+ {t('settings.models.state.cooldown')}
+ </Badge>
+ );
+ case 'error':
+ return (
+ <Badge variant="destructive" className={base}>
+ {t('settings.models.state.error')}
+ </Badge>
+ );
+ case 'standby':
+ default:
+ return (
+ <Badge variant="secondary" className={base}>
+ {t('settings.models.state.standby')}
+ </Badge>
+ );
+ }
+};
+
+/** 中枢 Hub / 直连 Direct — sized to sit beside the row's action button. */
+export const ModeChip: React.FC<{ mode: AgentMode }> = ({ mode }) => {
+ const { t } = useTranslation();
+ return mode === 'hub' ? (
+ <Badge variant="success" className="h-8 gap-1.5 rounded-lg px-3 text-[12px]">
+ <Zap className="size-3.5" />
+ {t('settings.models.mode.hub')}
+ </Badge>
+ ) : (
+ <Badge variant="secondary" className="h-8 gap-1.5 rounded-lg px-3 text-[12px]">
+ {t('settings.models.mode.direct')}
+ </Badge>
+ );
+};
+
+/** 菜单固定 / 菜单开放 — tiny label next to a backend name. */
+export const MenuKindBadge: React.FC<{ kind: 'fixed' | 'open' }> = ({ kind }) => {
+ const { t } = useTranslation();
+ return (
+ <Badge variant="secondary" className="rounded-md px-2 py-0.5 text-[10px] font-medium">
+ {kind === 'fixed' ? t('settings.models.menuKind.fixed') : t('settings.models.menuKind.open')}
+ </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>
+ );
+};
+
+/**
+ * Agent-card composite pill: `left | ● right` (UI, not copy). Fixed-menu
+ * backends show `model | ● source`; the open-menu backend shows
+ * `N 个模型 | ● 多来源…`.
+ */
+export const CompositePill: React.FC<{ left: string; dot: Accent; right: string }> = ({ left, dot, right }) => (
+ <div className="inline-flex items-center gap-2.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[13px]">
+ <span className="font-mono font-medium text-foreground">{left}</span>
+ <span className="h-3.5 w-px bg-border-strong" aria-hidden />
+ <span className="inline-flex items-center gap-1.5 text-muted">
+ <Dot accent={dot} />
+ {right}
+ </span>
+ </div>
+);
diff --git a/ui/src/components/settings/models/featureFlags.ts b/ui/src/components/settings/models/featureFlags.ts
new file mode 100644
index 000000000..abbd32849
--- /dev/null
+++ b/ui/src/components/settings/models/featureFlags.ts
@@ -0,0 +1,40 @@
+// Model Hub UI — feature flags.
+//
+// This lane (L4) lands ahead of its backend dependencies (L2 REST API, L3
+// backend injection, L5 model-menu drawers). The flags below keep the surface
+// reviewable and pixel-checkable now while preventing fabricated data from
+// reaching end users until the real endpoints exist.
+//
+// Flip sequence when dependencies merge (orchestrator):
+// 1. L2 API merged → set MODELS_API_MODE = 'live'
+// 2. L2/L3 both merged → set MODEL_HUB_NAV_ENABLED = true (advertise nav)
+// 3. L5 menus merged → set MODEL_MENUS_ENABLED = true (wire 模型菜单)
+
+/**
+ * Advertises the 设置 → 模型 entry in the admin sidebar. OFF by default so we
+ * do not surface mock-backed data as a first-class destination. The route is
+ * always registered (reachable by direct URL) for review + pixel verification.
+ */
+export const MODEL_HUB_NAV_ENABLED = false;
+
+/**
+ * 'mock' serves typed fixtures from `mockData.ts`; 'live' calls the real
+ * `/api/models/*` endpoints (L2). The client module switches on this value.
+ */
+export const MODELS_API_MODE: 'mock' | 'live' = 'mock';
+
+/**
+ * Wires the 模型菜单 buttons on the Agent card to L5's mapping / menu drawers.
+ * OFF until L5 lands — the buttons stay visible (pixel fidelity) but explain
+ * that the menus are coming rather than opening a non-existent drawer.
+ */
+export const MODEL_MENUS_ENABLED = false;
+
+/**
+ * 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/format.ts b/ui/src/components/settings/models/format.ts
new file mode 100644
index 000000000..35e58e6e8
--- /dev/null
+++ b/ui/src/components/settings/models/format.ts
@@ -0,0 +1,28 @@
+// Pure formatting helpers for the Model Hub UI (no i18n — callers wrap the
+// returned values in translated templates).
+import type { AgentSupply, Source } from './types';
+
+const CURRENCY_SYMBOL: Record<string, string> = { CNY: '¥', USD: '$', EUR: '€' };
+
+/** Monthly spend as symbol + amount (1 decimal), e.g. "¥12.4". */
+export function formatSpend(cents: number, currency?: string | null): string {
+ const symbol = CURRENCY_SYMBOL[currency ?? 'CNY'] ?? '';
+ return `${symbol}${(cents / 100).toFixed(1)}`;
+}
+
+/** Whole minutes until a cooldown retry_at (never negative). */
+export function cooldownEtaMinutes(retryAt?: string | null): number {
+ if (!retryAt) return 0;
+ const ms = new Date(retryAt).getTime() - Date.now();
+ return Math.max(0, Math.round(ms / 60_000));
+}
+
+/** Friendly model name for a backend's current supply: prefer the supplying
+ * source's display_name for the model id, else the bare id. */
+export function friendlyModelName(agent: AgentSupply, sources: Source[]): string {
+ const modelId = agent.current?.model_id;
+ if (!modelId) return '';
+ const source = sources.find((s) => s.id === agent.current?.source_id);
+ const named = source?.models.find((m) => m.id === modelId)?.display_name;
+ return named || modelId;
+}
diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.ts
new file mode 100644
index 000000000..bc0b3338b
--- /dev/null
+++ b/ui/src/components/settings/models/mockData.ts
@@ -0,0 +1,233 @@
+// Typed fixtures for the Model Hub UI while the L2 REST API is unmerged.
+// Mirrors the V4 design mock story (design.pen `产品改造 V4 01r`) and the frozen
+// contract example payloads. Timestamps are computed relative to "now" at fetch
+// time so the 最近切换 list always renders 今天 / 昨天 correctly.
+import type {
+ AgentSupply,
+ Priority,
+ ResolutionEvent,
+ RuntimeDependency,
+ Source,
+} from './types';
+import { CONTRACT_VERSION } from './types';
+
+const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString();
+const MIN = 60_000;
+const HOUR = 60 * MIN;
+
+export function buildMockSources(): Source[] {
+ return [
+ {
+ id: 'src_claudepro1',
+ kind: 'subscription',
+ vendor: 'anthropic',
+ display_name: 'Claude Pro 订阅',
+ protocol: 'anthropic',
+ base_url: null,
+ supply_channel: 'native_cli',
+ billing: 'monthly',
+ state: { status: 'active', retry_at: null, detail_key: null },
+ usage: { cycle_used_pct: 62, month_spend_cents: null, currency: null },
+ 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) },
+ ],
+ credential_ref: null,
+ },
+ {
+ id: 'src_chatgptplus',
+ kind: 'subscription',
+ vendor: 'openai',
+ display_name: 'ChatGPT Plus 订阅',
+ protocol: 'openai_responses',
+ base_url: null,
+ supply_channel: 'native_cli',
+ billing: 'monthly',
+ state: { status: 'active', retry_at: null, detail_key: null },
+ usage: { cycle_used_pct: 31, month_spend_cents: null, currency: null },
+ 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) },
+ ],
+ credential_ref: null,
+ },
+ {
+ id: 'src_anthkey01',
+ kind: 'api_key',
+ vendor: 'anthropic',
+ display_name: 'Anthropic API Key',
+ protocol: 'anthropic',
+ base_url: null,
+ supply_channel: 'hub',
+ billing: 'metered',
+ state: { status: 'standby', retry_at: null, detail_key: null },
+ usage: { cycle_used_pct: null, month_spend_cents: 1240, currency: 'CNY' },
+ 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) },
+ ],
+ credential_ref: 'cred_anth01',
+ },
+ {
+ id: 'src_zhipukey01',
+ kind: 'api_key',
+ vendor: 'zhipuai',
+ display_name: '智谱 API Key',
+ protocol: 'openai_compatible',
+ base_url: 'https://open.bigmodel.cn/api/paas/v4',
+ supply_channel: 'hub',
+ billing: 'metered',
+ state: { status: 'standby', retry_at: null, detail_key: null },
+ usage: { cycle_used_pct: null, month_spend_cents: 210, currency: 'CNY' },
+ 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 },
+ ],
+ credential_ref: 'cred_zhipu01',
+ },
+ {
+ id: 'src_relay9c1x',
+ kind: 'api_key',
+ vendor: 'custom',
+ display_name: 'relay.example',
+ protocol: 'openai_compatible',
+ base_url: 'https://relay.example/v1',
+ supply_channel: 'hub',
+ billing: 'metered',
+ state: { status: 'cooldown', retry_at: iso(47 * MIN), detail_key: 'settings.models.source.cooldown.timeout' },
+ usage: { cycle_used_pct: null, month_spend_cents: 320, currency: 'CNY' },
+ account_label: null,
+ masked_credential: 'key …9c1',
+ models: [
+ { id: 'glm-5.2-air', display_name: 'GLM 5.2 Air', provenance: 'manual', discovered_at: null },
+ ],
+ credential_ref: 'cred_relay01',
+ },
+ ];
+}
+
+export function buildMockPriority(): Priority {
+ return {
+ contract_version: CONTRACT_VERSION,
+ order: ['src_claudepro1', 'src_chatgptplus', 'src_anthkey01', 'src_zhipukey01', 'src_relay9c1x'],
+ };
+}
+
+export function buildMockAgents(): AgentSupply[] {
+ return [
+ {
+ backend: 'claude',
+ mode: 'hub',
+ menu_kind: 'fixed',
+ current: { model_id: 'claude-opus-4-6', source_id: 'src_claudepro1', channel: 'native_cli' },
+ mappings: [{ builtin_id: 'claude-opus-4-6', target_model_id: 'glm-5.2', enabled: false }],
+ menu: null,
+ },
+ {
+ backend: 'codex',
+ mode: 'direct',
+ menu_kind: 'fixed',
+ current: null,
+ mappings: [],
+ menu: null,
+ },
+ {
+ backend: 'opencode',
+ mode: 'hub',
+ menu_kind: 'open',
+ current: { model_id: 'glm-5.2', source_id: 'src_zhipukey01', channel: 'hub' },
+ mappings: [],
+ menu: {
+ view: 'featured',
+ checked: [
+ 'anthropic/claude-opus-4-6', 'anthropic/claude-sonnet-4-6', 'anthropic/claude-haiku-4-5',
+ 'openai/gpt-5.6', 'openai/gpt-5.6-mini',
+ 'zhipuai/glm-5.2', 'zhipuai/glm-5.2-air', 'zhipuai/glm-5-flash',
+ // …trimmed; menu.checked.length drives the "N 个模型" count.
+ ...Array.from({ length: 17 }, (_, i) => `zhipuai/extra-${i}`),
+ ],
+ },
+ },
+ ];
+}
+
+export function buildMockEvents(): ResolutionEvent[] {
+ // Stored in display order (adapter-owned feed order); the UI renders as-is.
+ return [
+ {
+ id: 'evt_a',
+ ts: iso(-2 * HOUR - 11 * MIN),
+ agent: 'claude',
+ kind: 'switch',
+ model_id: 'claude-opus-4-6',
+ from_source: 'src_claudepro1',
+ to_source: 'src_anthkey01',
+ reason: 'quota_exhausted',
+ billing_note: 'entered_metered',
+ human_zh: 'Claude Code:Claude Pro 本周期额度用完 → 已切到 Anthropic API Key(按量)',
+ human_en: 'Claude Code: Claude Pro cycle quota exhausted → switched to Anthropic API Key (metered)',
+ },
+ {
+ id: 'evt_b',
+ ts: iso(-38 * MIN),
+ agent: 'claude',
+ kind: 'recover',
+ model_id: 'claude-opus-4-6',
+ from_source: 'src_anthkey01',
+ to_source: 'src_claudepro1',
+ reason: 'recovery',
+ billing_note: 'left_metered',
+ human_zh: 'Claude Code:Claude Pro 额度恢复 → 已切回订阅',
+ human_en: 'Claude Code: Claude Pro quota recovered → switched back to the subscription',
+ },
+ {
+ id: 'evt_c',
+ ts: iso(-1 * 24 * HOUR - 30 * MIN),
+ agent: 'system',
+ kind: 'cooldown',
+ model_id: 'glm-5.2-air',
+ from_source: 'src_relay9c1x',
+ to_source: null,
+ reason: 'network',
+ billing_note: null,
+ human_zh: 'relay.example 连续超时 → 暂停使用 1 小时,期间自动跳过',
+ human_en: 'relay.example timed out repeatedly → paused for 1 hour, skipped automatically',
+ },
+ ];
+}
+
+export function buildMockRuntime(): RuntimeDependency {
+ return {
+ manifest: {
+ name: 'cliproxyapi',
+ version: 'v7.2.95',
+ source_sha: 'f71ec0eb6776854457892452cf28c47f0d658251',
+ assets: [],
+ },
+ status: {
+ installed_version: 'v7.2.95',
+ verified: true,
+ listening: { host: '127.0.0.1', port: 15220 },
+ health: 'ok',
+ last_check: iso(-3 * MIN),
+ },
+ };
+}
+
+// Model count a vendor's key "discovers" in the test-and-add flow (frame 06r).
+export function mockDiscoveredCount(vendor: string): number {
+ const table: Record<string, number> = { anthropic: 8, openai: 31, zhipuai: 12, kimi: 6, xai: 4, custom: 23 };
+ return table[vendor] ?? 23;
+}
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
new file mode 100644
index 000000000..df31f2b6c
--- /dev/null
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -0,0 +1,331 @@
+// 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
+// branch on the mode — flip `MODELS_API_MODE` in featureFlags.ts to switch.
+//
+// Methods unwrap the frozen envelope ({ok:true, …} | {ok:false, error}) and
+// throw an Error carrying the machine code on failure, so callers work with
+// plain domain objects.
+import { apiFetch } from '@/lib/apiFetch';
+import { MODELS_API_MODE } from './featureFlags';
+import {
+ buildMockAgents,
+ buildMockEvents,
+ buildMockPriority,
+ buildMockRuntime,
+ buildMockSources,
+ mockDiscoveredCount,
+} from './mockData';
+import type {
+ AgentBackend,
+ AgentMode,
+ AgentSupply,
+ ApiKeySourceCreate,
+ OAuthFlow,
+ Priority,
+ ResolutionEvent,
+ RuntimeDependency,
+ Source,
+ SupplyChannel,
+} from './types';
+import { CONTRACT_VERSION } from './types';
+
+export type ModelsApi = {
+ listSources(): Promise<Source[]>;
+ createApiKeySource(draft: ApiKeySourceCreate): Promise<Source>;
+ deleteSource(id: string): Promise<void>;
+ putPriority(order: string[]): Promise<Priority>;
+ listAgents(): Promise<AgentSupply[]>;
+ setAgentMode(backend: AgentBackend, mode: AgentMode): Promise<AgentSupply>;
+ listEvents(limit?: number): Promise<ResolutionEvent[]>;
+ getRuntimeStatus(): Promise<RuntimeDependency>;
+ startOAuth(vendor: string, channel: SupplyChannel): Promise<OAuthFlow>;
+ getOAuthStatus(flowId: string): Promise<OAuthFlow>;
+ submitOAuth(flowId: string, value: string): Promise<OAuthFlow>;
+ cancelOAuth(flowId: string): Promise<void>;
+};
+
+const isLive = () => MODELS_API_MODE === 'live';
+
+// ── Live client ─────────────────────────────────────────────────────────
+class ApiCallError extends Error {
+ code: string;
+ detail?: string;
+ constructor(code: string, detail?: string) {
+ super(detail || code);
+ this.name = 'ApiCallError';
+ this.code = code;
+ this.detail = detail;
+ }
+}
+
+async function call<T>(path: string, init?: RequestInit): Promise<T> {
+ const res = await apiFetch(path, init);
+ let payload: any = null;
+ try {
+ payload = await res.json();
+ } catch {
+ throw new ApiCallError('bad_response', `Non-JSON response from ${path}`);
+ }
+ if (!res.ok || payload?.ok === false) {
+ throw new ApiCallError(payload?.error || `http_${res.status}`, payload?.detail);
+ }
+ return payload as T;
+}
+
+const jsonInit = (method: string, body?: unknown): RequestInit => ({
+ method,
+ headers: { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+});
+
+const liveApi: ModelsApi = {
+ listSources: () => call<{ sources: Source[] }>('/api/models/sources').then((r) => r.sources),
+ createApiKeySource: (draft) => call<{ source?: Source } & Source>('/api/models/sources', jsonInit('POST', draft)).then((r) => (r.source ?? r) as Source),
+ deleteSource: (id) => call(`/api/models/sources/${encodeURIComponent(id)}`, jsonInit('DELETE')).then(() => undefined),
+ putPriority: (order) => call<{ priority?: Priority } & Priority>('/api/models/priority', jsonInit('PUT', { contract_version: CONTRACT_VERSION, order })).then((r) => (r.priority ?? r) as Priority),
+ listAgents: () => call<{ agents: AgentSupply[] }>('/api/models/agents').then((r) => r.agents),
+ setAgentMode: (backend, mode) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mode`, jsonInit('PATCH', { mode })).then((r) => (r.agent ?? r) as AgentSupply),
+ listEvents: (limit = 20) => call<{ events: ResolutionEvent[] }>(`/api/models/events?limit=${limit}`).then((r) => r.events),
+ getRuntimeStatus: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/status').then((r) => (r.runtime ?? r) as RuntimeDependency),
+ startOAuth: (vendor, channel) => call<{ flow?: OAuthFlow } & OAuthFlow>('/api/models/oauth/start', jsonInit('POST', { vendor, channel })).then((r) => (r.flow ?? r) as OAuthFlow),
+ getOAuthStatus: (flowId) => call<{ flow?: OAuthFlow } & OAuthFlow>(`/api/models/oauth/status/${encodeURIComponent(flowId)}`).then((r) => (r.flow ?? r) as OAuthFlow),
+ submitOAuth: (flowId, value) => call<{ flow?: OAuthFlow } & OAuthFlow>('/api/models/oauth/submit', jsonInit('POST', { flow_id: flowId, value })).then((r) => (r.flow ?? r) as OAuthFlow),
+ cancelOAuth: (flowId) => call('/api/models/oauth/cancel', jsonInit('POST', { flow_id: flowId })).then(() => undefined),
+};
+
+// ── Mock client ─────────────────────────────────────────────────────────
+// A single mutable store so reorder / add / mode-switch stick across calls
+// within a session, giving a realistic demo without a backend.
+type MockFlow = { flow: OAuthFlow; polls: number; submitted: boolean };
+
+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));
+
+class MockStore {
+ sources = buildMockSources();
+ priority = buildMockPriority();
+ agents = buildMockAgents();
+ events = buildMockEvents();
+ runtime = buildMockRuntime();
+ flows = new Map<string, MockFlow>();
+
+ private ordered(): Source[] {
+ const byId = new Map(this.sources.map((s) => [s.id, s]));
+ const ranked = this.priority.order.map((id) => byId.get(id)).filter((s): s is Source => Boolean(s));
+ const extras = this.sources.filter((s) => !this.priority.order.includes(s.id));
+ return [...ranked, ...extras];
+ }
+
+ listSources() {
+ return delay(structuredClone(this.ordered()));
+ }
+
+ createApiKeySource(draft: ApiKeySourceCreate) {
+ const count = mockDiscoveredCount(draft.vendor);
+ const source: Source = {
+ id: rid('src'),
+ kind: 'api_key',
+ vendor: draft.vendor,
+ display_name: draft.vendor === 'custom' ? hostLabel(draft.base_url) : vendorLabel(draft.vendor),
+ protocol: draft.vendor === 'anthropic' ? 'anthropic' : 'openai_compatible',
+ base_url: draft.base_url ?? null,
+ supply_channel: 'hub',
+ billing: 'metered',
+ state: { status: 'standby', retry_at: null, detail_key: null },
+ usage: { cycle_used_pct: null, month_spend_cents: 0, currency: 'CNY' },
+ account_label: null,
+ // Simulates L2 computing the display mask once at provisioning.
+ masked_credential: maskKey(draft.key),
+ models: Array.from({ length: count }, (_, i) => ({
+ id: `${draft.vendor}-model-${i + 1}`,
+ display_name: null,
+ provenance: 'discovered' as const,
+ discovered_at: new Date().toISOString(),
+ })),
+ credential_ref: rid('cred'),
+ };
+ this.sources.push(source);
+ this.priority.order.push(source.id);
+ return delay(structuredClone(source), 900); // simulate probe latency
+ }
+
+ deleteSource(id: string) {
+ this.sources = this.sources.filter((s) => s.id !== id);
+ this.priority.order = this.priority.order.filter((x) => x !== id);
+ return delay(undefined);
+ }
+
+ putPriority(order: string[]) {
+ // Server echoes the authoritative full order (every non-deleted source once).
+ const known = new Set(this.sources.map((s) => s.id));
+ const cleaned = order.filter((id) => known.has(id));
+ const missing = this.sources.map((s) => s.id).filter((id) => !cleaned.includes(id));
+ this.priority = { contract_version: CONTRACT_VERSION, order: [...cleaned, ...missing] };
+ return delay(structuredClone(this.priority));
+ }
+
+ listAgents() {
+ return delay(structuredClone(this.agents));
+ }
+
+ setAgentMode(backend: AgentBackend, mode: AgentMode) {
+ const agent = this.agents.find((a) => a.backend === backend);
+ if (!agent) throw new ApiCallError('source_not_found');
+ agent.mode = mode;
+ if (mode === 'direct') {
+ agent.current = null;
+ } else if (!agent.current) {
+ const top = this.ordered().find((s) => s.state.status !== 'error');
+ agent.current = top
+ ? { model_id: top.models[0]?.id ?? 'unknown', source_id: top.id, channel: top.supply_channel }
+ : null;
+ }
+ return delay(structuredClone(agent));
+ }
+
+ listEvents(limit = 20) {
+ return delay(structuredClone(this.events.slice(0, limit)));
+ }
+
+ getRuntimeStatus() {
+ return delay(structuredClone(this.runtime));
+ }
+
+ startOAuth(vendor: string, channel: SupplyChannel) {
+ const isDevice = vendor === 'openai';
+ const flow: OAuthFlow = {
+ flow_id: rid('oaf'),
+ vendor,
+ channel,
+ state: 'awaiting_action',
+ presentation: isDevice
+ ? {
+ auth_url: 'https://chatgpt.com/device',
+ device_code: 'KDWT-GBSF',
+ expects: 'none',
+ instructions_key: 'settings.models.oauth.deviceCode.hint',
+ }
+ : {
+ auth_url: 'https://claude.ai/oauth/authorize?code=true&client_id=avibe&scope=org%3Acreate_api_key',
+ device_code: null,
+ expects: 'paste_code',
+ instructions_key: 'settings.models.oauth.pasteCode.hint',
+ },
+ error_key: null,
+ expires_at: new Date(Date.now() + 15 * 60_000).toISOString(),
+ };
+ this.flows.set(flow.flow_id, { flow, polls: 0, submitted: false });
+ return delay(structuredClone(flow), 500);
+ }
+
+ getOAuthStatus(flowId: string) {
+ const entry = this.flows.get(flowId);
+ if (!entry) throw new ApiCallError('flow_not_found');
+ entry.polls += 1;
+ const { flow } = entry;
+ if (flow.state === 'success' || flow.state === 'failed' || flow.state === 'cancelled') {
+ return delay(structuredClone(flow));
+ }
+ if (flow.presentation.expects === 'none') {
+ // Device flow self-completes after a few polls.
+ if (entry.polls >= 3) this.completeFlow(entry);
+ } else if (entry.submitted) {
+ // Paste flows: verifying → success on the next poll.
+ this.completeFlow(entry);
+ }
+ return delay(structuredClone(flow));
+ }
+
+ submitOAuth(flowId: string, _value: string) {
+ const entry = this.flows.get(flowId);
+ if (!entry) throw new ApiCallError('flow_not_found');
+ entry.submitted = true;
+ entry.flow.state = 'verifying';
+ return delay(structuredClone(entry.flow));
+ }
+
+ cancelOAuth(flowId: string) {
+ const entry = this.flows.get(flowId);
+ if (entry) entry.flow.state = 'cancelled';
+ return delay(undefined);
+ }
+
+ private completeFlow(entry: MockFlow) {
+ entry.flow.state = 'success';
+ // A completed subscription connect materializes a new native_cli source.
+ const vendor = entry.flow.vendor;
+ const isOpenai = vendor === 'openai';
+ const source: Source = {
+ id: rid('src'),
+ kind: 'subscription',
+ vendor,
+ display_name: isOpenai ? 'ChatGPT 订阅' : 'Claude 订阅',
+ protocol: isOpenai ? 'openai_responses' : 'anthropic',
+ base_url: null,
+ supply_channel: entry.flow.channel,
+ experimental_consent_at: entry.flow.channel === 'hub' ? new Date().toISOString() : null,
+ billing: 'monthly',
+ state: { status: 'standby', retry_at: null, detail_key: null },
+ usage: { cycle_used_pct: 0, month_spend_cents: null, currency: null },
+ // native_cli subscriptions surface the sanctioned CLI account; hub-held
+ // experimental sources may stay null until a later adapter rev (schema).
+ account_label: entry.flow.channel === 'native_cli' ? '[email protected]' : null,
+ masked_credential: null,
+ models: isOpenai
+ ? [{ id: 'gpt-5.6', display_name: 'GPT-5.6', provenance: 'discovered', discovered_at: new Date().toISOString() }]
+ : [{ id: 'claude-opus-4-6', display_name: 'Opus 4.6', provenance: 'discovered', discovered_at: new Date().toISOString() }],
+ credential_ref: entry.flow.channel === 'hub' ? rid('cred') : null,
+ };
+ this.sources.push(source);
+ this.priority.order.push(source.id);
+ }
+}
+
+function vendorLabel(vendor: string): string {
+ const table: Record<string, string> = {
+ anthropic: 'Anthropic API Key',
+ openai: 'OpenAI API Key',
+ zhipuai: '智谱 API Key',
+ kimi: 'Kimi API Key',
+ xai: 'xAI API Key',
+ };
+ return table[vendor] ?? `${vendor} API Key`;
+}
+
+// Non-reversible display mask (contract rule: ≤7-char prefix + "…" + last 4).
+function maskKey(key: string): string {
+ const k = key.trim();
+ if (k.length <= 5) return `${k}…`;
+ const prefix = k.slice(0, Math.min(7, k.length - 4));
+ return `${prefix}…${k.slice(-4)}`;
+}
+
+function hostLabel(baseUrl: string | null | undefined): string {
+ if (!baseUrl) return 'API Key';
+ try {
+ return new URL(baseUrl).host;
+ } catch {
+ return 'API Key';
+ }
+}
+
+const mockStore = new MockStore();
+
+const mockApi: ModelsApi = {
+ listSources: () => mockStore.listSources(),
+ createApiKeySource: (draft) => mockStore.createApiKeySource(draft),
+ deleteSource: (id) => mockStore.deleteSource(id),
+ putPriority: (order) => mockStore.putPriority(order),
+ listAgents: () => mockStore.listAgents(),
+ setAgentMode: (backend, mode) => mockStore.setAgentMode(backend, mode),
+ listEvents: (limit) => mockStore.listEvents(limit),
+ getRuntimeStatus: () => mockStore.getRuntimeStatus(),
+ startOAuth: (vendor, channel) => mockStore.startOAuth(vendor, channel),
+ getOAuthStatus: (flowId) => mockStore.getOAuthStatus(flowId),
+ submitOAuth: (flowId, value) => mockStore.submitOAuth(flowId, value),
+ cancelOAuth: (flowId) => mockStore.cancelOAuth(flowId),
+};
+
+/** The single client instance. Stable across renders (safe in effect deps). */
+export const modelsApi: ModelsApi = isLive() ? liveApi : mockApi;
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
new file mode 100644
index 000000000..2f102acfa
--- /dev/null
+++ b/ui/src/components/settings/models/types.ts
@@ -0,0 +1,214 @@
+// Model Hub — TypeScript mirror of the FROZEN interface contracts
+// (`avibe/docs/plans/model-hub-contracts/*`). Field names are exact
+// (case included); the UI consumes these types and never edits the schemas.
+//
+// Contract version pinned to the frozen v1. If the orchestrator bumps a
+// contract, this file changes in lockstep — never ahead of it.
+
+export const CONTRACT_VERSION = 1 as const;
+
+// ── source.schema.json ──────────────────────────────────────────────────
+export type SourceKind = 'subscription' | 'api_key';
+export type SourceProtocol =
+ | 'anthropic'
+ | 'openai_responses'
+ | 'openai_chat'
+ | 'openai_compatible';
+export type SupplyChannel = 'native_cli' | 'hub';
+export type SourceStatus = 'active' | 'standby' | 'cooldown' | 'error';
+export type ModelProvenance = 'discovered' | 'manual';
+
+export type SourceState = {
+ status: SourceStatus;
+ /** ISO-8601; the cooldown retry ETA rendered in the row's mono sub-line. */
+ retry_at?: string | null;
+ /** i18n key, never raw upstream error text. */
+ detail_key?: string | null;
+};
+
+export type SourceUsage = {
+ cycle_used_pct?: number | null;
+ month_spend_cents?: number | null;
+ /** ISO 4217, e.g. CNY / USD. */
+ currency?: string | null;
+};
+
+export type SuppliedModel = {
+ /** Bare model id (no provider prefix). */
+ id: string;
+ display_name?: string | null;
+ provenance: ModelProvenance;
+ discovered_at?: string | null;
+};
+
+export type Source = {
+ id: string;
+ kind: SourceKind;
+ /** Standard vendor id (anthropic|openai|zhipuai|kimi|xai|…) or 'custom'. */
+ vendor: string;
+ display_name: string;
+ protocol: SourceProtocol;
+ /** 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;
+ /** Subscription identity for the row's mono sub-line (e.g. "[email protected]").
+ * Never secret material; may be null. */
+ account_label?: string | null;
+ /** api_key display mask, computed server-side once at provisioning
+ * (≤7-char prefix + "…" + last 4, e.g. "sk-ant-…8f2A"). Non-reversible;
+ * never secret material; may be null. */
+ masked_credential?: string | null;
+ models: SuppliedModel[];
+ /** Opaque handle. Secret material NEVER appears here. */
+ credential_ref?: string | null;
+};
+
+// ── priority.schema.json ────────────────────────────────────────────────
+export type Priority = {
+ contract_version: typeof CONTRACT_VERSION;
+ /** source ids, position 0 = spend first; every non-deleted source once. */
+ order: string[];
+};
+
+// ── agent-supply.schema.json ────────────────────────────────────────────
+export type AgentBackend = 'claude' | 'codex' | 'opencode';
+export type AgentMode = 'hub' | 'direct';
+export type MenuKind = 'fixed' | 'open';
+
+export type AgentCurrent = {
+ model_id: string;
+ source_id: string;
+ channel: SupplyChannel;
+};
+
+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[];
+};
+
+export type AgentSupply = {
+ backend: AgentBackend;
+ mode: AgentMode;
+ menu_kind: MenuKind;
+ /** What the next turn would use (composite pill). null when mode=direct. */
+ current?: AgentCurrent | null;
+ mappings?: AgentMapping[];
+ menu?: AgentMenu | null;
+};
+
+// ── resolution-event.schema.json ────────────────────────────────────────
+export type ResolutionEventKind =
+ | 'switch'
+ | 'cooldown'
+ | 'recover'
+ | 'skip'
+ | 'mapping_applied'
+ | 'channel_switch';
+export type ResolutionReason =
+ | 'quota_exhausted'
+ | 'rate_limited'
+ | 'server_error'
+ | 'network'
+ | 'recovery'
+ | 'manual'
+ | 'mapping';
+export type BillingNote = null | 'entered_metered' | 'left_metered';
+
+export type ResolutionEvent = {
+ id: string;
+ ts: string;
+ agent: AgentBackend | 'system';
+ kind: ResolutionEventKind;
+ model_id: string;
+ from_source?: string | null;
+ to_source?: string | null;
+ reason: ResolutionReason;
+ /** drives the gold dot in the 最近切换 list. */
+ billing_note?: BillingNote;
+ human_zh: string;
+ human_en: string;
+};
+
+// ── oauth-flow.schema.json ──────────────────────────────────────────────
+export type OAuthFlowState =
+ | 'starting'
+ | 'awaiting_action'
+ | 'verifying'
+ | 'success'
+ | 'failed'
+ | 'cancelled';
+/** What the UI must collect back from the user. */
+export type OAuthExpects = 'none' | 'paste_code' | 'paste_callback_url';
+
+export type OAuthPresentation = {
+ auth_url?: string | null;
+ device_code?: string | null;
+ expects: OAuthExpects;
+ /** i18n key for the step-2 helper line. */
+ instructions_key?: string | null;
+};
+
+export type OAuthFlow = {
+ flow_id: string;
+ vendor: string;
+ channel: SupplyChannel;
+ state: OAuthFlowState;
+ presentation: OAuthPresentation;
+ /** i18n key; raw upstream errors never surface. */
+ error_key?: string | null;
+ expires_at?: string | null;
+};
+
+// ── runtime-dependency.schema.json ──────────────────────────────────────
+export type RuntimeHealth = 'ok' | 'degraded' | 'down' | 'not_installed';
+
+export type RuntimeDependency = {
+ manifest: {
+ name: 'cliproxyapi';
+ version: string;
+ source_sha: string;
+ assets: Array<{
+ platform: 'darwin-arm64' | 'linux-amd64';
+ url: string;
+ size_bytes: number;
+ sha256: string;
+ }>;
+ };
+ status: {
+ installed_version?: string | null;
+ verified: boolean;
+ listening?: { host: '127.0.0.1'; port: number } | null;
+ health: RuntimeHealth;
+ last_check?: string | null;
+ };
+};
+
+// ── API envelope + request shapes (api.md) ──────────────────────────────
+export type ApiOk<T> = { ok: true; contract_version: typeof CONTRACT_VERSION } & T;
+export type ApiErr = {
+ ok: false;
+ contract_version: typeof CONTRACT_VERSION;
+ error: string;
+ detail?: string;
+};
+
+/** POST /api/models/sources — api_key create validates + discovers models. */
+export type ApiKeySourceCreate = {
+ kind: 'api_key';
+ vendor: string;
+ base_url?: string | null;
+ key: string;
+};
diff --git a/ui/src/components/settings/models/vendorMeta.tsx b/ui/src/components/settings/models/vendorMeta.tsx
new file mode 100644
index 000000000..af57ec2d7
--- /dev/null
+++ b/ui/src/components/settings/models/vendorMeta.tsx
@@ -0,0 +1,104 @@
+// 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.
+import type React from 'react';
+import { Bot, KeyRound, Sparkles, Terminal } from 'lucide-react';
+
+import type { AgentBackend, Source, SourceProtocol } 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',
+};
+
+export const ACCENT_ICON: Record<Accent, string> = {
+ mint: 'text-mint',
+ gold: 'text-gold',
+ cyan: 'text-cyan',
+ violet: 'text-violet',
+ muted: 'text-muted',
+};
+
+// Status dot fill (composite pill · recent-switch list). Gold reserved for the
+// "entered metered" billing marker.
+export const ACCENT_DOT: Record<Accent, string> = {
+ mint: 'bg-mint',
+ gold: 'bg-gold',
+ cyan: 'bg-cyan',
+ violet: 'bg-violet',
+ muted: 'bg-muted',
+};
+
+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 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 type SourceVisual = { Icon: IconType; accent: Accent };
+
+export function sourceVisual(source: Pick<Source, 'kind' | 'vendor'>): SourceVisual {
+ return {
+ Icon: source.kind === 'subscription' ? Sparkles : KeyRound,
+ accent: sourceAccent(source),
+ };
+}
+
+// ── Agent backends (Agent card rows) ────────────────────────────────────
+export type BackendVisual = { Icon: IconType; accent: Accent };
+
+const BACKEND_VISUAL: Record<AgentBackend, BackendVisual> = {
+ claude: { Icon: Sparkles, accent: 'mint' },
+ codex: { Icon: Bot, accent: 'gold' },
+ opencode: { Icon: Terminal, accent: 'violet' },
+};
+
+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 自定义. Protocol drives the created source.
+export type VendorOption = {
+ value: string;
+ labelKey: string;
+ base_url: string | null;
+ protocol: SourceProtocol;
+};
+
+export const VENDOR_OPTIONS: VendorOption[] = [
+ { value: 'custom', labelKey: 'settings.models.addKey.vendors.custom', base_url: null, protocol: 'openai_compatible' },
+ { value: 'anthropic', labelKey: 'settings.models.addKey.vendors.anthropic', base_url: 'https://api.anthropic.com', protocol: 'anthropic' },
+ { value: 'openai', labelKey: 'settings.models.addKey.vendors.openai', base_url: 'https://api.openai.com/v1', protocol: 'openai_chat' },
+ { value: 'zhipuai', labelKey: 'settings.models.addKey.vendors.zhipuai', base_url: 'https://open.bigmodel.cn/api/paas/v4', protocol: 'openai_compatible' },
+ { value: 'kimi', labelKey: 'settings.models.addKey.vendors.kimi', base_url: 'https://api.moonshot.cn/v1', protocol: 'openai_compatible' },
+ { value: 'xai', labelKey: 'settings.models.addKey.vendors.xai', base_url: 'https://api.x.ai/v1', protocol: 'openai_chat' },
+];
+
+export const DEFAULT_VENDOR = VENDOR_OPTIONS[0];
diff --git a/ui/src/components/settings/oauth/OAuthFlowParts.tsx b/ui/src/components/settings/oauth/OAuthFlowParts.tsx
new file mode 100644
index 000000000..3165091ce
--- /dev/null
+++ b/ui/src/components/settings/oauth/OAuthFlowParts.tsx
@@ -0,0 +1,87 @@
+// Shared visual atoms for subscription/backend OAuth flows. Extracted from
+// BackendOAuthPanel so both the Settings → Backends panel and the Model Hub
+// connect-subscription dialog compose the SAME link / device-code / submit
+// rows instead of forking near-duplicate markup (reuse ladder: promote the
+// repeated pattern to a shared home).
+//
+// These are presentation-only and i18n-agnostic: callers pass already-
+// translated strings and own the copy handler (which is where the defensive
+// stopPropagation for the iOS radio-bounce bug lives — see BackendOAuthPanel).
+import * as React from 'react';
+import { Copy, ExternalLink } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+
+type CopyProps = {
+ /** Receives the click event so the caller can stop propagation. */
+ onCopy: (e: React.MouseEvent) => void;
+ copyLabel: string;
+};
+
+/** Auth URL as a cyan link chip + a copy button (remote/phone operation). */
+export const OAuthLinkRow: React.FC<{ url: string } & CopyProps> = ({ url, onCopy, copyLabel }) => (
+ <div className="flex flex-wrap items-center gap-2">
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex max-w-full items-center gap-1.5 break-all rounded-md bg-cyan-soft/40 px-2 py-1 font-mono text-[12px] text-cyan transition-colors hover:bg-cyan-soft hover:text-cyan"
+ >
+ <ExternalLink className="size-3 shrink-0" />
+ <span className="break-all">{url}</span>
+ </a>
+ <Button type="button" variant="secondary" size="xs" onClick={onCopy}>
+ <Copy className="size-3" />
+ {copyLabel}
+ </Button>
+ </div>
+);
+
+/** Device code as a spaced mono chip + a copy button. */
+export const OAuthDeviceCodeRow: React.FC<{ code: string } & CopyProps> = ({ code, onCopy, copyLabel }) => (
+ <div className="flex flex-wrap items-center gap-2">
+ <code className="rounded-md bg-cyan-soft/40 px-2.5 py-1 font-mono text-[14px] font-semibold tracking-[0.18em] text-cyan">
+ {code}
+ </code>
+ <Button type="button" variant="secondary" size="xs" onClick={onCopy}>
+ <Copy className="size-3" />
+ {copyLabel}
+ </Button>
+ </div>
+);
+
+/** Mono text input + brand submit button (paste auth code / callback URL). */
+export const OAuthSubmitRow: React.FC<{
+ id?: string;
+ value: string;
+ onChange: (value: string) => void;
+ onSubmit: () => void;
+ submitting: boolean;
+ placeholder?: string;
+ submitLabel: string;
+ submittingLabel: string;
+}> = ({ id, value, onChange, onSubmit, submitting, placeholder, submitLabel, submittingLabel }) => (
+ <div className="flex gap-2">
+ <Input
+ id={id}
+ type="text"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder={placeholder}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ className="font-mono"
+ disabled={submitting}
+ />
+ <Button
+ type="button"
+ variant="brand"
+ size="sm"
+ onClick={onSubmit}
+ disabled={submitting || !value.trim()}
+ >
+ {submitting ? submittingLabel : submitLabel}
+ </Button>
+ </div>
+);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fde8ec44d..72697611a 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -123,7 +123,8 @@
"capabilities": "Capabilities",
"more": "More",
"apps": "Apps",
- "workbench": "Workbench"
+ "workbench": "Workbench",
+ "models": "Models"
},
"more": {
"title": "More",
@@ -601,7 +602,177 @@
"inProgressTitle": "This settings page is next in the redesign queue",
"inProgressBody": "The new route and shell are live, but the feature-specific UI for this section is still being migrated from the old dashboard and wizard flows.",
"inProgressHint": "Until this section is rebuilt, the setup wizard still exposes the underlying configuration paths.",
- "openSetup": "Open setup wizard"
+ "openSetup": "Open setup wizard",
+ "models": {
+ "title": "Models",
+ "subtitle": "Connect a source once and every agent uses it; the list order is the spend order — Avibe switches on exhaustion and switches back on recovery.",
+ "addSource": "Add source",
+ "loadError": "Failed to load: {{detail}}",
+ "statusPill": {
+ "ok": "All good · {{count}} agents connected",
+ "degraded": "Some sources need attention · {{count}} agents connected"
+ },
+ "sources": {
+ "title": "Sources",
+ "subtitle": "One global list; drag to reorder — the order is the spend order",
+ "empty": "No sources yet — use “Add source” to connect a subscription or API key."
+ },
+ "source": {
+ "nativeSupply": "Native supply",
+ "hubHosted": "Hub-hosted",
+ "officialEndpoint": "Official endpoint",
+ "customEndpoint": "Custom endpoint",
+ "retryIn": "retry in {{minutes}} min",
+ "reorder": "Reorder",
+ "cooldown": {
+ "timeout": "Repeated timeouts"
+ }
+ },
+ "billing": {
+ "monthly": "Monthly",
+ "metered": "Metered ¥"
+ },
+ "state": {
+ "active": "In use",
+ "standby": "Standby",
+ "cooldown": "Cooling down",
+ "error": "Unavailable"
+ },
+ "usage": {
+ "monthSpend": "{{amount}} this month"
+ },
+ "supplyTooltip": {
+ "label": "Supplies: "
+ },
+ "mode": {
+ "hub": "Hub",
+ "direct": "Direct"
+ },
+ "menuKind": {
+ "fixed": "Fixed menu",
+ "open": "Open menu"
+ },
+ "experimental": "Experimental",
+ "agents": {
+ "title": "Agent",
+ "subtitle": "Which model each agent uses, and who supplies it",
+ "backendSettings": "Backend settings",
+ "modelMenu": "Model menu",
+ "connectHub": "Connect to Hub",
+ "menuComingSoon": "Model menus arrive in the next milestone",
+ "modelCount": "{{count}} models",
+ "multiSource": "Multiple sources",
+ "multiSourceCustom": "Multiple sources · {{count}} custom"
+ },
+ "recent": {
+ "title": "Recent switches",
+ "viewAll": "View all",
+ "collapse": "Collapse",
+ "today": "Today",
+ "yesterday": "Yesterday",
+ "empty": "No switches yet"
+ },
+ "advanced": {
+ "title": "Advanced",
+ "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"
+ },
+ "chatgpt": {
+ "title": "Connect ChatGPT subscription",
+ "subtitle": "Plus / Pro · browser sign-in"
+ },
+ "apiKey": {
+ "title": "Add API Key…",
+ "subtitle": "Any vendor or compatible service, editable URL"
+ }
+ },
+ "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}} models, added to the supply list",
+ "failed": "Connection failed: {{detail}}",
+ "testing": "Connecting…",
+ "vaultNote": "Stored locally; can go in Vault",
+ "vendors": {
+ "custom": "Custom · OpenAI / Anthropic compatible",
+ "anthropic": "Anthropic",
+ "openai": "OpenAI",
+ "zhipuai": "Zhipu",
+ "kimi": "Kimi",
+ "xai": "xAI"
+ }
+ },
+ "oauth": {
+ "title": {
+ "anthropic": "Connect Claude subscription",
+ "openai": "Connect ChatGPT subscription",
+ "generic": "Connect subscription"
+ },
+ "starting": "Preparing…",
+ "connected": "Connected — added to your sources",
+ "step1": {
+ "authLink": "Open the authorization link (any device's browser works)",
+ "devicePage": "Open the device authorization page"
+ },
+ "pasteCode": {
+ "hint": "After you sign in and approve, paste the code back here"
+ },
+ "callback": {
+ "hint": "After signing in, paste the callback URL your browser landed on"
+ },
+ "deviceCode": {
+ "hint": "Enter the device code on that page; this continues automatically"
+ },
+ "status": {
+ "awaitingPaste": "Waiting for authorization · times out in {{time}}",
+ "awaitingDevice": "Waiting to finish · detected automatically, nothing to paste",
+ "verifying": "Verifying…",
+ "success": "Connected"
+ },
+ "error": {
+ "start": "Couldn't start authorization, please retry",
+ "timeout": "Authorization timed out, please reconnect",
+ "generic": "Connection failed, please retry"
+ },
+ "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"
+ }
+ },
+ "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",
+ "connectFailed": "Couldn't connect, please retry",
+ "refreshFailed": "Couldn't refresh, please retry"
+ },
+ "backends": {
+ "claude": "Claude Code",
+ "codex": "Codex",
+ "opencode": "OpenCode"
+ }
+ }
},
"remoteAccess": {
"badge": "Avibe Cloud provider",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index cfb59ec95..5948888e0 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -123,7 +123,8 @@
"capabilities": "能力",
"more": "更多",
"apps": "Apps",
- "workbench": "工作台"
+ "workbench": "工作台",
+ "models": "模型"
},
"more": {
"title": "更多",
@@ -601,7 +602,177 @@
"inProgressTitle": "这个设置页已经有新路由,但功能 UI 还在迁移中",
"inProgressBody": "新版路由和页面壳子已经就位,但这个分区的具体界面还在从旧 Dashboard 和向导流程迁移。",
"inProgressHint": "在该分区完成重构前,底层配置仍可先通过设置向导进行调整。",
- "openSetup": "打开设置向导"
+ "openSetup": "打开设置向导",
+ "models": {
+ "title": "模型",
+ "subtitle": "连一次来源,所有 Agent 统一供给;顺序即优先级,用完自动切换、恢复自动切回。",
+ "addSource": "添加来源",
+ "loadError": "加载失败:{{detail}}",
+ "statusPill": {
+ "ok": "一切正常 · {{count}} 个 Agent 已接入",
+ "degraded": "部分来源需留意 · {{count}} 个 Agent 已接入"
+ },
+ "sources": {
+ "title": "来源",
+ "subtitle": "全局一份;拖动调整顺序 —— 顺序就是花钱顺序",
+ "empty": "还没有来源,点“添加来源”连接订阅或 API Key。"
+ },
+ "source": {
+ "nativeSupply": "原生供给",
+ "hubHosted": "中枢托管",
+ "officialEndpoint": "官方地址",
+ "customEndpoint": "自定义地址",
+ "retryIn": "{{minutes}} 分后重试",
+ "reorder": "拖动排序",
+ "cooldown": {
+ "timeout": "连续超时"
+ }
+ },
+ "billing": {
+ "monthly": "包月",
+ "metered": "按量 ¥"
+ },
+ "state": {
+ "active": "使用中",
+ "standby": "备用",
+ "cooldown": "暂不可用",
+ "error": "不可用"
+ },
+ "usage": {
+ "monthSpend": "本月 {{amount}}"
+ },
+ "supplyTooltip": {
+ "label": "供应:"
+ },
+ "mode": {
+ "hub": "中枢 Hub",
+ "direct": "直连 Direct"
+ },
+ "menuKind": {
+ "fixed": "菜单固定",
+ "open": "菜单开放"
+ },
+ "experimental": "实验",
+ "agents": {
+ "title": "Agent",
+ "subtitle": "每个 Agent 用什么模型、由谁供给",
+ "backendSettings": "后端设置",
+ "modelMenu": "模型菜单",
+ "connectHub": "接入中枢",
+ "menuComingSoon": "模型菜单即将上线(随下一个里程碑发布)",
+ "modelCount": "{{count}} 个模型",
+ "multiSource": "多来源",
+ "multiSourceCustom": "多来源 · 含 {{count}} 个自定义"
+ },
+ "recent": {
+ "title": "最近切换",
+ "viewAll": "查看全部",
+ "collapse": "收起",
+ "today": "今天",
+ "yesterday": "昨天",
+ "empty": "暂无切换记录"
+ },
+ "advanced": {
+ "title": "高级",
+ "detail": "跨厂商自动顶替(默认关)· 请求日志 · 诊断",
+ "comingSoon": "高级设置即将上线"
+ },
+ "addMenu": {
+ "claude": {
+ "title": "连接 Claude 订阅",
+ "subtitle": "Pro / Max · 浏览器登录"
+ },
+ "chatgpt": {
+ "title": "连接 ChatGPT 订阅",
+ "subtitle": "Plus / Pro · 浏览器登录"
+ },
+ "apiKey": {
+ "title": "添加 API Key…",
+ "subtitle": "任何厂商或兼容服务,可改地址"
+ }
+ },
+ "addKey": {
+ "title": "添加 API Key",
+ "subtitle": "任何厂商或兼容服务;连接一次,所有 Agent 共用。",
+ "vendorLabel": "服务商",
+ "vendorHint": "选择 Anthropic / OpenAI / 智谱 / Kimi 等厂商时,自动填官方地址。",
+ "keyLabel": "API KEY",
+ "baseUrlLabel": "服务地址(BASE URL)",
+ "baseUrlHint": "官方厂商已预填,可改;使用兼容服务(如中转、自建网关)时填它提供的地址。",
+ "discovered": "连接成功 · 发现 {{count}} 个可用模型,已加入供应清单",
+ "failed": "连接失败:{{detail}}",
+ "testing": "连接中…",
+ "vaultNote": "只存本机,可入 Vault",
+ "vendors": {
+ "custom": "自定义 · OpenAI / Anthropic 兼容",
+ "anthropic": "Anthropic",
+ "openai": "OpenAI",
+ "zhipuai": "智谱",
+ "kimi": "Kimi",
+ "xai": "xAI"
+ }
+ },
+ "oauth": {
+ "title": {
+ "anthropic": "连接 Claude 订阅",
+ "openai": "连接 ChatGPT 订阅",
+ "generic": "连接订阅"
+ },
+ "starting": "正在准备…",
+ "connected": "连接成功,已加入来源列表",
+ "step1": {
+ "authLink": "打开授权链接(任何设备的浏览器都行)",
+ "devicePage": "打开设备授权页"
+ },
+ "pasteCode": {
+ "hint": "登录同意后,把页面给的授权码粘贴回来"
+ },
+ "callback": {
+ "hint": "登录后,把浏览器最终停留的回调地址粘贴回来"
+ },
+ "deviceCode": {
+ "hint": "在那个页面输入设备码,这里会自动继续"
+ },
+ "status": {
+ "awaitingPaste": "等待授权 · {{time}} 后超时",
+ "awaitingDevice": "等待完成 · 自动检测,无需回填",
+ "verifying": "验证中…",
+ "success": "连接成功"
+ },
+ "error": {
+ "start": "无法开始授权,请重试",
+ "timeout": "授权超时,请重新连接",
+ "generic": "连接失败,请重试"
+ },
+ "hubOption": {
+ "title": "由中枢托管此订阅(实验)",
+ "subtitle": "凭据由中枢保存并转发,可能违反厂商条款",
+ "on": "已开启",
+ "off": "关"
+ }
+ },
+ "consent": {
+ "title": "由中枢托管订阅 · 风险提示",
+ "subtitle": "启用前请确认你已了解以下风险。",
+ "points": [
+ "该来源使用你本人订阅的登录凭据;厂商条款通常要求订阅仅供个人在官方客户端内使用,经由中枢代理转发属于非官方用法,可能违反其服务条款。",
+ "存在账号被风控、限流或封禁的真实风险(已有 Claude 订阅经代理使用被自动封号的先例);是否启用由你自行决定并承担后果。",
+ "追求最稳妥时,请对订阅使用直连模式(官方客户端直接连接),或改用 API Key 来源(厂商明确允许程序化 / 代理调用)。"
+ ],
+ "confirm": "我已了解风险,继续"
+ },
+ "toast": {
+ "reorderFailed": "顺序保存失败",
+ "connected": "已接入中枢",
+ "connectFailed": "接入失败,请重试",
+ "refreshFailed": "刷新失败,请重试"
+ },
+ "backends": {
+ "claude": "Claude Code",
+ "codex": "Codex",
+ "opencode": "OpenCode"
+ }
+ }
},
"remoteAccess": {
"badge": "Avibe Cloud Provider",