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 — model menus, backend supply-mode card, migration dialog (L5) (#977)

Call Whiteca3eee6564b9
diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsx
index cfbdcc98f..c91e24412 100644
--- a/ui/src/components/settings/models/AgentCard.tsx
+++ b/ui/src/components/settings/models/AgentCard.tsx
@@ -21,18 +21,21 @@ const AgentRow: React.FC<{
agent: AgentSupply;
sources: Source[];
onConnectHub: (agent: AgentSupply) => void;
+ onOpenMenu?: (agent: AgentSupply) => void;
connecting: boolean;
-}> = ({ agent, sources, onConnectHub, connecting }) => {
+}> = ({ agent, sources, onConnectHub, onOpenMenu, connecting }) => {
const { t } = useTranslation();
const { showToast } = useToast();
const { Icon, accent } = backendVisual(agent.backend);
const openMenu = () => {
- if (!MODEL_MENUS_ENABLED) {
+ // L5's mapping / menu drawers are gated by MODEL_MENUS_ENABLED; until it
+ // flips, keep the buttons visible (pixel fidelity) but explain themselves.
+ if (!MODEL_MENUS_ENABLED || !onOpenMenu) {
showToast(t('settings.models.agents.menuComingSoon') as string, 'warning');
return;
}
- // L5 owns the mapping / menu drawers; wired when MODEL_MENUS_ENABLED flips.
+ onOpenMenu(agent);
};
// Composite pill content. Fixed-menu → model | source; open-menu → count |
@@ -99,8 +102,9 @@ export const AgentCard: React.FC<{
agents: AgentSupply[];
sources: Source[];
onConnectHub: (agent: AgentSupply) => void;
+ onOpenMenu?: (agent: AgentSupply) => void;
connectingBackend: string | null;
-}> = ({ agents, sources, onConnectHub, connectingBackend }) => {
+}> = ({ agents, sources, onConnectHub, onOpenMenu, connectingBackend }) => {
const { t } = useTranslation();
return (
<section className="rounded-xl border border-border bg-background">
@@ -124,6 +128,7 @@ export const AgentCard: React.FC<{
agent={agent}
sources={sources}
onConnectHub={onConnectHub}
+ onOpenMenu={onOpenMenu}
connecting={connectingBackend === agent.backend}
/>
))}
diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.tsx
new file mode 100644
index 000000000..c3e0d163a
--- /dev/null
+++ b/ui/src/components/settings/models/BackendSupplyModeCard.tsx
@@ -0,0 +1,221 @@
+// 供给方式 card for a backend detail page (frame 02). Two radio options — 中枢模式
+// Hub (推荐·默认; supply managed on the Models page, native config untouched) and
+// 直连模式 Direct (legacy behavior preserved). When a native config is detected in
+// Direct mode, a strip offers a one-click 导入中枢 into the migration dialog.
+// Switches mode via PATCH /agents/<backend>/mode (never silent, plan §4).
+import * as React from 'react';
+import { Link } from 'react-router-dom';
+import { ArrowDownToLine, ArrowRight, CheckCircle2, Info } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Card, CardContent } from '@/components/ui/card';
+import { cn } from '@/lib/utils';
+import { useToast } from '@/context/ToastContext';
+import { modelsApi } from './modelsApi';
+import { MigrationDialog } from './MigrationDialog';
+import type { AgentBackend, AgentMode, AgentSupply, MigrationItem } from './types';
+
+const RadioDot: React.FC<{ selected: boolean }> = ({ selected }) => (
+ <span
+ className={cn(
+ 'mt-0.5 flex size-[18px] shrink-0 items-center justify-center rounded-full border-2 transition-colors',
+ selected ? 'border-mint' : 'border-border-strong',
+ )}
+ >
+ {selected && <span className="size-2 rounded-full bg-mint" />}
+ </span>
+);
+
+const OptionCard: React.FC<{
+ selected: boolean;
+ disabled?: boolean;
+ onSelect: () => void;
+ title: React.ReactNode;
+ description: string;
+ headerRight?: React.ReactNode;
+ children?: React.ReactNode;
+}> = ({ selected, disabled, onSelect, title, description, headerRight, children }) => (
+ <div
+ role="radio"
+ aria-checked={selected}
+ tabIndex={disabled ? -1 : 0}
+ onClick={() => !disabled && onSelect()}
+ onKeyDown={(e) => {
+ if (disabled) return;
+ // Only act when the radio row itself is focused — Enter/Space on a nested
+ // control (the Models-page link / Import button) must drive that control,
+ // not switch the supply mode.
+ if (e.target !== e.currentTarget) return;
+ if (e.key === ' ' || e.key === 'Enter') {
+ e.preventDefault();
+ onSelect();
+ }
+ }}
+ className={cn(
+ 'flex cursor-pointer flex-col gap-3 rounded-xl border p-4 transition-colors',
+ selected ? 'border-mint/50 bg-mint-soft/40' : 'border-border hover:border-border-strong',
+ disabled && 'cursor-default opacity-70',
+ )}
+ >
+ <div className="flex items-start gap-3">
+ <RadioDot selected={selected} />
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex items-center gap-2">{title}</div>
+ {headerRight}
+ </div>
+ <p className="text-[13px] leading-relaxed text-muted">{description}</p>
+ </div>
+ </div>
+ {children}
+ </div>
+);
+
+export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ backend }) => {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+
+ const [agent, setAgent] = React.useState<AgentSupply | null>(null);
+ const [detected, setDetected] = React.useState<MigrationItem[]>([]);
+ const [switching, setSwitching] = React.useState<AgentMode | null>(null);
+ const [migrateOpen, setMigrateOpen] = React.useState(false);
+ const aliveRef = React.useRef(true);
+ React.useEffect(() => {
+ aliveRef.current = true;
+ return () => {
+ aliveRef.current = false;
+ };
+ }, []);
+
+ const load = React.useCallback(async () => {
+ try {
+ const agents = await modelsApi.listAgents();
+ if (aliveRef.current) setAgent(agents.find((a) => a.backend === backend) ?? null);
+ } catch {
+ /* card simply stays hidden if the hub is unreachable */
+ }
+ }, [backend]);
+
+ const scan = React.useCallback(async () => {
+ try {
+ const s = await modelsApi.scanMigration();
+ if (aliveRef.current) setDetected(s.items.filter((i) => i.backend === backend));
+ } catch {
+ /* detect strip is best-effort */
+ }
+ }, [backend]);
+
+ React.useEffect(() => {
+ void load();
+ void scan();
+ }, [load, scan]);
+
+ const setMode = async (mode: AgentMode) => {
+ if (!agent || agent.mode === mode || switching) return;
+ setSwitching(mode);
+ try {
+ const next = await modelsApi.setAgentMode(backend, mode);
+ if (!aliveRef.current) return;
+ setAgent(next);
+ showToast(t(mode === 'hub' ? 'settings.models.supplyMode.switchedHub' : 'settings.models.supplyMode.switchedDirect') as string, 'success');
+ } catch {
+ if (aliveRef.current) showToast(t('settings.models.supplyMode.switchFailed') as string, 'error');
+ } finally {
+ if (aliveRef.current) setSwitching(null);
+ }
+ };
+
+ if (!agent) return null;
+
+ const mode = agent.mode;
+ // Only surface the import strip for configs the migration dialog can actually
+ // apply — a reauth-only scan would open a dead-end dialog (reauth rows are
+ // disabled and excluded from apply), so those don't count as importable.
+ const importable = detected.filter((i) => i.proposed_action !== 'reauth');
+ const detectItem = importable.find((i) => i.kind === 'api_key' || i.kind === 'opencode_provider') ?? importable[0] ?? null;
+
+ return (
+ <Card>
+ <CardContent className="flex flex-col gap-4 p-6">
+ <div className="flex items-center justify-between gap-3">
+ <h2 className="text-[15px] font-semibold text-foreground">{t('settings.models.supplyMode.title')}</h2>
+ <Badge variant={mode === 'hub' ? 'success' : 'secondary'} className="gap-1.5 rounded-full px-3 py-1.5 text-[12px]">
+ {mode === 'hub' && <CheckCircle2 className="size-3.5" />}
+ {t(mode === 'hub' ? 'settings.models.supplyMode.currentHub' : 'settings.models.supplyMode.currentDirect')}
+ </Badge>
+ </div>
+
+ <OptionCard
+ selected={mode === 'hub'}
+ disabled={switching !== null}
+ onSelect={() => void setMode('hub')}
+ title={
+ <>
+ <span className="text-[15px] font-semibold text-foreground">{t('settings.models.supplyMode.hub.title')}</span>
+ <Badge variant="success" className="rounded-md px-2 py-0.5 text-[10px] font-semibold">
+ {t('settings.models.supplyMode.hub.recommended')}
+ </Badge>
+ </>
+ }
+ headerRight={
+ <Link
+ to="/admin/settings/models"
+ onClick={(e) => e.stopPropagation()}
+ className="inline-flex shrink-0 items-center gap-1 text-[13px] font-medium text-mint transition-colors hover:text-mint/80"
+ >
+ {t('settings.models.supplyMode.hub.openModels')}
+ <ArrowRight className="size-3.5" />
+ </Link>
+ }
+ description={t('settings.models.supplyMode.hub.description', {
+ backend: t(`settings.models.backends.${backend}`, { defaultValue: backend }),
+ }) as string}
+ />
+
+ <OptionCard
+ selected={mode === 'direct'}
+ disabled={switching !== null}
+ onSelect={() => void setMode('direct')}
+ title={<span className="text-[15px] font-semibold text-foreground">{t('settings.models.supplyMode.direct.title')}</span>}
+ description={t('settings.models.supplyMode.direct.description', {
+ backend: t(`settings.models.backends.${backend}`, { defaultValue: backend }),
+ }) as string}
+ >
+ {mode === 'direct' && detectItem && (
+ <div className="flex items-center justify-between gap-3 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-2.5">
+ <span className="flex min-w-0 items-center gap-2 text-[12px] leading-relaxed text-foreground">
+ <Info className="size-3.5 shrink-0 text-gold" />
+ <span className="truncate">
+ {t('settings.models.supplyMode.direct.detected', { detail: detectItem.masked_detail })}
+ </span>
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ onClick={(e) => {
+ e.stopPropagation();
+ setMigrateOpen(true);
+ }}
+ >
+ <ArrowDownToLine className="size-3.5" />
+ {t('settings.models.supplyMode.direct.import')}
+ </Button>
+ </div>
+ )}
+ </OptionCard>
+ </CardContent>
+
+ <MigrationDialog
+ open={migrateOpen}
+ onClose={() => setMigrateOpen(false)}
+ onApplied={() => {
+ void load();
+ void scan();
+ }}
+ />
+ </Card>
+ );
+};
diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsx
new file mode 100644
index 000000000..46926a2f7
--- /dev/null
+++ b/ui/src/components/settings/models/MigrationDialog.tsx
@@ -0,0 +1,203 @@
+// 迁移对话框 · 接入模型中枢 (frame 03). Non-destructive: a per-backend checklist of
+// detected native configs. Actions follow migration-scan.schema (spec v1.1,
+// Option 1): API keys / base URLs → import; Claude account OAuth → keep_native
+// (sanctioned as-is); Codex auth.json → controlled_import behind the
+// experimental flag, else keep_native. Originals are never modified or deleted.
+// Scans via POST /migration/scan; applies the selection via /migration/apply.
+import * as React from 'react';
+import { ArrowDownToLine, Bot, KeyRound, ShieldCheck, Sparkles } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { cn } from '@/lib/utils';
+import { useToast } from '@/context/ToastContext';
+import { modelsApi } from './modelsApi';
+import { ACCENT_ICON, ACCENT_TILE, type Accent } from './vendorMeta';
+import type { AgentBackend, MigrationItem, MigrationAction } from './types';
+
+const BACKEND_ORDER: AgentBackend[] = ['claude', 'codex', 'opencode'];
+
+function migrationVisual(item: MigrationItem): { Icon: React.ComponentType<{ size?: number; className?: string }>; accent: Accent } {
+ if (item.kind === 'oauth_native') {
+ if (item.backend === 'codex') return { Icon: Bot, accent: 'gold' };
+ return { Icon: Sparkles, accent: 'cyan' };
+ }
+ const accent: Accent = item.backend === 'opencode' ? 'cyan' : item.backend === 'codex' ? 'gold' : 'violet';
+ return { Icon: KeyRound, accent };
+}
+
+const ActionBadge: React.FC<{ action: MigrationAction }> = ({ action }) => {
+ const { t } = useTranslation();
+ const map: Record<MigrationAction, { variant: 'success' | 'warning' | 'secondary'; key: string }> = {
+ import: { variant: 'success', key: 'settings.models.migration.action.import' },
+ controlled_import: { variant: 'warning', key: 'settings.models.migration.action.controlledImport' },
+ keep_native: { variant: 'secondary', key: 'settings.models.migration.action.keepNative' },
+ reauth: { variant: 'warning', key: 'settings.models.migration.action.reauth' },
+ };
+ const { variant, key } = map[action];
+ return (
+ <Badge variant={variant} className="shrink-0 rounded-lg px-2.5 py-1 text-[12px] font-medium">
+ {t(key)}
+ </Badge>
+ );
+};
+
+const ItemRow: React.FC<{ item: MigrationItem; onToggle: () => void }> = ({ item, onToggle }) => {
+ const { t } = useTranslation();
+ const { Icon, accent } = migrationVisual(item);
+ // reauth needs the interactive browser flow, so it can't be bulk-applied here.
+ const selectable = item.proposed_action !== 'reauth';
+ return (
+ <div
+ className={cn(
+ 'flex items-center gap-3 rounded-xl border px-3.5 py-3',
+ item.selected ? 'border-mint/40 bg-mint-soft/40' : 'border-border',
+ )}
+ >
+ <Checkbox checked={item.selected} onCheckedChange={onToggle} disabled={!selectable} label={item.masked_detail} />
+ <span className={cn('flex size-9 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>
+ <Icon size={18} className={ACCENT_ICON[accent]} />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate text-[14px] font-semibold text-foreground">{item.masked_detail}</span>
+ {item.notes_key && <span className="truncate text-[12px] text-muted">{t(item.notes_key)}</span>}
+ </div>
+ <ActionBadge action={item.proposed_action} />
+ </div>
+ );
+};
+
+export const MigrationDialog: React.FC<{
+ open: boolean;
+ onClose: () => void;
+ /** Fired after a successful apply so callers can refresh sources/agents. */
+ onApplied?: (applied: number) => void;
+}> = ({ open, onClose, onApplied }) => {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+
+ const [items, setItems] = React.useState<MigrationItem[]>([]);
+ const [loading, setLoading] = React.useState(true);
+ const [applying, setApplying] = React.useState(false);
+ const aliveRef = React.useRef(true);
+ React.useEffect(() => {
+ aliveRef.current = true;
+ return () => {
+ aliveRef.current = false;
+ };
+ }, []);
+
+ React.useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ setLoading(true);
+ // Drop any rows from a prior scan so a failed rescan can't display — or
+ // submit — stale migration ids.
+ setItems([]);
+ modelsApi
+ .scanMigration()
+ .then((scan) => {
+ if (cancelled) return;
+ setItems(scan.items);
+ setLoading(false);
+ })
+ .catch(() => {
+ if (cancelled) return;
+ setLoading(false);
+ showToast(t('settings.models.migration.scanFailed') as string, 'error');
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, showToast, t]);
+
+ const toggle = (id: string) =>
+ setItems((prev) => prev.map((i) => (i.id === id ? { ...i, selected: !i.selected } : i)));
+
+ // reauth rows can't be bulk-applied (they need the interactive OAuth flow),
+ // and their checkbox is disabled — so exclude them from both the count and
+ // the submitted ids, even if a scan returned one pre-selected.
+ const appliable = items.filter((i) => i.selected && i.proposed_action !== 'reauth');
+ const selectedCount = appliable.length;
+
+ const apply = async () => {
+ if (applying || selectedCount === 0) return;
+ setApplying(true);
+ try {
+ const ids = appliable.map((i) => i.id);
+ const result = await modelsApi.applyMigration(ids);
+ if (!aliveRef.current) return;
+ showToast(t('settings.models.migration.applied', { count: result.applied }) as string, 'success');
+ onApplied?.(result.applied);
+ onClose();
+ } catch {
+ if (aliveRef.current) showToast(t('settings.models.migration.applyFailed') as string, 'error');
+ } finally {
+ if (aliveRef.current) setApplying(false);
+ }
+ };
+
+ const grouped = BACKEND_ORDER.map((backend) => ({
+ backend,
+ rows: items.filter((i) => i.backend === backend),
+ })).filter((g) => g.rows.length > 0);
+
+ return (
+ <Dialog open={open} onOpenChange={(v) => !v && !applying && onClose()}>
+ <DialogContent className="max-w-[640px] gap-5">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-3 text-[18px] font-bold">
+ <span className="flex size-10 shrink-0 items-center justify-center rounded-[12px] bg-mint-soft">
+ <ArrowDownToLine className="size-5 text-mint" />
+ </span>
+ {t('settings.models.migration.title')}
+ </DialogTitle>
+ <DialogDescription className="pl-[52px]">{t('settings.models.migration.subtitle')}</DialogDescription>
+ </DialogHeader>
+
+ {loading ? (
+ <div className="py-8 text-center text-[13px] text-muted">{t('common.loading')}</div>
+ ) : grouped.length === 0 ? (
+ <div className="py-8 text-center text-[13px] text-muted">{t('settings.models.migration.empty')}</div>
+ ) : (
+ <div className="flex flex-col gap-4">
+ {grouped.map((group) => (
+ <div key={group.backend} className="flex flex-col gap-2">
+ <span className="px-1 font-mono text-[11px] font-semibold uppercase tracking-[0.08em] text-muted">
+ {t(`settings.models.backends.${group.backend}`, { defaultValue: group.backend })}
+ </span>
+ {group.rows.map((item) => (
+ <ItemRow key={item.id} item={item} onToggle={() => toggle(item.id)} />
+ ))}
+ </div>
+ ))}
+ </div>
+ )}
+
+ <p className="flex items-start gap-2 text-[12px] leading-relaxed text-mint">
+ <ShieldCheck className="mt-0.5 size-4 shrink-0" />
+ {t('settings.models.migration.nonDestructive')}
+ </p>
+
+ <div className="flex items-center justify-end gap-2 border-t border-border pt-4">
+ <Button variant="outline" size="sm" onClick={onClose} disabled={applying}>
+ {t('settings.models.migration.later')}
+ </Button>
+ <Button variant="brand" size="sm" onClick={() => void apply()} disabled={selectedCount === 0 || applying}>
+ <ArrowDownToLine className="size-4" />
+ {t('settings.models.migration.apply', { count: selectedCount })}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 477f1843d..d417fb4f6 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -16,8 +16,10 @@ import { RecentSwitchesCard } from './RecentSwitchesCard';
import { AdvancedRow } from './AdvancedRow';
import { AddApiKeyDialog } from './AddApiKeyDialog';
import { OAuthConnectDialog } from './OAuthConnectDialog';
+import { MappingDrawer } from './menus/MappingDrawer';
+import { OpenCodeMenuDrawer } from './menus/OpenCodeMenuDrawer';
import { modelsApi } from './modelsApi';
-import type { AgentSupply, ResolutionEvent, RuntimeDependency, Source } from './types';
+import type { AgentBackend, AgentSupply, ResolutionEvent, RuntimeDependency, Source } from './types';
const StatusPill: React.FC<{ healthy: boolean; hubCount: number }> = ({ healthy, hubCount }) => {
const { t } = useTranslation();
@@ -48,6 +50,9 @@ export const SettingsModelsPage: React.FC = () => {
const [apiKeyOpen, setApiKeyOpen] = React.useState(false);
const [oauthVendor, setOauthVendor] = React.useState<string | null>(null);
+ // Which backend's 模型菜单 drawer is open. Tracked by backend id (not the agent
+ // object) so a background refresh keeps feeding the drawer the freshest agent.
+ const [menuBackend, setMenuBackend] = React.useState<AgentBackend | null>(null);
// Mirror the latest ordered sources for reorder-commit (drag end reads the
// freshest order without threading it through the framer callback).
@@ -140,6 +145,9 @@ export const SettingsModelsPage: React.FC = () => {
}
};
+ // Resolve the open drawer's agent from live state so edits see fresh data.
+ const menuAgent = agents.find((a) => a.backend === menuBackend) ?? 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.
@@ -169,7 +177,13 @@ export const SettingsModelsPage: React.FC = () => {
onConnectChatGPT={() => setOauthVendor('openai')}
onAddApiKey={() => setApiKeyOpen(true)}
/>
- <AgentCard agents={agents} sources={sources} onConnectHub={connectHub} connectingBackend={connecting} />
+ <AgentCard
+ agents={agents}
+ sources={sources}
+ onConnectHub={connectHub}
+ onOpenMenu={(agent) => setMenuBackend(agent.backend)}
+ connectingBackend={connecting}
+ />
<RecentSwitchesCard events={events} />
<AdvancedRow />
</div>
@@ -182,6 +196,26 @@ export const SettingsModelsPage: React.FC = () => {
onClose={() => setOauthVendor(null)}
onConnected={() => void refreshSourcesAgents()}
/>
+
+ {menuAgent && menuAgent.menu_kind === 'open' ? (
+ <OpenCodeMenuDrawer
+ open
+ agent={menuAgent}
+ sources={sources}
+ onClose={() => setMenuBackend(null)}
+ onSaved={() => void refreshSourcesAgents()}
+ onRefresh={() => void refreshSourcesAgents()}
+ />
+ ) : menuAgent && (menuAgent.backend === 'claude' || menuAgent.backend === 'codex') ? (
+ <MappingDrawer
+ open
+ backend={menuAgent.backend}
+ agent={menuAgent}
+ sources={sources}
+ onClose={() => setMenuBackend(null)}
+ onSaved={() => void refreshSourcesAgents()}
+ />
+ ) : null}
</SettingsPageShell>
);
};
diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsx
index c4f082829..0f4848bef 100644
--- a/ui/src/components/settings/models/SourceRow.tsx
+++ b/ui/src/components/settings/models/SourceRow.tsx
@@ -8,19 +8,10 @@ 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 { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, 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
diff --git a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx
new file mode 100644
index 000000000..79b7d309d
--- /dev/null
+++ b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx
@@ -0,0 +1,235 @@
+// 添加自定义模型 (frame 08). Supplements a source's supply list with a model the
+// auto-discovery missed, so it appears in the OpenCode menu. Source + model id
+// (+ optional display name) → a LIVE identifier preview built with the vendor-id
+// rule (`custom/` fallback). Persists via POST /custom-models; also used to edit
+// an existing custom entry (same upsert endpoint).
+import * as React from 'react';
+import { ChevronDown, Copy, Plus } 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 { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { cn } from '@/lib/utils';
+import { useToast } from '@/context/ToastContext';
+import { modelsApi } from '../modelsApi';
+import { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, sourceVisual } from '../vendorMeta';
+import type { Source } from '../types';
+import { buildIdentifier } from './identifiers';
+
+const FieldLabel: React.FC<{ mono?: boolean; children: React.ReactNode }> = ({ mono, children }) => (
+ <span
+ className={cn(
+ 'text-muted',
+ mono ? 'font-mono text-[11px] font-medium uppercase tracking-wide' : 'text-[12px] font-semibold text-foreground',
+ )}
+ >
+ {children}
+ </span>
+);
+
+const useEndpointSuffix = () => {
+ const { t } = useTranslation();
+ return (source: Source): string => {
+ if (source.kind === 'subscription') return ''; // subscriptions carry no endpoint suffix
+ // Reuse the 来源-list rule (base URL differs from the vendor's official one),
+ // so an official vendor edited to a relay reads as 自定义地址, not 官方地址.
+ return isCustomEndpoint(source)
+ ? (t('settings.models.source.customEndpoint') as string)
+ : (t('settings.models.source.officialEndpoint') as string);
+ };
+};
+
+const SourceSelect: React.FC<{
+ sources: Source[];
+ value: Source | null;
+ onChange: (source: Source) => void;
+ disabled?: boolean;
+}> = ({ sources, value, onChange, disabled }) => {
+ const [open, setOpen] = React.useState(false);
+ const suffix = useEndpointSuffix();
+ const renderRow = (source: Source) => {
+ const { Icon, accent } = sourceVisual(source);
+ const suf = suffix(source);
+ return (
+ <>
+ <span className={cn('flex size-7 shrink-0 items-center justify-center rounded-md', ACCENT_TILE[accent])}>
+ <Icon size={15} className={ACCENT_ICON[accent]} />
+ </span>
+ <span className="truncate text-[14px] text-foreground">
+ {source.display_name}
+ {suf ? <span className="text-muted"> · {suf}</span> : null}
+ </span>
+ </>
+ );
+ };
+ return (
+ <Popover open={open} onOpenChange={(v) => !disabled && setOpen(v)}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ disabled={disabled}
+ className="flex h-11 w-full items-center gap-2.5 rounded-lg border border-border bg-background px-3 text-left transition-colors hover:border-border-strong disabled:opacity-60"
+ >
+ {value ? renderRow(value) : <span className="text-muted">—</span>}
+ <ChevronDown className="ml-auto size-4 shrink-0 text-muted" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" sideOffset={6} className="max-h-[300px] w-[var(--radix-popover-trigger-width)] overflow-y-auto p-1.5">
+ {sources.map((source) => (
+ <button
+ key={source.id}
+ type="button"
+ onClick={() => {
+ onChange(source);
+ setOpen(false);
+ }}
+ className={cn(
+ 'flex w-full items-center gap-2.5 rounded-md px-2 py-2 text-left hover:bg-surface-2',
+ value?.id === source.id && 'bg-surface-2',
+ )}
+ >
+ {renderRow(source)}
+ </button>
+ ))}
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+export const AddCustomModelDialog: React.FC<{
+ open: boolean;
+ sources: Source[];
+ /** When set, prefill for editing an existing custom entry. */
+ edit?: { sourceId: string; modelId: string; displayName: string | null } | null;
+ onClose: () => void;
+ onSaved: (identifier: string) => void;
+}> = ({ open, sources, edit, onClose, onSaved }) => {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+
+ const [source, setSource] = React.useState<Source | null>(null);
+ const [modelId, setModelId] = React.useState('');
+ const [displayName, setDisplayName] = React.useState('');
+ const [saving, setSaving] = React.useState(false);
+
+ // Seed on open: edit prefill, else the first source that can carry custom
+ // models (an api_key source), else the first source.
+ React.useEffect(() => {
+ if (!open) return;
+ const editing = edit ? sources.find((s) => s.id === edit.sourceId) ?? null : null;
+ const preferred = editing ?? sources.find((s) => s.kind === 'api_key') ?? sources[0] ?? null;
+ setSource(preferred);
+ setModelId(edit?.modelId ?? '');
+ setDisplayName(edit?.displayName ?? '');
+ setSaving(false);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ const trimmedId = modelId.trim();
+ const identifier = source && trimmedId ? buildIdentifier(source.vendor, trimmedId) : '';
+
+ const copyIdentifier = () => {
+ if (!identifier || !navigator.clipboard?.writeText) {
+ if (identifier) showToast(t('common.copyFailed') as string, 'error');
+ return;
+ }
+ navigator.clipboard
+ .writeText(identifier)
+ .then(() => showToast(t('common.copied') as string, 'success'))
+ .catch(() => showToast(t('common.copyFailed') as string, 'error'));
+ };
+
+ const submit = async () => {
+ if (!source || !trimmedId || saving) return;
+ setSaving(true);
+ try {
+ await modelsApi.addCustomModel({ source_id: source.id, model_id: trimmedId, display_name: displayName.trim() || null });
+ onSaved(identifier);
+ onClose();
+ } catch {
+ showToast(t('settings.models.menus.custom.failed') as string, 'error');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={(v) => !v && !saving && onClose()}>
+ <DialogContent className="max-w-[560px] gap-5">
+ <DialogHeader>
+ <DialogTitle className="text-[18px] font-bold">{t('settings.models.menus.custom.title')}</DialogTitle>
+ <DialogDescription>{t('settings.models.menus.custom.subtitle')}</DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-2">
+ <FieldLabel>{t('settings.models.menus.custom.sourceLabel')}</FieldLabel>
+ <SourceSelect sources={sources} value={source} onChange={setSource} disabled={Boolean(edit)} />
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <FieldLabel mono>{t('settings.models.menus.custom.modelIdLabel')}</FieldLabel>
+ <Input
+ value={modelId}
+ onChange={(e) => setModelId(e.target.value)}
+ placeholder={t('settings.models.menus.custom.modelIdPlaceholder') as string}
+ autoComplete="off"
+ spellCheck={false}
+ disabled={Boolean(edit)}
+ className="h-11 font-mono text-[14px]"
+ />
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <FieldLabel>{t('settings.models.menus.custom.displayNameLabel')}</FieldLabel>
+ <Input
+ value={displayName}
+ onChange={(e) => setDisplayName(e.target.value)}
+ placeholder={t('settings.models.menus.custom.displayNamePlaceholder') as string}
+ autoComplete="off"
+ className="h-11 text-[14px]"
+ />
+ </div>
+
+ <div className="flex flex-col gap-2 rounded-xl border border-violet/30 bg-violet-soft/40 px-4 py-3.5">
+ <div className="flex items-center justify-between gap-2">
+ <span className="font-mono text-[11px] font-semibold uppercase tracking-wide text-violet">
+ {t('settings.models.menus.custom.previewLabel')}
+ </span>
+ <button
+ type="button"
+ aria-label={t('common.copy') as string}
+ onClick={copyIdentifier}
+ disabled={!identifier}
+ className="rounded-md p-1 text-muted transition-colors hover:text-foreground disabled:opacity-40"
+ >
+ <Copy className="size-4" />
+ </button>
+ </div>
+ <span className="font-mono text-[16px] font-semibold text-foreground">
+ {identifier || t('settings.models.menus.custom.previewEmpty')}
+ </span>
+ <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.menus.custom.previewHint')}</p>
+ </div>
+
+ <DialogFooter className="sm:justify-end">
+ <Button variant="outline" size="sm" onClick={onClose} disabled={saving}>
+ {t('common.cancel')}
+ </Button>
+ <Button variant="brand" size="sm" onClick={() => void submit()} disabled={!source || !trimmedId || saving}>
+ <Plus className="size-4" />
+ {t('settings.models.menus.custom.add')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/ui/src/components/settings/models/menus/MappingDrawer.tsx b/ui/src/components/settings/models/menus/MappingDrawer.tsx
new file mode 100644
index 000000000..4bff69a66
--- /dev/null
+++ b/ui/src/components/settings/models/menus/MappingDrawer.tsx
@@ -0,0 +1,294 @@
+// 模型菜单 · Claude Code / Codex — the fixed-menu mapping drawer (frame 04).
+// Left column: the backend's built-in model ids (mono, not editable). Right
+// column: the supply each id resolves to — 跟随原生 · 按优先级供给 by default, or
+// an override to another model (violet, with a per-row reset and a persistent
+// capability warning). Per-agent scope; commits via PUT .../mappings on 完成.
+import * as React from 'react';
+import { ArrowRight, CheckCircle2, ChevronDown, Info, RotateCcw } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { cn } from '@/lib/utils';
+import { useToast } from '@/context/ToastContext';
+import { modelsApi } from '../modelsApi';
+import { backendVisual } from '../vendorMeta';
+import type { AgentBackend, AgentMapping, AgentSupply, Source } from '../types';
+import { MenuDrawer } from './MenuDrawer';
+import { buildTargetModels, isSourceEligible, type TargetModel } from './identifiers';
+import { SupplyDots } from './supplyBits';
+import { useCompactSourceLabel } from './sourceLabel';
+
+// Mock stand-in for the fixed-menu backend's built-in model catalog. The
+// contract stores only OVERRIDES in agent.mappings (absent entry = 跟随原生), so
+// the full row list needs the backend's built-in id list, which agent-supply
+// does not yet expose.
+const MOCK_BUILTINS: Record<'claude' | 'codex', string[]> = {
+ claude: ['claude-opus-4-6', 'claude-sonnet-4-6', 'claude-haiku-4-5'],
+ codex: ['gpt-5.6', 'gpt-5.6-mini'],
+};
+
+// SINGLE swap point for the built-in catalog. Decided 2026-07-23: agent-supply
+// gains an additive optional `builtin_models: string[] | null` (fixed-menu
+// backends only), server-populated from the existing backend-models resolver,
+// in the post-batch integration pass. When it lands, this becomes:
+// return agent.builtin_models ?? MOCK_BUILTINS[agent.backend] ?? [];
+// (a one-line change; nothing else in the drawer needs to move).
+const resolveBuiltinIds = (agent: AgentSupply): string[] =>
+ MOCK_BUILTINS[agent.backend as 'claude' | 'codex'] ?? [];
+
+const seedDraft = (agent: AgentSupply): AgentMapping[] => {
+ const byId = new Map((agent.mappings ?? []).map((m) => [m.builtin_id, m]));
+ const ids = resolveBuiltinIds(agent);
+ // Preserve any stored builtin id we don't know about, appended after the
+ // canonical list, so a backend that adds ids stays visible.
+ const extra = (agent.mappings ?? []).map((m) => m.builtin_id).filter((id) => !ids.includes(id));
+ return [...ids, ...extra].map(
+ (builtin_id) => byId.get(builtin_id) ?? { builtin_id, target_model_id: '', enabled: false },
+ );
+};
+
+const sameDraft = (a: AgentMapping[], b: AgentMapping[]): boolean =>
+ a.length === b.length &&
+ a.every((m, i) => m.builtin_id === b[i].builtin_id && m.enabled === b[i].enabled && m.target_model_id === b[i].target_model_id);
+
+const BuiltinChip: React.FC<{ id: string }> = ({ id }) => (
+ <span className="shrink-0 whitespace-nowrap rounded-lg border border-border bg-surface-2 px-3 py-2 font-mono text-[13px] font-medium text-foreground">
+ {id}
+ </span>
+);
+
+const SupplySelector: React.FC<{
+ mapping: AgentMapping;
+ targets: TargetModel[];
+ onFollowNative: () => void;
+ onOverride: (targetId: string) => void;
+}> = ({ mapping, targets, onFollowNative, onOverride }) => {
+ const { t } = useTranslation();
+ const compactLabel = useCompactSourceLabel();
+ const [open, setOpen] = React.useState(false);
+ const override = mapping.enabled && Boolean(mapping.target_model_id);
+ const target = targets.find((x) => x.id === mapping.target_model_id);
+ const candidateLabel = target
+ ? (t('settings.models.menus.mapping.candidates', {
+ sources: target.sources.map(compactLabel).join(' / '),
+ }) as string)
+ : (t('settings.models.menus.mapping.candidatesUnavailable') as string);
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className={cn(
+ 'flex h-11 w-full items-center gap-2.5 rounded-lg border px-3.5 text-left text-[13px] transition-colors',
+ override
+ ? 'border-violet/40 bg-violet-soft/60 hover:border-violet/60'
+ : 'border-border bg-background hover:border-border-strong',
+ )}
+ >
+ {override ? (
+ <>
+ <span className="shrink-0 font-mono font-semibold text-violet">{mapping.target_model_id}</span>
+ {target && <SupplyDots accents={target.accents} className="flex shrink-0 items-center gap-1" />}
+ <span className="truncate text-muted">{candidateLabel}</span>
+ </>
+ ) : (
+ <>
+ <CheckCircle2 className="size-4 shrink-0 text-mint" />
+ <span className="truncate text-foreground">{t('settings.models.menus.mapping.followNative')}</span>
+ </>
+ )}
+ <ChevronDown className="ml-auto size-4 shrink-0 text-muted" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ sideOffset={6}
+ className="max-h-[320px] w-[var(--radix-popover-trigger-width)] overflow-y-auto p-1.5"
+ >
+ <button
+ type="button"
+ onClick={() => {
+ onFollowNative();
+ setOpen(false);
+ }}
+ className="flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] hover:bg-surface-2"
+ >
+ <CheckCircle2 className={cn('size-4 shrink-0', override ? 'text-muted/40' : 'text-mint')} />
+ <span className="text-foreground">{t('settings.models.menus.mapping.followNative')}</span>
+ </button>
+ <div className="my-1 h-px bg-border" />
+ {targets.map((tg) => {
+ const active = override && tg.id === mapping.target_model_id;
+ return (
+ <button
+ key={tg.id}
+ type="button"
+ onClick={() => {
+ onOverride(tg.id);
+ setOpen(false);
+ }}
+ className={cn(
+ 'flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left hover:bg-surface-2',
+ active && 'bg-violet-soft/60',
+ )}
+ >
+ <span className="font-mono text-[13px] font-medium text-foreground">{tg.id}</span>
+ {tg.displayName && <span className="truncate text-[12px] text-muted">{tg.displayName}</span>}
+ <SupplyDots accents={tg.accents} className="ml-auto flex shrink-0 items-center gap-1" />
+ </button>
+ );
+ })}
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+export const MappingDrawer: React.FC<{
+ open: boolean;
+ backend: Extract<AgentBackend, 'claude' | 'codex'>;
+ agent: AgentSupply;
+ sources: Source[];
+ onClose: () => void;
+ onSaved: () => void;
+}> = ({ open, backend, agent, sources, onClose, onSaved }) => {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+ const { Icon, accent } = backendVisual(backend);
+ // Override targets follow the backend eligibility predicate (isSourceEligible):
+ // hub-supplied API-key sources PLUS this backend's own native subscription.
+ // Anything else is rejected by the live API with `mapping_target_unavailable`.
+ const targets = React.useMemo(
+ () => buildTargetModels(sources.filter((s) => isSourceEligible(s, backend))),
+ [sources, backend],
+ );
+
+ const [draft, setDraft] = React.useState<AgentMapping[]>(() => seedDraft(agent));
+ const initialRef = React.useRef<AgentMapping[]>(draft);
+ const [saving, setSaving] = React.useState(false);
+
+ // Reseed only on open so an in-flight edit isn't clobbered by a background
+ // refresh of the agent prop.
+ React.useEffect(() => {
+ if (!open) return;
+ const seed = seedDraft(agent);
+ setDraft(seed);
+ initialRef.current = seed;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ const backendName = t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;
+
+ const setMapping = (builtinId: string, next: Partial<AgentMapping>) =>
+ setDraft((prev) => prev.map((m) => (m.builtin_id === builtinId ? { ...m, ...next } : m)));
+
+ const resetAll = () => setDraft((prev) => prev.map((m) => ({ ...m, enabled: false, target_model_id: '' })));
+
+ const commitAndClose = async () => {
+ if (saving) return;
+ if (sameDraft(draft, initialRef.current)) {
+ onClose();
+ return;
+ }
+ setSaving(true);
+ try {
+ // Contract: absent entry = 跟随原生 (identity). Send only enabled overrides
+ // — disabled rows carry an empty target_model_id that from_payload rejects.
+ await modelsApi.putMappings(backend, draft.filter((m) => m.enabled));
+ onSaved();
+ onClose();
+ } catch {
+ showToast(t('settings.models.menus.saveFailed') as string, 'error');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const anyOverride = draft.some((m) => m.enabled);
+
+ return (
+ <MenuDrawer
+ open={open}
+ onClose={() => void commitAndClose()}
+ Icon={Icon}
+ accent={accent}
+ title={t('settings.models.menus.mapping.title', { backend: backendName }) as string}
+ subtitle={t('settings.models.menus.mapping.subtitle', { backend: backendName }) as string}
+ footer={
+ <>
+ <Button variant="outline" size="sm" onClick={resetAll} disabled={!anyOverride || saving}>
+ <RotateCcw className="size-3.5" />
+ {t('settings.models.menus.resetAll')}
+ </Button>
+ <Button variant="brand" size="sm" onClick={() => void commitAndClose()} disabled={saving}>
+ {t('settings.models.menus.done')}
+ </Button>
+ </>
+ }
+ >
+ <div className="flex items-center gap-3 px-1 pb-2.5">
+ <span className="w-[172px] shrink-0 font-mono text-[11px] font-medium uppercase tracking-wide text-muted">
+ {t('settings.models.menus.mapping.builtinCol')}
+ </span>
+ <span className="font-mono text-[11px] font-medium uppercase tracking-wide text-muted">
+ {t('settings.models.menus.mapping.supplyCol')}
+ </span>
+ </div>
+
+ <div className="flex flex-col gap-2.5">
+ {draft.map((mapping) => {
+ const override = mapping.enabled && Boolean(mapping.target_model_id);
+ return (
+ <div key={mapping.builtin_id} className="flex items-start gap-2.5">
+ <div
+ className={cn(
+ 'flex flex-1 flex-col gap-2 rounded-xl border p-2.5',
+ override ? 'border-violet/40 bg-violet-soft/40' : 'border-border',
+ )}
+ >
+ <div className="flex items-center gap-2.5">
+ <div className="w-[172px] shrink-0">
+ <BuiltinChip id={mapping.builtin_id} />
+ </div>
+ <ArrowRight className={cn('size-4 shrink-0', override ? 'text-violet' : 'text-muted/60')} />
+ <div className="min-w-0 flex-1">
+ <SupplySelector
+ mapping={mapping}
+ targets={targets}
+ onFollowNative={() => setMapping(mapping.builtin_id, { enabled: false, target_model_id: '' })}
+ onOverride={(targetId) => setMapping(mapping.builtin_id, { enabled: true, target_model_id: targetId })}
+ />
+ </div>
+ </div>
+ {override && (
+ <p className="flex items-center gap-1.5 pl-[208px] text-[12px] text-gold">
+ <Info className="size-3.5 shrink-0" />
+ {t('settings.models.menus.mapping.warning')}
+ </p>
+ )}
+ </div>
+ <button
+ type="button"
+ aria-label={t('settings.models.menus.mapping.resetRow') as string}
+ onClick={() => setMapping(mapping.builtin_id, { enabled: false, target_model_id: '' })}
+ disabled={!override}
+ className={cn(
+ 'mt-0.5 flex size-11 shrink-0 items-center justify-center rounded-lg border border-border text-muted transition-colors',
+ override ? 'hover:border-border-strong hover:text-foreground' : 'opacity-0',
+ )}
+ >
+ <RotateCcw className="size-4" />
+ </button>
+ </div>
+ );
+ })}
+ </div>
+
+ <p className="mt-4 flex items-start gap-1.5 px-1 text-[12px] leading-relaxed text-muted">
+ <Info className="mt-0.5 size-3.5 shrink-0" />
+ {t('settings.models.menus.mapping.footnote', { backend: backendName })}
+ </p>
+ </MenuDrawer>
+ );
+};
diff --git a/ui/src/components/settings/models/menus/MenuDrawer.tsx b/ui/src/components/settings/models/menus/MenuDrawer.tsx
new file mode 100644
index 000000000..2f63675d8
--- /dev/null
+++ b/ui/src/components/settings/models/menus/MenuDrawer.tsx
@@ -0,0 +1,63 @@
+// Shared right-side sheet shell for the 模型菜单 drawers (frames 04 / 05r).
+// Built directly on the Radix dialog primitive (already a dependency) rather
+// than the centered `ui/dialog` Dialog, because these surfaces slide in from
+// the right edge and run full-height. Header (tinted icon tile + title +
+// subtitle + close), a scrollable body, and a sticky footer action bar.
+import * as React from 'react';
+import * as DialogPrimitive from '@radix-ui/react-dialog';
+import { X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { cn } from '@/lib/utils';
+import { ACCENT_ICON, ACCENT_TILE, type Accent } from '../vendorMeta';
+
+export const MenuDrawer: React.FC<{
+ open: boolean;
+ onClose: () => void;
+ Icon: React.ComponentType<{ size?: number; className?: string }>;
+ accent: Accent;
+ title: string;
+ subtitle: string;
+ /** Footer content; laid out with `justify-between` (left extras · right primary). */
+ footer: React.ReactNode;
+ children: React.ReactNode;
+}> = ({ open, onClose, Icon, accent, title, subtitle, footer, children }) => {
+ const { t } = useTranslation();
+ return (
+ <DialogPrimitive.Root open={open} onOpenChange={(v) => !v && onClose()}>
+ <DialogPrimitive.Portal>
+ <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-background/70 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
+ <DialogPrimitive.Content
+ className={cn(
+ 'fixed inset-y-0 right-0 z-50 flex w-full max-w-[620px] flex-col border-l border-border bg-card shadow-2xl outline-none',
+ 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:slide-in-from-right data-[state=closed]:slide-out-to-right data-[state=open]:duration-300 data-[state=closed]:duration-200',
+ )}
+ >
+ <header className="flex items-start gap-3 border-b border-border px-6 py-5">
+ <span className={cn('flex size-11 shrink-0 items-center justify-center rounded-[12px]', ACCENT_TILE[accent])}>
+ <Icon size={22} className={ACCENT_ICON[accent]} />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col gap-1 pt-0.5">
+ <DialogPrimitive.Title className="text-[18px] font-bold leading-tight text-foreground">
+ {title}
+ </DialogPrimitive.Title>
+ <DialogPrimitive.Description className="text-[13px] leading-relaxed text-muted">
+ {subtitle}
+ </DialogPrimitive.Description>
+ </div>
+ <DialogPrimitive.Close className="shrink-0 rounded-md p-1 text-muted opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring">
+ <X className="size-5" />
+ <span className="sr-only">{t('common.close')}</span>
+ </DialogPrimitive.Close>
+ </header>
+
+ <div className="flex-1 overflow-y-auto px-6 py-5">{children}</div>
+
+ <footer className="flex items-center justify-between gap-3 border-t border-border bg-surface/40 px-6 py-4">
+ {footer}
+ </footer>
+ </DialogPrimitive.Content>
+ </DialogPrimitive.Portal>
+ </DialogPrimitive.Root>
+ );
+};
diff --git a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
new file mode 100644
index 000000000..cd4fb9bce
--- /dev/null
+++ b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
@@ -0,0 +1,243 @@
+// 模型菜单 · OpenCode — the open-menu drawer (frame 05r). Models are grouped BY
+// provider prefix (one taxonomy); the full identifier is visible by construction
+// (group prefix + mono row id), friendly name secondary. 精选/全量 toggle,
+// checkbox = appears in OpenCode's picker, colored dots = supplying sources,
+// custom rows carry a 自定义 badge + edit. Commits via PUT .../menu on 完成.
+import * as React from 'react';
+import { Pencil, Plus } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import { SegmentedRadio } from '@/components/ui/segmented';
+import { useToast } from '@/context/ToastContext';
+import { modelsApi } from '../modelsApi';
+import { backendVisual } from '../vendorMeta';
+import type { AgentMenu, AgentSupply, Source } from '../types';
+import { MenuDrawer } from './MenuDrawer';
+import { AddCustomModelDialog } from './AddCustomModelDialog';
+import { buildMenuGroups, isSourceEligible, type MenuModelRow } from './identifiers';
+import { SupplyDots } from './supplyBits';
+
+type EditTarget = { sourceId: string; modelId: string; displayName: string | null } | null;
+
+const sameSet = (a: Set<string>, b: string[]): boolean =>
+ a.size === b.length && b.every((x) => a.has(x));
+
+const ModelRow: React.FC<{
+ row: MenuModelRow;
+ checked: boolean;
+ onToggle: () => void;
+ onEdit: () => void;
+}> = ({ row, checked, onToggle, onEdit }) => {
+ const { t } = useTranslation();
+ return (
+ <div className="flex items-center gap-3 rounded-xl border border-border px-3.5 py-3">
+ <Checkbox checked={checked} onCheckedChange={onToggle} label={row.identifier} />
+ <button type="button" onClick={onToggle} className="flex min-w-0 flex-1 items-center gap-2.5 text-left">
+ <span className="font-mono text-[14px] font-medium text-foreground">{row.modelId}</span>
+ {row.displayName && <span className="truncate text-[13px] text-muted">{row.displayName}</span>}
+ {row.isCustom && (
+ <Badge className="shrink-0 rounded-md bg-violet-soft px-2 py-0.5 text-[10px] font-medium text-violet">
+ {t('settings.models.menus.opencode.customBadge')}
+ </Badge>
+ )}
+ </button>
+ <SupplyDots accents={row.accents} className="flex shrink-0 items-center gap-1" />
+ {row.isCustom && (
+ <button
+ type="button"
+ aria-label={t('common.edit') as string}
+ onClick={onEdit}
+ className="shrink-0 rounded-md p-1 text-muted transition-colors hover:text-foreground"
+ >
+ <Pencil className="size-3.5" />
+ </button>
+ )}
+ </div>
+ );
+};
+
+export const OpenCodeMenuDrawer: React.FC<{
+ open: boolean;
+ agent: AgentSupply;
+ sources: Source[];
+ onClose: () => void;
+ onSaved: () => void;
+ /** Re-fetch sources after a custom model is added/edited. */
+ onRefresh: () => void;
+}> = ({ open, agent, sources, onClose, onSaved, onRefresh }) => {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+ const { Icon, accent } = backendVisual('opencode');
+
+ // Only OpenCode-eligible sources materialize as providers (isSourceEligible):
+ // API-key sources only — subscriptions (native_cli AND hub-held experimental)
+ // are excluded, matching the backend predicate, so we never offer a row the
+ // live `set_opencode_menu` would reject.
+ const eligibleSources = React.useMemo(() => sources.filter((s) => isSourceEligible(s, 'opencode')), [sources]);
+ const groups = React.useMemo(() => buildMenuGroups(eligibleSources), [eligibleSources]);
+ const allRows = React.useMemo(() => groups.flatMap((g) => g.rows), [groups]);
+
+ const [view, setView] = React.useState<'featured' | 'full'>(agent.menu?.view ?? 'featured');
+ const [checked, setChecked] = React.useState<Set<string>>(() => new Set(agent.menu?.checked ?? []));
+ const initialRef = React.useRef<AgentMenu>({ view, checked: [...checked] });
+ const [saving, setSaving] = React.useState(false);
+ const [customOpen, setCustomOpen] = React.useState(false);
+ const [editTarget, setEditTarget] = React.useState<EditTarget>(null);
+
+ React.useEffect(() => {
+ if (!open) return;
+ const v = agent.menu?.view ?? 'featured';
+ const c = agent.menu?.checked ?? [];
+ setView(v);
+ setChecked(new Set(c));
+ initialRef.current = { view: v, checked: [...c] };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ const featuredCount = allRows.filter((r) => checked.has(r.identifier)).length;
+ const fullCount = allRows.length;
+
+ const toggle = (identifier: string) =>
+ setChecked((prev) => {
+ const next = new Set(prev);
+ if (next.has(identifier)) next.delete(identifier);
+ else next.add(identifier);
+ return next;
+ });
+
+ const dirty = () => view !== initialRef.current.view || !sameSet(checked, initialRef.current.checked);
+
+ const commitAndClose = async () => {
+ if (saving) return;
+ if (!dirty()) {
+ onClose();
+ return;
+ }
+ setSaving(true);
+ try {
+ await modelsApi.putMenu({ view, checked: [...checked] });
+ onSaved();
+ onClose();
+ } catch {
+ showToast(t('settings.models.menus.saveFailed') as string, 'error');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const providerAnnotation = (provider: string) =>
+ t(`settings.models.menus.opencode.provider.${provider}`, { defaultValue: '' }) as string;
+
+ const visibleGroups = groups
+ .map((g) => ({
+ ...g,
+ rows: view === 'featured' ? g.rows.filter((r) => checked.has(r.identifier)) : g.rows,
+ }))
+ .filter((g) => g.rows.length > 0);
+
+ return (
+ <>
+ <MenuDrawer
+ open={open}
+ onClose={() => void commitAndClose()}
+ Icon={Icon}
+ accent={accent}
+ title={t('settings.models.menus.opencode.title') as string}
+ subtitle={t('settings.models.menus.opencode.subtitle') as string}
+ footer={
+ <>
+ <span />
+ <Button variant="brand" size="sm" onClick={() => void commitAndClose()} disabled={saving}>
+ {t('settings.models.menus.done')}
+ </Button>
+ </>
+ }
+ >
+ <div className="mb-4 flex items-center justify-between gap-3">
+ <div className="w-[220px]">
+ <SegmentedRadio
+ value={view}
+ onChange={setView}
+ ariaLabel={t('settings.models.menus.opencode.viewLabel') as string}
+ tone="muted"
+ options={[
+ { id: 'featured', label: t('settings.models.menus.opencode.featured', { count: featuredCount }) as string },
+ { id: 'full', label: t('settings.models.menus.opencode.full', { count: fullCount }) as string },
+ ]}
+ />
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className="border-violet/40 text-violet hover:border-violet/60 hover:text-violet"
+ onClick={() => {
+ setEditTarget(null);
+ setCustomOpen(true);
+ }}
+ >
+ <Plus className="size-4" />
+ {t('settings.models.menus.opencode.addCustom')}
+ </Button>
+ </div>
+
+ {visibleGroups.length === 0 ? (
+ <p className="px-1 py-8 text-center text-[13px] text-muted">{t('settings.models.menus.opencode.empty')}</p>
+ ) : (
+ <div className="flex flex-col gap-5">
+ {visibleGroups.map((group) => {
+ const annotation = providerAnnotation(group.provider);
+ return (
+ <div key={group.provider} className="flex flex-col gap-2">
+ <div className="flex items-baseline gap-2 px-1">
+ <span className="font-mono text-[13px] font-bold text-violet">{group.provider}/</span>
+ {annotation && <span className="text-[12px] text-muted">{annotation}</span>}
+ </div>
+ <div className="flex flex-col gap-2">
+ {group.rows.map((row) => (
+ <ModelRow
+ key={row.identifier}
+ row={row}
+ checked={checked.has(row.identifier)}
+ onToggle={() => toggle(row.identifier)}
+ onEdit={() => {
+ // Pull the display name from the CHOSEN manual model, not the
+ // aggregate row label (which may come from a discovered source),
+ // so saving unchanged can't overwrite it with another source's name.
+ const custom = row.sources.find((s) => s.models.some((m) => m.id === row.modelId && m.provenance === 'manual'));
+ const manual = custom?.models.find((m) => m.id === row.modelId && m.provenance === 'manual');
+ setEditTarget({ sourceId: (custom ?? row.sources[0]).id, modelId: row.modelId, displayName: manual?.display_name ?? null });
+ setCustomOpen(true);
+ }}
+ />
+ ))}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ <p className="mt-5 px-1 text-[12px] leading-relaxed text-muted">
+ {t('settings.models.menus.opencode.footnote')}
+ </p>
+ </MenuDrawer>
+
+ <AddCustomModelDialog
+ open={customOpen}
+ sources={eligibleSources}
+ edit={editTarget}
+ onClose={() => setCustomOpen(false)}
+ onSaved={(identifier) => {
+ // Auto-check only a NEWLY added model (so it shows in 精选). Editing an
+ // existing entry's metadata must not flip its menu-selection state — a
+ // display-name edit on an unchecked model would otherwise re-add it.
+ if (!editTarget) setChecked((prev) => new Set(prev).add(identifier));
+ onRefresh();
+ }}
+ />
+ </>
+ );
+};
diff --git a/ui/src/components/settings/models/menus/identifiers.ts b/ui/src/components/settings/models/menus/identifiers.ts
new file mode 100644
index 000000000..3238c7f00
--- /dev/null
+++ b/ui/src/components/settings/models/menus/identifiers.ts
@@ -0,0 +1,182 @@
+// OpenCode identifier scheme (spec §4.4, locked 07-23; opencode-overlay.md).
+// Identifiers are `provider/model-id`. The provider segment is the standard
+// vendor id; unrecognizable vendors fall back to a single `custom/` provider.
+// Identifiers are STABLE across Hub/Direct switches and across source
+// add/remove/failover — they never encode a concrete source. Users never
+// hand-assemble the string: the menu checkboxes and the custom-model form
+// generate and preview it.
+import type { Accent } from '../vendorMeta';
+import { sourceAccent } from '../vendorMeta';
+import type { AgentBackend, Source } from '../types';
+
+// Standard vendor ids that map 1:1 to an OpenCode provider prefix (identical to
+// native OpenCode usage — no `avibe-` namespace).
+//
+// MOCK MIRROR of the backend `STANDARD_OPENCODE_VENDOR_IDS`
+// (core/handlers/model_hub/identifiers.py). ESCALATED (2026-07-23): the UI
+// cannot import the Python list, so any divergence makes `set_opencode_menu`
+// reject identifiers in live mode. Authoritative source should be the backend
+// in the integration pass (surfaced via contract, like `builtin_models`); this
+// set is the interim mirror and the single swap point.
+const STANDARD_OPENCODE_VENDORS = new Set([
+ 'anthropic',
+ 'openai',
+ 'zhipuai',
+ 'kimi',
+ 'moonshot',
+ 'xai',
+ 'google',
+ 'deepseek',
+ 'mistral',
+ 'groq',
+ 'openrouter',
+ 'together',
+]);
+
+/**
+ * Provider segment for a source's model, per the FROZEN opencode-overlay.md
+ * contract: it is the SOURCE's vendor when that is a standard vendor id, else
+ * the single `custom` provider. It is deliberately NOT inferred from the model
+ * name — that must byte-match the backend's `opencode_model_id(source.vendor,
+ * model.id)`, or `set_opencode_menu` rejects the checked value with
+ * `mapping_target_unavailable`. So `relay.example` (vendor `custom`) supplying
+ * `glm-5.2-air` yields `custom/glm-5.2-air` (not `zhipuai/…`).
+ */
+export function inferProvider(sourceVendor: string): string {
+ return STANDARD_OPENCODE_VENDORS.has(sourceVendor) ? sourceVendor : 'custom';
+}
+
+/** Full prefixed identifier for a (source vendor, model id). */
+export function buildIdentifier(sourceVendor: string, modelId: string): string {
+ return `${inferProvider(sourceVendor)}/${modelId}`;
+}
+
+// Which backend a fixed-menu backend's own native subscription belongs to
+// (its sanctioned native_cli client): Claude sub → claude, ChatGPT sub → codex.
+const NATIVE_SUB_VENDOR: Partial<Record<AgentBackend, string>> = {
+ claude: 'anthropic',
+ codex: 'openai',
+};
+
+/**
+ * SINGLE chokepoint mirroring the backend `_eligible_for_agent` predicate — the
+ * one place that decides whether a source may feed an agent's menu/mapping, so
+ * the drawers never re-derive eligibility from `supply_channel` piecemeal.
+ *
+ * - OpenCode (open menu): only API-key sources materialize as providers;
+ * subscriptions (native_cli AND hub-held experimental) are excluded.
+ * - Fixed-menu (Claude / Codex mapping targets): any hub-supplied API-key
+ * source, PLUS this backend's own native subscription (a Claude sub is a
+ * valid target for Claude Code, a ChatGPT sub for Codex).
+ *
+ * ESCALATED (2026-07-23): this mirrors backend logic the UI can't read; the
+ * integration pass should drive it from a backend-provided signal (like
+ * `builtin_models`). This function is the swap point.
+ */
+export function isSourceEligible(source: Source, backend: AgentBackend): boolean {
+ if (backend === 'opencode') return source.kind === 'api_key';
+ if (source.kind === 'api_key') return true;
+ return source.kind === 'subscription' && source.vendor === NATIVE_SUB_VENDOR[backend];
+}
+
+// ── Grouped menu model, derived from the ordered sources list ──────────────
+
+export type MenuModelRow = {
+ /** Full prefixed identifier, e.g. `zhipuai/glm-5.2`. */
+ identifier: string;
+ /** Group prefix (the provider segment). */
+ provider: string;
+ /** Bare model id (no prefix). */
+ modelId: string;
+ displayName: string | null;
+ /** True when any supplying entry is a manual (custom) model. */
+ isCustom: boolean;
+ /** Supplying sources, in the order they appear in the input list (priority). */
+ sources: Source[];
+ /** Deduped supplying-source accents, for the row's supply dots. */
+ accents: Accent[];
+};
+
+export type MenuGroup = {
+ provider: string;
+ rows: MenuModelRow[];
+};
+
+/**
+ * Build the grouped, deduped model rows for the OpenCode open menu (frame 05r).
+ * `sources` MUST already be in priority order so the supply dots and candidate
+ * order track the 来源 band. The same identifier supplied by several sources
+ * collapses into one row carrying every supplying source.
+ */
+export function buildMenuGroups(sources: Source[]): MenuGroup[] {
+ const byIdentifier = new Map<string, MenuModelRow>();
+ for (const source of sources) {
+ for (const model of source.models) {
+ const identifier = buildIdentifier(source.vendor, model.id);
+ let row = byIdentifier.get(identifier);
+ if (!row) {
+ row = {
+ identifier,
+ provider: identifier.slice(0, identifier.indexOf('/')),
+ modelId: model.id,
+ displayName: model.display_name ?? null,
+ isCustom: model.provenance === 'manual',
+ sources: [],
+ accents: [],
+ };
+ byIdentifier.set(identifier, row);
+ }
+ if (model.display_name && !row.displayName) row.displayName = model.display_name;
+ if (model.provenance === 'manual') row.isCustom = true;
+ row.sources.push(source);
+ const accent = sourceAccent(source);
+ if (!row.accents.includes(accent)) row.accents.push(accent);
+ }
+ }
+ // Group by provider, preserving first-seen order (which follows priority).
+ const groups: MenuGroup[] = [];
+ const byProvider = new Map<string, MenuGroup>();
+ for (const row of byIdentifier.values()) {
+ let group = byProvider.get(row.provider);
+ if (!group) {
+ group = { provider: row.provider, rows: [] };
+ byProvider.set(row.provider, group);
+ groups.push(group);
+ }
+ group.rows.push(row);
+ }
+ return groups;
+}
+
+// ── Fixed-menu (mapping) helpers ───────────────────────────────────────────
+
+export type TargetModel = {
+ /** Bare model id. */
+ id: string;
+ displayName: string | null;
+ /** Sources able to supply it, in priority order. */
+ sources: Source[];
+ accents: Accent[];
+};
+
+/**
+ * Distinct target models a fixed-menu override can point at — the union of every
+ * source's supplied model ids, in priority order (frame 04 dropdown).
+ */
+export function buildTargetModels(sources: Source[]): TargetModel[] {
+ const byId = new Map<string, TargetModel>();
+ for (const source of sources) {
+ for (const model of source.models) {
+ let target = byId.get(model.id);
+ if (!target) {
+ target = { id: model.id, displayName: model.display_name ?? null, sources: [], accents: [] };
+ byId.set(model.id, target);
+ }
+ if (model.display_name && !target.displayName) target.displayName = model.display_name;
+ target.sources.push(source);
+ const accent = sourceAccent(source);
+ if (!target.accents.includes(accent)) target.accents.push(accent);
+ }
+ }
+ return [...byId.values()];
+}
diff --git a/ui/src/components/settings/models/menus/sourceLabel.ts b/ui/src/components/settings/models/menus/sourceLabel.ts
new file mode 100644
index 000000000..88fd32f90
--- /dev/null
+++ b/ui/src/components/settings/models/menus/sourceLabel.ts
@@ -0,0 +1,23 @@
+// Compact source label used in the mapping candidate line ("智谱 / relay.example",
+// frame 04): the vendor's friendly name for known vendors, else the source
+// display name (host for a custom endpoint). Kept in its own module so
+// `supplyBits.tsx` stays component-only (react-refresh).
+import * as React from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { Source } from '../types';
+
+/** Returns a stable function mapping a source to a compact label. */
+export function useCompactSourceLabel(): (source: Source) => string {
+ const { t } = useTranslation();
+ return React.useCallback(
+ (source: Source) => {
+ if (source.vendor && source.vendor !== 'custom') {
+ const label = t(`settings.models.addKey.vendors.${source.vendor}`, { defaultValue: '' }) as string;
+ if (label) return label;
+ }
+ return source.display_name;
+ },
+ [t],
+ );
+}
diff --git a/ui/src/components/settings/models/menus/supplyBits.tsx b/ui/src/components/settings/models/menus/supplyBits.tsx
new file mode 100644
index 000000000..afdf8a7fb
--- /dev/null
+++ b/ui/src/components/settings/models/menus/supplyBits.tsx
@@ -0,0 +1,16 @@
+// The supply dots — one colored dot per supplying source (frames 04 / 05r).
+// (The compact source label hook lives in ./sourceLabel to keep this file
+// component-only for fast refresh.)
+import * as React from 'react';
+
+import { Dot } from '../chips';
+import type { Accent } from '../vendorMeta';
+
+/** A run of supply dots — colored per supplying source. */
+export const SupplyDots: React.FC<{ accents: Accent[]; className?: string }> = ({ accents, className }) => (
+ <span className={className}>
+ {accents.map((accent, i) => (
+ <Dot key={`${accent}-${i}`} accent={accent} />
+ ))}
+ </span>
+);
diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.ts
index bc0b3338b..752a9c1c8 100644
--- a/ui/src/components/settings/models/mockData.ts
+++ b/ui/src/components/settings/models/mockData.ts
@@ -4,12 +4,14 @@
// time so the 最近切换 list always renders 今天 / 昨天 correctly.
import type {
AgentSupply,
+ MigrationScan,
Priority,
ResolutionEvent,
RuntimeDependency,
Source,
} from './types';
import { CONTRACT_VERSION } from './types';
+import { SUBSCRIPTION_HUB_EXPERIMENTAL } from './featureFlags';
const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString();
const MIN = 60_000;
@@ -132,7 +134,13 @@ export function buildMockAgents(): AgentSupply[] {
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 }],
+ // Fixed-menu backends surface their full built-in id list as mappings; an
+ // enabled entry is an override (frame 04), disabled = 跟随原生 (identity).
+ mappings: [
+ { builtin_id: 'claude-opus-4-6', target_model_id: 'glm-5.2', enabled: true },
+ { builtin_id: 'claude-sonnet-4-6', target_model_id: '', enabled: false },
+ { builtin_id: 'claude-haiku-4-5', target_model_id: '', enabled: false },
+ ],
menu: null,
},
{
@@ -140,7 +148,10 @@ export function buildMockAgents(): AgentSupply[] {
mode: 'direct',
menu_kind: 'fixed',
current: null,
- mappings: [],
+ mappings: [
+ { builtin_id: 'gpt-5.6', target_model_id: '', enabled: false },
+ { builtin_id: 'gpt-5.6-mini', target_model_id: '', enabled: false },
+ ],
menu: null,
},
{
@@ -149,14 +160,19 @@ export function buildMockAgents(): AgentSupply[] {
menu_kind: 'open',
current: { model_id: 'glm-5.2', source_id: 'src_zhipukey01', channel: 'hub' },
mappings: [],
+ // Prefixed identifiers (opencode-overlay.md): provider = the SOURCE's
+ // vendor (custom fallback), and only hub-channel sources materialize as
+ // OpenCode providers — so every checked id is backed by a hub source in
+ // buildMockSources (the two native_cli subscriptions never appear here).
+ // checked = 精选 (in the picker); the rest live under 全量.
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}`),
+ 'anthropic/claude-opus-4-6',
+ 'anthropic/claude-sonnet-4-6',
+ 'zhipuai/glm-5.2',
+ 'zhipuai/glm-5.2-air',
+ 'zhipuai/glm-5-flash',
],
},
},
@@ -226,6 +242,60 @@ export function buildMockRuntime(): RuntimeDependency {
};
}
+// Migration scan fixture (frame 03). Mirrors the frozen migration-scan schema
+// example, adapted to the mock backends. Per spec v1.1 + the 2026-07-23 L6
+// finding: API keys / base URLs → import; subscription OAuth (Claude account +
+// Codex auth.json) → keep_native ALWAYS (controlled_import is deferred — adapter
+// v1.2 forbids OAuth material in provision_credential). When the experimental
+// flag is on, those rows only add a "re-authorize inside the hub" hint; they
+// never become an import. So this fixture emits only import / keep_native.
+export function buildMockMigration(): MigrationScan {
+ // Subscription-OAuth rows stay native; the flag only swaps their hint line.
+ const oauthNote = SUBSCRIPTION_HUB_EXPERIMENTAL
+ ? 'settings.models.migration.notes.keepNativeReauthHint'
+ : 'settings.models.migration.notes.keepNativeSanctioned';
+ return {
+ items: [
+ {
+ id: 'mig_claude_key',
+ backend: 'claude',
+ kind: 'api_key',
+ masked_detail: 'Anthropic API Key · sk-…dd3c',
+ proposed_action: 'import',
+ selected: true,
+ notes_key: 'settings.models.migration.notes.customBaseUrl',
+ },
+ {
+ id: 'mig_claude_oauth',
+ backend: 'claude',
+ kind: 'oauth_native',
+ masked_detail: 'Claude 账号登录(OAuth)',
+ proposed_action: 'keep_native',
+ selected: false,
+ notes_key: oauthNote,
+ },
+ {
+ id: 'mig_codex_auth',
+ backend: 'codex',
+ kind: 'oauth_native',
+ masked_detail: 'ChatGPT 登录 · auth.json',
+ proposed_action: 'keep_native',
+ selected: false,
+ notes_key: oauthNote,
+ },
+ {
+ id: 'mig_opencode_zhipu',
+ backend: 'opencode',
+ kind: 'opencode_provider',
+ masked_detail: '智谱 API Key · glm-…c31b',
+ proposed_action: 'import',
+ selected: true,
+ notes_key: 'settings.models.migration.notes.fromOpencode',
+ },
+ ],
+ };
+}
+
// 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 };
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index df31f2b6c..96c097cf8 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -11,6 +11,7 @@ import { MODELS_API_MODE } from './featureFlags';
import {
buildMockAgents,
buildMockEvents,
+ buildMockMigration,
buildMockPriority,
buildMockRuntime,
buildMockSources,
@@ -18,9 +19,14 @@ import {
} from './mockData';
import type {
AgentBackend,
+ AgentMapping,
+ AgentMenu,
AgentMode,
AgentSupply,
ApiKeySourceCreate,
+ CustomModelCreate,
+ MigrationApplyResult,
+ MigrationScan,
OAuthFlow,
Priority,
ResolutionEvent,
@@ -37,6 +43,12 @@ export type ModelsApi = {
putPriority(order: string[]): Promise<Priority>;
listAgents(): Promise<AgentSupply[]>;
setAgentMode(backend: AgentBackend, mode: AgentMode): Promise<AgentSupply>;
+ putMappings(backend: AgentBackend, mappings: AgentMapping[]): Promise<AgentSupply>;
+ putMenu(menu: AgentMenu): Promise<AgentSupply>;
+ addCustomModel(draft: CustomModelCreate): Promise<Source>;
+ deleteCustomModel(sourceId: string, modelId: string): Promise<Source>;
+ scanMigration(): Promise<MigrationScan>;
+ applyMigration(itemIds: string[]): Promise<MigrationApplyResult>;
listEvents(limit?: number): Promise<ResolutionEvent[]>;
getRuntimeStatus(): Promise<RuntimeDependency>;
startOAuth(vendor: string, channel: SupplyChannel): Promise<OAuthFlow>;
@@ -86,6 +98,12 @@ const liveApi: ModelsApi = {
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),
+ putMappings: (backend, mappings) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mappings`, jsonInit('PUT', { mappings })).then((r) => (r.agent ?? r) as AgentSupply),
+ putMenu: (menu) => call<{ agent?: AgentSupply } & AgentSupply>('/api/models/agents/opencode/menu', jsonInit('PUT', { menu })).then((r) => (r.agent ?? r) as AgentSupply),
+ addCustomModel: (draft) => call<{ source?: Source } & Source>('/api/models/custom-models', jsonInit('POST', draft)).then((r) => (r.source ?? r) as Source),
+ deleteCustomModel: (sourceId, modelId) => call<{ source?: Source } & Source>('/api/models/custom-models', jsonInit('DELETE', { source_id: sourceId, model_id: modelId })).then((r) => (r.source ?? r) as Source),
+ scanMigration: () => call<{ scan?: MigrationScan } & MigrationScan>('/api/models/migration/scan', jsonInit('POST')).then((r) => (r.scan ?? r) as MigrationScan),
+ applyMigration: (itemIds) => call<MigrationApplyResult>('/api/models/migration/apply', jsonInit('POST', { item_ids: itemIds })),
listEvents: (limit = 20) => call<{ events: ResolutionEvent[] }>(`/api/models/events?limit=${limit}`).then((r) => r.events),
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),
@@ -184,6 +202,89 @@ class MockStore {
return delay(structuredClone(agent));
}
+ putMappings(backend: AgentBackend, mappings: AgentMapping[]) {
+ const agent = this.agents.find((a) => a.backend === backend);
+ if (!agent) throw new ApiCallError('source_not_found');
+ agent.mappings = mappings;
+ return delay(structuredClone(agent));
+ }
+
+ putMenu(menu: AgentMenu) {
+ const agent = this.agents.find((a) => a.backend === 'opencode');
+ if (!agent) throw new ApiCallError('source_not_found');
+ agent.menu = menu;
+ return delay(structuredClone(agent));
+ }
+
+ addCustomModel(draft: CustomModelCreate) {
+ const source = this.sources.find((s) => s.id === draft.source_id);
+ if (!source) throw new ApiCallError('source_not_found');
+ const existing = source.models.find((m) => m.id === draft.model_id);
+ if (existing) {
+ existing.display_name = draft.display_name ?? existing.display_name;
+ existing.provenance = 'manual';
+ } else {
+ source.models.push({
+ id: draft.model_id,
+ display_name: draft.display_name ?? null,
+ provenance: 'manual',
+ discovered_at: null,
+ });
+ }
+ return delay(structuredClone(source), 400);
+ }
+
+ deleteCustomModel(sourceId: string, modelId: string) {
+ const source = this.sources.find((s) => s.id === sourceId);
+ if (!source) throw new ApiCallError('source_not_found');
+ source.models = source.models.filter((m) => !(m.id === modelId && m.provenance === 'manual'));
+ return delay(structuredClone(source));
+ }
+
+ scanMigration() {
+ // Read-only: recompute the fixture each call so re-scans stay idempotent.
+ return delay(buildMockMigration(), 500);
+ }
+
+ applyMigration(itemIds: string[]) {
+ const scan = buildMockMigration();
+ // reauth needs the interactive OAuth flow, so it is never bulk-applied here.
+ const chosen = scan.items.filter((i) => itemIds.includes(i.id) && i.proposed_action !== 'reauth');
+ // Copy-only: each selected native config materializes a new source; the
+ // (simulated) originals are never touched. import lands on the hub channel;
+ // keep_native registers a sanctioned native_cli source. (controlled_import
+ // is deferred per the 2026-07-23 L6 finding, so it's never emitted here.)
+ for (const item of chosen) {
+ const isKey = item.kind === 'api_key' || item.kind === 'opencode_provider';
+ const channel: SupplyChannel = item.proposed_action === 'keep_native' ? 'native_cli' : 'hub';
+ this.sources.push({
+ id: rid('src'),
+ kind: isKey ? 'api_key' : 'subscription',
+ vendor: item.backend === 'opencode' ? 'zhipuai' : item.backend === 'codex' ? 'openai' : 'anthropic',
+ display_name: item.masked_detail.split(' · ')[0] || 'Imported',
+ protocol: item.backend === 'codex' ? 'openai_responses' : 'anthropic',
+ base_url: null,
+ supply_channel: channel,
+ // No hub-held subscription is created by migration, so never consented.
+ experimental_consent_at: null,
+ billing: isKey ? 'metered' : 'monthly',
+ state: { status: 'standby', retry_at: null, detail_key: null },
+ usage: isKey ? { cycle_used_pct: null, month_spend_cents: 0, currency: 'CNY' } : { cycle_used_pct: 0, month_spend_cents: null, currency: null },
+ account_label: channel === 'native_cli' ? '[email protected]' : null,
+ masked_credential: isKey ? 'sk-…dd3c' : null,
+ models: [{ id: item.backend === 'opencode' ? 'glm-5.2' : item.backend === 'codex' ? 'gpt-5.6' : 'claude-opus-4-6', display_name: null, provenance: 'discovered', discovered_at: new Date().toISOString() }],
+ credential_ref: channel === 'hub' ? rid('cred') : null,
+ });
+ }
+ // Enable hub on the backends that received a hub-channel import.
+ for (const backend of new Set(chosen.filter((i) => i.proposed_action !== 'keep_native').map((i) => i.backend))) {
+ const agent = this.agents.find((a) => a.backend === backend);
+ if (agent) agent.mode = 'hub';
+ }
+ this.priority.order = this.sources.map((s) => s.id);
+ return delay({ applied: chosen.length, sources: structuredClone(this.ordered()) }, 700);
+ }
+
listEvents(limit = 20) {
return delay(structuredClone(this.events.slice(0, limit)));
}
@@ -319,6 +420,12 @@ const mockApi: ModelsApi = {
putPriority: (order) => mockStore.putPriority(order),
listAgents: () => mockStore.listAgents(),
setAgentMode: (backend, mode) => mockStore.setAgentMode(backend, mode),
+ putMappings: (backend, mappings) => mockStore.putMappings(backend, mappings),
+ putMenu: (menu) => mockStore.putMenu(menu),
+ addCustomModel: (draft) => mockStore.addCustomModel(draft),
+ deleteCustomModel: (sourceId, modelId) => mockStore.deleteCustomModel(sourceId, modelId),
+ scanMigration: () => mockStore.scanMigration(),
+ applyMigration: (itemIds) => mockStore.applyMigration(itemIds),
listEvents: (limit) => mockStore.listEvents(limit),
getRuntimeStatus: () => mockStore.getRuntimeStatus(),
startOAuth: (vendor, channel) => mockStore.startOAuth(vendor, channel),
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 2f102acfa..0c59272f0 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -109,6 +109,27 @@ export type AgentSupply = {
menu?: AgentMenu | null;
};
+// ── migration-scan.schema.json ──────────────────────────────────────────
+export type MigrationKind = 'api_key' | 'oauth_native' | 'opencode_provider';
+/** Option 1 (spec v1.1): Claude oauth_native → keep_native (sanctioned as-is);
+ * Codex auth.json → controlled_import behind the consent-gated flag, else
+ * keep_native; keys / base URLs → import. */
+export type MigrationAction = 'import' | 'controlled_import' | 'keep_native' | 'reauth';
+
+export type MigrationItem = {
+ id: string;
+ backend: AgentBackend;
+ kind: MigrationKind;
+ /** e.g. "sk-…dd3c + 自定义 Base URL"; never full secrets. */
+ masked_detail: string;
+ proposed_action: MigrationAction;
+ selected: boolean;
+ /** i18n key for the row's secondary line. */
+ notes_key?: string | null;
+};
+
+export type MigrationScan = { items: MigrationItem[] };
+
// ── resolution-event.schema.json ────────────────────────────────────────
export type ResolutionEventKind =
| 'switch'
@@ -212,3 +233,17 @@ export type ApiKeySourceCreate = {
base_url?: string | null;
key: string;
};
+
+/** POST /api/models/custom-models — appends a manual-provenance model entry to
+ * a source's supply list (frame 08). */
+export type CustomModelCreate = {
+ source_id: string;
+ model_id: string;
+ display_name?: string | null;
+};
+
+/** POST /api/models/migration/apply response. */
+export type MigrationApplyResult = {
+ applied: number;
+ sources: Source[];
+};
diff --git a/ui/src/components/settings/models/vendorMeta.tsx b/ui/src/components/settings/models/vendorMeta.tsx
index af57ec2d7..a77ca038f 100644
--- a/ui/src/components/settings/models/vendorMeta.tsx
+++ b/ui/src/components/settings/models/vendorMeta.tsx
@@ -102,3 +102,13 @@ export const VENDOR_OPTIONS: VendorOption[] = [
];
export const DEFAULT_VENDOR = VENDOR_OPTIONS[0];
+
+// An api_key points at a custom endpoint when its base URL is set and differs
+// from the vendor's official one — covers both vendor='custom' (official = null)
+// and an official vendor whose prefilled Base URL was edited to a relay. Shared
+// by the 来源 list (SourceRow) and the custom-model source picker.
+export function isCustomEndpoint(source: Pick<Source, 'vendor' | 'base_url'>): boolean {
+ if (!source.base_url) return false;
+ const official = VENDOR_OPTIONS.find((v) => v.value === source.vendor)?.base_url ?? null;
+ return source.base_url !== official;
+}
diff --git a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
index 3d34110ab..a134cc3fd 100644
--- a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
@@ -20,6 +20,8 @@ import { Label } from '../../ui/label';
import { BackendOAuthPanel } from '../BackendOAuthPanel';
import { BackendTestPanel } from '../BackendTestPanel';
import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';
+import { BackendSupplyModeCard } from '../models/BackendSupplyModeCard';
+import { MODEL_HUB_NAV_ENABLED } from '../models/featureFlags';
import { SegmentedRadio } from '../shared/SegmentedRadio';
import { useBackendRuntime } from '../shared/useBackendRuntime';
import { useOAuthFlowLock } from '../shared/useOAuthFlowLock';
@@ -219,6 +221,9 @@ export const ClaudeProviderConfig: React.FC<{
hideEnableToggle={hideEnableToggle}
/>
+ {/* Model Hub 供给方式 card (L5); flag-gated until the hub feature is advertised. */}
+ {MODEL_HUB_NAV_ENABLED && <BackendSupplyModeCard backend="claude" />}
+
{authLoading ? (
<div className="text-sm text-muted">{t('common.loading')}</div>
) : (
diff --git a/ui/src/components/settings/providers/CodexProviderConfig.tsx b/ui/src/components/settings/providers/CodexProviderConfig.tsx
index 0a8d21ad9..739448be1 100644
--- a/ui/src/components/settings/providers/CodexProviderConfig.tsx
+++ b/ui/src/components/settings/providers/CodexProviderConfig.tsx
@@ -13,6 +13,8 @@ import { useToast } from '@/context/ToastContext';
import { BackendOAuthPanel } from '../BackendOAuthPanel';
import { BackendTestPanel } from '../BackendTestPanel';
import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';
+import { BackendSupplyModeCard } from '../models/BackendSupplyModeCard';
+import { MODEL_HUB_NAV_ENABLED } from '../models/featureFlags';
import { SegmentedRadio } from '../shared/SegmentedRadio';
import { surfaceBackendNotices } from '../shared/surfaceBackendNotices';
import { useBackendRuntime } from '../shared/useBackendRuntime';
@@ -223,6 +225,9 @@ export const CodexProviderConfig: React.FC<{
hideEnableToggle={hideEnableToggle}
/>
+ {/* Model Hub 供给方式 card (L5); flag-gated until the hub feature is advertised. */}
+ {MODEL_HUB_NAV_ENABLED && <BackendSupplyModeCard backend="codex" />}
+
<Card>
<CardContent className="flex flex-col gap-5 p-6">
<div className="flex flex-col gap-2">
diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
index 5a6848e0b..b0299bae7 100644
--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
@@ -32,6 +32,8 @@ import { Popover, PopoverContent, PopoverTrigger } from '../../ui/popover';
import { BackendOAuthPanel } from '../BackendOAuthPanel';
import { OpencodeProviderTestPanel } from '../OpencodeProviderTestPanel';
import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';
+import { BackendSupplyModeCard } from '../models/BackendSupplyModeCard';
+import { MODEL_HUB_NAV_ENABLED } from '../models/featureFlags';
import { OpencodePermissionSetup } from '../shared/OpencodePermissionSetup';
import { useBackendRuntime } from '../shared/useBackendRuntime';
import { useOpencodePermission } from '../shared/useOpencodePermission';
@@ -795,6 +797,9 @@ export const OpencodeProviderConfig: React.FC<{
}
/>
+ {/* Model Hub 供给方式 card (L5); flag-gated until the hub feature is advertised. */}
+ {MODEL_HUB_NAV_ENABLED && <BackendSupplyModeCard backend="opencode" />}
+
{/* Card 2 — provider catalog. */}
<Card>
<CardContent className="flex flex-col gap-5 p-6">
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 0e3954711..b10cb842e 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -767,6 +767,97 @@
"connectFailed": "Couldn't connect, please retry",
"refreshFailed": "Couldn't refresh, please retry"
},
+ "menus": {
+ "done": "Done",
+ "resetAll": "Reset all to default",
+ "saveFailed": "Couldn't save your changes, please retry",
+ "mapping": {
+ "title": "{{backend}} · Model menu",
+ "subtitle": "Fixed menu: {{backend}} only recognizes these built-in model IDs. Each ID can be redirected to another model — this affects {{backend}} only.",
+ "builtinCol": "Built-in model ID",
+ "supplyCol": "Actual supply",
+ "followNative": "Follow native · supply by priority",
+ "candidates": "By priority · {{sources}}",
+ "candidatesUnavailable": "No source can supply this model yet",
+ "warning": "Reasoning, cache and tool semantics aren't fully equivalent after remapping",
+ "resetRow": "Reset to default",
+ "footnote": "Remapping affects only this ID in {{backend}}; the Hub converts protocols automatically."
+ },
+ "opencode": {
+ "title": "OpenCode · Model menu",
+ "subtitle": "Open menu: grouped by provider prefix. Prefix + model ID = the full identifier, identical to native OpenCode. Checked = shown in the model picker.",
+ "viewLabel": "Menu scope",
+ "featured": "Featured · {{count}}",
+ "full": "All · {{count}}",
+ "addCustom": "Custom model",
+ "empty": "No models here yet.",
+ "footnote": "Prefix = the standard vendor ID (identical to native OpenCode; unrecognized vendors fall under custom/). Switching Hub/Direct never changes the identifier; dots = supplying sources.",
+ "customBadge": "Custom",
+ "provider": {
+ "anthropic": "Anthropic protocol · Claude family",
+ "openai": "OpenAI protocol · GPT family",
+ "zhipuai": "OpenAI-compatible · GLM family",
+ "custom": "Custom endpoints"
+ }
+ },
+ "custom": {
+ "title": "Add a custom model",
+ "subtitle": "Register a model that discovery missed and add it to the OpenCode menu.",
+ "sourceLabel": "Source (able to supply this model)",
+ "modelIdLabel": "Model ID",
+ "modelIdPlaceholder": "glm-5.2-air",
+ "displayNameLabel": "Display name (optional)",
+ "displayNamePlaceholder": "GLM 5.2 Air",
+ "previewLabel": "OpenCode identifier · generated",
+ "previewEmpty": "Enter a model ID to preview",
+ "previewHint": "The provider segment is chosen automatically: a recognized vendor uses its standard ID (identical to native OpenCode), otherwise it falls under custom/. Adding or removing sources and switching modes never change the identifier.",
+ "add": "Add to menu",
+ "failed": "Couldn't add the model, please retry"
+ }
+ },
+ "supplyMode": {
+ "title": "Supply mode",
+ "currentHub": "Current: Hub",
+ "currentDirect": "Current: Direct",
+ "switchedHub": "Switched to Hub",
+ "switchedDirect": "Switched to Direct",
+ "switchFailed": "Couldn't switch mode, please retry",
+ "hub": {
+ "title": "Hub mode",
+ "recommended": "Recommended · default",
+ "openModels": "Open Models page",
+ "description": "Model tokens are supplied from Settings → Models: sign-ins, API keys, priority and mappings all live there. {{backend}}'s native config is left untouched, and you can switch away anytime."
+ },
+ "direct": {
+ "title": "Direct mode",
+ "description": "{{backend}} uses its own native config (settings.json / CLI sign-in); Avibe only launches the process and doesn't manage models. Good for troubleshooting or fully self-managed setups.",
+ "detected": "Existing direct config detected: {{detail}} — import it into the Hub in one click",
+ "import": "Import to Hub…"
+ }
+ },
+ "migration": {
+ "title": "Connect to the Model Hub",
+ "subtitle": "Move your existing sign-ins and API keys into the Models Hub in one pass — all three Agents share one set of sources and priority.",
+ "empty": "No native configuration detected to migrate.",
+ "scanFailed": "Couldn't scan native configs, please retry",
+ "applyFailed": "Import failed, please retry",
+ "applied": "Imported {{count}} item(s)",
+ "later": "Maybe later",
+ "apply": "Import {{count}} & enable Hub",
+ "nonDestructive": "Non-destructive: native configs are never changed or deleted — importing only copies them; you can switch back to Direct on the Backends page anytime.",
+ "action": {
+ "import": "Import as source",
+ "controlledImport": "Controlled import · experimental",
+ "keepNative": "Keep native",
+ "reauth": "Re-authorize · one-click in browser"
+ },
+ "notes": {
+ "customBaseUrl": "Includes a custom Base URL",
+ "keepNativeSanctioned": "Stays in the CLI's own store (sanctioned)",
+ "keepNativeReauthHint": "Kept native; re-authorize inside the hub to make it hub-held (experimental)",
+ "fromOpencode": "From the opencode config"
+ }
+ },
"backends": {
"claude": "Claude Code",
"codex": "Codex",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1d0d60cf9..57ae0c89e 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -767,6 +767,97 @@
"connectFailed": "接入失败,请重试",
"refreshFailed": "刷新失败,请重试"
},
+ "menus": {
+ "done": "完成",
+ "resetAll": "恢复全部默认",
+ "saveFailed": "保存失败,请重试",
+ "mapping": {
+ "title": "{{backend}} · 模型菜单",
+ "subtitle": "菜单固定:{{backend}} 只认这些内置 model ID;每个 ID 可改写为其他模型供给,只影响 {{backend}}。",
+ "builtinCol": "内置 MODEL ID",
+ "supplyCol": "实际供给",
+ "followNative": "跟随原生 · 按优先级供给",
+ "candidates": "来源按优先级 · {{sources}}",
+ "candidatesUnavailable": "暂无来源可供给此模型",
+ "warning": "改写后思维链、缓存与工具语义与原生不完全等价",
+ "resetRow": "恢复默认",
+ "footnote": "改写只影响 {{backend}} 的这个 ID;协议转换由中枢自动完成。"
+ },
+ "opencode": {
+ "title": "OpenCode · 模型菜单",
+ "subtitle": "菜单开放:按 provider 前缀分组,前缀 + 模型 ID = 完整标识,与 OpenCode 原生写法一致。勾选 = 出现在模型选择里。",
+ "viewLabel": "菜单范围",
+ "featured": "精选 · {{count}}",
+ "full": "全量 · {{count}}",
+ "addCustom": "自定义模型",
+ "empty": "这里还没有模型。",
+ "footnote": "前缀 = 厂商标准 ID(与 OpenCode 原生一致,识别不了归 custom/);中枢 / 直连切换不改变标识;圆点 = 可供来源。",
+ "customBadge": "自定义",
+ "provider": {
+ "anthropic": "Anthropic 协议 · Claude 系",
+ "openai": "OpenAI 协议 · GPT 系",
+ "zhipuai": "OpenAI 兼容 · GLM 系",
+ "custom": "自定义端点"
+ }
+ },
+ "custom": {
+ "title": "添加自定义模型",
+ "subtitle": "补登来源清单里没有的模型,加入 OpenCode 菜单。",
+ "sourceLabel": "来源(它能供应这个模型)",
+ "modelIdLabel": "模型 ID",
+ "modelIdPlaceholder": "glm-5.2-air",
+ "displayNameLabel": "显示名(可选)",
+ "displayNamePlaceholder": "GLM 5.2 Air",
+ "previewLabel": "OPENCODE 标识 · 自动生成",
+ "previewEmpty": "填入模型 ID 后预览",
+ "previewHint": "provider 段自动选:可识别厂商用标准 ID(与 OpenCode 原生一致),识别不了归 custom/;来源增减、模式切换都不影响标识。",
+ "add": "添加到菜单",
+ "failed": "添加失败,请重试"
+ }
+ },
+ "supplyMode": {
+ "title": "供给方式",
+ "currentHub": "当前:中枢 Hub",
+ "currentDirect": "当前:直连 Direct",
+ "switchedHub": "已切换到中枢 Hub",
+ "switchedDirect": "已切换到直连 Direct",
+ "switchFailed": "切换失败,请重试",
+ "hub": {
+ "title": "中枢模式 · Hub",
+ "recommended": "推荐 · 默认",
+ "openModels": "打开模型页",
+ "description": "模型 token 由「设置 → 模型」统一供给:登录、API Key、优先级、映射都在那里管理。不改动 {{backend}} 的原生配置,随时可切走。"
+ },
+ "direct": {
+ "title": "直连模式 · Direct",
+ "description": "{{backend}} 使用自己的原生配置(settings.json / CLI 登录),Avibe 仅负责启动进程、不代管模型。适合排查问题,或想完全自管配置的用户。",
+ "detected": "检测到既有直连配置:{{detail}} —— 可一键搬进中枢",
+ "import": "导入中枢…"
+ }
+ },
+ "migration": {
+ "title": "接入模型中枢",
+ "subtitle": "把现有的登录和 API Key 一次搬进「模型」中枢,三个 Agent 共用一份来源和优先级。",
+ "empty": "没有检测到可迁移的原生配置。",
+ "scanFailed": "扫描原生配置失败,请重试",
+ "applyFailed": "导入失败,请重试",
+ "applied": "已导入 {{count}} 项",
+ "later": "稍后再说",
+ "apply": "导入 {{count}} 项并启用中枢",
+ "nonDestructive": "非破坏迁移:原生配置不改动、不删除,导入只是复制;随时可在「后端」页切回直连。",
+ "action": {
+ "import": "导入为来源",
+ "controlledImport": "受控导入 · 实验",
+ "keepNative": "保留原生",
+ "reauth": "需重新授权 · 浏览器一键"
+ },
+ "notes": {
+ "customBaseUrl": "含自定义 Base URL",
+ "keepNativeSanctioned": "保留在 CLI 自己的凭据库(受官方认可)",
+ "keepNativeReauthHint": "保持原生;可在中枢内重新授权以托管(实验)",
+ "fromOpencode": "来自 opencode 配置"
+ }
+ },
"backends": {
"claude": "Claude Code",
"codex": "Codex",