Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(models): close Model Hub UI completeness gaps (OAuth finalize, source actions, migration triggers, honest hub) (#997)
Call White452ebd4372e6
diff --git a/docs/plans/model-hub-f4-ui-completeness.md b/docs/plans/model-hub-f4-ui-completeness.mdnew file mode 100644index 000000000..142e3a79a--- /dev/null+++ b/docs/plans/model-hub-f4-ui-completeness.md@@ -0,0 +1,54 @@+# Model Hub — F4 UI completeness++Closes the UI-side gaps the completeness audit+(`model-hub-completeness-audit.md`) found: shipped backend capabilities that the+live UI leaves unreachable or dishonest. Server side is F2's (#995); this lane+codes strictly against the frozen contracts (`model-hub-contracts/`), which are+already implemented on master (`cf1b4314`).++## Scope (audit item → fix)++1. **P0-03 / R38 — OAuth success → persisted Source.** The live `OAuthConnectDialog`+ only toasted + refetched on `success`; the mock hid the gap by appending a+ Source inside `completeFlow`. Fix: on `success`, the dialog finalizes via+ `POST /api/models/sources` with `oauth_flow_ref` (the flow id) — the server's+ `create_source` → `_create_oauth_source` path (`service.py:737,751`). The mock+ is refactored to mirror the handoff: `completeFlow` no longer appends; a new+ `createOAuthSource` materializes the Source from the completed flow. A+ `finalizing` state holds the "Connected" banner until the Source is actually+ persisted, so no premature success is shown; a finalize failure surfaces+ honestly.++2. **P1-02 / R32,R42 — Source row actions + custom-model delete.** New+ `SourceRowMenu` (overflow menu, appears on row hover — quiet per the density+ rulings): rename (`PATCH {display_name}`), re-discover (`POST /test`, hub+ sources only — `native_cli` test is rejected server-side), delete+ (`DELETE`, with the only-supplier guard: a `mode_switch_blocked` response+ escalates the confirm to a `?force=1` delete). Custom-model delete lives in+ the OpenCode drawer's edit dialog (`DELETE /custom-models`).++3. **P1-03 / R30 — Migration triggers.** New self-contained `MigrationBanner`+ (scans on mount, shows a dismissible strip when importable native configs+ exist, owns its `MigrationDialog`, re-scans after apply). Mounted on the+ Models page (first-open-after-upgrade) and in the Setup Wizard's backend step+ (`AgentDetection`, wizard mode only — the Settings→Backends page already has+ `BackendSupplyModeCard`'s strip). Dismissal is persisted by a stable signature+ of the importable set's per-config identities (scan ids + action) so it is+ non-nagging but still resurfaces a genuinely new importable config.++4. **P1-06 / R46 — Honest Hub mode.** `set_agent_mode` returns a fresh+ `AgentSupply` whose `current` is computed honestly (null when hub is selected+ but no eligible+available source can supply — exactly the "silent Direct"+ condition, `service.py:935-958`). "接入中枢" now reports success only when the+ round-trip yields `mode==='hub' && current`; otherwise it warns with the true+ state (both the Models-page button and the backend supply card). The Agent+ row shows a persistent honest note when a hub agent has no usable supply.++Out of scope: backend Python (F2/F3), contracts, design.pen. No workflows.++## Evidence layers++- Contract types mirrored in `types.ts` (client), no schema edits.+- i18n en+zh parity for every new key.+- `npm run build` green; hermetic Vite preview screenshots per surface.+- Live end-to-end is the post-merge Incus pass (as with prior lanes).diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsxindex 75288bac2..bf8b59e7a 100644--- a/ui/src/components/settings/models/AgentCard.tsx+++ b/ui/src/components/settings/models/AgentCard.tsx@@ -5,7 +5,7 @@// itself rather than opening a missing surface.import * as React from 'react';import { Link } from 'react-router-dom';-import { ArrowDownToLine, ArrowRight, ChevronRight } from 'lucide-react';+import { ArrowDownToLine, ArrowRight, ChevronRight, TriangleAlert } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';@@ -62,6 +62,16 @@ const AgentRow: React.FC<{/>);}+ } else if (agent.mode === 'hub') {+ // Honest state: hub is selected but no eligible source can supply this agent+ // yet, so the next turn silently falls back to Direct. Say so plainly instead+ // of showing an empty (falsely "fine") row.+ pill = (+ <span className="flex items-center gap-1.5 text-[12px] font-medium text-gold">+ <TriangleAlert className="size-3.5 shrink-0" />+ {t('settings.models.agents.hubNoSupply')}+ </span>+ );}return (diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.tsxindex c3e0d163a..eb3036f37 100644--- a/ui/src/components/settings/models/BackendSupplyModeCard.tsx+++ b/ui/src/components/settings/models/BackendSupplyModeCard.tsx@@ -119,7 +119,15 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bacconst 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');+ if (mode === 'direct') {+ showToast(t('settings.models.supplyMode.switchedDirect') as string, 'success');+ } else if (next.mode === 'hub' && next.current) {+ showToast(t('settings.models.supplyMode.switchedHub') as string, 'success');+ } else {+ // Hub selected but nothing can supply this backend yet → the launch+ // silently falls back to Direct. Tell the truth, don't claim success.+ showToast(t('settings.models.supplyMode.switchedHubNoSupply') as string, 'warning');+ }} catch {if (aliveRef.current) showToast(t('settings.models.supplyMode.switchFailed') as string, 'error');} finally {@@ -172,7 +180,14 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bacdescription={t('settings.models.supplyMode.hub.description', {backend: t(`settings.models.backends.${backend}`, { defaultValue: backend }),}) as string}- />+ >+ {mode === 'hub' && !agent.current && (+ <div className="flex items-start gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-2.5 text-[12px] leading-relaxed text-foreground">+ <Info className="mt-0.5 size-3.5 shrink-0 text-gold" />+ <span>{t('settings.models.supplyMode.hubNoSupply')}</span>+ </div>+ )}+ </OptionCard><OptionCardselected={mode === 'direct'}diff --git a/ui/src/components/settings/models/MigrationBanner.tsx b/ui/src/components/settings/models/MigrationBanner.tsxnew file mode 100644index 000000000..3a845db43--- /dev/null+++ b/ui/src/components/settings/models/MigrationBanner.tsx@@ -0,0 +1,106 @@+// First-open-after-upgrade / setup-wizard migration trigger (spec §5-03). A+// self-contained, dismissible strip: it scans on mount and, when importable+// native configs exist, offers a one-click 导入中枢 that opens the shared+// MigrationDialog. Non-nagging — dismissal is persisted by a stable signature of+// the importable set (see modelHubMigrationDismiss), so it stays hidden until a+// genuinely new config appears. Self-gates to null when nothing is importable,+// the scan fails, or it was dismissed, so it's safe to drop anywhere.+import * as React from 'react';+import { ArrowDownToLine, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { isMigrationDismissed, writeMigrationDismissed } from '@/lib/modelHubMigrationDismiss';+import { MigrationDialog } from './MigrationDialog';+import { modelsApi } from './modelsApi';+import type { MigrationItem } from './types';++export const MigrationBanner: React.FC<{+ /** Bubble the applied count so a host page can refresh sources/agents. */+ onApplied?: (applied: number) => void;+}> = ({ onApplied }) => {+ const { t } = useTranslation();++ const [importable, setImportable] = React.useState<MigrationItem[]>([]);+ const [dialogOpen, setDialogOpen] = React.useState(false);+ const [dismissed, setDismissed] = React.useState(false);+ const [scanToken, setScanToken] = React.useState(0);+ const aliveRef = React.useRef(true);+ React.useEffect(() => {+ aliveRef.current = true;+ return () => {+ aliveRef.current = false;+ };+ }, []);++ React.useEffect(() => {+ let cancelled = false;+ modelsApi+ .scanMigration()+ .then((scan) => {+ if (cancelled || !aliveRef.current) return;+ // reauth rows need the interactive OAuth flow and can't be bulk-applied,+ // so they don't count as importable (they'd open a dead-end dialog).+ const items = scan.items.filter((i) => i.proposed_action !== 'reauth');+ setImportable(items);+ // Hidden while the current set is a subset of what was dismissed; a+ // genuinely new id/action resurfaces it.+ setDismissed(isMigrationDismissed(items));+ })+ .catch(() => {+ // A rescan (after apply, or a transient outage) that fails must not keep+ // advertising the previous importable rows — self-hide instead of leaving+ // a stale strip that reopens a dead migration dialog.+ if (!cancelled && aliveRef.current) setImportable([]);+ });+ return () => {+ cancelled = true;+ };+ }, [scanToken]);++ if (importable.length === 0 || dismissed) return null;++ const dismiss = () => {+ writeMigrationDismissed(importable);+ setDismissed(true);+ };++ return (+ <>+ <div className="flex items-center gap-3 rounded-xl border border-gold/40 bg-gold/[0.08] px-4 py-3">+ <span className="flex size-9 shrink-0 items-center justify-center rounded-[10px] bg-gold/15 text-gold">+ <ArrowDownToLine className="size-[18px]" />+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="text-[14px] font-semibold text-foreground">{t('settings.models.migrationBanner.title')}</span>+ <span className="text-[12px] leading-relaxed text-muted">+ {t('settings.models.migrationBanner.body', { count: importable.length })}+ </span>+ </div>+ <Button variant="outline" size="sm" className="shrink-0 border-gold/40 text-gold hover:bg-gold/10 hover:text-gold" onClick={() => setDialogOpen(true)}>+ <ArrowDownToLine className="size-3.5" />+ {t('settings.models.migrationBanner.import')}+ </Button>+ <button+ type="button"+ aria-label={t('settings.models.migrationBanner.dismiss') as string}+ onClick={dismiss}+ className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:bg-surface-2 hover:text-foreground"+ >+ <X className="size-4" />+ </button>+ </div>++ <MigrationDialog+ open={dialogOpen}+ onClose={() => setDialogOpen(false)}+ onApplied={(applied) => {+ setDialogOpen(false);+ // Re-scan so the strip reflects what's left (imported rows drop out).+ setScanToken((n) => n + 1);+ onApplied?.(applied);+ }}+ />+ </>+ );+};diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsxindex cde36fa1b..1e374010d 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx@@ -6,7 +6,7 @@// mirrors BackendOAuthPanel: start → 2s poll → verifying → success, 15-min// timeout, cancel.import * as React from 'react';-import { CheckCircle2, Sparkles, TriangleAlert } from 'lucide-react';+import { CheckCircle2, Loader2, Sparkles, TriangleAlert } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';@@ -50,8 +50,14 @@ export const OAuthConnectDialog: React.FC<{const [errorKey, setErrorKey] = React.useState<string | null>(null);const [channel, setChannel] = React.useState<SupplyChannel>('native_cli');const [consentOpen, setConsentOpen] = React.useState(false);+ // Between flow success and the Source being persisted (createOAuthSource):+ // holds the "Connected" banner so we never claim success before the Source+ // actually exists, and lets a finalize failure surface honestly.+ const [finalizing, setFinalizing] = React.useState(false);const [, tick] = React.useReducer((x) => x + 1, 0);+ // One-shot latch so the finalize handoff runs exactly once per flow.+ const finalizedRef = React.useRef(false);const flowRef = React.useRef<OAuthFlow | null>(null);const successTimer = React.useRef<number | null>(null);const onConnectedRef = React.useRef(onConnected);@@ -106,6 +112,39 @@ export const OAuthConnectDialog: React.FC<{if (cancelled) return;apply(next);if (next.state === 'success') {+ // P0: a completed flow is NOT yet a Source. Finalize the handoff+ // (POST /sources with oauth_flow_ref) — the server assigns the source+ // id from the flow binding and discovers models. Only then is the+ // connect truly done. `experimental_consent` goes only to the hub+ // channel; native_cli must not send it (server rejects otherwise).+ if (finalizedRef.current) return;+ finalizedRef.current = true;+ setFinalizing(true);+ try {+ await modelsApi.createOAuthSource({+ kind: 'subscription',+ vendor,+ oauth_flow_ref: next.flow_id,+ supply_channel: next.channel,+ ...(next.channel === 'hub' ? { experimental_consent: true } : {}),+ });+ } catch (err) {+ // OAuth succeeded but the Source wasn't persisted — say so, don't+ // flash a false "Connected". The Source may exist server-side if the+ // request landed, so a refetch still runs on the honest paths below.+ if (cancelled) return;+ const code = (err as { code?: string } | null)?.code;+ setErrorKey(+ code === 'consent_required'+ ? 'settings.models.oauth.error.consent'+ : 'settings.models.oauth.error.finalize',+ );+ apply({ ...next, state: 'failed' });+ setFinalizing(false);+ return;+ }+ if (cancelled) return;+ setFinalizing(false);showToast(t('settings.models.oauth.status.success') as string, 'success');onConnectedRef.current();successTimer.current = window.setTimeout(() => onCloseRef.current(), 1400);@@ -127,15 +166,22 @@ export const OAuthConnectDialog: React.FC<{setErrorKey(null);setCode('');setSubmitting(false);+ setFinalizing(false);+ finalizedRef.current = false;void (async () => {try {- const started = await modelsApi.startOAuth(vendor, channel);+ // A hub-held subscription connect (channel === 'hub' only when the user+ // has confirmed the experimental consent below) must carry consent, or+ // the server returns consent_required.+ const started = await modelsApi.startOAuth(vendor, channel, channel === 'hub');if (cancelled) return;apply(started);if (started.expires_at) deadline = new Date(started.expires_at).getTime() + 60_000;pollTimer = window.setTimeout(() => void poll(started.flow_id), POLL_MS);- } catch {- if (!cancelled) setErrorKey('settings.models.oauth.error.start');+ } catch (err) {+ if (cancelled) return;+ const code = (err as { code?: string } | null)?.code;+ setErrorKey(code === 'consent_required' ? 'settings.models.oauth.error.consent' : 'settings.models.oauth.error.start');}})();@@ -186,9 +232,11 @@ export const OAuthConnectDialog: React.FC<{const expects = presentation?.expects;const isDevice = expects === 'none';const state = flow?.state;- const success = state === 'success';+ // "Connected" only once the Source is persisted — never during finalize, and+ // never if the finalize handoff failed.+ const success = state === 'success' && !finalizing && !errorKey;const failed = state === 'failed' || state === 'cancelled' || Boolean(errorKey);- const active = !success && !failed;+ const active = !success && !failed && !finalizing;const remainingMs = flow?.expires_at ? Math.max(0, new Date(flow.expires_at).getTime() - Date.now()) : null;const mmss =@@ -206,7 +254,7 @@ export const OAuthConnectDialog: React.FC<{return (<>- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <Dialog open={open} onOpenChange={(v) => !v && !finalizing && onClose()}><DialogContent className="max-w-[520px] gap-5"><DialogHeader><DialogTitle className="flex items-center gap-2.5 text-[17px] font-bold">@@ -231,6 +279,11 @@ export const OAuthConnectDialog: React.FC<{<CheckCircle2 className="size-4 shrink-0" />{t('settings.models.oauth.connected')}</div>+ ) : finalizing ? (+ <div className="flex items-center gap-2 rounded-lg border border-border bg-surface-2/40 px-4 py-3 text-[13px] font-medium text-muted">+ <Loader2 className="size-4 shrink-0 animate-spin" />+ {t('settings.models.oauth.status.finalizing')}+ </div>) : (active && (<div className="flex flex-col gap-3">@@ -317,7 +370,7 @@ export const OAuthConnectDialog: React.FC<{) : (<span />)}- <Button variant={active ? 'ghost' : 'outline'} size="sm" onClick={onClose}>+ <Button variant={active ? 'ghost' : 'outline'} size="sm" onClick={onClose} disabled={finalizing}>{active ? t('common.cancel') : t('common.close')}</Button></div>diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex d417fb4f6..8c2a2db33 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -12,6 +12,7 @@ import { useToast } from '@/context/ToastContext';import { SettingsPageShell } from '../SettingsPageShell';import { SourcesCard } from './SourcesCard';import { AgentCard } from './AgentCard';+import { MigrationBanner } from './MigrationBanner';import { RecentSwitchesCard } from './RecentSwitchesCard';import { AdvancedRow } from './AdvancedRow';import { AddApiKeyDialog } from './AddApiKeyDialog';@@ -135,9 +136,18 @@ export const SettingsModelsPage: React.FC = () => {const connectHub = async (agent: AgentSupply) => {setConnecting(agent.backend);try {- await modelsApi.setAgentMode(agent.backend, 'hub');+ // The PATCH echoes a fresh AgentSupply whose `current` is the honest+ // "what the next turn uses" projection: it's null when the mode flipped to+ // hub but no eligible+available source can supply — i.e. the launch would+ // silently fall back to Direct. Report the true state, never a green lie.+ const next = await modelsApi.setAgentMode(agent.backend, 'hub');await refreshSourcesAgents();- if (aliveRef.current) showToast(t('settings.models.toast.connected') as string, 'success');+ if (!aliveRef.current) return;+ if (next.mode === 'hub' && next.current) {+ showToast(t('settings.models.toast.connected') as string, 'success');+ } else {+ showToast(t('settings.models.toast.connectedNoSupply') as string, 'warning');+ }} catch {if (aliveRef.current) showToast(t('settings.models.toast.connectFailed') as string, 'error');} finally {@@ -169,6 +179,7 @@ export const SettingsModelsPage: React.FC = () => {</div>) : (<div className="flex flex-col gap-5">+ <MigrationBanner onApplied={() => void refreshSourcesAgents()} /><SourcesCardsources={sources}onReorderPreview={reorderPreview}@@ -176,6 +187,7 @@ export const SettingsModelsPage: React.FC = () => {onConnectClaude={() => setOauthVendor('anthropic')}onConnectChatGPT={() => setOauthVendor('openai')}onAddApiKey={() => setApiKeyOpen(true)}+ onSourceChanged={() => void refreshSourcesAgents()}/><AgentCardagents={agents}diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsxindex 0f4848bef..928448cfe 100644--- a/ui/src/components/settings/models/SourceRow.tsx+++ b/ui/src/components/settings/models/SourceRow.tsx@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';import { BillingChip, ExperimentalChip, StateChip } from './chips';import { SupplyTooltip } from './SupplyTooltip';+import { SourceRowMenu } from './SourceRowMenu';import { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, sourceVisual } from './vendorMeta';import { cooldownEtaMinutes, formatSpend } from './format';import type { Source } from './types';@@ -65,14 +66,16 @@ export const SourceRow: React.FC<{source: Source;priority: number;onDragHandlePointerDown: (e: React.PointerEvent) => void;-}> = ({ source, priority, onDragHandlePointerDown }) => {+ /** Re-fetch after a row action (rename / re-discover / delete). */+ onChanged: () => void;+}> = ({ source, priority, onDragHandlePointerDown, onChanged }) => {const { t } = useTranslation();const { Icon, accent } = sourceVisual(source);const subline = useSubline(source);const isExperimental = source.kind === 'subscription' && source.supply_channel === 'hub';return (- <div className="flex items-center gap-3 border-b border-border px-5 py-3.5 last:border-b-0">+ <div className="group flex items-center gap-3 border-b border-border px-5 py-3.5 last:border-b-0"><buttontype="button"aria-label={t('settings.models.source.reorder') as string}@@ -103,6 +106,7 @@ export const SourceRow: React.FC<{<UsageCell source={source} /><BillingChip billing={source.billing} /><StateChip state={source.state} />+ <SourceRowMenu source={source} onChanged={onChanged} /></div></div>);diff --git a/ui/src/components/settings/models/SourceRowMenu.tsx b/ui/src/components/settings/models/SourceRowMenu.tsxnew file mode 100644index 000000000..4e8c1c3a9--- /dev/null+++ b/ui/src/components/settings/models/SourceRowMenu.tsx@@ -0,0 +1,216 @@+// Per-row lifecycle actions for the 来源 list (frame 01r): an overflow menu that+// stays out of the way (hidden until row hover / focus on desktop) and exposes+// the contracted source mutations the list otherwise couldn't reach — rename+// (PATCH), re-discover (POST /test, hub sources only), and delete (DELETE, with+// the only-supplier guard escalating to a forced delete). Presentation lives in+// SourceRow; this owns the actions + their dialogs so the row stays declarative.+import * as React from 'react';+import { MoreHorizontal, Pencil, RefreshCw, Trash2 } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { ConfirmDialog } from '@/components/ui/confirm-dialog';+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Input } from '@/components/ui/input';+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';+import { cn } from '@/lib/utils';+import { useToast } from '@/context/ToastContext';+import { modelsApi } from './modelsApi';+import type { Source } from './types';++const MenuAction: React.FC<{+ Icon: React.ComponentType<{ className?: string }>;+ label: string;+ onClick: () => void;+ destructive?: boolean;+}> = ({ Icon, label, onClick, destructive }) => (+ <button+ type="button"+ onClick={onClick}+ className={cn(+ 'flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] transition-colors',+ destructive ? 'text-destructive hover:bg-destructive/[0.08]' : 'text-foreground hover:bg-surface-2',+ )}+ >+ <Icon className="size-4 shrink-0" />+ {label}+ </button>+);++export const SourceRowMenu: React.FC<{+ source: Source;+ /** Re-fetch sources + agents after any successful mutation. */+ onChanged: () => void;+}> = ({ source, onChanged }) => {+ const { t } = useTranslation();+ const { showToast } = useToast();++ const [menuOpen, setMenuOpen] = React.useState(false);+ const [renameOpen, setRenameOpen] = React.useState(false);+ const [renameValue, setRenameValue] = React.useState(source.display_name);+ const [renaming, setRenaming] = React.useState(false);+ const [deleteOpen, setDeleteOpen] = React.useState(false);+ // Set once the server refuses a plain delete (only-supplier guard); the+ // confirm then escalates to a forced delete instead of silently failing.+ const [forceMode, setForceMode] = React.useState(false);+ const [testing, setTesting] = React.useState(false);++ const aliveRef = React.useRef(true);+ React.useEffect(() => () => {+ aliveRef.current = false;+ }, []);++ // Re-discovery only applies to hub sources; native_cli subscriptions are+ // rejected server-side, so we don't offer the action for them.+ const canRediscover = source.supply_channel === 'hub';++ const openRename = () => {+ setMenuOpen(false);+ setRenameValue(source.display_name);+ setRenameOpen(true);+ };++ const submitRename = async () => {+ const name = renameValue.trim();+ if (!name || name === source.display_name) {+ setRenameOpen(false);+ return;+ }+ setRenaming(true);+ try {+ await modelsApi.patchSource(source.id, { display_name: name });+ if (!aliveRef.current) return;+ setRenameOpen(false);+ onChanged();+ showToast(t('settings.models.sourceActions.renamed') as string, 'success');+ } catch {+ if (aliveRef.current) showToast(t('settings.models.sourceActions.renameFailed') as string, 'error');+ } finally {+ if (aliveRef.current) setRenaming(false);+ }+ };++ const rediscover = async () => {+ setMenuOpen(false);+ if (testing) return;+ setTesting(true);+ try {+ const count = await modelsApi.testSource(source.id);+ if (!aliveRef.current) return;+ onChanged();+ showToast(t('settings.models.sourceActions.rediscovered', { count }) as string, 'success');+ } catch {+ if (aliveRef.current) showToast(t('settings.models.sourceActions.rediscoverFailed') as string, 'error');+ } finally {+ if (aliveRef.current) setTesting(false);+ }+ };++ const openDelete = () => {+ setMenuOpen(false);+ setForceMode(false);+ setDeleteOpen(true);+ };++ const confirmDelete = async () => {+ try {+ await modelsApi.deleteSource(source.id, forceMode);+ if (!aliveRef.current) return;+ setDeleteOpen(false);+ onChanged();+ showToast(t('settings.models.sourceActions.deleted') as string, 'success');+ } catch (err) {+ const code = (err as { code?: string } | null)?.code;+ // Only-supplier guard: escalate to a forced delete instead of failing.+ if (code === 'mode_switch_blocked' && !forceMode) {+ if (aliveRef.current) setForceMode(true);+ return;+ }+ if (aliveRef.current) {+ setDeleteOpen(false);+ showToast(t('settings.models.sourceActions.deleteFailed') as string, 'error');+ }+ }+ };++ return (+ <>+ <Popover open={menuOpen} onOpenChange={setMenuOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ aria-label={t('settings.models.sourceActions.more') as string}+ className={cn(+ 'flex size-8 shrink-0 items-center justify-center rounded-md text-muted transition-all hover:bg-surface-2 hover:text-foreground',+ // Quiet on desktop (revealed on row hover / focus / when open),+ // always reachable on touch where hover doesn't exist.+ menuOpen ? 'opacity-100' : 'opacity-100 md:opacity-0 md:group-hover:opacity-100 md:focus-visible:opacity-100',+ )}+ >+ {testing ? <RefreshCw className="size-4 animate-spin" /> : <MoreHorizontal className="size-4" />}+ </button>+ </PopoverTrigger>+ <PopoverContent align="end" sideOffset={6} className="w-[200px] border-border bg-card p-1.5 text-foreground shadow-lg">+ <MenuAction Icon={Pencil} label={t('settings.models.sourceActions.rename') as string} onClick={openRename} />+ {canRediscover && (+ <MenuAction Icon={RefreshCw} label={t('settings.models.sourceActions.rediscover') as string} onClick={() => void rediscover()} />+ )}+ <MenuAction Icon={Trash2} label={t('settings.models.sourceActions.delete') as string} onClick={openDelete} destructive />+ </PopoverContent>+ </Popover>++ <Dialog open={renameOpen} onOpenChange={(v) => !v && !renaming && setRenameOpen(false)}>+ <DialogContent className="max-w-[420px] gap-4">+ <DialogHeader>+ <DialogTitle>{t('settings.models.sourceActions.renameTitle')}</DialogTitle>+ </DialogHeader>+ <div className="flex flex-col gap-2">+ <span className="text-[12px] font-semibold text-foreground">{t('settings.models.sourceActions.renameLabel')}</span>+ <Input+ value={renameValue}+ onChange={(e) => setRenameValue(e.target.value)}+ maxLength={64}+ autoFocus+ placeholder={t('settings.models.sourceActions.renamePlaceholder') as string}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ void submitRename();+ }+ }}+ className="h-11 text-[14px]"+ />+ </div>+ <DialogFooter className="sm:justify-end">+ <Button variant="outline" size="sm" onClick={() => setRenameOpen(false)} disabled={renaming}>+ {t('common.cancel')}+ </Button>+ <Button+ variant="brand"+ size="sm"+ onClick={() => void submitRename()}+ disabled={renaming || !renameValue.trim() || renameValue.trim() === source.display_name}+ >+ {t('common.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <ConfirmDialog+ open={deleteOpen}+ onOpenChange={(v) => {+ setDeleteOpen(v);+ if (!v) setForceMode(false);+ }}+ destructive+ title={t(forceMode ? 'settings.models.sourceActions.deleteForceTitle' : 'settings.models.sourceActions.deleteTitle')}+ description={t(forceMode ? 'settings.models.sourceActions.deleteForceBody' : 'settings.models.sourceActions.deleteBody', {+ name: source.display_name,+ })}+ confirmLabel={t(forceMode ? 'settings.models.sourceActions.deleteForceConfirm' : 'settings.models.sourceActions.deleteConfirm') as string}+ onConfirm={confirmDelete}+ />+ </>+ );+};diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsxindex 07a50617d..6059fba60 100644--- a/ui/src/components/settings/models/SourcesCard.tsx+++ b/ui/src/components/settings/models/SourcesCard.tsx@@ -10,10 +10,11 @@ import { AddSourceMenu } from './AddSourceMenu';import { SourceRow } from './SourceRow';import type { Source } from './types';-const SourceReorderItem: React.FC<{ source: Source; priority: number; onCommit: () => void }> = ({+const SourceReorderItem: React.FC<{ source: Source; priority: number; onCommit: () => void; onChanged: () => void }> = ({source,priority,onCommit,+ onChanged,}) => {const controls = useDragControls();return (@@ -28,6 +29,7 @@ const SourceReorderItem: React.FC<{ source: Source; priority: number; onCommit:source={source}priority={priority}onDragHandlePointerDown={(e) => controls.start(e)}+ onChanged={onChanged}/></Reorder.Item>);@@ -42,7 +44,9 @@ export const SourcesCard: React.FC<{onConnectClaude: () => void;onConnectChatGPT: () => void;onAddApiKey: () => void;-}> = ({ sources, onReorderPreview, onReorderCommit, onConnectClaude, onConnectChatGPT, onAddApiKey }) => {+ /** Re-fetch after a per-row action (rename / re-discover / delete). */+ onSourceChanged: () => void;+}> = ({ sources, onReorderPreview, onReorderCommit, onConnectClaude, onConnectChatGPT, onAddApiKey, onSourceChanged }) => {const { t } = useTranslation();const ids = sources.map((s) => s.id);@@ -66,7 +70,7 @@ export const SourcesCard: React.FC<{) : (<Reorder.Group axis="y" values={ids} onReorder={onReorderPreview} className="flex flex-col">{sources.map((source, index) => (- <SourceReorderItem key={source.id} source={source} priority={index + 1} onCommit={onReorderCommit} />+ <SourceReorderItem key={source.id} source={source} priority={index + 1} onCommit={onReorderCommit} onChanged={onSourceChanged} />))}</Reorder.Group>)}diff --git a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsxindex c9d344a04..3fc2af25e 100644--- a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx+++ b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx@@ -4,10 +4,11 @@// 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 { ChevronDown, Copy, Plus, Trash2 } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';+import { ConfirmDialog } from '@/components/ui/confirm-dialog';import {Dialog,DialogContent,@@ -115,7 +116,9 @@ export const AddCustomModelDialog: React.FC<{edit?: { sourceId: string; modelId: string; displayName: string | null } | null;onClose: () => void;onSaved: (identifier: string) => void;-}> = ({ open, sources, standardVendors, edit, onClose, onSaved }) => {+ /** Fired after a custom model is removed (edit mode only). */+ onDeleted?: (identifier: string) => void;+}> = ({ open, sources, standardVendors, edit, onClose, onSaved, onDeleted }) => {const { t } = useTranslation();const { showToast } = useToast();@@ -123,6 +126,7 @@ export const AddCustomModelDialog: React.FC<{const [modelId, setModelId] = React.useState('');const [displayName, setDisplayName] = React.useState('');const [saving, setSaving] = React.useState(false);+ const [deleteOpen, setDeleteOpen] = 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.@@ -165,8 +169,32 @@ export const AddCustomModelDialog: React.FC<{}};+ const submitDelete = async () => {+ if (!edit) return;+ try {+ await modelsApi.deleteCustomModel(edit.sourceId, edit.modelId);+ onDeleted?.(identifier);+ setDeleteOpen(false);+ onClose();+ showToast(t('settings.models.menus.custom.deleted') as string, 'success');+ } catch (err) {+ // The server guards a delete while the model is still the only selected+ // supplier for some agent — surface that honestly instead of a generic fail.+ const code = (err as { code?: string } | null)?.code;+ showToast(+ t(+ code === 'mode_switch_blocked'+ ? 'settings.models.menus.custom.deleteInUse'+ : 'settings.models.menus.custom.deleteFailed',+ ) as string,+ 'error',+ );+ }+ };+return (- <Dialog open={open} onOpenChange={(v) => !v && !saving && onClose()}>+ <>+ <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>@@ -223,16 +251,44 @@ export const AddCustomModelDialog: React.FC<{<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 className={cn('gap-2', edit ? 'sm:justify-between' : 'sm:justify-end')}>+ {edit && (+ <Button+ variant="ghost"+ size="sm"+ className="text-destructive hover:bg-destructive/[0.08] hover:text-destructive"+ onClick={() => setDeleteOpen(true)}+ disabled={saving}+ >+ <Trash2 className="size-4" />+ {t('settings.models.menus.custom.delete')}+ </Button>+ )}+ <div className="flex items-center gap-2 max-sm:w-full max-sm:justify-end">+ <Button variant="outline" size="sm" 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(edit ? 'common.save' : 'settings.models.menus.custom.add')}+ </Button>+ </div></DialogFooter></DialogContent>- </Dialog>+ </Dialog>++ <ConfirmDialog+ open={deleteOpen}+ onOpenChange={setDeleteOpen}+ destructive+ title={t('settings.models.menus.custom.deleteConfirmTitle')}+ description={t('settings.models.menus.custom.deleteConfirmBody', {+ model: identifier || edit?.modelId,+ source: source?.display_name ?? '',+ })}+ confirmLabel={t('settings.models.menus.custom.delete') as string}+ onConfirm={submitDelete}+ />+ </>);};diff --git a/ui/src/components/settings/models/menus/MappingDrawer.tsx b/ui/src/components/settings/models/menus/MappingDrawer.tsxindex ff7427ea9..b7ffc25e1 100644--- a/ui/src/components/settings/models/menus/MappingDrawer.tsx+++ b/ui/src/components/settings/models/menus/MappingDrawer.tsx@@ -160,9 +160,17 @@ export const MappingDrawer: React.FC<{// refresh of the agent prop.React.useEffect(() => {if (!open) return;- const seed = seedDraft(agent);- setDraft(seed);- initialRef.current = seed;+ const raw = seedDraft(agent);+ // Self-heal: an enabled override whose target's supplier was deleted is no+ // longer selectable — display it as 跟随原生. Seed initialRef with the RAW+ // draft so the heal makes the drawer dirty and Done PERSISTS the cleaned+ // mappings; a no-op close still heals the stored config.+ const targetIds = new Set(targets.map((tg) => tg.id));+ const healed = raw.map((m) =>+ m.enabled && !targetIds.has(m.target_model_id) ? { ...m, enabled: false, target_model_id: '' } : m,+ );+ setDraft(healed);+ initialRef.current = raw;// eslint-disable-next-line react-hooks/exhaustive-deps}, [open]);@@ -183,7 +191,11 @@ export const MappingDrawer: React.FC<{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));+ // Self-heal: drop an override whose target is no longer available (its+ // supplier source was deleted); it reverts to 跟随原生 instead of being+ // resubmitted and rejected as mapping_target_unavailable.+ const targetIds = new Set(targets.map((tg) => tg.id));+ await modelsApi.putMappings(backend, draft.filter((m) => m.enabled && targetIds.has(m.target_model_id)));onSaved();onClose();} catch {diff --git a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsxindex 54bb4814e..6b4fc5640 100644--- a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx+++ b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx@@ -83,6 +83,11 @@ export const OpenCodeMenuDrawer: React.FC<{const eligibleSources = React.useMemo(() => sources.filter((s) => isSourceEligible(s, 'opencode')), [sources]);const groups = React.useMemo(() => buildMenuGroups(eligibleSources, standardVendors), [eligibleSources, standardVendors]);const allRows = React.useMemo(() => groups.flatMap((g) => g.rows), [groups]);+ // Identifiers a source currently supplies. Persisted `checked` is self-healed+ // against this so an identifier whose only supplier was deleted (e.g. a+ // force-deleted source) is dropped rather than shown as an invisible checked+ // row or sent to putMenu (which the server rejects as mapping_target_unavailable).+ const availableIds = React.useMemo(() => new Set(allRows.map((r) => r.identifier)), [allRows]);const [view, setView] = React.useState<'featured' | 'full'>(agent.menu?.view ?? 'featured');const [checked, setChecked] = React.useState<Set<string>>(() => new Set(agent.menu?.checked ?? []));@@ -94,10 +99,15 @@ export const OpenCodeMenuDrawer: React.FC<{React.useEffect(() => {if (!open) return;const v = agent.menu?.view ?? 'featured';- const c = agent.menu?.checked ?? [];+ const raw = agent.menu?.checked ?? [];+ // Self-heal the DISPLAY: drop checked ids whose supplier no longer exists+ // (e.g. after a force-delete). Seed initialRef with the RAW persisted list so,+ // when the heal removed entries, the drawer is dirty and Done PERSISTS the+ // cleaned menu — a no-op close still heals the stored config.+ const healed = raw.filter((id) => availableIds.has(id));setView(v);- setChecked(new Set(c));- initialRef.current = { view: v, checked: [...c] };+ setChecked(new Set(healed));+ initialRef.current = { view: v, checked: [...raw] };// eslint-disable-next-line react-hooks/exhaustive-deps}, [open]);@@ -122,6 +132,9 @@ export const OpenCodeMenuDrawer: React.FC<{}setSaving(true);try {+ // `checked` is already self-healed at open and only grows via toggles/adds+ // of available (or just-added) identifiers, so send it as-is — filtering+ // here would strip a just-added custom model before onRefresh lands.await modelsApi.putMenu({ view, checked: [...checked] });onSaved();onClose();@@ -242,6 +255,14 @@ export const OpenCodeMenuDrawer: React.FC<{if (!editTarget) setChecked((prev) => new Set(prev).add(identifier));onRefresh();}}+ onDeleted={() => {+ // No local uncheck: the backend only lets the delete through when the+ // model is NOT the sole selected supplier, so any checked identifier that+ // survives a successful delete is still supplied by another source and+ // must stay checked. A sole-supplier checked model is blocked (the dialog+ // shows an honest "in use" message). Just refresh the source list.+ onRefresh();+ }}/></>);diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 96c097cf8..8afb582a8 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -28,10 +28,12 @@ import type {MigrationApplyResult,MigrationScan,OAuthFlow,+ OAuthSourceCreate,Priority,ResolutionEvent,RuntimeDependency,Source,+ SourcePatch,SupplyChannel,} from './types';import { CONTRACT_VERSION } from './types';@@ -39,7 +41,14 @@ import { CONTRACT_VERSION } from './types';export type ModelsApi = {listSources(): Promise<Source[]>;createApiKeySource(draft: ApiKeySourceCreate): Promise<Source>;- deleteSource(id: string): Promise<void>;+ /** Finalize a completed subscription OAuth flow into a persisted Source. */+ createOAuthSource(draft: OAuthSourceCreate): Promise<Source>;+ /** Rename / re-point a source (display_name, base_url). */+ patchSource(id: string, patch: SourcePatch): Promise<Source>;+ /** Re-run discovery on a hub source; resolves with the discovered count. */+ testSource(id: string): Promise<number>;+ /** Delete a source. `force` overrides the only-supplier guard. */+ deleteSource(id: string, force?: boolean): Promise<void>;putPriority(order: string[]): Promise<Priority>;listAgents(): Promise<AgentSupply[]>;setAgentMode(backend: AgentBackend, mode: AgentMode): Promise<AgentSupply>;@@ -51,7 +60,9 @@ export type ModelsApi = {applyMigration(itemIds: string[]): Promise<MigrationApplyResult>;listEvents(limit?: number): Promise<ResolutionEvent[]>;getRuntimeStatus(): Promise<RuntimeDependency>;- startOAuth(vendor: string, channel: SupplyChannel): Promise<OAuthFlow>;+ /** `experimentalConsent` MUST be true for a consent-gated hub-held+ * subscription connect, or the server returns consent_required. */+ startOAuth(vendor: string, channel: SupplyChannel, experimentalConsent?: boolean): Promise<OAuthFlow>;getOAuthStatus(flowId: string): Promise<OAuthFlow>;submitOAuth(flowId: string, value: string): Promise<OAuthFlow>;cancelOAuth(flowId: string): Promise<void>;@@ -94,7 +105,10 @@ const jsonInit = (method: string, body?: unknown): RequestInit => ({const liveApi: ModelsApi = {listSources: () => call<{ sources: Source[] }>('/api/models/sources').then((r) => r.sources),createApiKeySource: (draft) => call<{ source?: Source } & Source>('/api/models/sources', jsonInit('POST', draft)).then((r) => (r.source ?? r) as Source),- deleteSource: (id) => call(`/api/models/sources/${encodeURIComponent(id)}`, jsonInit('DELETE')).then(() => undefined),+ createOAuthSource: (draft) => call<{ source?: Source } & Source>('/api/models/sources', jsonInit('POST', draft)).then((r) => (r.source ?? r) as Source),+ patchSource: (id, patch) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(id)}`, jsonInit('PATCH', patch)).then((r) => (r.source ?? r) as Source),+ testSource: (id) => call<{ discovered: number }>(`/api/models/sources/${encodeURIComponent(id)}/test`, jsonInit('POST')).then((r) => r.discovered),+ deleteSource: (id, force) => call(`/api/models/sources/${encodeURIComponent(id)}${force ? '?force=1' : ''}`, jsonInit('DELETE')).then(() => undefined),putPriority: (order) => call<{ priority?: Priority } & Priority>('/api/models/priority', jsonInit('PUT', { contract_version: CONTRACT_VERSION, order })).then((r) => (r.priority ?? r) as Priority),listAgents: () => call<{ agents: AgentSupply[] }>('/api/models/agents').then((r) => r.agents),setAgentMode: (backend, mode) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mode`, jsonInit('PATCH', { mode })).then((r) => (r.agent ?? r) as AgentSupply),@@ -106,7 +120,11 @@ const liveApi: ModelsApi = {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),+ startOAuth: (vendor, channel, experimentalConsent) =>+ call<{ flow?: OAuthFlow } & OAuthFlow>(+ '/api/models/oauth/start',+ jsonInit('POST', { vendor, channel, ...(experimentalConsent ? { experimental_consent: true } : {}) }),+ ).then((r) => (r.flow ?? r) as OAuthFlow),getOAuthStatus: (flowId) => call<{ flow?: OAuthFlow } & OAuthFlow>(`/api/models/oauth/status/${encodeURIComponent(flowId)}`).then((r) => (r.flow ?? r) as OAuthFlow),submitOAuth: (flowId, value) => call<{ flow?: OAuthFlow } & OAuthFlow>('/api/models/oauth/submit', jsonInit('POST', { flow_id: flowId, value })).then((r) => (r.flow ?? r) as OAuthFlow),cancelOAuth: (flowId) => call('/api/models/oauth/cancel', jsonInit('POST', { flow_id: flowId })).then(() => undefined),@@ -168,9 +186,15 @@ class MockStore {return delay(structuredClone(source), 900); // simulate probe latency}- deleteSource(id: string) {+ deleteSource(id: string, force = false) {+ // Mirror the server's only-supplier guard (mode_switch_blocked): a source+ // currently bound as some agent's supply can't be dropped without force.+ if (!force && this.agents.some((a) => a.current?.source_id === id)) {+ throw new ApiCallError('mode_switch_blocked');+ }this.sources = this.sources.filter((s) => s.id !== id);this.priority.order = this.priority.order.filter((x) => x !== id);+ for (const a of this.agents) if (a.current?.source_id === id) a.current = null;return delay(undefined);}@@ -293,10 +317,16 @@ class MockStore {return delay(structuredClone(this.runtime));}- startOAuth(vendor: string, channel: SupplyChannel) {+ startOAuth(vendor: string, channel: SupplyChannel, experimentalConsent?: boolean) {+ // Mirror the server: a hub-held subscription connect requires recorded consent.+ if (channel === 'hub' && !experimentalConsent) throw new ApiCallError('consent_required');const isDevice = vendor === 'openai';const flow: OAuthFlow = {flow_id: rid('oaf'),+ // Deterministic pending-source binding (schema: hub flows always set it),+ // consumed by createOAuthSource on finalize — mirrors the server, where+ // create_source assigns source.id = flow.source_id.+ source_id: rid('src'),vendor,channel,state: 'awaiting_action',@@ -352,34 +382,66 @@ class MockStore {return delay(undefined);}+ // A completed flow reaches `success` but does NOT itself materialize a Source+ // (mirrors the server, where flow completion and source creation are split):+ // the UI must finalize via createOAuthSource. Earlier the mock appended here,+ // which hid the live P0 gap the audit flagged.private completeFlow(entry: MockFlow) {entry.flow.state = 'success';- // A completed subscription connect materializes a new native_cli source.- const vendor = entry.flow.vendor;- const isOpenai = vendor === 'openai';+ }++ createOAuthSource(draft: OAuthSourceCreate) {+ const entry = this.flows.get(draft.oauth_flow_ref);+ if (!entry || entry.flow.state !== 'success') throw new ApiCallError('flow_not_found');+ const flow = entry.flow;+ const isOpenai = flow.vendor === 'openai';+ const id = flow.source_id ?? rid('src');+ // Idempotent finalize: a duplicate browser retry must not double-create+ // (the server raises migration_item_conflict; here we just re-echo).+ const existing = this.sources.find((s) => s.id === id);+ if (existing) return delay(structuredClone(existing), 300);const source: Source = {- id: rid('src'),+ id,kind: 'subscription',- vendor,- display_name: isOpenai ? 'ChatGPT 订阅' : 'Claude 订阅',+ vendor: flow.vendor,+ display_name: draft.display_name ?? (isOpenai ? 'ChatGPT 订阅' : 'Claude 订阅'),protocol: isOpenai ? 'openai_responses' : 'anthropic',base_url: null,- supply_channel: entry.flow.channel,- experimental_consent_at: entry.flow.channel === 'hub' ? new Date().toISOString() : null,+ supply_channel: draft.supply_channel,+ experimental_consent_at: draft.supply_channel === 'hub' ? new Date().toISOString() : null,billing: 'monthly',state: { status: 'standby', retry_at: null, detail_key: null },usage: { cycle_used_pct: 0, month_spend_cents: null, currency: null },// native_cli subscriptions surface the sanctioned CLI account; hub-held// experimental sources may stay null until a later adapter rev (schema).- account_label: entry.flow.channel === 'native_cli' ? '[email protected]' : null,+ account_label: draft.supply_channel === 'native_cli' ? '[email protected]' : null,masked_credential: null,models: isOpenai? [{ id: 'gpt-5.6', display_name: 'GPT-5.6', provenance: 'discovered', discovered_at: new Date().toISOString() }]: [{ id: 'claude-opus-4-6', display_name: 'Opus 4.6', provenance: 'discovered', discovered_at: new Date().toISOString() }],- credential_ref: entry.flow.channel === 'hub' ? rid('cred') : null,+ credential_ref: draft.supply_channel === 'hub' ? rid('cred') : null,};this.sources.push(source);this.priority.order.push(source.id);+ return delay(structuredClone(source), 300);+ }++ patchSource(id: string, patch: SourcePatch) {+ const source = this.sources.find((s) => s.id === id);+ if (!source) throw new ApiCallError('source_not_found');+ if (typeof patch.display_name === 'string') source.display_name = patch.display_name;+ if ('base_url' in patch && source.kind === 'api_key') source.base_url = patch.base_url ?? null;+ return delay(structuredClone(source), 300);+ }++ testSource(id: string) {+ const source = this.sources.find((s) => s.id === id);+ if (!source) throw new ApiCallError('source_not_found');+ // Native-CLI subscriptions can't be re-discovered (server rejects them);+ // the UI only offers this action for hub sources, but fail closed anyway.+ if (source.supply_channel === 'native_cli') throw new ApiCallError('discovery_failed');+ source.state = { status: 'standby', retry_at: null, detail_key: null };+ return delay(source.models.length, 700);}}@@ -416,7 +478,10 @@ const mockStore = new MockStore();const mockApi: ModelsApi = {listSources: () => mockStore.listSources(),createApiKeySource: (draft) => mockStore.createApiKeySource(draft),- deleteSource: (id) => mockStore.deleteSource(id),+ createOAuthSource: (draft) => mockStore.createOAuthSource(draft),+ patchSource: (id, patch) => mockStore.patchSource(id, patch),+ testSource: (id) => mockStore.testSource(id),+ deleteSource: (id, force) => mockStore.deleteSource(id, force),putPriority: (order) => mockStore.putPriority(order),listAgents: () => mockStore.listAgents(),setAgentMode: (backend, mode) => mockStore.setAgentMode(backend, mode),@@ -428,7 +493,7 @@ const mockApi: ModelsApi = {applyMigration: (itemIds) => mockStore.applyMigration(itemIds),listEvents: (limit) => mockStore.listEvents(limit),getRuntimeStatus: () => mockStore.getRuntimeStatus(),- startOAuth: (vendor, channel) => mockStore.startOAuth(vendor, channel),+ startOAuth: (vendor, channel, experimentalConsent) => mockStore.startOAuth(vendor, channel, experimentalConsent),getOAuthStatus: (flowId) => mockStore.getOAuthStatus(flowId),submitOAuth: (flowId, value) => mockStore.submitOAuth(flowId, value),cancelOAuth: (flowId) => mockStore.cancelOAuth(flowId),diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 6a9331a36..e0b328967 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -192,6 +192,9 @@ export type OAuthPresentation = {export type OAuthFlow = {flow_id: string;+ /** Pending Source this flow binds to (deterministic association; hub-channel+ * flows always set it). The server derives the created source's id from it. */+ source_id?: string | null;vendor: string;channel: SupplyChannel;state: OAuthFlowState;@@ -242,6 +245,27 @@ export type ApiKeySourceCreate = {key: string;};+/** POST /api/models/sources — finalize a completed subscription OAuth flow into+ * a persisted Source. `oauth_flow_ref` is the flow id; the server derives the+ * source id from the flow binding and rejects credential/state fields, so the+ * UI never sends them. `experimental_consent` is sent only for the consent-+ * gated hub-held channel. */+export type OAuthSourceCreate = {+ kind: 'subscription';+ vendor: string;+ oauth_flow_ref: string;+ supply_channel: SupplyChannel;+ display_name?: string;+ experimental_consent?: boolean;+};++/** PATCH /api/models/sources/<id> — display_name and/or base_url only+ * (contract: never accepts credential material). */+export type SourcePatch = {+ display_name?: string;+ base_url?: string | null;+};+/** POST /api/models/custom-models — appends a manual-provenance model entry to* a source's supply list (frame 08). */export type CustomModelCreate = {diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsxindex ba03fd741..0910522f6 100644--- a/ui/src/components/steps/AgentDetection.tsx+++ b/ui/src/components/steps/AgentDetection.tsx@@ -19,6 +19,7 @@ import { BackendLifecycleChip } from '../settings/BackendLifecycleChip';import { ToggleSwitch } from '../settings/SettingsPrimitives';import { BackendProviderConfig } from '../settings/providers/BackendProviderConfig';import { OpencodePermissionSetup } from '../settings/shared/OpencodePermissionSetup';+import { MigrationBanner } from '../settings/models/MigrationBanner';import type { BackendId as RuntimeBackendId } from '../settings/shared/useBackendRuntime';import { useOpencodePermission } from '../settings/shared/useOpencodePermission';import { Button } from '../ui/button';@@ -250,6 +251,12 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on// Page mode keeps the existing settings shell — render the inner content onlyconst Inner = (<>+ {/* Setup-wizard migration trigger (spec §5-03): offer to import pre-existing+ native CLI configs into the Hub. Wizard-only — the Settings → Backends+ page already surfaces this via BackendSupplyModeCard. Self-hides when+ nothing is importable or the hub isn't reachable yet. */}+ {!isPage && <MigrationBanner />}+<div className="flex flex-col gap-3 rounded-xl border border-border bg-background px-4 py-3 sm:flex-row sm:items-center sm:justify-between"><div className="min-w-0"><span className="text-[11px] font-semibold uppercase tracking-[0.12em] text-muted">diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex bd69185a8..8e83ef02f 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -662,7 +662,8 @@"menuComingSoon": "Model menus arrive in the next milestone","modelCount": "{{count}} models","multiSource": "Multiple sources",- "multiSourceCustom": "Multiple sources · {{count}} custom"+ "multiSourceCustom": "Multiple sources · {{count}} custom",+ "hubNoSupply": "On Hub · no source available yet (using Direct)"},"recent": {"title": "Recent switches",@@ -736,12 +737,15 @@"awaitingPaste": "Waiting for authorization · times out in {{time}}","awaitingDevice": "Waiting to finish · detected automatically, nothing to paste","verifying": "Verifying…",- "success": "Connected"+ "success": "Connected",+ "finalizing": "Creating the source…"},"error": {"start": "Couldn't start authorization, please retry","timeout": "Authorization timed out, please reconnect",- "generic": "Connection failed, please retry"+ "generic": "Connection failed, please retry",+ "finalize": "Authorized, but couldn't create the source — please retry",+ "consent": "A hub-hosted subscription needs experimental consent — restart the connect and enable the hub option."},"hubOption": {"title": "Let the Hub hold this subscription (experimental)",@@ -764,7 +768,8 @@"reorderFailed": "Couldn't save the new order","connected": "Connected to the Hub","connectFailed": "Couldn't connect, please retry",- "refreshFailed": "Couldn't refresh, please retry"+ "refreshFailed": "Couldn't refresh, please retry",+ "connectedNoSupply": "Switched to Hub, but no source can supply yet — still on Direct"},"menus": {"done": "Done",@@ -811,7 +816,13 @@"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"+ "failed": "Couldn't add the model, please retry",+ "delete": "Remove model",+ "deleteConfirmTitle": "Remove custom model?",+ "deleteConfirmBody": "This removes {{model}} from “{{source}}”.",+ "deleted": "Custom model removed",+ "deleteFailed": "Couldn't remove the model, please retry",+ "deleteInUse": "This model is still selected by an agent — unselect it in that menu/mapping first."}},"supplyMode": {@@ -832,7 +843,9 @@"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…"- }+ },+ "switchedHubNoSupply": "Switched to Hub, but no source can supply yet — still on Direct",+ "hubNoSupply": "Hub is selected, but no source can supply this backend yet, so it's still using Direct. Add or enable a source on the Models page to activate it."},"migration": {"title": "Connect to the Model Hub",@@ -861,6 +874,33 @@"claude": "Claude Code","codex": "Codex","opencode": "OpenCode"+ },+ "sourceActions": {+ "more": "More actions",+ "rename": "Rename",+ "rediscover": "Re-discover models",+ "delete": "Delete source",+ "renameTitle": "Rename source",+ "renameLabel": "Display name",+ "renamePlaceholder": "e.g. Production key",+ "renamed": "Renamed",+ "renameFailed": "Couldn't rename, please retry",+ "rediscovered": "Re-discovered {{count}} model(s)",+ "rediscoverFailed": "Couldn't re-discover, please retry",+ "deleteTitle": "Delete source?",+ "deleteBody": "This removes “{{name}}” from the Hub and revokes its credential. This can't be undone.",+ "deleteConfirm": "Delete",+ "deleteForceTitle": "Delete this source anyway?",+ "deleteForceBody": "“{{name}}” is the only supplier of a selected model; deleting it leaves that agent with no source. Force delete?",+ "deleteForceConfirm": "Force delete",+ "deleted": "Source deleted",+ "deleteFailed": "Couldn't delete, please retry"+ },+ "migrationBanner": {+ "title": "Native configs ready to import",+ "body": "Found {{count}} native sign-in(s) / API key(s) you can move into the Hub — all three agents share one set of sources.",+ "import": "Import to Hub",+ "dismiss": "Dismiss"}}},diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 9de4d19bf..b73a846d2 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -662,7 +662,8 @@"menuComingSoon": "模型菜单即将上线(随下一个里程碑发布)","modelCount": "{{count}} 个模型","multiSource": "多来源",- "multiSourceCustom": "多来源 · 含 {{count}} 个自定义"+ "multiSourceCustom": "多来源 · 含 {{count}} 个自定义",+ "hubNoSupply": "已接入中枢 · 暂无可用来源(当前走直连)"},"recent": {"title": "最近切换",@@ -736,12 +737,15 @@"awaitingPaste": "等待授权 · {{time}} 后超时","awaitingDevice": "等待完成 · 自动检测,无需回填","verifying": "验证中…",- "success": "连接成功"+ "success": "连接成功",+ "finalizing": "正在创建来源…"},"error": {"start": "无法开始授权,请重试","timeout": "授权超时,请重新连接",- "generic": "连接失败,请重试"+ "generic": "连接失败,请重试",+ "finalize": "已完成授权,但创建来源失败,请重试",+ "consent": "连接中枢托管订阅需先同意实验条款;请重新发起连接并在弹窗中开启「中枢托管」选项。"},"hubOption": {"title": "由中枢托管此订阅(实验)",@@ -764,7 +768,8 @@"reorderFailed": "顺序保存失败","connected": "已接入中枢","connectFailed": "接入失败,请重试",- "refreshFailed": "刷新失败,请重试"+ "refreshFailed": "刷新失败,请重试",+ "connectedNoSupply": "已切到中枢,但暂无可用来源,当前仍走直连"},"menus": {"done": "完成",@@ -811,7 +816,13 @@"previewEmpty": "填入模型 ID 后预览","previewHint": "provider 段自动选:可识别厂商用标准 ID(与 OpenCode 原生一致),识别不了归 custom/;来源增减、模式切换都不影响标识。","add": "添加到菜单",- "failed": "添加失败,请重试"+ "failed": "添加失败,请重试",+ "delete": "删除模型",+ "deleteConfirmTitle": "移除自定义模型?",+ "deleteConfirmBody": "将从「{{source}}」的清单移除 {{model}}。",+ "deleted": "已移除自定义模型",+ "deleteFailed": "移除失败,请重试",+ "deleteInUse": "该模型仍被某个 Agent 选用,请先在其菜单/映射里取消后再删除。"}},"supplyMode": {@@ -832,7 +843,9 @@"description": "{{backend}} 使用自己的原生配置(settings.json / CLI 登录),Avibe 仅负责启动进程、不代管模型。适合排查问题,或想完全自管配置的用户。","detected": "检测到既有直连配置:{{detail}} —— 可一键搬进中枢","import": "导入中枢…"- }+ },+ "switchedHubNoSupply": "已切到中枢,但暂无可用来源,当前仍走直连",+ "hubNoSupply": "已选中枢,但还没有可供给本后端的来源,当前仍走直连。去「模型」页添加或启用来源后即生效。"},"migration": {"title": "接入模型中枢",@@ -861,6 +874,33 @@"claude": "Claude Code","codex": "Codex","opencode": "OpenCode"+ },+ "sourceActions": {+ "more": "更多操作",+ "rename": "重命名",+ "rediscover": "重新发现模型",+ "delete": "删除来源",+ "renameTitle": "重命名来源",+ "renameLabel": "显示名",+ "renamePlaceholder": "例如 生产环境 Key",+ "renamed": "已重命名",+ "renameFailed": "重命名失败,请重试",+ "rediscovered": "已重新发现 {{count}} 个模型",+ "rediscoverFailed": "重新发现失败,请重试",+ "deleteTitle": "删除来源?",+ "deleteBody": "将从中枢移除「{{name}}」并撤销其凭证,此操作不可撤销。",+ "deleteConfirm": "删除",+ "deleteForceTitle": "仍要删除该来源?",+ "deleteForceBody": "「{{name}}」是某个已选模型的唯一供给,删除后相关 Agent 将无来源可用。确认强制删除?",+ "deleteForceConfirm": "强制删除",+ "deleted": "已删除来源",+ "deleteFailed": "删除失败,请重试"+ },+ "migrationBanner": {+ "title": "发现可导入中枢的原生配置",+ "body": "检测到 {{count}} 项原生登录 / API Key 可搬进中枢,三个 Agent 共用一份来源和优先级。",+ "import": "导入中枢",+ "dismiss": "忽略"}}},diff --git a/ui/src/lib/modelHubMigrationDismiss.ts b/ui/src/lib/modelHubMigrationDismiss.tsnew file mode 100644index 000000000..652b2afb2--- /dev/null+++ b/ui/src/lib/modelHubMigrationDismiss.ts@@ -0,0 +1,37 @@+// Remembers which Model Hub migration configs the user dismissed, so the banner+// stays non-nagging. Stores the dismissed set of per-config identities (stable+// scan id + proposed action — the backend derives ids as content hashes,+// `migration.py` sha256[:16]). The banner stays hidden while the current+// importable set is a SUBSET of what was dismissed — so importing or removing one+// config from a dismissed batch does NOT re-nag — and resurfaces only when a+// genuinely new id/action appears. Mirrors the localStorage conventions used+// elsewhere (module-level key, best-effort try/catch, pure helpers).+import type { MigrationItem } from '@/components/settings/models/types';++const STORAGE_KEY = 'vibe-remote:model-hub-migration-dismissed';++const identity = (item: MigrationItem): string => `${item.id}:${item.proposed_action}`;++/** Record the current importable set as dismissed. */+export function writeMigrationDismissed(items: MigrationItem[]): void {+ try {+ const ids = [...new Set(items.map(identity))].sort();+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(ids));+ } catch {+ // Best-effort persistence only (private mode / SSR / blocked storage).+ }+}++/** True when every current importable config was already dismissed (subset of the+ * dismissed set) — i.e. nothing genuinely new to surface. */+export function isMigrationDismissed(items: MigrationItem[]): boolean {+ if (items.length === 0) return false;+ try {+ const raw = window.localStorage.getItem(STORAGE_KEY);+ if (!raw) return false;+ const dismissed = new Set<string>(JSON.parse(raw));+ return items.every((i) => dismissed.has(identity(i)));+ } catch {+ return false;+ }+}