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(setup): build the model providers screen (#2089)
Max4461b09265f7
diff --git a/docs/plans/setup-three-screen/contracts.md b/docs/plans/setup-three-screen/contracts.mdindex 41db1e4a0..5b14f388e 100644--- a/docs/plans/setup-three-screen/contracts.md+++ b/docs/plans/setup-three-screen/contracts.md@@ -76,6 +76,15 @@ and the shell-owned `SetupFlowState`.inactive/stale publications and clicks only the current `SetupScreenHandle.activate()`.Clear the previous action on navigation; disable it during capability reads, handoffs,and pending mutations. `busy` also disables clicking. `activate()` must reject re-entry.+- `SetupAction.labelKey` names a shipped C1 string, in one of the two forms C1 actually+ ships: a text leaf that resolves on its own, or the base of a `_one`/`_other` family+ together with a required `labelArgs.count`. A family does not resolve without a count, so+ the count is part of the claim rather than something the shell supplies on faith, and+ `TranslationKey` alone — deliberately the leaves that resolve without count — cannot name+ a counted label at all. The two forms are derived from the live bundle, so a string that+ has not shipped stays unnameable either way. Field names and the publication protocol are+ unchanged: a screen publishes `labelKey`/`labelArgs` and the shell resolves them in one+ `t` call, with no narrowing.- All registered screens remain mounted, `hidden` + `inert` when inactive. This preservesdrafts but does NOT suspend effects. Screens gate polling, authorization, scans andanimations on `active` (and dialog open state). A hidden screen must not start installs,@@ -349,7 +358,7 @@ of silently changing either the handoff or another owner.| counts | CTA count = deduplicated appliable item IDs in selected complete groups; summary provider count = distinct displayed providers of those items. Capsule count = distinct key IDs in complete, unblocked, key-only groups, independent of selection. `importedCount` = confirmed `result.applied`, once per successful submitted batch, not number of sources or guessed key count. `addedThroughMore` = unique IDs returned by successful manual creation, badge filtered against current usable sources || capsule | retain dismissal signature owner `modelHubMigrationDismiss` and the reserved slot. Existing `ImportKeysNotice` scans/owns a dialog internally: L2 must adapt it to the shared scan/selection owner before claiming consistency; it is not a drop-in consumer of C2 || import / Detected tab | use the complete-group rule below. Hiding card duplicates or out-of-scope rows must never shrink consent. Already-added status follows fresh scan/source evidence, not a vendor-name match. D10 delegates confirmation/apply/recovery to the existing migration feature; setup never applies from selection or normal navigation |-| add — API key | shared `AddApiKeyDialog` form: observe then create with the confirmed observation, preserve its existing unknown-write recovery. Read `SourceCreated.source` and placement tails (`added_to`, `adopted_by`); refresh sources and affected supplies before reporting ready |+| add — API key | shared `AddApiKeyDialog` form: one create carrying `save_unverified: true` (`apiKeySourceDraft.ts`), no observe or probe first — the credential is saved on the person's word and verified afterwards, so a provider that is slow or briefly down does not cost them the key they pasted. Preserve its existing unknown-write recovery exactly: only a server-named non-409 4xx settles the write (`apiKeyWriteSettled`), anything else reconciles against `client_nonce` through `reconcileUnknownWrite` rather than repeating the create. Read `SourceCreated.source` and placement tails (`added_to`, `adopted_by`); refresh sources and affected supplies before reporting ready, and a source that comes back `verification_pending` is shown as saved-but-unverified per the `selected and connected` row — never as a completed verification || add — subscription | reuse `subscriptionOptions.ts` / `OAuthConnectDialog` / `OAuthFlowParts` for the offered product vendors, custody choice and flow ownership. Setup limits the shipped vendor list to OpenAI/Anthropic per handoff; there is no callable vendor-capability-list API in `ModelsApi`, and no such producer should be invented. `getOAuthStatus` / `submitOAuth` return `OAuthResult`; terminal create carries `created.source` and placement tails. Do not create the source a second time or equate terminal OAuth with assistant readiness || picker order | `apiKeyVendors.ts` reads `vibe/data/api_key_vendors.json`; first eight in file order, remainder plus custom. No browser re-sort or prototype Cohere || runtime | with enabled capability and saved intent, D11 starts only a confirmed stopped controller; its existing recovery owns initial ensure/start and server admission. The browser then observes health and only requests admitted recovery if still needed (D3). Healthy-engine writes follow the operation table below, independently of new-install permission. Unsupported/non-running or unread stays on the normal flow with retry/guide/Back; no install-confirmation or automatic credential takeover |diff --git a/docs/plans/setup-three-screen/copy-contract.json b/docs/plans/setup-three-screen/copy-contract.jsonindex eab6dc626..842fbd902 100644--- a/docs/plans/setup-three-screen/copy-contract.json+++ b/docs/plans/setup-three-screen/copy-contract.json@@ -208,6 +208,7 @@"action_one": "查看选中的 {{count}} 项","action_other": "查看选中的 {{count}} 项","scopeNote": "此入口仅处理完整的 API Key 组。涉及订阅登录或阻塞项的关联组不可在此接管,请前往设置检查。",+ "outOfScope": "此凭据可以迁移,但不能在此入口迁移,请前往设置检查。","progress_one": "正在迁移 {{count}} 项配置…","progress_other": "正在迁移 {{count}} 项配置…","progressDetail": "正在迁移认证并更新关联助手的连接",@@ -331,6 +332,7 @@"action_one": "Review {{count}} selected","action_other": "Review {{count}} selected","scopeNote": "This entry handles complete API-key groups only. Linked groups with subscription sign-ins or blockers cannot be taken over here; review them in Settings.",+ "outOfScope": "This credential can be migrated, but not from here. Review it in Settings.","progress_one": "Migrating {{count}} configuration item…","progress_other": "Migrating {{count}} configuration items…","progressDetail": "Migrating authentication and updating linked assistant connections",@@ -385,6 +387,7 @@"onboarding.import.description","onboarding.import.helpBody","onboarding.import.scopeNote",+ "onboarding.import.outOfScope","onboarding.import.progress_one","onboarding.import.progress_other","onboarding.import.progressDetail",diff --git a/ui/e2e/onboarding-fidelity/provider-support.ts b/ui/e2e/onboarding-fidelity/provider-support.tsnew file mode 100644index 000000000..1d84c92bf--- /dev/null+++ b/ui/e2e/onboarding-fidelity/provider-support.ts@@ -0,0 +1,293 @@+// A small stateful server for the providers screen, layered over `support.ts`.+//+// `serveModelHub` there answers a scan and an apply, which is all the setup STEP+// needed. This screen reads and WRITES sources, resumes a runtime and reads agent+// supply, and its interesting properties are relations between numbers — the badge+// against what was added, the summary against what exists, the capsule against what+// is left. Canned replies cannot express those: a fixture that always returns the+// same three rows can only be compared against literals copied out of itself.+//+// So this keeps real state and hands the spec a reader for it. Every assertion in+// `providers.spec.ts` compares what the page says to what this server actually holds,+// which is what makes them rules rather than transcriptions.+//+// `support.ts` is L1's file and is imported, never edited.+import type { Page, Route } from '@playwright/test';++/** Shapes only as far as the product reads them; this is a fixture, not a mirror. */+type FakeItem = {+ id: string;+ backend: string;+ kind: string;+ masked_detail: string;+ proposed_action: string;+ selected: boolean;+ vendor?: string;+ display_name?: string;+ masked_credential?: string | null;+};++type FakeSource = {+ id: string;+ vendor: string;+ kind: string;+ display_name: string;+ protocol: string;+ supply_channel: string;+ billing: string;+ state: { status: string };+ models: unknown[];+ masked_credential?: string | null;+ client_nonce?: string | null;+ last_discovered_at: null;+};++/**+ * The scan the screen opens on.+ *+ * Three importable keys across two independent consent groups, plus a third group+ * holding a native token the entry point must leave alone and an API key that cannot+ * be taken without it. The shapes matter to what the screen derives:+ * `openai` and `qwen` rank inside the setup shortlist so they take the two card slots,+ * `zhipu` ranks outside it so it stays an unlisted candidate — which is the only+ * reason the add dialog's 已检测到 method exists at all, and therefore the only way+ * the stable-frame proof can switch between three panes. The Claude key ranks outside+ * it too, so the blocked row and the sentence explaining it are laid out beside that+ * candidate at every size measured here — the longest line either surface can hold.+ *+ * No row carries `required_backends`, so the three groups are genuinely independent+ * and consenting to one submits one.+ */+export const SCAN_ITEMS: FakeItem[] = [+ {+ id: 'codex-key',+ backend: 'codex',+ kind: 'api_key',+ masked_detail: 'sk-…9d31',+ proposed_action: 'import',+ selected: true,+ vendor: 'openai',+ display_name: 'OpenAI',+ masked_credential: 'sk-…9d31',+ },+ {+ id: 'opencode-qwen',+ backend: 'opencode',+ kind: 'opencode_provider',+ masked_detail: 'sk-…7c08 · 阿里云百炼',+ proposed_action: 'import',+ selected: true,+ vendor: 'qwen',+ display_name: 'alibaba-cn',+ masked_credential: 'sk-…7c08',+ },+ {+ id: 'opencode-zhipu',+ backend: 'opencode',+ kind: 'opencode_provider',+ masked_detail: 'sk-…3456 · 智谱',+ proposed_action: 'import',+ selected: true,+ vendor: 'zhipu',+ display_name: 'zhipu',+ masked_credential: 'sk-…3456',+ },+ {+ id: 'claude-key',+ backend: 'claude',+ kind: 'api_key',+ masked_detail: 'sk-ant-…4f2a',+ proposed_action: 'import',+ selected: true,+ vendor: 'anthropic',+ display_name: 'Anthropic',+ masked_credential: 'sk-ant-…4f2a',+ },+ {+ id: 'claude-oauth',+ backend: 'claude',+ kind: 'oauth_native',+ masked_detail: 'Claude 订阅令牌',+ proposed_action: 'keep_native',+ selected: false,+ },+];++const CONFIG = {+ platforms: { enabled: [] },+ agents: {+ claude: { enabled: true, cli_path: 'claude' },+ codex: { enabled: true, cli_path: 'codex' },+ opencode: { enabled: true, cli_path: 'opencode' },+ },+ agent: { default_cwd: '/fixture/work' },+ show_duration: false,+ model_hub: { enabled: true },+ capabilities: { model_hub: { enabled: true } },+};++/** Installed, verified and serving: the screen's `gatewayIntent` reads `running` and+ * starts no install, which is the state every proof below is about something else. */+const RUNTIME = {+ contract_version: 10,+ enabled: true,+ host_platform: 'darwin',+ manifest: {+ name: 'cliproxyapi',+ resolution: 'resolved',+ version: '1.0.0',+ source_sha: 'fixture',+ assets: [],+ },+ status: {+ installed_version: '1.0.0',+ verified: true,+ listening: { host: '127.0.0.1', port: 8317 },+ health: 'ok',+ last_check: null,+ },+};++const AGENTS = ['claude', 'codex', 'opencode'].map((backend) => ({+ backend,+ cli_present: true,+ mode: 'direct',+ menu_kind: 'builtin',+ selected_model_id: null,+ selected_by_agent: null,+}));++/** What the server holds right now — the other half of every assertion. */+export type ServerFacts = {+ /** Every source that exists, however it got there. */+ sources: FakeSource[];+ /** Only the ones written through the add dialog, which is what the badge counts. */+ written: FakeSource[];+ /** Rows a scan would still return. */+ items: FakeItem[];+ /** One entry per apply, holding the exact ids that batch submitted. */+ applied: string[][];+};++export type ProviderServer = {+ facts: () => ServerFacts;+};++const migrated = (item: FakeItem): FakeSource => ({+ id: `src_${item.id}`,+ vendor: item.vendor ?? 'custom',+ kind: 'api_key',+ display_name: item.display_name ?? item.vendor ?? 'custom',+ protocol: 'openai_chat',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active' },+ models: [],+ masked_credential: item.masked_credential ?? null,+ client_nonce: null,+ last_discovered_at: null,+});++/**+ * Answers everything the providers screen reads and writes.+ *+ * Call AFTER `serveProduct`: Playwright matches routes newest-first, which is what+ * lets these override that fixture's `/api/config` and answer the POSTs its catch-all+ * would otherwise refuse. Everything it does not name is still refused, so the fixture+ * cannot reach a running service.+ */+export async function serveProviders(page: Page): Promise<ProviderServer> {+ let items = SCAN_ITEMS.map((item) => ({ ...item }));+ const sources: FakeSource[] = [];+ const written: FakeSource[] = [];+ const applied: string[][] = [];++ // The writes are POSTs, so the product asks for a CSRF token first. The base+ // fixture refuses that along with every other write-enabling request.+ await page.route('**/api/csrf-token', (route) =>+ route.fulfill({ json: { csrf_token: 'fixture-token' } }));+ await page.route('**/api/config', (route) => route.fulfill({ json: CONFIG }));++ await page.route('**/api/models/sources', (route: Route) => {+ if (route.request().method() !== 'POST') return route.fulfill({ json: { sources } });+ const draft = JSON.parse(route.request().postData() || '{}');+ const source: FakeSource = {+ id: `src_written_${written.length + 1}`,+ vendor: draft.vendor ?? 'custom',+ kind: 'api_key',+ display_name: draft.display_name ?? draft.vendor ?? 'custom',+ protocol: draft.protocol ?? 'openai_chat',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active' },+ models: [],+ // Masked by the server, which is the only side that ever sees the key.+ masked_credential: `${String(draft.key ?? '').slice(0, 3)}…${String(draft.key ?? '').slice(-4)}`,+ client_nonce: draft.client_nonce ?? null,+ last_discovered_at: null,+ };+ sources.push(source);+ written.push(source);+ return route.fulfill({ json: { source, added_to: [], adopted_by: [] } });+ });++ await page.route('**/api/models/migration/scan', (route) =>+ route.fulfill({ json: { scan: { items } } }));+ await page.route('**/api/models/migration/apply', (route) => {+ const ids: string[] = JSON.parse(route.request().postData() || '{}').item_ids ?? [];+ applied.push(ids);+ // A migration produces sources too. Removing the rows it consumed is what makes+ // the capsule's remainder the server's answer rather than the page's subtraction.+ for (const item of items) if (ids.includes(item.id)) sources.push(migrated(item));+ items = items.filter((item) => !ids.includes(item.id));+ return route.fulfill({ json: { applied: ids.length, sources: [] } });+ });++ await page.route('**/api/models/agents**', (route) => route.fulfill({ json: { agents: AGENTS } }));+ await page.route('**/api/models/runtime/status', (route) => route.fulfill({ json: { runtime: RUNTIME } }));+ await page.route('**/api/models/runtime/install', (route) => route.fulfill({ json: { runtime: RUNTIME } }));+ await page.route('**/api/models/runtime/start', (route) => route.fulfill({ json: { runtime: RUNTIME } }));++ return {+ facts: () => ({+ sources: sources.map((source) => ({ ...source })),+ written: written.map((source) => ({ ...source })),+ items: items.map((item) => ({ ...item })),+ applied: applied.map((batch) => [...batch]),+ }),+ };+}++/** Distinct provider identities the server holds — what the summary sentence counts. */+export const vendorCount = (facts: ServerFacts): number =>+ new Set(facts.sources.map((source) => source.vendor)).size;++/**+ * Importable rows this entry point could actually take — what the capsule counts.+ *+ * Stated from the server's own rule rather than from the product's projection: the+ * server migrates a backend whole and refuses a batch that omits one of its rows, so+ * one row it will not import takes its whole backend out of the offer. Written out+ * here because the point of every count below is to be derived twice.+ *+ * Enough for the shapes this fixture serves: no row carries `required_backends`, and+ * every importable row in it is a key, so there is no closure to walk and nothing+ * importable that setup's key-only scope would decline.+ */+export const importableCount = (facts: ServerFacts): number => {+ const blocked = new Set(+ facts.items.filter((item) => item.proposed_action !== 'import').map((item) => item.backend),+ );+ return facts.items+ .filter((item) => item.proposed_action === 'import' && !blocked.has(item.backend))+ .length;+};++export async function openProviders(page: Page, options: { lang?: string; theme?: string } = {}) {+ const query = new URLSearchParams({ lang: options.lang ?? 'en', theme: options.theme ?? 'dark' });+ await page.goto(`/e2e/onboarding-fidelity/providers-fixture.html?${query}`);+ await page.locator('.setup-provider-stage').waitFor();+ // The screen's first read is a scan and a source list in one `Promise.all`; the+ // summary is the last thing either of them moves, so it is what "settled" means here.+ await page.locator('.setup-provider-summary').waitFor();+}diff --git a/ui/e2e/onboarding-fidelity/providers-fixture.html b/ui/e2e/onboarding-fidelity/providers-fixture.htmlnew file mode 100644index 000000000..87230fb1b--- /dev/null+++ b/ui/e2e/onboarding-fidelity/providers-fixture.html@@ -0,0 +1,2 @@+<!doctype html>+<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Providers screen fidelity fixture</title></head><body><div id="root"></div><script type="module" src="./providers-fixture.tsx"></script></body></html>diff --git a/ui/e2e/onboarding-fidelity/providers-fixture.tsx b/ui/e2e/onboarding-fidelity/providers-fixture.tsxnew file mode 100644index 000000000..5cad3a628--- /dev/null+++ b/ui/e2e/onboarding-fidelity/providers-fixture.tsx@@ -0,0 +1,163 @@+// Mounts the real providers screen inside the real providers, under a stand-in for+// the parts of the setup shell L1 owns.+//+// `fixture.tsx` mounts the `Wizard`, and the Wizard reaches this screen only through+// the registry line that lands after L1 merges. Rather than edit L1's fixture — or+// wait, and ship this screen with no browser evidence at all — this is a second entry+// point onto the same component tree, the way `e2e/model-catalog/gatewayFixture.tsx`+// already does for one surface of Settings.+//+// What is stood in for is only what the shell owns and this screen does not: the+// runtime read, the screen's activity, the flow state, and the primary button. Each+// one is the smallest thing that satisfies the C2 interface — a one-shot read rather+// than L1's owner, a literal `true` rather than a route change — because a fuller+// imitation would start proving the imitation. Everything inside `.onboarding-setup`+// is the shipped component, measured by the browser.+//+// The shell's own header is absent: it is L1's surface and `geometry.spec.ts` already+// measures it in the real Wizard. It contributes nothing to what this fixture is for.+import { createRoot } from 'react-dom/client';+import { createInstance } from 'i18next';+import { I18nextProvider, useTranslation } from 'react-i18next';+import { useCallback, useEffect, useRef, useState } from 'react';+import { ArrowRight, LoaderCircle } from 'lucide-react';+import { MemoryRouter } from 'react-router-dom';++import en from '../../src/i18n/en.json';+import zh from '../../src/i18n/zh.json';+import '../../src/index.css';+import { ApiProvider } from '../../src/context/ApiContext';+import { ThemeProvider } from '../../src/context/ThemeProvider';+import { ToastProvider } from '../../src/context/ToastProvider';+import { StatusProvider } from '../../src/context/StatusProvider';+import { InstanceAuthorizationContext } from '../../src/context/InstanceAuthorizationContext';+import { OWNER_INSTANCE_CAPABILITIES } from '../../src/lib/sessionInfo';+import { Button } from '../../src/components/ui/button';+import { ProvidersScreen } from '../../src/components/onboarding/providers/ProvidersScreen';+import {+ INITIAL_SETUP_FLOW_STATE,+ type SetupAction,+ type SetupFlowState,+ type SetupScreenHandle,+ type SetupScreenId,+} from '../../src/components/onboarding/setupFlow';+import { modelsApi } from '../../src/components/settings/models/modelsApi';+import { useModelHubCapability } from '../../src/components/settings/models/useModelHubCapability';+import {+ foldRegionRead,+ loadingRegion,+ readRegion,+ type RegionRead,+} from '../../src/components/settings/models/regionRead';+import type { RuntimeDependency } from '../../src/components/settings/models/types';++// Exported for the same reason `e2e/model-catalog/gatewayFixture.tsx` exports its+// own: a module that declares a component and exports nothing opts the file out of+// fast refresh, which the lint baseline holds the whole tree to.+export function Shell() {+ const { t } = useTranslation();+ const screen = useRef<SetupScreenHandle>(null);+ const [flowState, setFlowState] = useState<SetupFlowState>(INITIAL_SETUP_FLOW_STATE);+ const [action, setAction] = useState<SetupAction | null>(null);+ const [navigated, setNavigated] = useState<SetupScreenId | null>(null);++ // The shell's single runtime owner, in its smallest honest form: one read, retried+ // on request. L1's owner does more (it is the only writer of this region for three+ // screens); what this screen consumes of it is the projection and the retry.+ const [runtimeRead, setRuntimeRead] = useState<RegionRead<RuntimeDependency>>(loadingRegion);+ const [readToken, setReadToken] = useState(0);+ useEffect(() => {+ let cancelled = false;+ void readRegion(() => modelsApi.getRuntimeStatus()).then((read) => {+ if (!cancelled) setRuntimeRead(read);+ });+ return () => { cancelled = true; };+ }, [readToken]);++ const capability = useModelHubCapability();+ const gatewayEnabled = foldRegionRead<RuntimeDependency, boolean | null>(runtimeRead, {+ loading: () => null,+ ready: (runtime) => runtime.enabled !== false,+ unread: () => null,+ degraded: (runtime) => runtime.enabled !== false,+ });++ const onActionChange = useCallback((next: SetupAction) => setAction(next), []);+ const onNavigate = useCallback((next: SetupScreenId) => setNavigated(next), []);+ const onRetrySetup = useCallback(() => setReadToken((token) => token + 1), []);++ return (+ <div className="onboarding-shell" data-navigated={navigated ?? ''}>+ <main className="onboarding-shell-content">+ <div className="onboarding-step">+ <ProvidersScreen+ ref={screen}+ active+ handoff={false}+ capability={capability === null ? 'pending' : capability ? 'enabled' : 'disabled'}+ gatewayEnabled={gatewayEnabled}+ runtimeRead={runtimeRead}+ onRetrySetup={onRetrySetup}+ flowState={flowState}+ setFlowState={setFlowState}+ onActionChange={onActionChange}+ onNavigate={onNavigate}+ />+ {/* The shell renders the primary action; the screen only publishes it. The+ width rule is a share of the content column, and `.onboarding-setup` —+ which carries that cap in the real shell — is inside the screen here, so+ the cap is restated on the footer's own box rather than left to resolve+ against the full step width. */}+ <div className="onboarding-setup-footer" style={{ maxWidth: 'var(--ob-content-w)' }}>+ <Button+ type="button"+ variant="brand"+ className="group onboarding-action-w onboarding-primary-action"+ disabled={!action || action.disabled}+ onClick={() => screen.current?.activate()}+ >+ {action ? t(action.labelKey, action.labelArgs) : ''}+ {action?.icon === 'spinner' && (+ <LoaderCircle size={16} className="motion-safe:animate-spin" />+ )}+ {action?.icon === 'arrow-right' && <ArrowRight size={16} />}+ </Button>+ </div>+ </div>+ </main>+ </div>+ );+}++const params = new URLSearchParams(location.search);+const language = createInstance();+await language.init({+ lng: params.get('lang') ?? 'en',+ resources: { en: { translation: en }, zh: { translation: zh } },+ interpolation: { escapeValue: false },+});++createRoot(document.getElementById('root')!).render(+ <I18nextProvider i18n={language}>+ <ThemeProvider>+ <ToastProvider>+ <ApiProvider>+ <InstanceAuthorizationContext.Provider+ value={{+ remote: false,+ instanceKind: null,+ instanceRole: 'owner',+ capabilities: OWNER_INSTANCE_CAPABILITIES,+ }}+ >+ <MemoryRouter>+ <StatusProvider>+ <Shell />+ </StatusProvider>+ </MemoryRouter>+ </InstanceAuthorizationContext.Provider>+ </ApiProvider>+ </ToastProvider>+ </ThemeProvider>+ </I18nextProvider>,+);diff --git a/ui/e2e/onboarding-fidelity/providers.spec.ts b/ui/e2e/onboarding-fidelity/providers.spec.tsnew file mode 100644index 000000000..7e3474a3c--- /dev/null+++ b/ui/e2e/onboarding-fidelity/providers.spec.ts@@ -0,0 +1,233 @@+import { expect, test, type Locator, type Page } from '@playwright/test';+import { VIEWPORTS, serveProduct, settleEffects, size } from './support';+import { importableCount, openProviders, serveProviders, vendorCount } from './provider-support';++/**+ * The four things about the providers screen that only a browser can settle.+ *+ * Its component tests already hold the rules that are decidable from the DOM — which+ * rows a batch submits, which card is selectable, what a switch preserves. What they+ * cannot see is layout: whether a frame really holds still, whether a capsule really+ * leaves the button where it was, whether anything spills sideways at the sizes the+ * design bands for. Those are measurements, so they are made here.+ *+ * And one thing that is not layout at all: the numbers. The badge, the summary and the+ * capsule each count a different set, and the interesting failure is not that one of+ * them is wrong in isolation but that they disagree — the badge counting an import, or+ * the summary counting a card rather than a source. So every count below is compared+ * against what the fake server actually holds, never against a literal. A test that+ * asserted "2 providers" would keep passing on a screen that had stopped counting.+ */++const round = (value: number) => Math.round(value * 100) / 100;++/** A box, rounded, so a sub-pixel difference in two reads of a still frame is not a+ * failure while a real one-pixel move still is. */+const rect = async (locator: Locator) => {+ const box = await locator.boundingBox();+ if (!box) throw new Error('not rendered');+ return { x: round(box.x), y: round(box.y), width: round(box.width), height: round(box.height) };+};++/** Every number in a sentence, in order — how a count is read back out of copy+ * without the test restating the copy. */+const numbers = (text: string | null): number[] =>+ [...(text ?? '').matchAll(/\d+/g)].map((match) => Number(match[0]));++const method = (page: Page, name: string) =>+ page.locator('.setup-add-method').filter({ hasText: name });++const primaryAction = (page: Page) => page.locator('.onboarding-primary-action');++const addDialog = (page: Page) => page.locator('.setup-add-dialog');++/** Holds whatever is arriving. Radix animates the dialog in, and the stage plays its+ * wire sequence; a box measured mid-entrance is a box of something still moving. */+const arrived = async (locator: Locator) => {+ await locator.evaluate((node) => Promise.all(+ node.getAnimations({ subtree: true }).map((animation) => animation.finished.catch(() => null)),+ ));+};++const openAddDialog = async (page: Page) => {+ await page.locator('.setup-provider-card[data-state="add"]').click();+ await addDialog(page).waitFor();+ await arrived(addDialog(page));+};++test.describe('providers screen', () => {+ test('C5: the add dialog keeps one frame across repeated method switching', async ({ page }) => {+ const denied = await serveProduct(page);+ await serveProviders(page);+ await page.setViewportSize({ width: 1440, height: 900 });+ await openProviders(page);+ await openAddDialog(page);++ // Three methods exist here only because the fixture leaves one detected candidate+ // off the stage. Asserting that first means a later failure to switch is read as a+ // failure to switch, not as a method that was never offered.+ await expect(page.locator('.setup-add-method')).toHaveCount(3);++ const anchors = {+ dialog: await rect(addDialog(page)),+ head: await rect(page.locator('.setup-add-head')),+ foot: await rect(page.locator('.setup-add-foot')),+ };+ const contentHeights: number[] = [];++ // Back and forth, not once through: the frame that survives one switch and drifts+ // on the third is the one a person actually comparing two methods would meet.+ for (const [name, expected] of [+ ['API Key', 'apiKey'],+ ['Subscription', 'subscription'],+ ['Detected', 'detected'],+ ['API Key', 'apiKey'],+ ['Detected', 'detected'],+ ['Subscription', 'subscription'],+ ] as const) {+ await method(page, name).click();+ await expect(page.locator('.setup-add-body')).toHaveAttribute('data-method', expected);++ expect(await rect(addDialog(page))).toEqual(anchors.dialog);+ expect(await rect(page.locator('.setup-add-head'))).toEqual(anchors.head);+ expect(await rect(page.locator('.setup-add-foot'))).toEqual(anchors.foot);++ contentHeights.push(await page.locator('.setup-add-body').evaluate((node) => node.scrollHeight));+ }++ // And the frame held still because it is sized by the rule rather than by what is+ // in it: the panes genuinely differ in height, so a content-fitted box could not+ // have produced the identical rects above.+ expect(new Set(contentHeights).size).toBeGreaterThan(1);+ expect(denied).toEqual([]);+ });++ test('the badge, the summary and the capsule each count their own set', async ({ page }) => {+ const denied = await serveProduct(page);+ const server = await serveProviders(page);+ await page.setViewportSize({ width: 1440, height: 900 });+ await openProviders(page);++ const summary = page.locator('.setup-provider-summary');+ const capsule = page.locator('.onboarding-import-notice-text');+ const badge = page.locator('.setup-provider-badge');++ // ── Nothing yet ─────────────────────────────────────────────────────────+ expect(vendorCount(server.facts())).toBe(0);+ await expect(badge).toHaveCount(0);+ // Three importable keys on the machine, and the capsule says so.+ expect(numbers(await capsule.textContent())).toEqual([importableCount(server.facts())]);++ // ── An import ───────────────────────────────────────────────────────────+ // Every proposed row arrives consented to, as the shipped takeover opens it.+ await expect(primaryAction(page)).toContainText(String(importableCount(server.facts())));++ // Withdrawing one card withdraws that provider's rows and nothing else.+ await page.locator('.setup-provider-card[data-provider="openai"]').click();+ await expect(primaryAction(page)).toContainText('2');+ await primaryAction(page).click();++ const takeover = page.getByRole('dialog');+ await takeover.getByRole('button', { name: 'Start migration' }).click();+ await expect(takeover.getByRole('button', { name: 'Done', exact: true })).toBeVisible();++ // One atomic batch holding exactly the consented rows — the withdrawn provider's+ // key was never in it, and nothing was submitted a second time.+ expect(server.facts().applied).toHaveLength(1);+ expect([...server.facts().applied[0]].sort()).toEqual(['opencode-qwen', 'opencode-zhipu']);++ await takeover.getByRole('button', { name: 'Done', exact: true }).click();+ await expect(page.getByRole('dialog')).toHaveCount(0);++ const imported = server.facts().applied.flat().length;+ // The summary counts providers that EXIST, so an import moves it.+ await expect.poll(async () => numbers(await summary.textContent())[0])+ .toBe(vendorCount(server.facts()));+ // The capsule reports what landed and what the refreshed scan still holds.+ await expect.poll(async () => numbers(await capsule.textContent()))+ .toEqual([imported, importableCount(server.facts())]);+ // The badge counts what was added THROUGH 「Add more」, and an import is not that.+ // A badge that moved here would be counting sources.+ await expect(badge).toHaveCount(0);++ // ── A write ─────────────────────────────────────────────────────────────+ await openAddDialog(page);+ await method(page, 'API Key').click();+ const body = page.locator('.setup-add-body');+ await body.getByLabel('Base URL').fill('https://proxy.example/v1');+ // Exactly, because the reveal toggle beside it is labelled 「Show API key」.+ await body.getByLabel('API key', { exact: true }).fill('sk-e2e-provider');+ await page.locator('.setup-add-foot button').last().click();+ await expect(addDialog(page)).toHaveCount(0);++ // Now the badge moves, because this one did come through 「Add more」…+ await expect.poll(async () => numbers(await badge.textContent())[0])+ .toBe(server.facts().written.length);+ // …and the summary moves with it, still counting every provider that exists+ // rather than only the two the stage draws.+ await expect.poll(async () => numbers(await summary.textContent())[0])+ .toBe(vendorCount(server.facts()));+ expect(vendorCount(server.facts())).toBeGreaterThan(server.facts().written.length);+ expect(denied).toEqual([]);+ });++ test('dismissing the import capsule leaves the primary action where it was', async ({ page }) => {+ const denied = await serveProduct(page);+ await serveProviders(page);+ await page.setViewportSize({ width: 1440, height: 900 });+ await openProviders(page);+ await page.locator('.onboarding-import-notice').waitFor();+ await settleEffects(page);++ const before = { slot: await rect(page.locator('.setup-provider-offer')), action: await rect(primaryAction(page)) };++ await page.getByRole('button', { name: 'Dismiss import notice' }).click();+ await expect(page.locator('.onboarding-import-notice')).toHaveCount(0);+ await settleEffects(page);++ // The offer is an optional sentence in a slot that is not optional. Letting the+ // slot collapse would pull the button someone was about to press up under their+ // cursor — which is the whole reason the slot is reserved rather than conditional.+ expect(await rect(page.locator('.setup-provider-offer'))).toEqual(before.slot);+ expect((await rect(primaryAction(page))).y).toBe(before.action.y);+ expect(denied).toEqual([]);+ });++ // The bands the stylesheet declares, plus the two ends of the range. Taken from the+ // shared table rather than retyped, so a size the suite stops covering is visible as+ // a size the suite stops covering.+ const OVERFLOW_SIZES = VIEWPORTS.filter((viewport) => [1920, 1440, 1366, 390, 320].includes(viewport.width));++ for (const viewport of OVERFLOW_SIZES) {+ test(`nothing spills sideways at ${size(viewport)}`, async ({ page }) => {+ const denied = await serveProduct(page);+ await serveProviders(page);+ await page.setViewportSize(viewport);+ await openProviders(page);+ await settleEffects(page);++ const horizontal = () => page.evaluate(() => ({+ scrollWidth: document.documentElement.scrollWidth,+ clientWidth: document.documentElement.clientWidth,+ }));++ const stage = await horizontal();+ expect(stage.scrollWidth).toBeLessThanOrEqual(stage.clientWidth + 1);++ // The dialog is the harder case: it is fixed, so a box wider than the window+ // would not show up as document overflow at all — it would simply be cut off,+ // with its footer buttons somewhere off the right edge.+ await openAddDialog(page);+ await settleEffects(page);++ const dialog = await rect(addDialog(page));+ const window = await page.evaluate(() => globalThis.innerWidth);+ expect(dialog.x).toBeGreaterThanOrEqual(-1);+ expect(dialog.x + dialog.width).toBeLessThanOrEqual(window + 1);++ const withDialog = await horizontal();+ expect(withDialog.scrollWidth).toBeLessThanOrEqual(withDialog.clientWidth + 1);+ expect(denied).toEqual([]);+ });+ }+});diff --git a/ui/package.json b/ui/package.jsonindex 0215f5945..f6784fac0 100644--- a/ui/package.json+++ b/ui/package.json@@ -15,7 +15,7 @@"lint:baseline": "node scripts/lint-baseline.mjs --update","preview": "vite preview","test": "vitest run",- "typecheck:tests": "tsc -p src/components/settings/models/tsconfig.tests.json --noEmit && tsc -p tsconfig.i18n-tests.json --noEmit && tsc -p src/i18n/tsconfig.guard.json --noEmit",+ "typecheck:tests": "tsc -p src/components/settings/models/tsconfig.tests.json --noEmit && tsc -p tsconfig.i18n-tests.json --noEmit && tsc -p src/i18n/tsconfig.guard.json --noEmit && tsc -p src/components/onboarding/providers/tsconfig.tests.json --noEmit","test:crypto": "vitest run src/lib/vaultCrypto.test.ts","e2e": "playwright test","e2e:headed": "playwright test --headed",diff --git a/ui/src/components/onboarding/ImportKeysNotice.test.tsx b/ui/src/components/onboarding/ImportKeysNotice.test.tsxindex 8448f0885..5501f05f1 100644--- a/ui/src/components/onboarding/ImportKeysNotice.test.tsx+++ b/ui/src/components/onboarding/ImportKeysNotice.test.tsx@@ -17,6 +17,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import i18n from '@/i18n';import type { MigrationItem } from '@/components/settings/models/types';+import { isMigrationDismissed, writeMigrationDismissed } from '@/lib/modelHubMigrationDismiss';import { RouteSurfaceActiveContext } from '@/lib/routeSurfaceActivity';const showToast = vi.hoisted(() => vi.fn());@@ -72,6 +73,21 @@ const CODEX_REAUTH: MigrationItem = {masked_credential: 'sk-…9f21',};+// The same backend without the blocker beside it: a key this entry really may take+// over, and the second consent group that makes a partial selection possible at all.+const CODEX_KEY: MigrationItem = {+ id: 'mig_codex_key',+ backend: 'codex',+ kind: 'api_key',+ masked_detail: 'sk-…5e77',+ proposed_action: 'import',+ selected: true,+ notes_key: null,+ vendor: 'openai',+ display_name: 'OpenAI',+ masked_credential: 'sk-…5e77',+};+// An OpenCode key: `opencode_provider`, never `api_key`, and its display_name is// only the provider id echoed back.const OPENCODE_ZHIPU: MigrationItem = {@@ -128,7 +144,7 @@ const renderNotice = (onApplied?: (applied: number) => void) =>);const openDialog = async (user: ReturnType<typeof userEvent.setup>) => {- await user.click(await screen.findByRole('button', { name: 'Review and migrate' }));+ await user.click(await screen.findByRole('button', { name: 'Review migration' }));return screen.findByRole('dialog');};@@ -162,16 +178,28 @@ describe('ImportKeysNotice', () => {expect(modelsApi.scanMigration).toHaveBeenCalledTimes(1);view.rerender(notice(true));await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalledTimes(2));- await waitFor(() => expect(screen.queryByRole('button', { name: 'Review and migrate' })).toBeNull());+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Review migration' })).toBeNull());expect(modelsApi.applyMigration).not.toHaveBeenCalled();});- it('counts the importable keys — not the rows the scan returned', async () => {+ it('counts the keys its own review can act on, not every importable row', async () => {serve(FULL_SCAN);renderNotice();+ const user = userEvent.setup();- // Three of five: the subscription and the reauth row are not offers.- expect(await screen.findByText('Found 3 API keys to import into Model Hub')).toBeTruthy();+ // Two of five. The subscription and the reauth row are not offers; and the+ // Claude key beside that subscription is not one either, because the dialog this+ // sentence opens takes a backend whole and will not submit a batch that omits+ // the sign-in sitting in the same file. Counting it would advertise a key whose+ // own review has nothing to press.+ expect(await screen.findByText('Found 2 API keys to import into Model Hub')).toBeTruthy();++ // The same number, read off the dialog: what it counted is what can be ticked.+ const dialog = await openDialog(user);+ const offered = within(dialog)+ .getAllByRole('checkbox')+ .filter((box) => !(box as HTMLButtonElement).disabled);+ expect(offered).toHaveLength(2);});it('offers exactly the rows it counted, and no subscription or reauth row', async () => {@@ -212,21 +240,22 @@ describe('ImportKeysNotice', () => {});it('stays to report what was imported and what is still available', async () => {- serve(FULL_SCAN);+ // Two independent groups, so half the offer can be left for later.+ serve([CODEX_KEY, OPENCODE_ZHIPU, OPENCODE_LEGACY]);renderNotice();const user = userEvent.setup();const dialog = await openDialog(user);- await user.click(within(dialog).getByRole('checkbox', { name: /sk-…dd3c/ }));+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…5e77/ }));await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));// The remainder is the server's answer after the rescan, not a subtraction.expect(await screen.findByText('Migrated 2 · 1 API key still available')).toBeTruthy();// A partial selection can still be finished from here.- expect(screen.getByRole('button', { name: 'Review and migrate' })).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Review migration' })).toBeTruthy();});- it('keeps a blocked CLI group available after importing independent keys', async () => {+ it('reports the outcome without offering a review of what it may not take', async () => {serve(FULL_SCAN);renderNotice();const user = userEvent.setup();@@ -234,10 +263,11 @@ describe('ImportKeysNotice', () => {const dialog = await openDialog(user);await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));- expect(await screen.findByText('Migrated 2 · 1 API key still available')).toBeTruthy();- expect(screen.getByRole('button', { name: 'Review and migrate' })).toBeTruthy();- // The blocked Claude group remains on this machine, including its import- // row, and the unrelated reauth row is untouched.+ // What is left on the machine is a Claude key nothing here may take and a reauth+ // row that was never an offer. The receipt says what happened; it does not invite+ // a second look at a review with nothing to press. Settings still has both.+ expect(await screen.findByText('Migrated 2 API keys into Model Hub')).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Review migration' })).toBeNull();expect(stored.map((i) => i.id)).toEqual(['mig_claude_key','mig_claude_oauth',@@ -268,10 +298,28 @@ describe('ImportKeysNotice', () => {await user.click(await screen.findByRole('button', { name: 'Dismiss import notice' }));unmount();cleanup();+ stored = [...stored, { ...OPENCODE_ZHIPU, id: 'mig_opencode_new', masked_detail: 'kimi · sk-…7a10' }];+ renderNotice();++ expect(await screen.findByText('Found 3 API keys to import into Model Hub')).toBeTruthy();+ });++ it('does not ask again for a key its review could not act on', async () => {+ serve(FULL_SCAN);+ const { unmount } = renderNotice();+ const user = userEvent.setup();++ await user.click(await screen.findByRole('button', { name: 'Dismiss import notice' }));+ unmount();+ cleanup();+ // A second Claude key, in the group the sign-in beside it blocks. Nothing this+ // entry can offer has changed, so reappearing would be a notice about keys it+ // would then decline to import.stored = [...stored, { ...CLAUDE_KEY, id: 'mig_claude_key_2', masked_detail: 'sk-…7a10' }];renderNotice();- expect(await screen.findByText('Found 4 API keys to import into Model Hub')).toBeTruthy();+ await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalledTimes(2));+ expect(screen.queryByText(/API keys? to import/)).toBeNull();});it('says nothing when there is nothing to import', async () => {@@ -302,3 +350,132 @@ describe('ImportKeysNotice', () => {expect(screen.queryByText(/Model Gateway/)).toBeNull();});});++// The providers screen holds one scan for the stage, the footer action and this+// sentence at once. Hosting hands the capsule the rows rather than letting it take+// a second scan, because two reads of the same machine are how three surfaces end+// up advertising different numbers of the same keys. What the capsule keeps is what+// it always owned: the sentence, the help, and the dismissal signature.+describe('ImportKeysNotice — hosted by a screen that already scanned', () => {+ const renderHosted = (props: { candidates: MigrationItem[]; imported?: number; onReview?: () => void }) => {+ const element = ({ candidates, imported = 0, onReview }: typeof props) => (+ <I18nextProvider i18n={i18n}>+ <ImportKeysNotice candidates={candidates} imported={imported} onReview={onReview} />+ </I18nextProvider>+ );+ const view = render(element(props));+ return { ...view, show: (next: typeof props) => view.rerender(element(next)) };+ };++ it('takes no scan of its own and says what the host gave it', async () => {+ serve(FULL_SCAN);+ const onReview = vi.fn();+ renderHosted({ candidates: [CLAUDE_KEY, OPENCODE_ZHIPU], onReview });+ const user = userEvent.setup();++ expect(screen.getByText('Found 2 API keys to import into Model Hub')).toBeTruthy();+ await user.click(screen.getByRole('button', { name: 'Review migration' }));++ // The host's dialog, over the host's rows.+ expect(onReview).toHaveBeenCalledTimes(1);+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(modelsApi.scanMigration).not.toHaveBeenCalled();+ });++ it('does not let its own capability probe overrule a host that has real evidence', async () => {+ // The probe resolves its own failures to `false`. A host holding rows has+ // better evidence than that, and hiding a real offer on a blip is the worse+ // failure of the two.+ capability.value = false;+ serve(FULL_SCAN);+ renderHosted({ candidates: [CLAUDE_KEY] });++ expect(screen.getByText('Found 1 API key to import into Model Hub')).toBeTruthy();+ });++ it('honours a dismissal the first batch is recognised by', async () => {+ writeMigrationDismissed([CLAUDE_KEY, OPENCODE_ZHIPU]);+ serve(FULL_SCAN);+ // The host is still scanning: an empty batch is not the first batch.+ const { show } = renderHosted({ candidates: [] });++ show({ candidates: [CLAUDE_KEY, OPENCODE_ZHIPU] });++ expect(screen.queryByText(/API keys to import/)).toBeNull();+ });++ it('reports what the host just imported even against a remembered dismissal', async () => {+ // These two were dismissed on some earlier visit.+ writeMigrationDismissed([CLAUDE_KEY, OPENCODE_ZHIPU]);+ serve(FULL_SCAN);+ const { show } = renderHosted({ candidates: [OPENCODE_LEGACY] });+ expect(screen.getByText('Found 1 API key to import into Model Hub')).toBeTruthy();++ // The host's rescan after an import someone just asked for. Its remainder is+ // a subset of that old dismissal, and consulting it again here would hide the+ // person's own result.+ show({ candidates: [OPENCODE_ZHIPU], imported: 1 });++ expect(screen.getByText('Migrated 1 · 1 API key still available')).toBeTruthy();+ });++ it('brings the receipt back when the host imports against a dismissal it honoured', async () => {+ // Dismissed on an earlier visit, so the capsule opens hidden — and the footer+ // CTA can still submit that very batch, because the stage and the action read+ // the scan, not this signature. Once it lands, `imported` is the answer to+ // something the person just asked for; a remembered opinion about the offer+ // cannot outrank it, and the remainder has to come back with it.+ writeMigrationDismissed([CLAUDE_KEY, OPENCODE_ZHIPU]);+ serve(FULL_SCAN);+ const { show } = renderHosted({ candidates: [CLAUDE_KEY, OPENCODE_ZHIPU] });+ expect(screen.queryByText(/API keys to import/)).toBeNull();++ show({ candidates: [OPENCODE_ZHIPU], imported: 1 });++ expect(screen.getByText('Migrated 1 · 1 API key still available')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Review migration' })).toBeTruthy();+ });++ it('keeps a dismissed receipt closed until something new lands', async () => {+ serve(FULL_SCAN);+ const { show } = renderHosted({ candidates: [OPENCODE_ZHIPU], imported: 1 });+ const user = userEvent.setup();++ await user.click(screen.getByRole('button', { name: 'Dismiss import notice' }));+ expect(screen.queryByText(/Migrated/)).toBeNull();++ // The host's ordinary re-renders — a rescan that found the same remainder —+ // are not news, and a capsule returning on each one is the nag the dismissal+ // exists to prevent.+ show({ candidates: [OPENCODE_ZHIPU], imported: 1 });+ expect(screen.queryByText(/Migrated/)).toBeNull();++ // A second batch landing is news.+ show({ candidates: [], imported: 2 });+ expect(screen.getByText('Migrated 2 API keys into Model Hub')).toBeTruthy();+ });++ it('closes the receipt without remembering an empty set', async () => {+ serve(FULL_SCAN);+ renderHosted({ candidates: [], imported: 2 });+ const user = userEvent.setup();++ expect(screen.getByText('Migrated 2 API keys into Model Hub')).toBeTruthy();+ // Nothing left to review, so nothing to review.+ expect(screen.queryByRole('button', { name: 'Review migration' })).toBeNull();++ await user.click(screen.getByRole('button', { name: 'Dismiss import notice' }));++ expect(screen.queryByText(/Migrated/)).toBeNull();+ // Remembering nothing would overwrite the signature an earlier batch was+ // dismissed by, and those keys would start asking again.+ expect(isMigrationDismissed([CLAUDE_KEY])).toBe(false);+ });++ it('says nothing when the host has neither an offer nor an outcome', async () => {+ serve(FULL_SCAN);+ renderHosted({ candidates: [] });++ expect(screen.queryByText(/Model Hub/)).toBeNull();+ });+});diff --git a/ui/src/components/onboarding/ImportKeysNotice.tsx b/ui/src/components/onboarding/ImportKeysNotice.tsxindex ced74757a..25dbefd99 100644--- a/ui/src/components/onboarding/ImportKeysNotice.tsx+++ b/ui/src/components/onboarding/ImportKeysNotice.tsx@@ -5,7 +5,9 @@// It is deliberately narrower than the settings migration: this entry is about// keys only, while OAuth takeover and re-authentication stay in Settings. The// sentence, the rows in the dialog, the batch submitted and the count left-// afterwards all read the single `isImportableKey` predicate.+// afterwards all read the single `isImportableKey` predicate — through the same+// consent grouping the dialog applies it with, because a key whose group cannot be+// taken over from here is not one this sentence may offer.//// It stays visible after an import to say what happened and what is left, so a// partial selection can be finished without hunting for the entry again.@@ -16,7 +18,8 @@ import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';import { InfoHint } from '@/components/ui/info-hint';import { MigrationDialog } from '@/components/settings/models/MigrationDialog';-import { importableKeys, isImportableKey, scanMigrationWhenEnabled } from '@/components/settings/models/migrationScan';+import { takeableImportRows } from '@/components/settings/models/migrationGrouping';+import { isImportableKey, scanMigrationWhenEnabled } from '@/components/settings/models/migrationScan';import type { MigrationItem } from '@/components/settings/models/types';import { useModelHubCapability } from '@/components/settings/models/useModelHubCapability';import { isMigrationDismissed, writeMigrationDismissed } from '@/lib/modelHubMigrationDismiss';@@ -25,16 +28,46 @@ import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';export const ImportKeysNotice: React.FC<{/** Bubble the applied count so the host step can refresh assistants/sources. */onApplied?: (applied: number) => void;-}> = ({ onApplied }) => {+ /**+ * The rows to offer, when the host already holds them.+ *+ * Passing this hands over the whole data side: the capsule stops scanning, stops+ * counting what it imported, and stops owning a dialog. The providers screen does+ * that because it holds one scan for the stage, the CTA and this sentence at once,+ * and a second scan taken by the capsule would make those three disagree about the+ * same machine. What stays the capsule's is what it always was — the sentence, the+ * help, and the dismissal signature.+ */+ candidates?: MigrationItem[];+ /** Cumulative imported count, when the host owns it. */+ imported?: number;+ /** Replaces the capsule's own dialog. Required alongside `candidates`. */+ onReview?: () => void;+}> = ({ onApplied, candidates: hostedCandidates, imported: hostedImported, onReview }) => {const { t } = useTranslation();const modelHubEnabled = useModelHubCapability();const routeSurfaceActive = useRouteSurfaceActive();+ const hosted = hostedCandidates !== undefined;- const [candidates, setCandidates] = React.useState<MigrationItem[]>([]);- const [imported, setImported] = React.useState(0);+ const [ownCandidates, setCandidates] = React.useState<MigrationItem[]>([]);+ const [ownImported, setImported] = React.useState(0);const [dialogOpen, setDialogOpen] = React.useState(false);- const [dismissed, setDismissed] = React.useState(false);+ /**+ * The imported count this capsule was last dismissed against, `null` while it has+ * never been.+ *+ * A dismissal is a statement about the offer the person was looking at, and it is+ * spent the moment an import lands: the receipt for what they just asked for is+ * the one thing this capsule exists to report, and the remainder beside it is how+ * a partial selection gets finished. Remembering WHICH result the decision was+ * made against is what separates 「the same thing again」 from 「something new+ * happened」 — and it is read during render, so a stale dismissal can never draw+ * an empty frame first and correct itself afterwards.+ */+ const [dismissedAt, setDismissedAt] = React.useState<number | null>(null);const [scanToken, setScanToken] = React.useState(0);+ const candidates = hostedCandidates ?? ownCandidates;+ const imported = hostedImported ?? ownImported;const aliveRef = React.useRef(true);React.useEffect(() => {aliveRef.current = true;@@ -44,6 +77,7 @@ export const ImportKeysNotice: React.FC<{}, []);React.useEffect(() => {+ if (hosted) return;if (modelHubEnabled !== true) {setCandidates([]);return;@@ -55,12 +89,22 @@ export const ImportKeysNotice: React.FC<{scanMigrationWhenEnabled(true).then((scan) => {if (cancelled || !aliveRef.current || scan === null) return;- const keys = importableKeys(scan.items);+ // Grouped, not filtered: the dialog this sentence opens takes a backend+ // whole and refuses a group holding a subscription sign-in or a blocker, so+ // a count of loose importable keys would advertise keys its own review has+ // nothing to offer for. One rule, so the number and the rows behind it agree.+ const keys = takeableImportRows(scan.items, isImportableKey, isImportableKey);setCandidates(keys);// Only the first scan consults the persisted dismissal. A rescan follows an// import the person just asked for, and hiding their own result because an// older batch was once dismissed would lose the outcome report.- if (scanToken === 0) setDismissed(isMigrationDismissed(keys));+ if (scanToken === 0) {+ // Adopted as a decision about nothing-imported-yet, which is what it is:+ // the only thing that moves this capsule's count is an import, and an+ // import bumps the token above. So at token 0 the count is `0`, and the+ // first one to land is news the dismissal cannot outrank.+ setDismissedAt(isMigrationDismissed(keys) ? 0 : null);+ }}).catch(() => {// A failed scan must not keep advertising the previous rows: the dialog it@@ -70,10 +114,30 @@ export const ImportKeysNotice: React.FC<{return () => {cancelled = true;};- }, [modelHubEnabled, routeSurfaceActive, scanToken]);+ }, [hosted, modelHubEnabled, routeSurfaceActive, scanToken]);++ // A hosted capsule has no first scan to hang the dismissal check on, so the first+ // batch the host delivers plays that part. Later batches are the host's own rescan+ // after an import, and hiding someone's result because an older batch was once+ // dismissed would lose the outcome report — the same reason the scan path only+ // consults it at token 0. The latch is what makes this once-only, which is why+ // `imported` can be read straight from the render scope: a re-run on a batch that+ // landed reaches it and returns without doing anything.+ const consultedRef = React.useRef(false);+ React.useEffect(() => {+ if (!hosted || consultedRef.current || (hostedCandidates?.length ?? 0) === 0) return;+ consultedRef.current = true;+ setDismissedAt(isMigrationDismissed(hostedCandidates ?? []) ? imported : null);+ }, [hosted, hostedCandidates, imported]);const remaining = candidates.length;- if (modelHubEnabled !== true || dismissed) return null;+ // Hidden while the result standing now is the one that was dismissed. An import+ // that has landed since is news, and news reopens the capsule.+ const dismissed = dismissedAt !== null && imported <= dismissedAt;+ // The capability gate belongs to the path that would otherwise call the scan+ // itself. A host that already scanned has better evidence than this hook, which+ // resolves its own failures to `false` and would hide a real offer on a blip.+ if ((!hosted && modelHubEnabled !== true) || dismissed) return null;// Nothing found and nothing done — there is no offer and no outcome to report.if (remaining === 0 && imported === 0) return null;@@ -82,7 +146,7 @@ export const ImportKeysNotice: React.FC<{// dismissed earlier would start nagging again. With nothing left to import there// is nothing to remember: this is just closing a receipt.if (remaining > 0) writeMigrationDismissed(candidates);- setDismissed(true);+ setDismissedAt(imported);};const message = imported === 0@@ -101,8 +165,8 @@ export const ImportKeysNotice: React.FC<{// A light button, not a text link: this is the capsule's own action and// it has to read as one next to the primary CTA below it.<Button type="button" variant="secondary" size="sm" className="onboarding-import-notice-action"- onClick={() => setDialogOpen(true)}>- {t('settings.models.importNotice.review')}+ onClick={() => (onReview ? onReview() : setDialogOpen(true))}>+ {t('onboarding.import.review')}</Button>)}<InfoHint@@ -111,7 +175,7 @@ export const ImportKeysNotice: React.FC<{className="onboarding-import-notice-help"label={t('settings.models.importNotice.help') as string}trigger={t('settings.models.importNotice.help')}- content={t('settings.models.importNotice.helpBody')}+ content={t('onboarding.import.helpBody')}contentClassName="w-72"/></div>@@ -125,10 +189,11 @@ export const ImportKeysNotice: React.FC<{</button></div>- {dialogOpen && (+ {dialogOpen && !hosted && (<MigrationDialogopeneligible={isImportableKey}+ takeable={isImportableKey}onClose={() => setDialogOpen(false)}onApplied={(applied) => {setDialogOpen(false);diff --git a/ui/src/components/onboarding/onboarding-providers.css b/ui/src/components/onboarding/onboarding-providers.cssnew file mode 100644index 000000000..45a862819--- /dev/null+++ b/ui/src/components/onboarding/onboarding-providers.css@@ -0,0 +1,645 @@+/* Setup screen 2 — model providers.+ *+ * The screen is one diagram: provider cards feed a gateway, the gateway feeds the+ * assistants the introduction just showed. Everything below describes that diagram+ * and nothing else; the shell, the heading, the footer action and the import capsule+ * belong to `onboarding.css`, which this file only consumes.+ *+ * Two different rules are at work here, on purpose.+ *+ * Geometry scales with `--ob-u`. The reference frame draws the diagram at 88 + 40 ++ * 72 + 40 + 84 + 34, then 16 and a 44 capsule — measured under an 800px window, which+ * is exactly the band where `--ob-card-h` is 232 and `--ob-u` is therefore 1. So every+ * authored number is written as `N * --ob-u` and is exact where it was measured, while+ * the diagram grows and shrinks with the card the rest of the composition is built on.+ * That is the same unit the story's own interior already uses, and it means this file+ * introduces no band of its own.+ *+ * Type and logos do not scale with `--ob-u`; they take the tier tokens the story cards+ * take. The handoff morphs `.onboarding-card-logo` / `.onboarding-card-name` into+ * `.setup-destination-logo` / `.setup-destination-name` and back out again, so those+ * pairs have to hold the same values or the transition animates a size change nobody+ * asked for. Authored type is L1's to set per tier; scaling it here would fight that.+ * Where the diagram needs a size no `--ob-*` token names yet — the card's key line and+ * the gateway's two lines — this file declares an `--obp-*` default behind the+ * `--ob-*` name L1 would use, so promoting it later is a one-line change upstream and+ * no change here.+ *+ * Colors come from the shared scale only. The reference's `#5bffa014` fill is exactly+ * `--card-wash` in both themes, its `#ffffff24` idle border is exactly+ * `--border-strong`, and its solid mint is `--mint`; the wires, ports and pulses reuse+ * the story's `--ob-wire` family. Active and hover wear `--ob-active-shadow`.+ */++.setup-provider-stage {+ /* Behind every `--ob-*` name L1 owns or may promote, the value this screen was+ measured at. Reading through the token first means a promotion upstream lands+ here automatically and a missing token never silently drops the diagram. */+ --obp-card-h: var(--ob-provider-card-h, calc(88 * var(--ob-u)));+ --obp-card-pv: var(--ob-provider-card-pad-v, calc(14 * var(--ob-u)));+ --obp-card-ph: var(--ob-provider-card-pad-h, calc(16 * var(--ob-u)));+ --obp-card-gap: var(--ob-provider-card-gap, calc(10 * var(--ob-u)));+ --obp-card-key: var(--ob-provider-card-key, calc(var(--ob-cap-fs) - 1px));+ --obp-check: var(--ob-provider-card-check, calc(20 * var(--ob-u)));+ --obp-add: var(--ob-provider-card-add, calc(28 * var(--ob-u)));+ --obp-wire-h: var(--ob-wire-h, calc(40 * var(--ob-u)));+ --obp-gateway-h: var(--ob-gateway-h, calc(72 * var(--ob-u)));+ --obp-gateway-name: var(--ob-gateway-name, calc(var(--ob-card-name) + 2px));+ --obp-destination-h: var(--ob-destination-h, calc(84 * var(--ob-u)));+ --obp-summary-h: var(--ob-summary-h, calc(34 * var(--ob-u)));+ --obp-offer-gap: var(--ob-gap, calc(16 * var(--ob-u)));++ width: 100%;+ display: flex;+ flex-direction: column;+ /* The reference stacks the six diagram bands with no gap at all — each one's top is+ the previous one's bottom — and spends its only gap above the capsule. */+ gap: 0;+}++/* ---- Provider sources ---------------------------------------------------- */++/* The same three tracks the story's cards use, so the diagram's columns and the+ composition's columns are one set: 299-wide cards with 39.5 gaps in a 976 box,+ written as the fraction rather than the pixels so it holds at every width. */+.setup-provider-grid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 30.6352%));+ justify-content: space-between;+ height: var(--obp-card-h);+}++.setup-provider-card {+ min-width: 0;+ display: flex;+ align-items: center;+ gap: var(--obp-card-gap);+ padding: var(--obp-card-pv) var(--obp-card-ph);+ border-radius: 12px;+ border: 1px solid var(--ob-card-border);+ background: var(--ob-card);+ text-align: start;+ transition: border-color 150ms, background 150ms, box-shadow 150ms;+}+/* A card the person has decided about — a source that exists, or a detected key they+ have consented to — wears the mint fill. Hover has no translate or scale (C3). */+.setup-provider-card[data-state='connected'],+.setup-provider-card[aria-pressed='true'] {+ border-color: var(--mint);+ background: var(--card-wash);+}+.setup-provider-card[aria-pressed]:hover:not(:disabled),+.setup-provider-card[aria-pressed]:focus-visible {+ border-color: var(--mint);+ box-shadow: var(--ob-active-shadow, var(--shadow-glow-onboarding-mint));+}+.setup-provider-card:disabled {+ cursor: not-allowed;+ opacity: 0.55;+}+/* The third card is an invitation rather than a thing that exists, so it is drawn as+ an outline on nothing: no fill, and the dashed edge the handoff asks for in place of+ the reference's solid one. */+.setup-provider-card[data-state='add'] {+ border-style: dashed;+ border-color: var(--border-strong);+ background: transparent;+}+.setup-provider-card[data-state='add']:hover,+.setup-provider-card[data-state='add']:focus-visible {+ border-color: var(--mint);+ box-shadow: var(--ob-active-shadow, var(--shadow-glow-onboarding-mint));+}++/* Both marks sit in a box of the story's own logo size, restated rather than+ borrowed by class: `.onboarding-card-logo` is one of the names the handoff+ queries, and putting it on this screen's elements too would make the outgoing+ and incoming sets overlap. Three declarations are cheaper than that ambiguity.+ The `!important` matches it for the same reason it exists there — `BackendIcon`+ writes an inline size on its span, and the tier owns the mark's size. */+.setup-provider-logo,+.setup-destination-logo {+ flex-shrink: 0;+ display: inline-flex;+ align-items: center;+ justify-content: center;+}+.setup-provider-logo,+.setup-destination-logo,+.setup-destination-logo > span {+ width: var(--ob-card-logo) !important;+ height: var(--ob-card-logo) !important;+}+/* The destination's mark is a full-bleed brand path and fills its box, exactly as+ the story card it morphs out of does. */+.setup-destination-logo svg {+ width: 100%;+ height: 100%;+ display: block;+}+/* A vendor mark is single-color ink, not a brand lockup, so it is drawn small in a+ well rather than full-bleed — the same treatment, and the same 15-in-28 ink, the+ provider picker already gives it. The descendant selector also settles the size+ without depending on whether the Model Hub sheet is loaded on this route. */+.setup-provider-logo {+ border-radius: 8px;+ border: 1px solid var(--border);+ background: var(--logo-well-background);+}+.setup-provider-logo svg {+ height: calc(var(--ob-card-logo) * 15 / 28);+ width: auto;+ display: block;+ color: var(--foreground);+}+.setup-provider-add-icon {+ flex-shrink: 0;+ width: var(--obp-add);+ height: var(--obp-add);+ color: var(--muted-foreground);+}+.setup-provider-copy {+ flex: 1 1 0;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: calc(3 * var(--ob-u));+}+.setup-provider-name {+ font-size: var(--ob-card-name);+ font-weight: 600;+ line-height: 1.45;+ color: var(--foreground);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.setup-provider-key {+ font-size: var(--obp-card-key);+ line-height: 1.45;+ color: var(--muted-foreground);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.setup-provider-check {+ flex-shrink: 0;+ width: var(--obp-check);+ height: var(--obp-check);+ color: var(--mint-ink);+}+/* The count of what was added through Add more rides the card it describes. */+.setup-provider-badge {+ flex-shrink: 0;+ font-size: var(--obp-card-key);+ line-height: 1.45;+ color: var(--mint-ink);+ white-space: nowrap;+}++/* ---- Wires --------------------------------------------------------------- */++/* Each band is its own box and its own SVG, drawn in a px viewBox that matches the+ box it was measured in, because the paths are built from the real centres of the+ real cards. Stretching one viewBox over the whole diagram — which is how the+ story draws its fixed circuit — would skew every curve the moment the column+ width changed. */+.setup-wires {+ position: relative;+ width: 100%;+ height: var(--obp-wire-h);+ flex-shrink: 0;+}+.setup-wires > svg {+ display: block;+ width: 100%;+ height: 100%;+ overflow: visible;+ pointer-events: none;+}+.setup-wire {+ fill: none;+ stroke: var(--ob-wire);+ stroke-width: 1;+}+/* One 16-unit segment of a 100-unit path: the pulse crosses once and leaves, the+ same signature the story's circuit uses. */+.setup-wire-pulse {+ fill: none;+ stroke: var(--ob-pulse);+ stroke-width: 1.6;+ stroke-linecap: round;+ stroke-dasharray: 16 116;+ stroke-dashoffset: 16;+ opacity: 0;+}+.setup-wire-pulse-halo {+ stroke: var(--ob-pulse-glow);+ stroke-width: 4;+}+.setup-provider-stage[data-motion='running'] .setup-wire-pulse {+ animation: setup-wire-pulse 1100ms ease-in-out var(--setup-pulse-delay, 0ms) 1 both;+}+@keyframes setup-wire-pulse {+ 0% { stroke-dashoffset: 16; opacity: 0; }+ 15% { opacity: 1; }+ 85% { opacity: 1; }+ 100% { stroke-dashoffset: -116; opacity: 0; }+}++/* ---- Gateway ------------------------------------------------------------- */++/* One track wide and centred, which puts it on the column the middle card sits on. */+.setup-gateway {+ width: 30.6352%;+ min-width: 0;+ margin: 0 auto;+ height: var(--obp-gateway-h);+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: calc(4 * var(--ob-u));+ padding: 0 var(--obp-card-ph);+ border-radius: 14px;+ border: 1px solid var(--ob-card-border);+ background: var(--ob-card);+ text-align: center;+ transition: border-color 150ms, background 150ms;+}+/* Running — including degraded but routable — is the state the diagram is drawn in. */+.setup-gateway[data-state='running'] {+ border-color: var(--mint);+ background: var(--card-wash);+}+/* The one place the band's fixed height gives way, because what replaces the tagline+ is two sentences and a way out of them. The wires re-measure on the stage's resize,+ so the diagram follows the card rather than detaching from it. */+.setup-gateway[data-state='failed'],+.setup-gateway[data-state='unsupported'] {+ height: auto;+ min-height: var(--obp-gateway-h);+ padding: calc(10 * var(--ob-u)) var(--obp-card-ph);+ border-color: var(--destructive-ink);+}+/* Both places a read can fail offer the same way out, at a size that fits the band it+ sits in: the button's own `sm` height is a fixed 32px, which overflows the summary+ line once `--ob-u` drops below 1. Scaling it with the tier is what keeps the row one+ row at every width. */+.setup-gateway-retry,+.setup-summary-retry {+ height: calc(26 * var(--ob-u));+ padding: 0 calc(10 * var(--ob-u));+ font-size: var(--obp-card-key);+}+.setup-summary-retry { margin-inline-start: calc(8 * var(--ob-u)); flex: none; }+/* Below the recheck, not beside it: the two are not alternatives of the same weight —+ one asks the machine again, the other explains what would have to change first. */+.setup-gateway-help {+ height: calc(20 * var(--ob-u));+ font-size: var(--obp-card-key);+}+.setup-gateway-name {+ font-size: var(--obp-gateway-name);+ font-weight: 600;+ line-height: 1.45;+ color: var(--foreground);+}+.setup-gateway-tagline {+ max-width: 100%;+ font-size: var(--obp-card-key);+ line-height: 1.45;+ color: var(--muted-foreground);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.setup-gateway-tagline[data-tone='error'] {+ color: var(--destructive-ink);+ white-space: normal;+}+/* Spinning is Tailwind's `motion-safe:animate-spin` on the icon itself, the same way+ every other busy control in this surface does it; only the size is ours. */+.setup-gateway-spinner {+ flex-shrink: 0;+ width: calc(14 * var(--ob-u));+ height: calc(14 * var(--ob-u));+ color: var(--mint-ink);+}++/* ---- Assistant destinations ---------------------------------------------- */++/* The row the introduction's three cards shrink into. Same tracks, same logo and+ name tokens, so the handoff has nothing to interpolate but position and size of+ the frame itself. */+.setup-destinations {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 30.6352%));+ justify-content: space-between;+ height: var(--obp-destination-h);+}+.setup-destination {+ min-width: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: var(--obp-card-gap);+ padding: 0 var(--obp-card-ph);+ border-radius: 12px;+ border: 1px solid var(--border-strong);+ background: transparent;+}+.setup-destination-name {+ font-size: var(--ob-card-name);+ font-weight: 600;+ line-height: 1.45;+ color: var(--foreground);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* ---- Summary and the offer's reserved slot ------------------------------- */++.setup-provider-summary {+ height: var(--obp-summary-h);+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 0 var(--obp-card-ph);+ font-size: var(--ob-cap-fs);+ line-height: 1.45;+ color: var(--muted-foreground);+ text-align: center;+}+.setup-provider-summary[data-tone='error'] { color: var(--destructive-ink); }++/* The slot, not the capsule: it keeps its height whether the offer is showing, was+ dismissed, or was never made, so the footer action cannot move under the hand of+ someone who just declined it (C3, handoff §4). */+.setup-provider-offer {+ margin-top: var(--obp-offer-gap);+ min-height: 44px;+ display: flex;+ align-items: center;+ justify-content: center;+}++/* ---- Add-source dialog --------------------------------------------------- */++/* C5's stable frame, and the reason it is written as a height rather than as+ * padding around whatever is inside: the three methods have genuinely different+ * content lengths, and a box fitted to each one moves its own close button and+ * its own primary action every time someone compares two of them. So the frame is+ * one size — the tallest ordinary pane — the head and foot are anchored, and only+ * the middle scrolls. A pane shorter than the body simply leaves space below it.+ *+ * None of this scales with `--ob-u`. Radix portals the dialog out of the stage's+ * subtree, so the diagram's unit does not reach it — and should not: the diagram+ * grows with the composition it belongs to, while a dialog is chrome over the+ * whole viewport and is bounded by the viewport instead.+ *+ * The fields inside come from `ApiKeySourceForm`, dressed by the Model Hub's own+ * stylesheet, which that component now carries. Nothing here restyles them: the+ * two dialogs asking for a key must look like the same question. */+.setup-add-dialog {+ --obs-dialog-w: 568px;+ --obs-dialog-h: 632px;+ --obs-pad: 24px;+ --obs-gap: 20px;+ --obs-row-h: 56px;+ --obs-radius: 16px;+ --obs-row-radius: 10px;++ width: min(var(--obs-dialog-w), calc(100vw - 32px));+ height: var(--obs-dialog-h);+ max-height: calc(100dvh - 48px);+ border: 1px solid var(--border);+ border-radius: var(--obs-radius);+ background: var(--card);+ box-shadow: var(--ob-active-shadow, var(--shadow-glow-onboarding-mint));+}++.setup-add-head {+ display: flex;+ flex: none;+ flex-direction: column;+ gap: 10px;+ padding: var(--obs-pad) var(--obs-pad) 0;+}++.setup-add-title {+ font-size: 16px;+ font-weight: 600;+ line-height: 1.3;+ color: var(--foreground);+}++.setup-add-subtitle {+ font-size: 12.5px;+ line-height: 1.5;+ color: var(--muted-foreground);+}++/* The same segmented control `ApiKeySourceForm` uses for protocol, at this+ dialog's scale: one track, equal segments, the chosen one filled. */+.setup-add-methods {+ display: grid;+ grid-auto-columns: minmax(0, 1fr);+ grid-auto-flow: column;+ gap: 4px;+ padding: 4px;+ border: 1px solid var(--border);+ border-radius: var(--obs-row-radius);+ background: var(--card-wash);+}++.setup-add-method {+ height: 30px;+ min-width: 0;+ border-radius: 7px;+ font-size: 12.5px;+ font-weight: 500;+ color: var(--muted-foreground);+ transition: background 0.15s ease, color 0.15s ease;+}+.setup-add-method:hover:not(:disabled) { color: var(--foreground); }+.setup-add-method[aria-pressed='true'] {+ background: var(--card);+ color: var(--foreground);+ box-shadow: var(--ob-active-shadow, var(--shadow-glow-onboarding-mint));+}+.setup-add-method:disabled { cursor: not-allowed; opacity: 0.5; }++.setup-add-body {+ display: flex;+ flex: 1 1 auto;+ min-height: 0;+ flex-direction: column;+ gap: 12px;+ overflow-y: auto;+ padding: var(--obs-gap) var(--obs-pad);+}++.setup-add-note {+ font-size: 12px;+ line-height: 1.55;+ color: var(--muted-foreground);+}++.setup-add-group {+ font-size: 11.5px;+ font-weight: 600;+ color: var(--muted-foreground);+}++.setup-add-row {+ display: flex;+ flex: none;+ align-items: center;+ gap: 12px;+ height: var(--obs-row-h);+ padding: 0 14px;+ border: 1px solid var(--border-strong);+ border-radius: var(--obs-row-radius);+ background: transparent;+ text-align: left;+ transition: border-color 0.15s ease, background 0.15s ease, box-shadow 0.15s ease;+}+.setup-add-row[aria-pressed='true'] {+ border-color: var(--mint);+ background: var(--card-wash);+}+.setup-add-row[aria-pressed]:hover:not(:disabled),+.setup-add-row[aria-pressed]:focus-visible {+ border-color: var(--mint);+ box-shadow: var(--ob-active-shadow, var(--shadow-glow-onboarding-mint));+}+/* An already-added brand is shown so the list stays a complete account of what+ was found, and disabled so it cannot be added twice. */+.setup-add-row:disabled { cursor: default; opacity: 0.55; }++.setup-add-row-logo {+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+}+.setup-add-row-logo svg { width: 100%; height: 100%; }++.setup-add-row-copy {+ display: flex;+ flex: 1;+ min-width: 0;+ flex-direction: column;+ gap: 3px;+}++.setup-add-row-name {+ font-size: 13px;+ font-weight: 500;+ color: var(--foreground);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.setup-add-row-detail {+ font-family: "JetBrains Mono", ui-monospace, monospace;+ font-size: 11px;+ color: var(--muted-foreground);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.setup-add-row-check {+ flex: none;+ width: 18px;+ height: 18px;+ color: var(--mint);+}++.setup-add-row-tag {+ flex: none;+ font-size: 11px;+ color: var(--muted-foreground);+}++.setup-add-foot {+ display: flex;+ flex: none;+ align-items: center;+ gap: 10px;+ padding: 0 var(--obs-pad) var(--obs-pad);+}++/* Reserved, not conditional: the strip holds its line whether or not there is+ anything to say, so a progress message arriving cannot push the two buttons+ under a hand that is already over one of them. */+.setup-add-status {+ display: flex;+ flex: 1;+ min-width: 0;+ min-height: 18px;+ align-items: center;+ gap: 6px;+ font-size: 11.5px;+ line-height: 1.4;+ color: var(--muted-foreground);+}++.setup-add-status-icon {+ flex: none;+ width: 13px;+ height: 13px;+}+.setup-add-status-icon--error { color: var(--destructive-ink); }+.setup-add-status-error { color: var(--destructive-ink); }++/* ---- Bands --------------------------------------------------------------- */++/* Only the two stacked bands `onboarding.css` already declares, restated for this+ root. Nothing new is introduced: below 1024 the composition loses its third+ column, and below 760 the diagram is a single column with the wires removed,+ because a vertical wire between two stacked boxes describes nothing. */+@media (max-width: 1023px) {+ .setup-provider-grid,+ .setup-destinations {+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: calc(12 * var(--ob-u));+ justify-content: stretch;+ }+ .setup-gateway { width: 100%; }+}+@media (max-width: 759px) {+ .setup-provider-stage { gap: 10px; }+ .setup-provider-grid,+ .setup-destinations {+ grid-template-columns: minmax(0, 1fr);+ height: auto;+ gap: 10px;+ }+ .setup-provider-card,+ .setup-destination { height: calc(64 * var(--ob-u)); }+ .setup-destination { justify-content: flex-start; }+ .setup-wires { display: none; }+ .setup-gateway { height: calc(64 * var(--ob-u)); }+ .setup-provider-summary { height: auto; min-height: var(--obp-summary-h); }+ .setup-provider-offer { margin-top: 0; }++ /* Tighter insets and the phone's full width. The height stays one value and+ stays independent of the method — clamped harder against a short viewport,+ never fitted to what is showing, which is the whole point of C5's frame. */+ .setup-add-dialog {+ --obs-pad: 18px;+ --obs-gap: 16px;+ width: calc(100vw - 24px);+ max-height: calc(100dvh - 32px);+ }+}+@media (prefers-reduced-motion: reduce) {+ .setup-wire-pulse { animation: none !important; }+}diff --git a/ui/src/components/onboarding/providers/AddSourceDialog.test.tsx b/ui/src/components/onboarding/providers/AddSourceDialog.test.tsxnew file mode 100644index 000000000..f6a492d2f--- /dev/null+++ b/ui/src/components/onboarding/providers/AddSourceDialog.test.tsx@@ -0,0 +1,867 @@+// @vitest-environment jsdom+//+// C5: one frame, three methods. What that rule protects is a comparison — someone+// switching between 「订阅」 and 「API Key」 to decide which they have — so every case+// here is a way the switch could cost them something: a frame that rebuilt itself,+// a draft that was thrown away, a control still reachable in a pane nobody is+// looking at, or a method that vanished and took the dialog's contents with it.+//+// The geometry half of C5 (the box not resizing) is browser evidence and lives in+// `providers.spec.ts`. What is provable here is the structural half it rests on:+// the anchored parts are the same nodes before and after, and only the body+// changes.+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import * as React from 'react';+import { I18nextProvider } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import { apiKeyVendorPreset } from '@/components/settings/models/apiKeyVendors';+import { createSourceCollectionReadAuthority } from '@/components/settings/models/collectionReadAuthority';+import type { Source } from '@/components/settings/models/types';++const showToast = vi.hoisted(() => vi.fn());+vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast }) }));++// The authorization flow owns its own frame, poll and cancellation; what this file+// has to prove is how its two callback shapes are read. Standing in for it keeps+// that readable without driving a device-code flow to get there.+type OAuthProps = {+ vendor: string | null;+ onConnected: (source?: Source, placement?: unknown) => void;+ onClose: () => void;+};+const oauth = vi.hoisted(() => ({ current: null as OAuthProps | null }));+vi.mock('@/components/settings/models/OAuthConnectDialog', () => ({+ OAuthConnectDialog: (props: OAuthProps) => {+ oauth.current = props;+ return React.createElement('div', { 'data-testid': 'oauth-stub' });+ },+}));++import { ApiCallError, modelsApi, type SourceCreated } from '@/components/settings/models/modelsApi';+import { AddSourceDialog } from './AddSourceDialog';+import type { ProviderSlot } from './providerStage';++const slot = (vendor: string, over: Partial<ProviderSlot> = {}): ProviderSlot => ({+ vendor,+ brand: vendor,+ label: vendor === 'openai' ? 'OpenAI' : vendor === 'anthropic' ? 'Anthropic' : vendor,+ kind: 'detected',+ mask: 'sk-…9f21',+ supply: null,+ pending: false,+ // Takeable from here, and no reason not to be: the blocked shape is the+ // opposite pair — no backend may take it, and it says why.+ backends: ['codex'],+ reasons: [],+ ...over,+});++/** Found, and not this screen's to take: the rows the stage keeps visible anyway. */+const blockedSlot = (vendor: string, over: Partial<ProviderSlot> = {}): ProviderSlot =>+ slot(vendor, { backends: [], reasons: ['onboarding.import.outOfScope'], ...over });++const source = (over: Partial<Source> & { id: string; vendor: string }): Source => ({+ last_discovered_at: null,+ kind: 'api_key',+ display_name: over.vendor,+ protocol: 'openai_chat',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active' },+ models: [],+ ...over,+});++const created = (row: Source): SourceCreated => ({ source: row, added_to: [], adopted_by: [] });++const onToggleDetected = vi.fn();+const onReviewDetected = vi.fn();+const onAdded = vi.fn<(value: SourceCreated | null) => Promise<void>>();+const onClose = vi.fn();++type Options = {+ more?: boolean;+ vendor?: string | null;+ detected?: ProviderSlot[];+ pendingCount?: number;+ sources?: Source[];+ selected?: (slot: ProviderSlot) => boolean;+ writable?: boolean;+};++const renderDialog = ({+ more = true,+ vendor = null,+ detected = [],+ pendingCount = 0,+ sources = [],+ selected = () => false,+ writable = true,+}: Options = {}) => {+ const view = render(+ <I18nextProvider i18n={i18n}>+ <AddSourceDialog+ more={more}+ vendor={vendor}+ detected={detected}+ pendingCount={pendingCount}+ writable={writable}+ sources={sources}+ sourceReads={createSourceCollectionReadAuthority()}+ isSelected={selected}+ onToggleDetected={onToggleDetected}+ onReviewDetected={onReviewDetected}+ onAdded={onAdded}+ onClose={onClose}+ />+ </I18nextProvider>,+ );+ const rerender = (next: Options) => view.rerender(+ <I18nextProvider i18n={i18n}>+ <AddSourceDialog+ more={next.more ?? more}+ vendor={next.vendor ?? vendor}+ detected={next.detected ?? detected}+ pendingCount={next.pendingCount ?? pendingCount}+ writable={next.writable ?? writable}+ sources={next.sources ?? sources}+ sourceReads={createSourceCollectionReadAuthority()}+ isSelected={next.selected ?? selected}+ onToggleDetected={onToggleDetected}+ onReviewDetected={onReviewDetected}+ onAdded={onAdded}+ onClose={onClose}+ />+ </I18nextProvider>,+ );+ return { ...view, rerender };+};++const frame = () => {+ const dialog = document.querySelector<HTMLElement>('.setup-add-dialog');+ if (!dialog) throw new Error('no dialog');+ return dialog;+};+const body = () => {+ const pane = document.querySelector<HTMLElement>('.setup-add-body');+ if (!pane) throw new Error('no body');+ return pane;+};+const methodButtons = () => [...document.querySelectorAll<HTMLElement>('.setup-add-method')];+const methodNames = () => methodButtons().map((button) => button.textContent);+const activeMethod = () => body().dataset.method;+const chooseMethod = async (user: ReturnType<typeof userEvent.setup>, name: string) => {+ await user.click(screen.getByRole('button', { name }));+};+/** The footer's two buttons, in the order they are read: cancel, then the offer. */+const footButtons = () => [...document.querySelectorAll<HTMLButtonElement>('.setup-add-foot button')];+const cancelButton = () => footButtons()[0];+const primary = () => footButtons()[footButtons().length - 1];++beforeEach(async () => {+ onToggleDetected.mockReset();+ onReviewDetected.mockReset();+ onClose.mockReset();+ onAdded.mockReset();+ onAdded.mockResolvedValue(undefined);+ oauth.current = null;+ vi.stubGlobal('ResizeObserver', class {+ observe() {}+ unobserve() {}+ disconnect() {}+ });+ // Radix measures the viewport for the popover the vendor picker opens into.+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ }));+ await i18n.changeLanguage('en');+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ showToast.mockReset();+});++describe('AddSourceDialog — the frame', () => {+ it('offers Detected only when something was detected', async () => {+ renderDialog();+ expect(methodNames()).toEqual(['Subscription', 'API Key']);+ cleanup();++ renderDialog({ detected: [slot('openai')] });+ expect(methodNames()).toEqual(['Detected', 'Subscription', 'API Key']);+ // And it opens on it: what is already on the machine is the cheapest way in.+ expect(activeMethod()).toBe('detected');+ });++ it('keeps one frame across repeated switching, changing only the body', async () => {+ renderDialog({ detected: [slot('openai')] });+ const user = userEvent.setup();+ const dialog = frame();+ const head = document.querySelector('.setup-add-head');+ const foot = document.querySelector('.setup-add-foot');+ const buttons = methodButtons();+ const pane = body();++ for (const round of ['API Key', 'Subscription', 'Detected', 'API Key', 'Detected']) {+ await chooseMethod(user, round);+ // The same elements, not merely matching ones: a frame React rebuilt would+ // lose scroll position, focus and any transition mid-flight.+ expect(frame()).toBe(dialog);+ expect(document.querySelector('.setup-add-head')).toBe(head);+ expect(document.querySelector('.setup-add-foot')).toBe(foot);+ expect(methodButtons()).toEqual(buttons);+ expect(body()).toBe(pane);+ // One pane at a time, named by the body itself so the stylesheet sizes the+ // frame by the method rather than by its contents.+ expect(activeMethod()).toBe(+ round === 'API Key' ? 'apiKey' : round === 'Subscription' ? 'subscription' : 'detected',+ );+ }+ });++ it('states the chosen method exactly once', async () => {+ renderDialog({ detected: [slot('openai')] });+ const user = userEvent.setup();+ await chooseMethod(user, 'Subscription');++ const pressed = methodButtons().filter((button) => button.getAttribute('aria-pressed') === 'true');+ expect(pressed.map((button) => button.textContent)).toEqual(['Subscription']);+ expect(document.querySelector('[role="group"][aria-label="Add method"]')).toBeTruthy();+ });++ it('leaves nothing of an unchosen method behind', async () => {+ renderDialog({ detected: [slot('openai')] });+ const user = userEvent.setup();++ await chooseMethod(user, 'API Key');+ // The subscription rows are gone, not hidden: a hidden pane keeps its effects,+ // and this one's is an authorization flow where a duplicate is a second device+ // code for the same account.+ expect(within(body()).queryByRole('button', { name: /Sign in with/ })).toBeNull();+ expect(within(body()).queryByRole('button', { name: /Select existing/ })).toBeNull();+ expect(within(body()).getByLabelText('API key')).toBeTruthy();++ await chooseMethod(user, 'Subscription');+ expect(within(body()).queryByLabelText('API key')).toBeNull();+ expect(within(body()).queryByLabelText('Base URL')).toBeNull();+ // Nothing reachable by keyboard either, which is the part a `hidden` attribute+ // would have covered and the part a person actually trips over.+ expect(within(body()).getAllByRole('button').every((node) => node.closest('.setup-add-body'))).toBe(true);+ });++ it('falls back when the method someone is on stops existing', async () => {+ const { rerender } = renderDialog({ detected: [slot('openai')] });+ expect(activeMethod()).toBe('detected');++ // The last detected candidate was taken over while this was open.+ rerender({ detected: [] });++ expect(methodNames()).toEqual(['Subscription', 'API Key']);+ // A frame rendering nothing at all would be the alternative.+ expect(activeMethod()).toBe('subscription');+ });++ it('says what it is for, without changing what it can do', async () => {+ const { rerender } = renderDialog({ more: true });+ expect(screen.getByText('Add more model providers')).toBeTruthy();+ const methods = methodNames();++ rerender({ more: false });++ expect(screen.getByText('Add subscription or API Key')).toBeTruthy();+ expect(methodNames()).toEqual(methods);+ });+});++describe('AddSourceDialog — what a switch preserves', () => {+ it('keeps a half-typed key across a switch away and back', async () => {+ renderDialog();+ const user = userEvent.setup();+ await chooseMethod(user, 'API Key');+ await user.type(within(body()).getByLabelText('Base URL'), 'https://proxy.example/v1');+ await user.type(within(body()).getByLabelText('API key'), 'sk-half-typed');++ await chooseMethod(user, 'Subscription');+ await chooseMethod(user, 'API Key');++ expect((within(body()).getByLabelText('Base URL') as HTMLInputElement).value)+ .toBe('https://proxy.example/v1');+ expect((within(body()).getByLabelText('API key') as HTMLInputElement).value).toBe('sk-half-typed');+ // And it is still submittable: the draft came back whole, not just its text.+ expect(primary().disabled).toBe(false);+ });++ it('keeps the subscription someone had chosen', async () => {+ renderDialog();+ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: /Sign in with Claude/ }));+ expect(primary().textContent).toContain('Claude');++ await chooseMethod(user, 'API Key');+ await chooseMethod(user, 'Subscription');++ expect(primary().textContent).toContain('Claude');+ });++ it('opens a named brand on the way in that brand is offered', async () => {+ renderDialog({ more: false, vendor: 'anthropic' });+ // A subscription brand opens on its sign-in rather than on a key field.+ expect(activeMethod()).toBe('subscription');+ expect(primary().textContent).toContain('Claude');+ cleanup();++ renderDialog({ more: false, vendor: 'deepseek' });+ expect(activeMethod()).toBe('apiKey');+ // With the endpoint that brand publishes already filled: re-selecting the+ // vendor that is already selected is identity, so a prefill left undone here+ // could not be reached from inside the form at all.+ expect((within(body()).getByLabelText('Base URL') as HTMLInputElement).value)+ .toBe(apiKeyVendorPreset('deepseek')?.official_base_url);+ expect(within(body()).getByLabelText('DeepSeek API Key')).toBeTruthy();+ });+});++describe('AddSourceDialog — detected', () => {+ it('counts the selection in the footer and hands it to the takeover', async () => {+ renderDialog({ detected: [slot('openai')], pendingCount: 0 });+ expect(primary().disabled).toBe(true);+ cleanup();++ renderDialog({ detected: [slot('openai'), slot('gemini')], pendingCount: 2 });+ expect(primary().textContent).toBe('Review 2 selected');+ await userEvent.setup().click(primary());++ // Consent belongs to the shipped takeover; this dialog only points at it.+ expect(onReviewDetected).toHaveBeenCalledTimes(1);+ expect(onAdded).not.toHaveBeenCalled();+ });++ it('marks what is already there and offers no choice about it', async () => {+ renderDialog({+ detected: [slot('openai'), slot('gemini', { mask: 'sk-…3456' })],+ // The same credential, not merely the same brand: both masks come from the+ // server's one masking function, so this is the only evidence either side has+ // that the native store and the Hub hold one key.+ sources: [source({ id: 'src_openai', vendor: 'openai', masked_credential: 'sk-…9f21' })],+ });+ const user = userEvent.setup();+ const [added, open] = [...document.querySelectorAll<HTMLButtonElement>('.setup-add-row')];++ expect(added.dataset.state).toBe('added');+ expect(within(added).getByText('Added')).toBeTruthy();+ expect(added.disabled).toBe(true);+ expect(added.getAttribute('aria-pressed')).toBeNull();++ await user.click(open);+ expect(onToggleDetected).toHaveBeenCalledTimes(1);+ expect(onToggleDetected.mock.calls[0][0]).toMatchObject({ vendor: 'gemini' });+ });++ it('offers a second key under a brand that is already connected', async () => {+ renderDialog({+ detected: [slot('openai')],+ // Same provider, different key. A vendor match is not evidence of a duplicate:+ // the scan reads native stores and never sees the Hub's inventory, so marking+ // this 「已添加」 would refuse the one action the row exists for and leave the+ // capsule counting a key nobody can take.+ sources: [source({ id: 'src_openai', vendor: 'openai', masked_credential: 'sk-…1111' })],+ });+ const user = userEvent.setup();+ const [second] = [...document.querySelectorAll<HTMLButtonElement>('.setup-add-row')];++ expect(second.dataset.state).toBe('detected');+ expect(second.disabled).toBe(false);+ expect(second.getAttribute('aria-pressed')).toBe('false');+ expect(within(second).queryByText('Added')).toBeNull();++ await user.click(second);+ expect(onToggleDetected).toHaveBeenCalledTimes(1);+ expect(onToggleDetected.mock.calls[0][0]).toMatchObject({ vendor: 'openai' });+ });++ it('keeps a credential nobody may take here, and says why instead of offering it', async () => {+ renderDialog({ detected: [blockedSlot('anthropic'), slot('openai')], selected: () => true });+ const user = userEvent.setup();+ const [blocked, open] = [...document.querySelectorAll<HTMLButtonElement>('.setup-add-row')];++ // Still on the list, with the migration feature's own sentence about it. The+ // alternative — dropping it — is how a person ends up adding a second copy of a+ // key that is already on the machine.+ expect(blocked.dataset.blocked).toBe('true');+ expect(within(blocked).getByText(/can be migrated, but not from here/)).toBeTruthy();+ expect(blocked.disabled).toBe(true);+ // Not a toggle that happens to be off: there is no consent to give here, and+ // `aria-pressed="false"` beside a selected sibling would say there is.+ expect(blocked.getAttribute('aria-pressed')).toBeNull();+ expect(open.getAttribute('aria-pressed')).toBe('true');++ await user.click(blocked);+ expect(onToggleDetected).not.toHaveBeenCalled();+ });++ it('opens on something that can be done when every detection is blocked', async () => {+ renderDialog({ detected: [blockedSlot('anthropic')] });+ const user = userEvent.setup();++ // The method still exists — it is where the explanation lives — but landing on+ // a pane whose every row is disabled answers nothing for someone who came here+ // to add a provider.+ expect(methodNames()).toEqual(['Detected', 'Subscription', 'API Key']);+ expect(activeMethod()).toBe('subscription');++ await chooseMethod(user, 'Detected');+ expect(document.querySelectorAll('.setup-add-row')).toHaveLength(1);+ // Nothing to hand to the take-over, so nothing is offered.+ expect(primary().disabled).toBe(true);+ await user.click(primary());+ expect(onReviewDetected).not.toHaveBeenCalled();+ });+});++describe('AddSourceDialog — the one write it owns', () => {+ const fill = async (user: ReturnType<typeof userEvent.setup>) => {+ await chooseMethod(user, 'API Key');+ await user.type(within(body()).getByLabelText('Base URL'), 'https://api.example/v1');+ await user.type(within(body()).getByLabelText('API key'), 'sk-live-1');+ };++ it('saves on the person\'s word, reads back, and closes once the caller has', async () => {+ const row = source({ id: 'src_new', vendor: 'custom', client_nonce: 'scn_x' });+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValue(created(row));+ let release!: () => void;+ onAdded.mockImplementation(() => new Promise<void>((resolve) => { release = () => resolve(); }));+ renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(primary());++ await waitFor(() => expect(onAdded).toHaveBeenCalledWith(created(row)));+ expect(create).toHaveBeenCalledTimes(1);+ expect(create.mock.calls[0][0]).toMatchObject({+ kind: 'api_key',+ base_url: 'https://api.example/v1',+ key: 'sk-live-1',+ // Deliberate policy, the same in both hosts of this form: a provider that is+ // briefly down does not cost someone the key they just pasted.+ save_unverified: true,+ });+ expect(create.mock.calls[0][0].client_nonce).toMatch(/^scn_/);++ // Still open while the caller reads back, and locked shut while it does.+ expect(screen.getByText('Checking the model connection…')).toBeTruthy();+ expect(onClose).not.toHaveBeenCalled();+ // Every way out, including the one in the corner: a write in flight is not a+ // state anyone should be able to abandon the frame on.+ expect(cancelButton().disabled).toBe(true);+ expect((screen.getByRole('button', { name: 'Close' }) as HTMLButtonElement).disabled).toBe(true);+ expect(methodButtons().every((button) => (button as HTMLButtonElement).disabled)).toBe(true);++ release();+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));+ });++ it('keeps the entries when the server refuses, and sends again on retry', async () => {+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockRejectedValueOnce(new ApiCallError('source_invalid', 'bad key', true, [], [], [], 400))+ .mockResolvedValueOnce(created(source({ id: 'src_new', vendor: 'custom' })));+ renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(primary());++ await waitFor(() => expect(screen.getByText(/Your entries are preserved/)).toBeTruthy());+ expect((within(body()).getByLabelText('API key') as HTMLInputElement).value).toBe('sk-live-1');+ expect(primary().textContent).toBe('Retry');+ expect(onClose).not.toHaveBeenCalled();++ await user.click(primary());++ // A server verdict is a verdict: the same request may simply be sent again.+ await waitFor(() => expect(create).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));+ });++ it('adopts a write whose outcome was unknown instead of sending a second one', async () => {+ const landed = source({ id: 'src_landed', vendor: 'custom' });+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockRejectedValue(new ApiCallError('gateway_timeout', 'timeout', true, [], [], [], 504));+ const list = vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(primary());+ await waitFor(() => expect(screen.getByText(/Your entries are preserved/)).toBeTruthy());++ // It had landed after all — the response was what was lost.+ const nonce = create.mock.calls[0][0].client_nonce;+ list.mockResolvedValue([{ ...landed, client_nonce: nonce }]);+ await user.click(primary());++ await waitFor(() => expect(onAdded).toHaveBeenCalledTimes(1));+ expect(onAdded.mock.calls[0][0]).toMatchObject({ source: { id: 'src_landed' } });+ // Repeating the write is exactly how a second identical source appears.+ expect(create).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));+ });++ it('sends the write the readback proved absent', async () => {+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockRejectedValueOnce(new ApiCallError('gateway_timeout', 'timeout', true, [], [], [], 504))+ .mockResolvedValueOnce(created(source({ id: 'src_new', vendor: 'custom' })));+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(primary());+ await waitFor(() => expect(screen.getByText(/Your entries are preserved/)).toBeTruthy());+ await user.click(primary());++ await waitFor(() => expect(create).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));+ });++ it('leaves an unreadable inventory as unknown as it was', async () => {+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockRejectedValue(new ApiCallError('gateway_timeout', 'timeout', true, [], [], [], 504));+ vi.spyOn(modelsApi, 'listSources').mockRejectedValue(new Error('offline'));+ renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(primary());+ await waitFor(() => expect(screen.getByText(/Your entries are preserved/)).toBeTruthy());+ await user.click(primary());++ // Neither adopted nor re-sent: an unknown outcome that could not be read is+ // still unknown, and the retry is still there to take.+ await waitFor(() => expect(primary().textContent).toBe('Retry'));+ expect(create).toHaveBeenCalledTimes(1);+ expect(onAdded).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ });++ it('hands an unknown outcome back on the way out rather than forgetting it', async () => {+ const landed = source({ id: 'src_landed', vendor: 'custom' });+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockRejectedValue(new ApiCallError('gateway_timeout', 'timeout', true, [], [], [], 504));+ const list = vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(primary());+ await waitFor(() => expect(screen.getByText(/Your entries are preserved/)).toBeTruthy());++ // It had landed. The nonce that would identify it lives in this frame, so+ // leaving without reading would make it unattributable: the parent would show+ // nothing, and the next attempt would carry a new nonce and write a duplicate.+ const nonce = create.mock.calls[0][0].client_nonce;+ list.mockResolvedValue([{ ...landed, client_nonce: nonce }]);++ await user.click(cancelButton());++ // Closed on the press, not held until the read answers — nobody is kept in a+ // dialog because a request timed out.+ expect(onClose).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(onAdded).toHaveBeenCalledTimes(1));+ expect(onAdded.mock.calls[0][0]).toMatchObject({ source: { id: 'src_landed' } });+ // And still exactly one write: closing is not a retry.+ expect(create).toHaveBeenCalledTimes(1);+ });++ it('closes on an unknown outcome it could not read, and says only that', async () => {+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockRejectedValue(new ApiCallError('gateway_timeout', 'timeout', true, [], [], [], 504));+ vi.spyOn(modelsApi, 'listSources').mockRejectedValue(new Error('offline'));+ renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(primary());+ await waitFor(() => expect(screen.getByText(/Your entries are preserved/)).toBeTruthy());++ await user.click(cancelButton());++ expect(onClose).toHaveBeenCalledTimes(1);+ // A read that failed leaves the outcome exactly as unknown as it already was.+ // Reporting nothing named is what makes the parent refresh and say so.+ await waitFor(() => expect(onAdded).toHaveBeenCalledWith(null));+ expect(create).toHaveBeenCalledTimes(1);+ });++ it('cancels without writing anything', async () => {+ const create = vi.spyOn(modelsApi, 'createApiKeySource');+ renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(cancelButton());++ expect(onClose).toHaveBeenCalledTimes(1);+ expect(create).not.toHaveBeenCalled();+ });++ it('names its two ways out differently', async () => {+ renderDialog();++ // Both close the frame, and a screen reader that hears 「取消」 twice cannot+ // tell which one it is on.+ expect(cancelButton().textContent).toBe('Cancel');+ expect(screen.getByRole('button', { name: 'Close' })).toBeTruthy();+ });++ it('refuses from the keyboard exactly what the footer refuses', async () => {+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockResolvedValue(created(source({ id: 'src_new', vendor: 'custom' })));+ renderDialog();+ const user = userEvent.setup();+ await chooseMethod(user, 'API Key');+ await user.type(within(body()).getByLabelText('Base URL'), 'https://api.example/v1');++ await user.type(within(body()).getByLabelText('API key'), '{Enter}');++ // Enter IS the footer button. An incomplete draft sent from the keyboard would+ // be the same write the disabled control is there to refuse.+ expect(primary().disabled).toBe(true);+ expect(create).not.toHaveBeenCalled();++ await user.type(within(body()).getByLabelText('API key'), 'sk-live-1{Enter}');++ await waitFor(() => expect(create).toHaveBeenCalledTimes(1));+ });++ it('refuses every method\'s offer once the screen stops admitting a write', async () => {+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockResolvedValue(created(source({ id: 'src_new', vendor: 'custom' })));+ const { rerender } = renderDialog({ detected: [slot('openai')], pendingCount: 1 });+ const user = userEvent.setup();+ await chooseMethod(user, 'API Key');+ await user.type(within(body()).getByLabelText('Base URL'), 'https://api.example/v1');+ await user.type(within(body()).getByLabelText('API key'), 'sk-live-1');+ expect(primary().disabled).toBe(false);++ // The engine this write would go to stopped being one the screen can vouch for,+ // while the form was being filled. The frame stays — what is in it is the+ // person's, and the read may come back — and the offer is what is withdrawn.+ rerender({ writable: false });+ expect(frame()).toBeTruthy();+ expect(primary().disabled).toBe(true);+ await user.type(within(body()).getByLabelText('API key'), '{Enter}');+ expect(create).not.toHaveBeenCalled();++ // Every method's offer is a write: a key saved, a sign-in started, a batch handed+ // to the take-over.+ await chooseMethod(user, 'Subscription');+ expect(primary().disabled).toBe(true);+ await chooseMethod(user, 'Detected');+ expect(primary().disabled).toBe(true);+ expect(onReviewDetected).not.toHaveBeenCalled();+ });++ it('does not resend a write whose permission was withdrawn while it read back', async () => {+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockRejectedValue(new ApiCallError('gateway_timeout', 'timeout', true, [], [], [], 504));+ let answer!: (rows: Source[]) => void;+ const list = vi.spyOn(modelsApi, 'listSources')+ .mockImplementation(() => new Promise<Source[]>((resolve) => { answer = resolve; }));+ const { rerender } = renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(primary());+ await waitFor(() => expect(screen.getByText(/Your entries are preserved/)).toBeTruthy());++ // The retry reads the inventory back before deciding whether to send: an unsettled+ // failure may have landed, and a blind second write is how a duplicate appears.+ await user.click(primary());+ await waitFor(() => expect(list).toHaveBeenCalledTimes(1));++ // Permission goes away INSIDE that read. The press that started it saw a screen+ // that admitted a write; by the time the readback answers, that is a memory of a+ // permission rather than one, and the POST is where the current answer counts.+ rerender({ writable: false });+ await act(async () => { answer([]); });++ expect(create).toHaveBeenCalledTimes(1);+ // And nothing was thrown away in the refusing: the entries, the retry and the+ // identity that write was sent under are all still here, so the outcome nobody+ // knows yet is still reconcilable rather than abandoned.+ expect((within(body()).getByLabelText('API key') as HTMLInputElement).value).toBe('sk-live-1');+ expect(primary().textContent).toBe('Retry');+ expect(onAdded).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();++ const nonce = create.mock.calls[0][0].client_nonce;+ list.mockResolvedValue([{ ...source({ id: 'src_landed', vendor: 'custom' }), client_nonce: nonce }]);+ rerender({ writable: true });+ await user.click(primary());+ await waitFor(() => expect(onAdded).toHaveBeenCalledTimes(1));+ expect(onAdded.mock.calls[0][0]).toMatchObject({ source: { id: 'src_landed' } });+ expect(create).toHaveBeenCalledTimes(1);+ });++ it('delivers the source a readback found even once no further write is admitted', async () => {+ const landed = source({ id: 'src_landed', vendor: 'custom' });+ const create = vi.spyOn(modelsApi, 'createApiKeySource')+ .mockRejectedValue(new ApiCallError('gateway_timeout', 'timeout', true, [], [], [], 504));+ let answer!: (rows: Source[]) => void;+ vi.spyOn(modelsApi, 'listSources')+ .mockImplementation(() => new Promise<Source[]>((resolve) => { answer = resolve; }));+ const { rerender } = renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(primary());+ await waitFor(() => expect(screen.getByText(/Your entries are preserved/)).toBeTruthy());+ await user.click(primary());+ await waitFor(() => expect(modelsApi.listSources).toHaveBeenCalledTimes(1));++ // Same withdrawal, and this time the read says the write had landed. A source that+ // exists is a receipt: permission governs the next write, never the delivery of one+ // that already happened. Withholding it would hide a credential the person owns.+ rerender({ writable: false });+ const nonce = create.mock.calls[0][0].client_nonce;+ await act(async () => { answer([{ ...landed, client_nonce: nonce }]); });++ await waitFor(() => expect(onAdded).toHaveBeenCalledTimes(1));+ expect(onAdded.mock.calls[0][0]).toMatchObject({ source: { id: 'src_landed' } });+ expect(create).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));+ });++ it('locks the draft an unknown outcome is still attached to', async () => {+ vi.spyOn(modelsApi, 'createApiKeySource')+ .mockRejectedValueOnce(new ApiCallError('gateway_timeout', 'timeout', true, [], [], [], 504))+ .mockRejectedValueOnce(new ApiCallError('source_invalid', 'bad key', true, [], [], [], 400));+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ renderDialog();+ const user = userEvent.setup();+ await fill(user);++ await user.click(primary());+ await waitFor(() => expect(screen.getByText(/Your entries are preserved/)).toBeTruthy());++ // Reconciliation adopts the row the ORIGINAL draft wrote, so an edit made under+ // an unknown outcome is one the retry can discard without saying so.+ expect((within(body()).getByLabelText('API key') as HTMLInputElement).disabled).toBe(true);+ expect((within(body()).getByLabelText('Base URL') as HTMLInputElement).disabled).toBe(true);++ await user.click(primary());++ // A verdict ends that: the server answered about this draft, so editing it is+ // the whole point of keeping the entries.+ await waitFor(() => expect((within(body()).getByLabelText('API key') as HTMLInputElement).disabled).toBe(false));+ expect((within(body()).getByLabelText('Base URL') as HTMLInputElement).disabled).toBe(false);+ });+});++describe('AddSourceDialog — what comes back from an authorization', () => {+ const signIn = async () => {+ renderDialog();+ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: /Sign in with Claude/ }));+ await user.click(primary());+ await screen.findByTestId('oauth-stub');+ return user;+ };++ it('reads an argument-less arrival as stale rows, not as a provider added', async () => {+ await signIn();++ // The shipped dialog fires this on every terminal arrival — failures,+ // cancellations, cleanup, a flow resolved after its frame closed.+ act(() => oauth.current?.onConnected());++ await waitFor(() => expect(onAdded).toHaveBeenCalledWith(null));+ // Closing here would report someone's cancelled sign-in as a provider they+ // added, and take the frame they were working in with it.+ expect(onClose).not.toHaveBeenCalled();+ expect(frame()).toBeTruthy();+ expect(screen.getByTestId('oauth-stub')).toBeTruthy();+ });++ it('lands a source that really arrived, with the placement it arrived in', async () => {+ const row = source({ id: 'src_claude', vendor: 'anthropic' });+ await signIn();++ act(() => oauth.current?.onConnected(row, { added_to: ['claude'], adopted_by: ['claude'] }));++ await waitFor(() => expect(onAdded).toHaveBeenCalledWith({+ source: row,+ added_to: ['claude'],+ adopted_by: ['claude'],+ }));+ // The read happens BEHIND the flow's own success panel, which owns the report+ // of where the source landed and the handoff that dismisses it. Replacing that+ // with this dialog's spinner would discard the one thing worth reading.+ expect(screen.getByTestId('oauth-stub')).toBeTruthy();+ expect(onClose).not.toHaveBeenCalled();++ act(() => oauth.current?.onClose());++ // And when the flow does hand back, there is nothing left to add here.+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));+ });++ it('asks for one read when a landing reports itself twice', async () => {+ const row = source({ id: 'src_claude', vendor: 'anthropic' });+ await signIn();++ // How the shipped flow really reports a success: the source, then the+ // argument-less call, both in the same breath. The second one means 「the rows+ // you are holding are stale」 — and the only row it can be about is the one the+ // first call just handed over, whose read is already on its way. A second+ // request for the same inventory is two list reads racing, and the stage draws+ // whichever answers last.+ act(() => {+ oauth.current?.onConnected(row, { added_to: ['claude'], adopted_by: ['claude'] });+ oauth.current?.onConnected();+ });++ await waitFor(() => expect(onAdded).toHaveBeenCalledTimes(1));+ expect(onAdded).toHaveBeenCalledWith({+ source: row,+ added_to: ['claude'],+ adopted_by: ['claude'],+ });+ expect(onAdded).not.toHaveBeenCalledWith(null);++ // And the extra call changed nothing about the handback: the flow's own panel+ // still owns the close, and this frame still goes with it.+ act(() => oauth.current?.onClose());+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));+ });++ it('returns to the frame it was launched from when nothing arrived', async () => {+ const user = await signIn();++ act(() => oauth.current?.onClose());++ // A cancelled sign-in is not an ending: the method row, the draft and the+ // chosen brand are all still what they were.+ await waitFor(() => expect(screen.queryByTestId('oauth-stub')).toBeNull());+ expect(onClose).not.toHaveBeenCalled();+ expect(activeMethod()).toBe('subscription');+ expect(primary().textContent).toContain('Claude');++ await chooseMethod(user, 'API Key');+ expect(within(body()).getByLabelText('API key')).toBeTruthy();+ });+});diff --git a/ui/src/components/onboarding/providers/AddSourceDialog.tsx b/ui/src/components/onboarding/providers/AddSourceDialog.tsxnew file mode 100644index 000000000..7e9bb13f3--- /dev/null+++ b/ui/src/components/onboarding/providers/AddSourceDialog.tsx@@ -0,0 +1,580 @@+// The one place setup adds a provider, whichever way it is added.+//+// Three methods, one frame. That is the whole design constraint (C5): the box does+// not resize, move or re-anchor when the method changes, because a person comparing+// 「订阅」 against 「API Key」 switches back and forth, and a frame that jumps under+// them makes the comparison cost something. So the header, the method row and the+// footer are anchored, only the middle scrolls, and the frame's height is fixed at+// the tallest ordinary pane rather than fitted to whichever one is showing.+//+// Only the active pane is rendered. `hidden` would have been enough to keep a+// control out of the tab order, but not enough to stop a hidden pane's effects —+// and the effect here is an authorization flow, where a duplicate is a second+// device code for the same account. Rendering one pane makes that unrepresentable+// rather than merely avoided. What it costs is pane state, so pane state lives+// here: the half-typed key survives a switch away and back because nothing+// unmounted it in the first place.+//+// The dialog's lifetime IS its openness — the caller mounts it to open it. That is+// what makes every initial value below a plain `useState` initializer instead of an+// effect that has to decide whether this render is a new opening; an effect that+// re-ran on a prop change would wipe the draft it exists to preserve.+//+// None of the three methods is implemented here. Detected hands rows back to the+// screen, which owns the selection and opens the existing migration takeover;+// subscription launches `OAuthConnectDialog`, which owns the channel choice, the+// poll, the deadline and cancellation; API Key renders the shared+// `ApiKeySourceForm`. This file is the frame, the method choice, and the one write+// that has no other owner.+import * as React from 'react';+import * as DialogPrimitive from '@radix-ui/react-dialog';+import { Check, CircleX, KeyRound, LoaderCircle, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { DialogOverlay } from '@/components/ui/dialog';+import { ApiKeySourceForm } from '@/components/settings/models/ApiKeySourceForm';+import {+ apiKeySourceCreate,+ apiKeyWriteSettled,+ draftComplete,+ EMPTY_API_KEY_DRAFT,+ selectVendor,+ sourceClientNonce,+ type ApiKeySourceDraft,+} from '@/components/settings/models/apiKeySourceDraft';+import { apiKeyVendorPreset } from '@/components/settings/models/apiKeyVendors';+import type { CollectionReadAuthority } from '@/components/settings/models/collectionReadAuthority';+import { BLOCKED_REASON_FALLBACK_KEY } from '@/components/settings/models/migrationGrouping';+import {+ createContinuationSettlement,+ type ContinuationTicket,+} from '@/components/settings/models/mutationSettlement';+import { modelsApi, type Adoption, type SourceCreated } from '@/components/settings/models/modelsApi';+import { OAuthConnectDialog } from '@/components/settings/models/OAuthConnectDialog';+import { reconcileUnknownWrite } from '@/components/settings/models/reconcileUnknownWrite';+import { serverText } from '@/components/settings/models/serverCopy';+import { subscriptionChooser } from '@/components/settings/models/subscriptionOptions';+import type { Source } from '@/components/settings/models/types';+import { VendorGlyph } from '@/components/settings/models/vendorGlyph';+import { providerBrandLabel } from '@/components/settings/providers/providerIdentity';+import type { TranslationKey } from '@/i18n/types';++import { usableSource, type ProviderSlot } from './providerStage';++/**+ * The subscriptions setup offers.+ *+ * Two, named here rather than derived: `ModelsApi` publishes no vendor-capability+ * list, and C6 ruled out inventing a producer for one. The full set lives in+ * `subscriptionOptions.ts` and Settings is where the rest are connected — this is+ * the shortlist the handoff ships, in the shortlist's own order.+ */+const SUBSCRIPTION_CHOICES: readonly string[] = ['openai', 'anthropic'];++export type AddSourceMethod = 'detected' | 'subscription' | 'apiKey';++const METHOD_LABEL = {+ detected: 'onboarding.providers.addMethodDetected',+ subscription: 'onboarding.providers.addMethodSubscription',+ apiKey: 'onboarding.providers.addMethodApiKey',+} as const satisfies Record<AddSourceMethod, TranslationKey>;++/** Where the API-key write is. The other two methods report through the dialog and+ * the screen that own them, so neither has a state here. */+type WritePhase =+ | { kind: 'idle' }+ | { kind: 'saving' }+ /** Written; the caller is reading back what it landed (C6). */+ | { kind: 'checking' }+ /** The authorization dialog is up; this frame waits under it. */+ | { kind: 'waitingAuth' }+ /** `settled` separates a server verdict from a write whose outcome is unknown —+ * and an unknown one may never simply be sent again. */+ | { kind: 'failed'; settled: boolean };++const subscriptionBrand = (vendor: string): string =>+ subscriptionChooser(vendor)?.brand ?? providerBrandLabel(vendor);++const DetectedRow: React.FC<{+ slot: ProviderSlot;+ selected: boolean;+ added: boolean;+ onToggle: () => void;+}> = ({ slot, selected, added, onToggle }) => {+ const { t } = useTranslation();+ // Detected, and not takeable from here. The row stays — this list is what the+ // screen found, and a credential that vanished because nobody may act on it is a+ // credential the person will add a second copy of.+ const blocked = slot.reasons.length > 0;+ const detail = [+ slot.mask ? t('onboarding.providers.cardKeyDetected', { mask: slot.mask }) : '',+ ...slot.reasons.map((key) => serverText(t, key, BLOCKED_REASON_FALLBACK_KEY) ?? ''),+ ].filter(Boolean).join(' · ');+ return (+ <button+ type="button"+ className="setup-add-row"+ data-provider={slot.vendor}+ data-state={added ? 'added' : 'detected'}+ {...(blocked ? { 'data-blocked': 'true' } : {})}+ disabled={added || blocked}+ {...(added || blocked ? {} : { 'aria-pressed': selected })}+ aria-label={blocked+ ? [slot.label, detail].filter(Boolean).join(' · ')+ : t('onboarding.providers.addDetectedSelectNamed', { name: slot.label })}+ onClick={onToggle}+ >+ <span className="setup-add-row-logo">+ {slot.brand ? <VendorGlyph vendor={slot.brand} /> : <KeyRound size={18} aria-hidden="true" />}+ </span>+ <span className="setup-add-row-copy">+ <span className="setup-add-row-name">{slot.label}</span>+ {detail && <span className="setup-add-row-detail">{detail}</span>}+ </span>+ {added+ ? <span className="setup-add-row-tag">{t('onboarding.providers.addDetectedAdded')}</span>+ : selected && <Check className="setup-add-row-check" strokeWidth={2.2} aria-hidden="true" />}+ </button>+ );+};++export const AddSourceDialog: React.FC<{+ /** Opened from 「Add more」 rather than from a named brand slot. It changes what+ * the dialog says it is for, and nothing about what it can do. */+ more: boolean;+ /** The brand the opener named, when it named one: a subscription brand opens on+ * its sign-in, any other opens the key form already set to it. */+ vendor?: string | null;+ /** Detected candidates the stage is not already drawing. Empty means the method+ * does not exist rather than that it is empty. */+ detected: readonly ProviderSlot[];+ /** Rows the current selection would submit — the number the review names. */+ pendingCount: number;+ /** Whether the screen still admits a write. It can turn false while this is open —+ * the engine stopped, or the read that said it was serving failed — and then the+ * submit is what has to refuse. An authorization already in flight is left alone:+ * it owns its own outcome, and this frame stays up to report it. */+ writable: boolean;+ sources: Source[];+ /** The generation-controlled source read, used to settle an unknown write. */+ sourceReads: CollectionReadAuthority<Source[]>;+ isSelected: (slot: ProviderSlot) => boolean;+ onToggleDetected: (slot: ProviderSlot) => void;+ /** Hand the current selection to the existing migration takeover. */+ onReviewDetected: () => void;+ /** Resolves once the caller has read back what the write landed. `null` is a+ * landing with no snapshot to report — re-read everything. */+ onAdded: (created: SourceCreated | null) => Promise<void>;+ onClose: () => void;+}> = ({+ more,+ vendor,+ detected,+ pendingCount,+ writable,+ sources,+ sourceReads,+ isSelected,+ onToggleDetected,+ onReviewDetected,+ onAdded,+ onClose,+}) => {+ const { t } = useTranslation();+ const methods: AddSourceMethod[] = detected.length > 0+ ? ['detected', 'subscription', 'apiKey']+ : ['subscription', 'apiKey'];+ const namedSubscription = vendor && SUBSCRIPTION_CHOICES.includes(vendor) ? vendor : null;++ // The detected list exists as discovery whatever it holds, but it only OPENS the+ // dialog when something in it can be taken over. A person who pressed 「添加」 and+ // landed on rows that all explain why they cannot be imported has been handed an+ // answer to a question they did not ask, with nothing to press; the tab is still+ // right there, saying what is on this machine.+ const [method, setMethod] = React.useState<AddSourceMethod>(+ namedSubscription+ ? 'subscription'+ : vendor+ ? 'apiKey'+ : detected.some((slot) => slot.backends.length > 0)+ ? 'detected'+ : 'subscription',+ );+ const [subscriptionVendor, setSubscriptionVendor] = React.useState(+ namedSubscription ?? SUBSCRIPTION_CHOICES[0],+ );+ // Through `selectVendor`, so a named brand arrives with its published endpoint+ // already filled. Setting the field alone would be worse than not naming one:+ // re-selecting the vendor that is already selected is identity, so the+ // prefill this brand publishes would be unreachable from inside the form.+ const [draft, setDraft] = React.useState<ApiKeySourceDraft>(+ () => (vendor && !namedSubscription ? selectVendor(EMPTY_API_KEY_DRAFT, vendor) : EMPTY_API_KEY_DRAFT),+ );+ const [revealed, setRevealed] = React.useState(false);+ const [phase, setPhase] = React.useState<WritePhase>({ kind: 'idle' });+ const [continuation] = React.useState(createContinuationSettlement);+ const clientNonce = React.useRef(sourceClientNonce());+ // Set when an authorization really produced a source. It is what tells that+ // flow's own close apart from a cancellation: both arrive the same way.+ const authorizedLanded = React.useRef(false);+ // Permission as of now, not as of the press. A submit that first reads the inventory+ // back can be inside that await when the engine stops, and the value the press saw is+ // by then a memory of a permission rather than one. Everything that SENDS reads this.+ const writableRef = React.useRef(writable);+ writableRef.current = writable;+ React.useEffect(() => () => continuation.invalidate(), [continuation]);++ // A method that stopped existing — the last detected candidate was taken over+ // while the dialog was open — falls back rather than rendering nothing.+ const active = methods.includes(method) ? method : methods[0];++ // 「已添加」 is a claim about a credential, not about a brand. The scan reads native+ // stores and never sees the Hub's inventory, so the only evidence that a detected+ // row and a connected source are one key is the mask — and it is real evidence:+ // both sides come from the server's single masking function. Marking by vendor+ // instead would disable the second key someone keeps under a provider they have+ // already connected, while the capsule behind this pane goes on counting it.+ const addedCredentials = React.useMemo(+ () => new Set(+ sources.filter(usableSource)+ .map((source) => source.masked_credential?.trim())+ .filter((mask): mask is string => Boolean(mask)),+ ),+ [sources],+ );++ const land = React.useCallback(async (seq: ContinuationTicket, created: SourceCreated | null) => {+ if (continuation.settle(seq, () => setPhase({ kind: 'checking' })) === 'stale') return;+ // The write is committed either way; what the caller reads back is the routing+ // it produced, and a failed read is the screen's to report, not this dialog's.+ await onAdded(created).catch(() => undefined);+ continuation.settle(seq, () => {+ setPhase({ kind: 'idle' });+ onClose();+ });+ }, [continuation, onAdded, onClose]);++ const persist = React.useCallback(async (seq: ContinuationTicket) => {+ // The actual boundary of the POST, and the last place the answer is still current.+ // Refusing here changes nothing else on purpose: the draft, the nonce and an+ // unsettled failure all stay exactly as they were, so the outcome nobody knows yet+ // is still reconcilable from the same identity once the engine is back. What it will+ // not do is send. There is no queued attempt behind this — recovery is another press.+ if (!writableRef.current) return;+ if (continuation.settle(seq, () => setPhase({ kind: 'saving' })) === 'stale') return;+ try {+ await land(seq, await modelsApi.createApiKeySource(apiKeySourceCreate(draft, clientNonce.current)));+ } catch (error) {+ continuation.settle(seq, () => setPhase({ kind: 'failed', settled: apiKeyWriteSettled(error) }));+ }+ }, [continuation, draft, land]);++ const submitKey = React.useCallback(async () => {+ // The footer below already refuses this; refusing it here too is what makes a+ // write against an engine the screen no longer vouches for unrepresentable+ // rather than merely hard to reach.+ if (!writable) return;+ const seq = continuation.begin();+ // An unsettled failure is not a verdict. Read the inventory back and adopt the+ // write if it did land, rather than sending a second one that would duplicate it.+ if (phase.kind === 'failed' && !phase.settled) {+ const reconciliation = await reconcileUnknownWrite(+ () => sourceReads.readValue(),+ (rows) => rows.find((row) => row.client_nonce === clientNonce.current),+ );+ // A source that is there is a receipt, and a receipt is reported whatever the+ // screen now admits: permission governs the NEXT write, never the delivery of one+ // that already happened. Withdrawing it here would hide a credential that exists.+ if (reconciliation.kind === 'committed') {+ await land(seq, {+ source: reconciliation.value,+ added_to: [],+ adopted_by: reconciliation.value.adopted_by ?? [],+ });+ return;+ }+ // `unread` leaves the outcome exactly as unknown as it already was.+ if (reconciliation.kind === 'absent') await persist(seq);+ return;+ }+ await persist(seq);+ }, [continuation, land, persist, phase, sourceReads, writable]);++ // Editing clears a verdict the server gave about a form that no longer exists.+ // It does NOT clear an unsettled one: that outcome is still unknown, and the+ // nonce it would be reconciled by has to outlive the edit.+ const editDraft = (next: ApiKeySourceDraft) => {+ setDraft(next);+ setPhase((current) => (current.kind === 'failed' && current.settled ? { kind: 'idle' } : current));+ };++ const authorized = (source?: Source, placement?: Adoption) => {+ // No source is 「你手上的行已经过期」, not 「新增了一个来源」. The shipped dialog fires+ // that argument-less call on every terminal arrival — failures, cancellations,+ // cleanup, a flow resolved after its frame closed — so refresh behind it and stay+ // where we are. Landing on it would close this dialog on someone's cancelled+ // sign-in and report it as a provider they added.+ if (!source) {+ // Except immediately behind this flow's own landing. A success is reported by+ // two calls in one breath — the source, then the argument-less one — and the+ // second is not news about anything: the row it would say had gone stale is+ // the one just created, and the read that describes it is already in flight.+ // Asking again sends a second inventory read racing the first, so which of+ // the two the stage ends up drawing is decided by whichever answers last.+ if (authorizedLanded.current) return;+ void onAdded(null).catch(() => undefined);+ return;+ }+ // A source did arrive — and the flow's own success panel is still on screen,+ // holding the report of where it landed for the 1400ms it owns. Tearing that+ // down here to show this dialog's spinner would take the one thing the person+ // was waiting to read. So read back behind it, and let its close be what+ // closes this frame. The shipped host does exactly this.+ authorizedLanded.current = true;+ void onAdded({ source, ...(placement ?? { added_to: [], adopted_by: source.adopted_by ?? [] }) })+ .catch(() => undefined);+ };++ const writing = phase.kind === 'saving' || phase.kind === 'checking';+ const busy = writing || phase.kind === 'waitingAuth';+ // An unsettled failure has an unknown outcome and a nonce that must outlive the+ // retry. Editing under it would produce a form whose edits the retry can discard+ // without saying so — reconciliation adopts the row the ORIGINAL draft wrote — so+ // the fields stay locked until that retry has an answer.+ const unsettled = phase.kind === 'failed' && !phase.settled;+ const keyBlocked = busy || !writable || !draftComplete(draft);+ const keyPreset = apiKeyVendorPreset(draft.vendor);++ // Every method's primary is a write — a key saved, a sign-in started, a batch handed+ // to the takeover — so every one of them needs the screen to still admit one. The+ // frame stays exactly as it is: what is on it was worth opening and is still worth+ // reading, and the reason it cannot be submitted is on the gateway card behind it,+ // next to the only control that can do anything about it.+ const primary = active === 'detected'+ ? {+ label: t('onboarding.providers.addFooterAdd', { count: pendingCount }),+ disabled: pendingCount === 0 || !writable,+ run: onReviewDetected,+ }+ : active === 'subscription'+ ? {+ label: t('onboarding.providers.addFooterSignInNamed', { name: subscriptionBrand(subscriptionVendor) }),+ disabled: busy || !writable,+ run: () => setPhase({ kind: 'waitingAuth' }),+ }+ : {+ label: writing+ ? t('onboarding.providers.addFooterAdding')+ : t(phase.kind === 'failed' ? 'common.retry' : 'onboarding.providers.addFooterAddKey'),+ disabled: keyBlocked,+ run: () => void submitKey(),+ };++ const progressKey: TranslationKey | null = phase.kind === 'saving'+ ? 'onboarding.providers.addProgressSaving'+ : phase.kind === 'checking'+ ? 'onboarding.providers.addProgressChecking'+ : phase.kind === 'waitingAuth'+ ? 'onboarding.providers.addProgressWaitingAuth'+ : null;++ const close = () => {+ if (busy) return;+ // An unknown outcome is closable — holding someone in a dialog because a request+ // timed out is its own failure — but it may not be closed by forgetting it. The+ // nonce that identifies this write lives in this frame, so a source it did create+ // would become unattributable the moment the frame went away: the parent would+ // still show nothing, the next attempt would carry a new nonce, and that attempt+ // is the duplicate reconciliation exists to prevent.+ //+ // So the read is started here and not awaited: it runs outside the continuation,+ // which this very close invalidates, and reports through the same `onAdded` a+ // settled landing uses. A read that fails leaves the outcome exactly as unknown+ // as it already was, which the parent's own refresh is what reports.+ if (unsettled) {+ const nonce = clientNonce.current;+ void reconcileUnknownWrite(+ () => sourceReads.readValue(),+ (rows) => rows.find((row) => row.client_nonce === nonce),+ ).then((reconciliation) => onAdded(+ reconciliation.kind === 'committed'+ ? {+ source: reconciliation.value,+ added_to: [],+ adopted_by: reconciliation.value.adopted_by ?? [],+ }+ : null,+ )).catch(() => undefined);+ }+ continuation.invalidate();+ onClose();+ };++ return (+ <DialogPrimitive.Root open onOpenChange={(next) => !next && close()}>+ <DialogPrimitive.Portal>+ {/* The app's scrim, not one of this screen's own: a dialog over setup should+ dim the way a dialog over anything else does. */}+ <DialogOverlay />+ <DialogPrimitive.Content+ className="setup-add-dialog fixed left-1/2 top-1/2 z-50 flex -translate-x-1/2 -translate-y-1/2 flex-col outline-none"+ onEscapeKeyDown={(event) => { if (busy) event.preventDefault(); }}+ onPointerDownOutside={(event) => { if (busy) event.preventDefault(); }}+ >+ <header className="setup-add-head">+ <div className="flex items-start justify-between gap-3">+ <DialogPrimitive.Title className="setup-add-title">+ {t(more ? 'onboarding.providers.addTitleMore' : 'onboarding.providers.addTitle')}+ </DialogPrimitive.Title>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="setup-add-close size-7 shrink-0"+ // Not 「取消」: the footer already has a button by that name, and two+ // controls announcing the same word is exactly the ambiguity a+ // label exists to remove.+ aria-label={t('common.close')}+ disabled={busy}+ onClick={close}+ >+ <X className="size-[15px]" />+ </Button>+ </div>+ <DialogPrimitive.Description className="setup-add-subtitle">+ {t(more ? 'onboarding.providers.addDescriptionMore' : 'onboarding.providers.addDescription')}+ </DialogPrimitive.Description>+ {/* A segmented group rather than a tablist: these buttons state which+ method is chosen, and what follows is a form rather than a tab+ panel. It is the control `ApiKeySourceForm` already uses for+ protocol, wearing this screen's tokens. */}+ <div role="group" aria-label={t('onboarding.providers.addMethodsLabel')} className="setup-add-methods">+ {methods.map((item) => (+ <button+ key={item}+ type="button"+ className="setup-add-method"+ aria-pressed={active === item}+ disabled={busy}+ onClick={() => setMethod(item)}+ >+ {t(METHOD_LABEL[item])}+ </button>+ ))}+ </div>+ </header>++ <div className="setup-add-body" data-method={active}>+ {active === 'detected' && (+ <>+ <p className="setup-add-note">{t('onboarding.providers.addDetectedNote')}</p>+ <span className="setup-add-group">{t('onboarding.providers.addDetectedGroup')}</span>+ {detected.map((slot) => (+ <DetectedRow+ key={slot.vendor}+ slot={slot}+ selected={isSelected(slot)}+ added={slot.mask !== null && addedCredentials.has(slot.mask)}+ onToggle={() => onToggleDetected(slot)}+ />+ ))}+ </>+ )}++ {active === 'subscription' && (+ <>+ <p className="setup-add-note">{t('onboarding.providers.addSubscriptionNote')}</p>+ {SUBSCRIPTION_CHOICES.map((item) => (+ <button+ key={item}+ type="button"+ className="setup-add-row"+ data-provider={item}+ data-state="offer"+ aria-pressed={subscriptionVendor === item}+ disabled={busy}+ onClick={() => setSubscriptionVendor(item)}+ >+ <span className="setup-add-row-logo"><VendorGlyph vendor={item} /></span>+ <span className="setup-add-row-copy">+ <span className="setup-add-row-name">+ {t('onboarding.providers.addSignInNamed', { name: subscriptionBrand(item) })}+ </span>+ </span>+ {subscriptionVendor === item && (+ <Check className="setup-add-row-check" strokeWidth={2.2} aria-hidden="true" />+ )}+ </button>+ ))}+ </>+ )}++ {active === 'apiKey' && (+ <ApiKeySourceForm+ draft={draft}+ disabled={writing || unsettled}+ revealed={revealed}+ keyLabel={keyPreset+ ? t('onboarding.providers.addKeyLabelNamed', { name: keyPreset.label })+ : undefined}+ onChange={editDraft}+ onToggleReveal={() => setRevealed((value) => !value)}+ // Enter is the footer button, so it obeys the footer button's rule:+ // an incomplete draft submitted from the keyboard is the same write+ // the disabled control exists to refuse.+ onSubmit={() => { if (!keyBlocked) void submitKey(); }}+ />+ )}+ </div>++ <footer className="setup-add-foot">+ <span className="setup-add-status" role="status" aria-live="polite">+ {progressKey && (+ <>+ <LoaderCircle className="setup-add-status-icon motion-safe:animate-spin" aria-hidden="true" />+ {t(progressKey)}+ </>+ )}+ {phase.kind === 'failed' && (+ <>+ <CircleX className="setup-add-status-icon setup-add-status-icon--error" aria-hidden="true" />+ <span className="setup-add-status-error">{t('onboarding.providers.addErrorPreserved')}</span>+ </>+ )}+ </span>+ <Button type="button" variant="outline" size="sm" disabled={busy} onClick={close}>+ {t('common.cancel')}+ </Button>+ <Button type="button" variant="brand" size="sm" disabled={primary.disabled} onClick={primary.run}>+ {primary.label}+ </Button>+ </footer>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>++ {/* Launched, not switched to: the authorization flow owns its own frame, its+ channel choice, its poll, its deadline and its cancellation. This dialog+ only waits under it, which is why C5's still-frame rule is untouched. */}+ {phase.kind === 'waitingAuth' && (+ <OAuthConnectDialog+ open+ vendor={subscriptionVendor}+ sources={sources}+ onClose={() => {+ if (!authorizedLanded.current) {+ // Cancelled, failed, or abandoned: back to the frame it was launched+ // from, with the method and the draft it was launched with.+ setPhase({ kind: 'idle' });+ return;+ }+ authorizedLanded.current = false;+ continuation.invalidate();+ onClose();+ }}+ onConnected={authorized}+ />+ )}+ </DialogPrimitive.Root>+ );+};diff --git a/ui/src/components/onboarding/providers/DestinationRow.tsx b/ui/src/components/onboarding/providers/DestinationRow.tsxnew file mode 100644index 000000000..0dae53076--- /dev/null+++ b/ui/src/components/onboarding/providers/DestinationRow.tsx@@ -0,0 +1,27 @@+// The three assistants, as the shape the introduction's cards shrink into.+//+// This row is the handoff's landing target (C3), which is why it carries no state of+// its own: an enabled/disabled mark here would be a second, staler answer to a+// question screen 3 owns, and the handoff would have to animate it appearing. The+// row says who the routing is for and nothing else.+import type { FC } from 'react';+import { useTranslation } from 'react-i18next';++import { ASSISTANT_ORDER } from '../collaborationTimeline';+import { BackendIcon } from '../../visual';++export const DestinationRow: FC = () => {+ const { t } = useTranslation();+ return (+ <div className="setup-destinations">+ {ASSISTANT_ORDER.map((backend) => (+ <div key={backend} className="setup-destination" data-backend={backend}>+ <span className="setup-destination-logo">+ <BackendIcon backend={backend} size={28} variant="brand" aria-hidden="true" />+ </span>+ <span className="setup-destination-name">{t(`onboarding.story.${backend}.name`)}</span>+ </div>+ ))}+ </div>+ );+};diff --git a/ui/src/components/onboarding/providers/GatewayCard.tsx b/ui/src/components/onboarding/providers/GatewayCard.tsxnew file mode 100644index 000000000..bb43cc0b3--- /dev/null+++ b/ui/src/components/onboarding/providers/GatewayCard.tsx@@ -0,0 +1,107 @@+// The middle of the diagram: the thing everything above feeds and everything below+// draws from.+//+// The card is the engine's only status surface on this screen. What the lifecycle+// reports — installing, starting, a classified failure, or running — is said here,+// on the object it is about, rather than in a banner somewhere else on the page. A+// running-but-degraded engine still routes, so it reads as running; saying otherwise+// would push someone to repair something that is working.+import type { FC } from 'react';+import { ExternalLink, RefreshCw } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import type { GatewayAdoptionFailure } from '@/components/settings/models/gatewayAdoption';+import { Button } from '@/components/ui/button';+import type { TranslationKey } from '@/i18n/types';++export type GatewayPhase = 'idle' | 'installing' | 'starting' | 'running' | 'failed' | 'unsupported';++const PHASE_LINE = {+ idle: 'onboarding.providers.gatewayTagline',+ installing: 'onboarding.providers.gatewayInstalling',+ starting: 'onboarding.providers.gatewayStarting',+ running: 'onboarding.providers.gatewayTagline',+ failed: 'onboarding.providers.gatewayNotReady',+ unsupported: 'onboarding.providers.gatewayUnsupported',+} as const satisfies Record<GatewayPhase, TranslationKey>;++const BUSY: ReadonlySet<GatewayPhase> = new Set<GatewayPhase>(['installing', 'starting']);++/** Where 「查看安装指南」 goes: the guide the contract names, in the language the+ * person is reading. It ships a Chinese counterpart, and sending someone who is+ * reading Chinese to the English file is a worse answer than the docs root — which+ * is what this used to be, and which left them to find the page themselves while+ * the screen they are on is the one they cannot get past. */+const INSTALL_GUIDE_URL = {+ en: 'https://github.com/avibe-bot/avibe/blob/master/docs/INSTALL_FOR_AI.md',+ zh: 'https://github.com/avibe-bot/avibe/blob/master/docs/INSTALL_FOR_AI_ZH.md',+} as const;++const installGuideUrl = (language: string): string =>+ (language.toLowerCase().startsWith('zh') ? INSTALL_GUIDE_URL.zh : INSTALL_GUIDE_URL.en);++/**+ * @param failedStep Which step of the lifecycle failed, published as a DOM hook+ * rather than as copy: the two failure sentences C1 ships do not name a step,+ * and inventing a third that does would be copy this screen made up. It is what+ * a bug report and a test can read off the rendered card.+ * @param onRetry Absent means the state has no recovery from here. Both failure+ * lines ask for one ("Try again", "Recheck availability"), so the card carries+ * it: the engine is what failed, and an action about it belongs on it rather+ * than in the footer, which is claimed by whatever the person came here to do.+ */+export const GatewayCard: FC<{+ phase: GatewayPhase;+ failedStep?: GatewayAdoptionFailure['step'] | null;+ onRetry?: (() => void) | null;+}> = ({ phase, failedStep, onRetry }) => {+ const { t, i18n } = useTranslation();+ const busy = BUSY.has(phase);+ const bad = phase === 'failed' || phase === 'unsupported';++ return (+ <div+ className="setup-gateway"+ data-state={phase}+ {...(bad && failedStep ? { 'data-failed-step': failedStep } : {})}+ // The whole card is one status: a reader should hear what the gateway is+ // doing, not a name and then, separately, a line that changed.+ role="status"+ aria-live="polite"+ >+ <span className="setup-gateway-name">{t('onboarding.providers.gatewayName')}</span>+ <span className="setup-gateway-tagline" {...(bad ? { 'data-tone': 'error' } : {})}>+ {busy && (+ <RefreshCw+ className="setup-gateway-spinner motion-safe:animate-spin inline-block align-[-2px] me-1.5"+ aria-hidden="true"+ />+ )}+ {t(PHASE_LINE[phase])}+ </span>+ {bad && onRetry && (+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="setup-gateway-retry"+ onClick={onRetry}+ >+ {t('common.retry')}+ </Button>+ )}+ {/* Rechecking availability is the only thing this screen can do about an+ unsupported host, and on its own it is a button that will keep saying no.+ The guide is the other half of that answer — what would have to change for+ the recheck to come back differently — which is why C1 ships the label. */}+ {phase === 'unsupported' && (+ <Button variant="link" size="sm" className="setup-gateway-help gap-1.5 px-0" asChild>+ <a href={installGuideUrl(i18n.language)} target="_blank" rel="noopener noreferrer">+ {t('onboarding.providers.gatewayEnvironmentHelp')}+ <ExternalLink className="size-[13px]" aria-hidden="true" />+ </a>+ </Button>+ )}+ </div>+ );+};diff --git a/ui/src/components/onboarding/providers/ProviderCard.tsx b/ui/src/components/onboarding/providers/ProviderCard.tsxnew file mode 100644index 000000000..a32ada78c--- /dev/null+++ b/ui/src/components/onboarding/providers/ProviderCard.tsx@@ -0,0 +1,134 @@+// The first two cards of the diagram, and the third that offers more.+//+// A card is either a fact or an offer, and the difference is what it does when+// pressed: a connected card does nothing, a detected card toggles consent, an empty+// card opens the add dialog. Only the detected one carries `aria-pressed`, because+// only it is a toggle — giving a connected card a pressed state would announce that+// something already true can be turned off here, which it cannot.+import type { FC } from 'react';+import { Check, KeyRound, Plus } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { BLOCKED_REASON_FALLBACK_KEY } from '@/components/settings/models/migrationGrouping';+import { serverText } from '@/components/settings/models/serverCopy';+import type { SourceKind } from '@/components/settings/models/types';+import { VendorGlyph } from '@/components/settings/models/vendorGlyph';+import type { TranslationKey } from '@/i18n/types';++import type { ProviderSlot } from './providerStage';++/** What a connected card says when there is no mask to say — Settings' own words for+ * the same distinction, so one source reads one way in both places. */+const SUPPLY_KIND_COPY = {+ subscription: 'settings.models.upstream.kind.subscription',+ api_key: 'settings.models.upstream.kind.apiKey',+} as const satisfies Record<SourceKind, TranslationKey>;++export const ProviderCard: FC<{+ slot: ProviderSlot;+ selected: boolean;+ onToggle: () => void;+ onAdd: () => void;+}> = ({ slot, selected, onToggle, onAdd }) => {+ const { t } = useTranslation();+ const detected = slot.kind === 'detected';+ const connected = slot.kind === 'connected';+ // Found, and not something this flow may take over. It keeps its card and its+ // reason: an invitation to add a key for a provider whose key is right there is+ // an answer to a question nobody asked.+ const blocked = slot.reasons.length > 0;++ // The second line says where the card's knowledge came from. A connected+ // subscription has no key to mask, so it names the sign-in instead; only a card+ // with nothing behind it describes the offer, which is the one thing a connected+ // or detected card must never do — neither can be pressed into adding one, so an+ // invitation there is an invitation to press something that does nothing. A+ // detected row the server named no provider for has no second line at all: its+ // masked detail is already the name above.+ const written = slot.mask+ ? t(connected ? 'onboarding.providers.cardKeyAdded' : 'onboarding.providers.cardKeyDetected', { mask: slot.mask })+ : slot.supply+ ? [t(SUPPLY_KIND_COPY[slot.supply.kind]), slot.supply.account].filter(Boolean).join(' · ')+ : detected+ ? ''+ : t('onboarding.providers.cardAddKeyNamed', { name: slot.label });++ // The migration feature's own words for the same group, so the card and the+ // review it opens from give one answer.+ const reason = slot.reasons+ .map((key) => serverText(t, key, BLOCKED_REASON_FALLBACK_KEY))+ .filter(Boolean)+ .join(' · ');++ // A key saved without verification is `standby` carrying `verification_pending`:+ // stored, but nothing has confirmed it answers. Settings states that difference+ // with the same word, and a card that looked identical either way would report an+ // unchecked key as a provider that is already supplying models. It is said in both+ // places the card is read, because `aria-label` replaces the text rather than+ // adding to it.+ const note = slot.pending ? ` · ${t('settings.models.sourceDetail.status.saved')}` : '';+ const keyLine = [`${written}${note}`, reason].filter(Boolean).join(' · ');++ const label = connected+ ? t('onboarding.providers.cardUseExistingNamed', { name: slot.label })+ : detected+ ? t('onboarding.providers.cardSelected')+ : t('onboarding.providers.cardAddSubscriptionNamed', { name: slot.label });++ return (+ <button+ type="button"+ className="setup-provider-card"+ data-provider={slot.vendor}+ data-state={slot.kind}+ {...(slot.pending ? { 'data-pending': 'true' } : {})}+ {...(blocked ? { 'data-blocked': 'true' } : {})}+ {...(detected && !blocked ? { 'aria-pressed': selected } : {})}+ aria-label={detected ? `${slot.label} · ${keyLine}` : `${label}${note}`}+ disabled={connected || blocked}+ onClick={detected ? onToggle : onAdd}+ >+ {/* The catalog's own mark, filed by the same vendor id the slot carries — the+ picker, the import rows and this card therefore draw one provider one way,+ and a vendor with no published mark falls back to its initial rather than+ to a neighbour's logo. A credential the server named no provider for gets+ the key it is, because every other mark here would name a brand. */}+ <span className="setup-provider-logo">+ {slot.brand+ ? <VendorGlyph vendor={slot.brand} />+ // No class: the logo well already sizes whatever svg it holds.+ : <KeyRound strokeWidth={1.6} aria-hidden="true" />}+ </span>+ <span className="setup-provider-copy">+ <span className="setup-provider-name">{slot.label}</span>+ <span className="setup-provider-key">{keyLine}</span>+ </span>+ {/* The check states a decision, not a label: the reference draws no word+ beside it, and the card's accessible name already carries the meaning. */}+ {(connected || selected) && (+ <Check className="setup-provider-check" strokeWidth={2.2} aria-hidden="true" />+ )}+ </button>+ );+};++/** The third slot. Always present, whatever the first two hold. */+export const AddMoreCard: FC<{ count: number; onAdd: () => void }> = ({ count, onAdd }) => {+ const { t } = useTranslation();+ return (+ <button+ type="button"+ className="setup-provider-card"+ data-state="add"+ aria-label={t('onboarding.providers.addMoreAction')}+ onClick={onAdd}+ >+ <Plus className="setup-provider-add-icon" strokeWidth={1.6} aria-hidden="true" />+ <span className="setup-provider-copy">+ <span className="setup-provider-name">{t('onboarding.providers.addMoreTitle')}</span>+ <span className="setup-provider-key">{t('onboarding.providers.addMoreSubtitle')}</span>+ </span>+ {count > 0 && <span className="setup-provider-badge">{t('onboarding.providers.addMoreCount', { count })}</span>}+ </button>+ );+};diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsxnew file mode 100644index 000000000..88ac1a66f--- /dev/null+++ b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx@@ -0,0 +1,1625 @@+// @vitest-environment jsdom+//+// The screen as a whole, against a fake server rather than a queue of canned+// replies: the stage, the sentence, the capsule and the footer action are four+// readings of one machine, and a fixture that answers them in a fixed order would+// decide which of them saw what. Everything underneath is the real thing — the+// real collection authority, the real lifecycle helper, the real takeover dialog —+// because the failures worth catching here are the ones where this screen wires+// two correct pieces together wrongly.+//+// What each case pins is a way the four readings could quietly stop agreeing: a+// connected card that changes under a selection, a footer that offers a batch the+// dialog would refuse, an engine that installs twice, a dismissed capsule that+// moves the button.+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import * as React from 'react';+import { I18nextProvider } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import {+ beginRegionRead,+ readyRegion,+ unreadRegion,+ type RegionRead,+} from '@/components/settings/models/regionRead';+import { providerBrandLabel } from '@/components/settings/providers/providerIdentity';+import type {+ AgentSupply,+ MigrationItem,+ RuntimeDependency,+ RuntimeHealth,+ Source,+} from '@/components/settings/models/types';++const showToast = vi.hoisted(() => vi.fn());++vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast }) }));+// The capsule's own capability probe. Hosted here, it decides nothing about the+// offer — the screen's scan does — but the hook would still fire a request.+vi.mock('@/components/settings/models/useModelHubCapability', () => ({+ useModelHubCapability: () => true,+}));++import { ApiCallError, modelsApi } from '@/components/settings/models/modelsApi';+import {+ INITIAL_SETUP_FLOW_STATE,+ type SetupAction,+ type SetupCapability,+ type SetupFlowState,+ type SetupScreenHandle,+ type SetupScreenId,+} from '../setupFlow';+import { ProvidersScreen } from './ProvidersScreen';++// ── Fixtures ──────────────────────────────────────────────────────────────++const source = (over: Partial<Source> & { id: string; vendor: string }): Source => ({+ last_discovered_at: null,+ kind: 'api_key',+ display_name: over.vendor,+ protocol: 'openai_chat',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active' },+ models: [],+ ...over,+});++const supply = (over: Partial<AgentSupply> & { backend: AgentSupply['backend'] }): AgentSupply => ({+ cli_present: true,+ mode: 'direct',+ menu_kind: 'native' as AgentSupply['menu_kind'],+ ...over,+});++const runtimeOf = (health: RuntimeHealth, over: Partial<RuntimeDependency> = {}): RuntimeDependency => ({+ contract_version: 10,+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },+ status: { verified: true, health },+ ...over,+});++const UNSUPPORTED = runtimeOf('not_installed', {+ manifest: { name: 'cliproxyapi', resolution: 'unsupported', version: '1.0.0', source_sha: 'sha', assets: [] },+});++// The same host with an engine already up on it. Health and install admission are+// separate facts on purpose: the manifest has no asset for this platform, and the+// runtime running here arrived some other way. Reads and writes to it are fine; only+// something that would install one is not.+const UNSUPPORTED_RUNNING = runtimeOf('ok', {+ manifest: { name: 'cliproxyapi', resolution: 'unsupported', version: '1.0.0', source_sha: 'sha', assets: [] },+});++const CODEX_KEY: MigrationItem = {+ id: 'mig_codex_key',+ backend: 'codex',+ kind: 'api_key',+ masked_detail: 'sk-…9f21 · Codex configuration',+ masked_credential: 'sk-…9f21',+ proposed_action: 'import',+ selected: true,+ notes_key: null,+ vendor: 'openai',+ display_name: 'OpenAI',+};++const OPENCODE_KEY: MigrationItem = {+ id: 'mig_opencode_key',+ backend: 'opencode',+ kind: 'opencode_provider',+ masked_detail: 'google · sk-…3456',+ masked_credential: 'sk-…3456',+ proposed_action: 'import',+ selected: true,+ notes_key: null,+ // The scan's spelling, not the catalog's: resolving the two to one id is what+ // stops the same provider occupying two slots.+ vendor: 'google',+ display_name: 'google',+};++// A subscription sign-in. Its presence blocks its whole backend group, which is+// what keeps a Claude card off the stage.+const CLAUDE_SUBSCRIPTION: MigrationItem = {+ id: 'mig_claude_oauth',+ backend: 'claude',+ kind: 'oauth_native',+ masked_detail: 'Claude account (OAuth)',+ proposed_action: 'keep_native',+ selected: true,+ notes_key: null,+ vendor: 'anthropic',+ display_name: 'Anthropic',+};++// The API key in the same store as the sign-in above. The server migrates a+// backend whole, so this key cannot be taken without the subscription beside it —+// and setup's copy offers keys only. Found, and not this screen's to take.+const CLAUDE_KEY: MigrationItem = {+ id: 'mig_claude_key',+ backend: 'claude',+ kind: 'api_key',+ masked_detail: 'sk-…dd3c',+ masked_credential: 'sk-…dd3c',+ proposed_action: 'import',+ selected: true,+ notes_key: null,+ vendor: 'anthropic',+ display_name: 'Anthropic',+};++// No presentation metadata at all: an older server, or a provider nothing names.+const OPENCODE_LEGACY: MigrationItem = {+ id: 'mig_opencode_legacy',+ backend: 'opencode',+ kind: 'opencode_provider',+ masked_detail: 'Self-hosted relay · sk-…abcd',+ proposed_action: 'import',+ selected: true,+ notes_key: null,+};++/** The one sentence the migration feature has for a row it cannot take. */+const BLOCKED_SENTENCE = 'This credential cannot be imported.';++// ── The fake server ───────────────────────────────────────────────────────++type Server = {+ sources: Source[];+ agents: AgentSupply[];+ scan: MigrationItem[];+ runtime: RuntimeDependency;+};++let server: Server;+const applied: string[][] = [];++const serve = (over: Partial<Server> = {}) => {+ server = {+ sources: [],+ agents: [supply({ backend: 'codex' }), supply({ backend: 'opencode' })],+ scan: [],+ runtime: runtimeOf('ok'),+ ...over,+ };+ vi.spyOn(modelsApi, 'listSources').mockImplementation(async () => server.sources.map((row) => ({ ...row })));+ vi.spyOn(modelsApi, 'listAgents').mockImplementation(async () => server.agents.map((row) => ({ ...row })));+ vi.spyOn(modelsApi, 'refreshAgentPresence')+ .mockImplementation(async () => server.agents.map((row) => ({ ...row })));+ vi.spyOn(modelsApi, 'scanMigration').mockImplementation(async () => ({+ items: server.scan.map((row) => ({ ...row })),+ }));+ vi.spyOn(modelsApi, 'applyMigration').mockImplementation(async (ids) => {+ applied.push([...ids]);+ const taken = server.scan.filter((row) => ids.includes(row.id));+ server.scan = server.scan.filter((row) => !ids.includes(row.id));+ // A landed take-over is a source that now exists. Saying so is what makes the+ // post-import readings an answer from the machine instead of arithmetic.+ server.sources = [+ ...server.sources,+ ...taken.map((row) => source({ id: `src_${row.id}`, vendor: row.vendor ?? 'custom' })),+ ];+ return { applied: taken.length, sources: [] };+ });+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockImplementation(async () => ({ ...server.runtime }));+ vi.spyOn(modelsApi, 'installRuntime').mockImplementation(async () => {+ server.runtime = { ...server.runtime, status: { ...server.runtime.status, health: 'not_started' } };+ return { ...server.runtime };+ });+ vi.spyOn(modelsApi, 'startRuntime').mockImplementation(async () => {+ server.runtime = { ...server.runtime, status: { ...server.runtime.status, health: 'ok' } };+ return { ...server.runtime };+ });+};++const deferred = <T,>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });+ return { promise, resolve, reject };+};++// ── The shell's half of the contract ──────────────────────────────────────++const actions: SetupAction[] = [];+const navigated: SetupScreenId[] = [];+const retrySetup = vi.fn();++type ScreenOptions = {+ active?: boolean;+ capability?: SetupCapability;+ gatewayEnabled?: boolean | null;+ runtimeRead?: RegionRead<RuntimeDependency>;+ flow?: Partial<SetupFlowState>;+};++const Harness: React.FC<ScreenOptions & { handle: React.RefObject<SetupScreenHandle | null> }> = ({+ handle,+ active = true,+ capability = 'enabled',+ gatewayEnabled = true,+ runtimeRead = readyRegion(runtimeOf('ok')),+ flow,+}) => {+ // The shell owns the flow state, so the test does too: a screen that kept its+ // own copy would pass every assertion here and lose the selection on re-entry.+ const [flowState, setFlowState] = React.useState<SetupFlowState>({ ...INITIAL_SETUP_FLOW_STATE, ...flow });+ return (+ <I18nextProvider i18n={i18n}>+ <ProvidersScreen+ ref={handle}+ active={active}+ handoff={false}+ capability={capability}+ gatewayEnabled={gatewayEnabled}+ runtimeRead={runtimeRead}+ onRetrySetup={retrySetup}+ flowState={flowState}+ setFlowState={setFlowState}+ onActionChange={(action) => { actions.push(action); }}+ onNavigate={(screen) => { navigated.push(screen); }}+ />+ </I18nextProvider>+ );+};++const renderScreen = (options: ScreenOptions = {}) => {+ const handle = React.createRef<SetupScreenHandle | null>();+ const view = render(<Harness handle={handle} {...options} />);+ /** Change the shell's half of the contract without remounting: the wizard hiding+ * this screen, or handing down a runtime read that moved. */+ const show = async (next: ScreenOptions) => {+ await act(async () => { view.rerender(<Harness handle={handle} {...options} {...next} />); });+ };+ return { ...view, handle, show };+};++const cards = () => [...document.querySelectorAll<HTMLElement>('.setup-provider-card')];+const cardFor = (vendor: string) => {+ const card = document.querySelector<HTMLElement>(`.setup-provider-card[data-provider="${vendor}"]`);+ if (!card) throw new Error(`no card for ${vendor}`);+ return card;+};+const gatewayCard = () => {+ const card = document.querySelector<HTMLElement>('.setup-gateway');+ if (!card) throw new Error('no gateway card');+ return card;+};+const summary = () => document.querySelector<HTMLElement>('.setup-provider-summary');+const offerSlot = () => document.querySelector<HTMLElement>('.setup-provider-offer');+const lastAction = () => actions[actions.length - 1];+const activate = async (handle: React.RefObject<SetupScreenHandle | null>) => {+ await act(async () => { handle.current?.activate(); });+};++/** The stage has settled once the one scan every reading derives from has landed. */+const settled = async () => {+ await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalled());+ await waitFor(() => expect(lastAction()).toBeTruthy());+};++beforeEach(async () => {+ applied.length = 0;+ actions.length = 0;+ navigated.length = 0;+ retrySetup.mockReset();+ window.localStorage.clear();+ vi.stubGlobal('ResizeObserver', class {+ observe() {}+ unobserve() {}+ disconnect() {}+ });+ await i18n.changeLanguage('en');+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ showToast.mockReset();+});++describe('ProvidersScreen — the stage', () => {+ it('opens on the shortlist and always offers a third way in', async () => {+ serve();+ renderScreen();+ await settled();++ // Two brand slots and the add-more card, whatever the two brand slots hold.+ expect(cards()).toHaveLength(3);+ expect(cards().map((card) => card.dataset.provider)).toEqual(['openai', 'anthropic', undefined]);+ expect(cards().slice(0, 2).every((card) => card.dataset.state === 'empty')).toBe(true);+ expect(cards()[2].dataset.state).toBe('add');+ });++ it('draws what exists ahead of what was only found, and never captions a card', async () => {+ serve({+ sources: [source({ id: 'src_zhipu', vendor: 'zhipuai' })],+ scan: [CODEX_KEY],+ });+ renderScreen();+ await settled();++ await waitFor(() => expect(cards()[0].dataset.state).toBe('connected'));+ expect(cards().map((card) => card.dataset.provider)).toEqual(['zhipuai', 'openai', undefined]);+ expect(cards()[1].dataset.state).toBe('detected');+ // The check states the decision; the reference draws no word beside it, and+ // the add dialog's 「Added」 tag belongs to that list, not to the stage.+ expect(cardFor('zhipuai').querySelector('.setup-provider-check')).toBeTruthy();+ expect(within(cardFor('zhipuai')).queryByText('Added')).toBeNull();+ });++ it('resolves one provider to one card however the two readings spell it', async () => {+ serve({+ // `google` from the scan, `gemini` from the catalog: one card, not two.+ sources: [source({ id: 'src_gemini', vendor: 'gemini' })],+ scan: [OPENCODE_KEY],+ });+ renderScreen();+ await settled();++ await waitFor(() => expect(cards()[0].dataset.state).toBe('connected'));+ expect(cards().filter((card) => card.dataset.provider === 'gemini')).toHaveLength(1);+ });++ it('a selection toggle never changes a connected card', async () => {+ serve({+ sources: [source({ id: 'src_zhipu', vendor: 'zhipuai' })],+ scan: [CODEX_KEY],+ });+ renderScreen();+ await settled();+ const user = userEvent.setup();+ await waitFor(() => expect(cards()[0].dataset.state).toBe('connected'));++ const connected = cardFor('zhipuai');+ const detected = cardFor('openai');+ // A fact is not a toggle: no pressed state to announce, and nothing to press.+ expect(connected.getAttribute('aria-pressed')).toBeNull();+ expect((connected as HTMLButtonElement).disabled).toBe(true);+ // The server proposed this row, so the card opens on that proposal.+ expect(detected.getAttribute('aria-pressed')).toBe('true');++ await user.click(detected);+ await waitFor(() => expect(cardFor('openai').getAttribute('aria-pressed')).toBe('false'));+ expect(cardFor('openai').querySelector('.setup-provider-check')).toBeNull();+ expect(cardFor('zhipuai').dataset.state).toBe('connected');+ expect(cardFor('zhipuai').querySelector('.setup-provider-check')).toBeTruthy();++ await user.click(cardFor('openai'));+ await waitFor(() => expect(cardFor('openai').getAttribute('aria-pressed')).toBe('true'));+ expect(cardFor('openai').querySelector('.setup-provider-check')).toBeTruthy();+ expect(cardFor('zhipuai').querySelector('.setup-provider-check')).toBeTruthy();+ });++ it('opens on the rows the server proposed, and leaves the ones it did not', async () => {+ // The shipped takeover opens ticked on exactly these rows. A screen that ignored+ // them would show the same scan with a different answer, and someone who trusted+ // the cards would import less than the dialog behind them offered.+ serve({ scan: [CODEX_KEY, { ...OPENCODE_KEY, selected: false }] });+ renderScreen();+ await settled();++ await waitFor(() => expect(cardFor('openai').getAttribute('aria-pressed')).toBe('true'));+ expect(cardFor('gemini').getAttribute('aria-pressed')).toBe('false');+ expect(lastAction()).toMatchObject({ labelKey: 'onboarding.providers.actionImport', labelArgs: { count: 1 } });+ });++ it('says so when a key is stored but nothing has checked it yet', async () => {+ // `save_unverified: true` is what the key form sends, so a card can be connected+ // with nothing having confirmed the key answers. Settings discloses that; a card+ // that did not would report it as a provider already supplying models.+ serve({+ sources: [source({+ id: 'src_pending',+ vendor: 'openai',+ state: { status: 'standby' },+ verification_pending: 'vp_fixture',+ })],+ });+ renderScreen();+ await settled();++ await waitFor(() => expect(cardFor('openai').dataset.pending).toBe('true'));+ expect(within(cardFor('openai')).getByText(/Saved/)).toBeTruthy();+ expect(cardFor('openai').getAttribute('aria-label')).toContain('Saved');+ });++ it('names a subscription by its sign-in, not by a mask it cannot have', async () => {+ // A subscription has no key to mask by construction. A card describing itself by+ // its mask alone would fall through to the offer an empty card makes and invite+ // a key for a provider that is already connected — and the card is disabled, so+ // that invitation is to press something that does nothing. What it says instead+ // is what Settings says about the same source.+ serve({+ sources: [source({+ id: 'src_claude',+ vendor: 'anthropic',+ kind: 'subscription',+ account_label: '[email protected]',+ })],+ });+ renderScreen();+ await settled();++ await waitFor(() => expect(cardFor('anthropic').dataset.state).toBe('connected'));+ expect(within(cardFor('anthropic')).getByText('Subscription · [email protected]')).toBeTruthy();+ expect(within(cardFor('anthropic')).queryByText(/Add a .* API Key/)).toBeNull();+ });++ it('names a connected API key by its kind when the server sent no mask', async () => {+ serve({ sources: [source({ id: 'src_key', vendor: 'openai' })] });+ renderScreen();+ await settled();++ await waitFor(() => expect(cardFor('openai').dataset.state).toBe('connected'));+ // No account either: the line is the kind alone rather than a stray separator.+ expect(within(cardFor('openai')).getByText('API key')).toBeTruthy();+ });++ it('says a source was written even when the read that would show it fails', async () => {+ serve();+ renderScreen();+ await settled();+ const user = userEvent.setup();++ vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValue({+ source: source({ id: 'src_new', vendor: 'custom' }),+ added_to: [],+ adopted_by: [],+ });+ vi.mocked(modelsApi.listSources).mockRejectedValue(new Error('offline'));++ await user.click(cards()[2]);+ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('button', { name: 'API Key' }));+ await user.type(within(dialog).getByLabelText('Base URL'), 'https://api.example/v1');+ await user.type(within(dialog).getByLabelText('API key'), 'sk-live-1');+ await user.click(within(dialog).getByRole('button', { name: 'Add' }));++ // The write landed; the read that would show it did not. Keeping the old list+ // silently would report a provider that exists as one that does not.+ await waitFor(() => expect(summary()?.dataset.tone).toBe('error'));+ });++ it('counts only the sources added through Add more that are still there', async () => {+ serve({ sources: [source({ id: 'src_kept', vendor: 'zhipu' })] });+ // `src_gone` was added here and has since been removed elsewhere. The badge+ // describes what exists now.+ renderScreen({ flow: { addedThroughMore: ['src_kept', 'src_gone'] } });+ await settled();++ await waitFor(() => expect(within(cards()[2]).queryByText('1 added')).toBeTruthy());+ });++ it('names what is there rather than counting it', async () => {+ serve({ sources: [source({ id: 'src_zhipu', vendor: 'zhipuai', display_name: 'zhipuai' })] });+ renderScreen();+ await settled();++ await waitFor(() => expect(summary()?.textContent)+ .toContain(`1 provider added: ${providerBrandLabel('zhipuai')}`));+ expect(summary()?.dataset.tone).toBeUndefined();+ });++ it('offers a way back when the machine cannot be read, and asks again only for the read that failed', async () => {+ serve();+ vi.mocked(modelsApi.scanMigration).mockRejectedValue(new Error('offline'));+ renderScreen();++ await waitFor(() => expect(summary()?.dataset.tone).toBe('error'));+ const failed = summary();+ if (!failed) throw new Error('no summary');+ await userEvent.setup().click(within(failed).getByRole('button', { name: 'Retry' }));++ // What broke the sentence is a read, so a read is what this asks for again. The+ // engine is not what failed: asking the shell to resume its bootstrap, or arming an+ // install or a start from here, would be a mutation nobody asked for.+ await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalledTimes(2));+ expect(retrySetup).not.toHaveBeenCalled();+ expect(modelsApi.installRuntime).not.toHaveBeenCalled();+ expect(modelsApi.startRuntime).not.toHaveBeenCalled();+ });++ it('keeps the sources that did arrive when the scan beside them fails', async () => {+ // Two reads, two questions. A scan that fails says nothing about the sources,+ // and throwing away a list that did arrive would report providers that exist as+ // providers that do not — leaving the action offering 「添加」 on a machine that+ // already has credentials.+ serve({ sources: [source({ id: 'src_zhipu', vendor: 'zhipuai' })] });+ vi.mocked(modelsApi.scanMigration).mockRejectedValue(new Error('offline'));+ renderScreen();+ await settled();++ await waitFor(() => expect(cardFor('zhipuai').dataset.state).toBe('connected'));+ // Said, not hidden: half the machine could not be read.+ expect(summary()?.dataset.tone).toBe('error');+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ });++ it('keeps the scan that did arrive when the source read beside it fails', async () => {+ serve({ scan: [CODEX_KEY] });+ vi.mocked(modelsApi.listSources).mockRejectedValue(new Error('offline'));+ renderScreen();+ await settled();++ await waitFor(() => expect(cardFor('openai').dataset.state).toBe('detected'));+ expect(summary()?.dataset.tone).toBe('error');+ });++ it('says it is still looking before the first inventory read lands', async () => {+ // Not 「添加」. An empty list and a list nobody has read yet are the same+ // `Source[]`, and the difference is the whole question the button is answering.+ serve();+ const read = deferred<Source[]>();+ vi.mocked(modelsApi.listSources).mockReturnValue(read.promise);+ renderScreen();++ await waitFor(() => expect(lastAction()).toBeTruthy());+ expect(lastAction()).toMatchObject({+ labelKey: 'onboarding.providers.actionChecking',+ disabled: true,+ busy: true,+ });++ await act(async () => { read.resolve([]); });+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionAdd'));+ });++ it('offers to ask again, not to add, when the inventory could not be read', async () => {+ // 「添加」 against an unread inventory is the same button on a machine that+ // already holds the credential as on one that holds nothing — which is how a+ // second copy of an existing key gets written.+ serve();+ vi.mocked(modelsApi.listSources).mockRejectedValue(new Error('offline'));+ const { handle } = renderScreen();+ await settled();++ await waitFor(() => expect(lastAction().labelKey).toBe('common.retry'));+ expect(lastAction()).toMatchObject({ disabled: false, busy: false, icon: 'none' });++ vi.mocked(modelsApi.listSources)+ .mockImplementation(async () => [source({ id: 'src_zhipu', vendor: 'zhipuai' })]);+ await activate(handle);++ // Asking again is the whole action, and the answer it gets is what the screen+ // then offers. No dialog: nothing was added here.+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ expect(screen.queryByRole('dialog')).toBeNull();+ await waitFor(() => expect(cardFor('zhipuai').dataset.state).toBe('connected'));+ });++ it('keeps a detected key reachable behind the connected card of the same brand', async () => {+ // The stage draws one OpenAI card, and it draws the fact: a source exists. The+ // native store beside it still holds a DIFFERENT key — the scan never reads the+ // Hub's inventory, so it cannot be a duplicate of the connected one — and the+ // capsule counts it. A row the capsule counts and no pane can act on is the+ // contradiction this pins: Add more is where it stays reachable.+ serve({+ sources: [source({ id: 'src_openai', vendor: 'openai', masked_credential: 'sk-…1111' })],+ scan: [CODEX_KEY],+ });+ renderScreen();+ await settled();+ const user = userEvent.setup();++ await waitFor(() => expect(cardFor('openai').dataset.state).toBe('connected'));+ expect(cards().filter((card) => card.dataset.state === 'detected')).toHaveLength(0);+ expect(await screen.findByText('Found 1 API key to import into Model Hub')).toBeTruthy();++ const addMore = cards().find((card) => card.dataset.state === 'add');+ await user.click(addMore as HTMLElement);+ const dialog = await screen.findByRole('dialog');++ // Listed, under its own masked credential, and pressable — not marked 「已添加」+ // because a brand it shares with a source is not the key that source holds.+ const row = within(dialog).getByRole('button', { name: /Select existing OpenAI/ });+ expect(row.dataset.state).toBe('detected');+ expect((row as HTMLButtonElement).disabled).toBe(false);+ expect(within(row).getByText(/sk-…9f21/)).toBeTruthy();+ });++ it('still offers a take-over the scan found while the inventory beside it is unread', async () => {+ // Two reads, two questions. Taking over a key the scan found does not depend on+ // knowing what else is already there.+ serve({ scan: [CODEX_KEY] });+ vi.mocked(modelsApi.listSources).mockRejectedValue(new Error('offline'));+ renderScreen();+ await settled();++ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionImport'));+ expect(lastAction().labelArgs).toEqual({ count: 1 });+ });+});++describe('ProvidersScreen — the import capsule', () => {+ it('counts the keys the import list would offer, not the rows the scan returned', async () => {+ serve({ scan: [CODEX_KEY, OPENCODE_KEY, CLAUDE_SUBSCRIPTION] });+ renderScreen();++ expect(await screen.findByText('Found 2 API keys to import into Model Hub')).toBeTruthy();+ });++ it('keeps its slot when the offer is dismissed, so the action below cannot move', async () => {+ serve({ scan: [CODEX_KEY] });+ renderScreen();+ await settled();+ const user = userEvent.setup();++ const slot = offerSlot();+ expect(slot).toBeTruthy();+ expect(slot?.closest('.setup-provider-stage')).toBeTruthy();+ expect(await screen.findByText('Found 1 API key to import into Model Hub')).toBeTruthy();++ await user.click(screen.getByRole('button', { name: 'Dismiss import notice' }));++ await waitFor(() => expect(screen.queryByText(/API key to import/)).toBeNull());+ // The capsule went; the box it sat in did not.+ expect(offerSlot()).toBe(slot);+ });++ it('hands its review to the screen rather than opening a second dialog', async () => {+ serve({ scan: [CODEX_KEY] });+ renderScreen();+ await settled();+ const user = userEvent.setup();++ await user.click(await screen.findByRole('button', { name: 'Review migration' }));++ const dialog = await screen.findByRole('dialog');+ // The screen's own scan, in the screen's own dialog: a capsule that scanned+ // again could offer rows the stage and the footer never counted.+ expect(within(dialog).getByText('Migrate to Model Hub')).toBeTruthy();+ expect(modelsApi.scanMigration).toHaveBeenCalledTimes(1);+ });+});++// A scan answers two different questions: what is on this machine, and what this+// entry may take over. They are two projections of one grouping, not two rules —+// and every case here is a way a screen that conflated them would lie. Hiding a+// found key behind an empty 「add Anthropic」 invitation is the loud version; a+// capsule counting a key its own review would refuse is the quiet one.+describe('ProvidersScreen — what it found but may not take', () => {+ it('keeps a blocked credential on the stage, with its reason and no way to consent', async () => {+ serve({ scan: [CLAUDE_KEY, CLAUDE_SUBSCRIPTION] });+ renderScreen();+ await settled();+ const user = userEvent.setup();++ const card = cardFor('anthropic');+ expect(card.dataset.state).toBe('detected');+ expect(card.dataset.blocked).toBe('true');+ expect(within(card).getByText(new RegExp(BLOCKED_SENTENCE))).toBeTruthy();+ // Not a toggle that happens to be off, and not an invitation to add a key for a+ // provider whose key is right there on the card.+ expect((card as HTMLButtonElement).disabled).toBe(true);+ expect(card.getAttribute('aria-pressed')).toBeNull();+ // Still the found key, said in the card and in what a screen reader reads: the+ // mask is the evidence that this is a detection and not an offer.+ expect(card.getAttribute('aria-label')).toContain('sk-…dd3c');++ await user.click(card);+ expect(screen.queryByRole('dialog')).toBeNull();+ // Nothing to import, so the footer asks for a provider instead of offering a+ // batch, and the capsule — whose whole sentence is a count — says nothing.+ expect(lastAction().labelKey).toBe('onboarding.providers.actionAdd');+ expect(screen.queryByText(/to import into Model Hub/)).toBeNull();+ expect(screen.queryByRole('button', { name: 'Review migration' })).toBeNull();+ });++ it('counts the takeable group beside it, and only that one', async () => {+ serve({ scan: [CLAUDE_KEY, CLAUDE_SUBSCRIPTION, CODEX_KEY] });+ renderScreen();+ await settled();+ const user = userEvent.setup();++ // What can be done comes first, and both stay on the stage. The second slot has+ // to be the Claude key that was found — an empty 「add Anthropic」 card would fill+ // the same position from the shortlist and read as if nothing had been found.+ await waitFor(() => expect(cards().map((card) => [card.dataset.provider, card.dataset.state]))+ .toEqual([['openai', 'detected'], ['anthropic', 'detected'], [undefined, 'add']]));+ expect(cardFor('anthropic').dataset.blocked).toBe('true');+ expect(cardFor('openai').getAttribute('aria-pressed')).toBe('true');++ // One number, three readings: the card that is ticked, the sentence, the footer.+ expect(await screen.findByText('Found 1 API key to import into Model Hub')).toBeTruthy();+ expect(lastAction()).toMatchObject({+ labelKey: 'onboarding.providers.actionImport',+ labelArgs: { count: 1 },+ });++ // Pressing the blocked card cannot borrow the consent of the one beside it, and+ // does not open the add dialog an empty card in that slot would have opened.+ await user.click(cardFor('anthropic'));+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(cardFor('anthropic').getAttribute('aria-pressed')).toBeNull();+ expect(lastAction().labelArgs).toEqual({ count: 1 });+ });++ it('submits the batch it counted, and keeps the blocked card after the rescan', async () => {+ serve({ scan: [CLAUDE_KEY, CLAUDE_SUBSCRIPTION, CODEX_KEY] });+ const { handle } = renderScreen();+ await settled();+ const user = userEvent.setup();++ await waitFor(() => expect(lastAction().labelArgs).toEqual({ count: 1 }));+ await activate(handle);+ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('button', { name: /Start migration/ }));++ // No half group and no sign-in: one row, from the one group that consented.+ await waitFor(() => expect(applied).toHaveLength(1));+ expect(applied[0]).toEqual([CODEX_KEY.id]);+ expect(await screen.findByText('Migrated 1 API key into Model Hub')).toBeTruthy();++ // The rescan still finds the Claude store, so the card is still there, still+ // saying why. Settings is where it is resolved; forgetting it is not.+ await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(cardFor('anthropic').dataset.blocked).toBe('true'));+ expect(within(cardFor('anthropic')).getByText(new RegExp(BLOCKED_SENTENCE))).toBeTruthy();+ // And nothing left to offer: the receipt is the whole sentence now.+ expect(screen.queryByRole('button', { name: 'Review migration' })).toBeNull();+ });++ it('names a credential the server did not name, rather than guessing a brand', async () => {+ serve({ scan: [OPENCODE_LEGACY] });+ renderScreen();+ await settled();++ // Its own slot, keyed by the row: a card named 「OpenCode」 would name the file+ // it was found in, and a brand mark would name a provider nobody identified.+ const card = cardFor(OPENCODE_LEGACY.id);+ expect(card.dataset.state).toBe('detected');+ expect(within(card).getByText('Self-hosted relay · sk-…abcd')).toBeTruthy();+ expect(card.querySelector('.setup-provider-logo svg')).toBeTruthy();+ // Unnamed is not blocked: it is still a key this entry may take over.+ expect(card.getAttribute('aria-pressed')).toBe('true');+ expect(card.dataset.blocked).toBeUndefined();+ expect(await screen.findByText('Found 1 API key to import into Model Hub')).toBeTruthy();+ });+});++describe('ProvidersScreen — the action the shell renders', () => {+ it('offers to add when there is nothing yet, and opens the add dialog when pressed', async () => {+ serve();+ const { handle } = renderScreen();+ await settled();++ expect(lastAction()).toMatchObject({+ labelKey: 'onboarding.providers.actionAdd',+ disabled: false,+ busy: false,+ icon: 'none',+ });+ expect(lastAction().labelArgs).toBeUndefined();++ await activate(handle);++ const dialog = await screen.findByRole('dialog');+ expect(within(dialog).getByText('Add more model providers')).toBeTruthy();+ });++ it('continues once something is really there to continue with', async () => {+ serve({ sources: [source({ id: 'src_zhipu', vendor: 'zhipu' })] });+ const { handle } = renderScreen();+ await settled();++ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ await activate(handle);++ expect(navigated).toEqual(['assistants']);+ });++ it('offers the pending batch ahead of continuing, counted the way the dialog counts it', async () => {+ serve({ sources: [source({ id: 'src_zhipu', vendor: 'zhipu' })], scan: [CODEX_KEY, OPENCODE_KEY] });+ const { handle } = renderScreen();+ await settled();+ const user = userEvent.setup();++ // A source already holds the first slot, so the stage has room to draw one of+ // the two proposed groups. The count is the batch the dialog would submit, not+ // the number of cards that fit.+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionImport'));+ expect(lastAction().labelArgs).toEqual({ count: 2 });+ expect(cards().filter((card) => card.dataset.state === 'detected')).toHaveLength(1);++ // Dropping the group that is drawn leaves the one that is not: still a batch,+ // one row smaller.+ await user.click(cardFor('openai'));+ await waitFor(() => expect(lastAction().labelArgs).toEqual({ count: 1 }));+ expect(lastAction().labelKey).toBe('onboarding.providers.actionImport');+ await activate(handle);++ const dialog = await screen.findByRole('dialog');+ expect(within(dialog).getByText('Migrate to Model Hub')).toBeTruthy();+ // Opening the takeover is not continuing: the report of what landed would be+ // lost behind a navigation.+ expect(navigated).toEqual([]);+ });+});++describe('ProvidersScreen — what an import leaves behind', () => {+ it('submits one batch, reports what landed and re-reads the machine', async () => {+ serve({ scan: [CODEX_KEY, OPENCODE_KEY, CLAUDE_SUBSCRIPTION] });+ const { handle } = renderScreen();+ await settled();+ const user = userEvent.setup();++ // Both proposed groups arrive consented to; the third is blocked and cannot be.+ await waitFor(() => expect(lastAction().labelArgs).toEqual({ count: 2 }));++ await activate(handle);+ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('button', { name: /Start migration/ }));++ // One atomic batch, holding exactly the rows the count promised.+ await waitFor(() => expect(applied).toHaveLength(1));+ expect(applied[0]).toEqual([CODEX_KEY.id, OPENCODE_KEY.id]);+ expect(await screen.findByText('Migrated 2 API keys into Model Hub')).toBeTruthy();+ // The batch is spent in the tick it landed, not a round trip later: until the+ // rescan answers, the old scan still names rows that are now imported.+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ expect(modelsApi.listSources).toHaveBeenCalledTimes(2);+ });++ it('never re-offers a spent batch while the rescan is still in flight', async () => {+ serve({ scan: [CODEX_KEY] });+ const { handle } = renderScreen();+ await settled();+ const user = userEvent.setup();++ // Hold the rescan open, so the window between the apply and its answer is the+ // whole of what this case observes.+ const rescan = deferred<{ items: MigrationItem[] }>();+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionImport'));+ vi.mocked(modelsApi.scanMigration).mockReturnValueOnce(rescan.promise);++ await activate(handle);+ await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: /Start migration/ }));++ await waitFor(() => expect(applied).toHaveLength(1));+ // The capsule, the cards and the action all read the same emptied scan.+ await waitFor(() => expect(lastAction().labelKey).not.toBe('onboarding.providers.actionImport'));+ expect(screen.queryByText(/API key to import/)).toBeNull();++ await act(async () => { rescan.resolve({ items: [] }); });+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ });++ it('spends a terminally rejected batch before the rescan, so a failed reread cannot resubmit it', async () => {+ serve({ scan: [CODEX_KEY] });+ const { handle } = renderScreen();+ await settled();+ const user = userEvent.setup();++ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionImport'));+ expect(lastAction().labelArgs).toEqual({ count: 1 });++ vi.mocked(modelsApi.applyMigration)+ .mockRejectedValueOnce(new ApiCallError('migration_credentials_invalid', 'refused'));+ vi.mocked(modelsApi.scanMigration).mockRejectedValue(new Error('offline'));++ await activate(handle);+ await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: /Start migration/ }));++ // Spent in the same tick as the rejection: the refused ids are gone before the+ // rescan answers, the count does not move because nothing landed, and a failed+ // reread has nothing left to revive.+ await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ await waitFor(() => {+ expect(lastAction().labelKey).not.toBe('onboarding.providers.actionImport');+ expect(lastAction().labelKey).not.toBe('onboarding.providers.actionRetryImport');+ });+ expect(lastAction().labelArgs).toBeUndefined();+ expect(cardFor('openai').dataset.state).toBe('empty');+ expect(screen.queryByText(/Migrated/)).toBeNull();+ expect(screen.queryByText(/API key to import/)).toBeNull();+ expect(vi.mocked(modelsApi.applyMigration).mock.calls[0][0]).toEqual([CODEX_KEY.id]);++ await activate(handle);+ const dialog = screen.queryByRole('dialog');+ if (dialog) {+ expect(within(dialog).queryByRole('button', { name: /Start migration/ })).toBeNull();+ }+ expect(modelsApi.applyMigration).toHaveBeenCalledTimes(1);+ });++ it('refuses a batch the engine behind it can no longer take, without taking the review away', async () => {+ // A take-over migrates keys INTO the Hub. An engine that stopped being readable+ // while the review was open has nothing to migrate them into — and this is a write+ // like any other, so it is refused at the submit and not only at the door.+ serve({ scan: [CODEX_KEY] });+ const { handle, show } = renderScreen();+ await settled();+ const user = userEvent.setup();++ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionImport'));+ await activate(handle);+ await screen.findByRole('dialog');++ await show({ runtimeRead: unreadRegion<RuntimeDependency>() });+ const start = () => within(screen.getByRole('dialog')).getByRole<HTMLButtonElement>(+ 'button', { name: /Start migration/ },+ );+ expect(start().disabled).toBe(true);+ await user.click(start());+ expect(modelsApi.applyMigration).not.toHaveBeenCalled();++ // What the person was reading is still there, still says what it found, and can+ // still be left. Closing it for them would be a different answer than refusing+ // the write, and would lose the one place the offer is spelled out.+ expect(within(screen.getByRole('dialog')).getByText(CODEX_KEY.masked_detail!)).toBeTruthy();+ await user.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Not now' }));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ // Nothing was consumed: the offer is exactly the one it was.+ expect(lastAction()).toMatchObject({ labelKey: 'onboarding.providers.actionImport', labelArgs: { count: 1 } });+ });++ it('refuses a take-over the host cannot install an engine for, and still writes a key', async () => {+ // A running engine on a host with no published runtime asset for its platform.+ // The take-over is the one write on this screen with an install still waiting+ // behind it: `apply_native_migration` ensures the runtime dependency before it+ // touches a credential, and that ensure refuses an unsupported platform ahead of+ // the branch that would have reused the engine already up — so the batch comes+ // back 422 however healthy the engine is.+ serve({ runtime: UNSUPPORTED_RUNNING, scan: [CODEX_KEY] });+ const { handle } = renderScreen({ runtimeRead: readyRegion(UNSUPPORTED_RUNNING) });+ await settled();+ const user = userEvent.setup();++ // The offer is still made and the review still opens. What the scan found is+ // worth reading, and Settings is where it can be acted on.+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionImport'));+ await activate(handle);+ const review = await screen.findByRole('dialog');+ expect(within(review).getByText(CODEX_KEY.masked_detail!)).toBeTruthy();+ const start = within(review).getByRole<HTMLButtonElement>('button', { name: /Start migration/ });+ expect(start.disabled).toBe(true);+ await user.click(start);+ expect(modelsApi.applyMigration).not.toHaveBeenCalled();+ await user.click(within(review).getByRole('button', { name: 'Not now' }));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());++ // And nothing else is narrowed. A key is a write to an engine that is up, which+ // this one is; refusing it because a fresh install would fail would strand a+ // working machine on a boundary that is not about writing.+ vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValue({+ source: source({ id: 'src_new', vendor: 'custom' }),+ added_to: [],+ adopted_by: [],+ });+ await user.click(cards()[2]);+ const add = await screen.findByRole('dialog');+ await user.click(within(add).getByRole('button', { name: 'API Key' }));+ await user.type(within(add).getByLabelText('Base URL'), 'https://api.example/v1');+ await user.type(within(add).getByLabelText('API key'), 'sk-live-1');+ await user.click(within(add).getByRole('button', { name: 'Add' }));++ await waitFor(() => expect(modelsApi.createApiKeySource).toHaveBeenCalledTimes(1));+ });++ it('settles a batch it had already sent, whatever the screen admits by the time it answers', async () => {+ serve({ scan: [CODEX_KEY] });+ const gate = deferred<void>();+ // The server's own behaviour, held open at the wire: the batch is on its way and+ // the answer is what this case gets to choose the moment for.+ vi.mocked(modelsApi.applyMigration).mockImplementationOnce(async (ids) => {+ applied.push([...ids]);+ await gate.promise;+ server.scan = server.scan.filter((row) => !ids.includes(row.id));+ server.sources = [...server.sources, source({ id: 'src_mig_codex', vendor: 'openai' })];+ return { applied: ids.length, sources: [] };+ });+ const { handle, show } = renderScreen();+ await settled();+ const user = userEvent.setup();++ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionImport'));+ await activate(handle);+ await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: /Start migration/ }));+ await waitFor(() => expect(applied).toHaveLength(1));++ // The engine goes unreadable while that batch is in flight. It is already on the+ // server's side of the wire: permission governs the next write, never the delivery+ // of one that happened, and dropping the report would leave keys migrated with+ // nothing on screen saying so.+ await show({ runtimeRead: unreadRegion<RuntimeDependency>() });+ await act(async () => { gate.resolve(); });++ expect(await screen.findByText('Migrated 1 API key into Model Hub')).toBeTruthy();+ expect(modelsApi.applyMigration).toHaveBeenCalledTimes(1);+ // Reported once, counted once — and a screen that no longer admits a write does+ // not offer the spent batch again either.+ await waitFor(() => expect(lastAction().labelKey).not.toBe('onboarding.providers.actionImport'));+ });+});++describe('ProvidersScreen — the engine', () => {+ it('resumes the install the first recovery left undone, once', async () => {+ serve({ runtime: runtimeOf('not_installed') });+ const install = deferred<RuntimeDependency>();+ vi.mocked(modelsApi.installRuntime).mockReturnValue(install.promise);+ const { handle } = renderScreen({ runtimeRead: readyRegion(runtimeOf('not_installed')) });++ await waitFor(() => expect(gatewayCard().dataset.state).toBe('installing'));+ // Nothing else is possible while the engine is coming up, and the shell is+ // told so rather than left to infer it.+ expect(lastAction()).toMatchObject({+ labelKey: 'onboarding.providers.actionConnecting',+ disabled: true,+ busy: true,+ icon: 'spinner',+ });+ // A press that arrives anyway does nothing at all.+ await activate(handle);+ expect(navigated).toEqual([]);+ expect(screen.queryByRole('dialog')).toBeNull();++ await act(async () => { install.resolve(runtimeOf('not_started')); });++ await waitFor(() => expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(gatewayCard().dataset.state).not.toBe('installing'));+ expect(modelsApi.installRuntime).toHaveBeenCalledTimes(1);+ // An engine that just came up can answer reads that failed before it did.+ await waitFor(() => expect(modelsApi.listSources).toHaveBeenCalledTimes(2));+ });++ it('starts an installed engine even where installing one is unsupported', async () => {+ const stopped = { ...UNSUPPORTED, status: { ...UNSUPPORTED.status, health: 'not_started' as const } };+ serve({ runtime: stopped });+ renderScreen({ runtimeRead: readyRegion(stopped) });++ await waitFor(() => expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1));+ // Refusing to start a working engine on an installation technicality would+ // strand it.+ expect(modelsApi.installRuntime).not.toHaveBeenCalled();+ });++ it('says installation is not possible here rather than attempting it', async () => {+ serve({ runtime: UNSUPPORTED });+ renderScreen({ runtimeRead: readyRegion(UNSUPPORTED) });+ await settled();++ await waitFor(() => expect(gatewayCard().dataset.state).toBe('unsupported'));+ expect(modelsApi.installRuntime).not.toHaveBeenCalled();+ expect(modelsApi.startRuntime).not.toHaveBeenCalled();+ expect(within(gatewayCard()).getByRole('button', { name: 'Retry' })).toBeTruthy();+ // On its own a recheck is a button that will keep saying no. The guide is the+ // other half of the answer: what would have to change for it to say yes — so it+ // is the installation page the contract names, not the docs root, which leaves+ // someone to find that page themselves from the one screen they cannot get past.+ const guide = within(gatewayCard()).getByRole('link', { name: 'View installation guide' });+ expect(guide.getAttribute('href'))+ .toBe('https://github.com/avibe-bot/avibe/blob/master/docs/INSTALL_FOR_AI.md');+ expect(guide.getAttribute('rel')).toContain('noopener');+ });++ it('sends a Chinese reader to the guide that is written in Chinese', async () => {+ // The guide ships a translated counterpart. Handing someone reading Chinese the+ // English file is a worse answer than the one above.+ serve({ runtime: UNSUPPORTED });+ await act(async () => { await i18n.changeLanguage('zh'); });+ try {+ renderScreen({ runtimeRead: readyRegion(UNSUPPORTED) });+ await settled();++ await waitFor(() => expect(gatewayCard().dataset.state).toBe('unsupported'));+ const guide = within(gatewayCard()).getByRole('link', { name: '查看安装指南' });+ expect(guide.getAttribute('href'))+ .toBe('https://github.com/avibe-bot/avibe/blob/master/docs/INSTALL_FOR_AI_ZH.md');+ } finally {+ await act(async () => { await i18n.changeLanguage('en'); });+ }+ });++ it('offers no guide for a failure a guide would not explain', async () => {+ serve({ runtime: runtimeOf('not_started') });+ vi.mocked(modelsApi.startRuntime).mockRejectedValue(new ApiCallError('engine_down', 'down'));+ renderScreen({ runtimeRead: readyRegion(runtimeOf('not_started')) });++ await waitFor(() => expect(gatewayCard().dataset.state).toBe('failed'));+ // The engine is installable here; it did not start. Pointing at installation+ // instructions would send someone to fix something that is not broken.+ expect(within(gatewayCard()).queryByRole('link')).toBeNull();+ expect(within(gatewayCard()).getByRole('button', { name: 'Retry' })).toBeTruthy();+ });++ it('reports a failed step on the card it is about, and retries it on the read that answers', async () => {+ serve({ runtime: runtimeOf('not_started') });+ vi.mocked(modelsApi.startRuntime).mockRejectedValueOnce(new ApiCallError('engine_down', 'down'));+ const { show } = renderScreen({ runtimeRead: readyRegion(runtimeOf('not_started')) });++ await waitFor(() => expect(gatewayCard().dataset.state).toBe('failed'));+ expect(gatewayCard().dataset.failedStep).toBe('start');+ // A failed start moved supervisor health too. The shell's read still describes+ // the health the engine had before the attempt, so it is asked again here.+ await waitFor(() => expect(retrySetup).toHaveBeenCalledTimes(1));++ await userEvent.setup().click(within(gatewayCard()).getByRole('button', { name: 'Retry' }));++ // The press asks the shell for the read and stops there. Starting a second attempt+ // now would run it against the only read a press can see — the one the failure was+ // read from — so the failure stays on the card until something actually changes.+ expect(retrySetup).toHaveBeenCalledTimes(2);+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);+ expect(gatewayCard().dataset.state).toBe('failed');++ // The shell's read STARTS. This is what it really hands down first: the previous+ // value degraded to 「refreshing」, and a configuration back to unknown while it is+ // re-read. None of it is an answer, and a request spent here is a request lost —+ // the read lands a moment later saying the engine is stopped, and nothing starts it.+ await show({+ capability: 'pending',+ gatewayEnabled: null,+ runtimeRead: beginRegionRead(readyRegion(runtimeOf('not_started'))),+ });+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);+ expect(gatewayCard().dataset.state).toBe('failed');++ // The shell answers. The answer is what re-arms the attempt.+ await show({+ capability: 'enabled',+ gatewayEnabled: true,+ runtimeRead: readyRegion(runtimeOf('not_started')),+ });++ await waitFor(() => expect(modelsApi.startRuntime).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(gatewayCard().dataset.state).not.toBe('failed'));+ // Three reads, not two: the press asked for one, and the engine moving asked for+ // another. That last one is the only thing that turns the card and the footer+ // around — the attempt's own success is not the machine answering.+ await waitFor(() => expect(retrySetup).toHaveBeenCalledTimes(3));+ });++ it('stays retryable when the answer still calls for a resume after a spent attempt', async () => {+ // The local attempt succeeded — the engine started, there was nothing to adopt —+ // and the read that followed it still says stopped. That read is the authority+ // here, and 「my attempt did not fail」 is not evidence against it. With the+ // attempt already spent for this demand, an idle card leaves nothing on the+ // screen that could start the engine while Continue stays blocked for a reason+ // the card does not give.+ serve({ runtime: runtimeOf('not_started') });+ const { show } = renderScreen({ runtimeRead: readyRegion(runtimeOf('not_started')) });++ await waitFor(() => expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1));+ // The attempt asks the shell for the read that would turn the card around.+ await waitFor(() => expect(retrySetup).toHaveBeenCalledTimes(1));++ // And the shell's answer is 「still stopped」.+ await show({ runtimeRead: readyRegion(runtimeOf('not_started')) });++ await waitFor(() => expect(gatewayCard().dataset.state).toBe('failed'));+ // Retryable, not retried: a demand this screen has already attempted once must+ // not re-arm itself, or a machine the engine keeps dying on becomes a loop of+ // installs nobody asked for.+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);+ // No step is named, because nothing failed. What the card reports is that the+ // engine is not ready and that asking again is possible.+ expect(gatewayCard().dataset.failedStep).toBeUndefined();++ await userEvent.setup().click(within(gatewayCard()).getByRole('button', { name: 'Retry' }));++ // Same rule as a failed attempt: the press asks for a read, and only the answer+ // arms anything.+ expect(retrySetup).toHaveBeenCalledTimes(2);+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);++ // And the card the press was made on is still there while that read is in+ // flight. This is the state the shell really hands down first — the previous+ // value degraded to 「refreshing」 — and a verdict recomputed from it would take+ // the Retry away from under the person who just pressed it and replace it with+ // an idle card claiming the engine is fine.+ await show({ runtimeRead: beginRegionRead(readyRegion(runtimeOf('not_started'))) });+ expect(gatewayCard().dataset.state).toBe('failed');+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);++ await show({ runtimeRead: readyRegion(runtimeOf('not_started')) });+ await waitFor(() => expect(modelsApi.startRuntime).toHaveBeenCalledTimes(2));+ });++ it('admits one engine mutation at a time, whatever else on the screen has failed', async () => {+ serve({ runtime: runtimeOf('not_installed') });+ const install = deferred<RuntimeDependency>();+ vi.mocked(modelsApi.installRuntime).mockReturnValue(install.promise);+ vi.mocked(modelsApi.scanMigration).mockRejectedValue(new Error('offline'));+ renderScreen({ runtimeRead: readyRegion(runtimeOf('not_installed')) });++ await waitFor(() => expect(gatewayCard().dataset.state).toBe('installing'));+ await waitFor(() => expect(summary()?.dataset.tone).toBe('error'));+ const user = userEvent.setup();+ const retry = () => within(summary()!).getByRole('button', { name: 'Retry' });+ await user.click(retry());+ await user.click(retry());++ // The install is unsettled and still owns the engine. The broken sentence has its+ // own recovery, and pressing it — twice — reaches the reads and nothing else: a+ // second install over one the server is still performing is not a retry.+ await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalledTimes(3));+ expect(modelsApi.installRuntime).toHaveBeenCalledTimes(1);+ expect(modelsApi.startRuntime).not.toHaveBeenCalled();++ // Nor can a write start around the side of the footer: every add control obeys the+ // same admission the footer publishes.+ await user.click(cards()[cards().length - 1]);+ expect(screen.queryByRole('dialog')).toBeNull();++ await act(async () => { install.resolve(runtimeOf('not_started')); });++ await waitFor(() => expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1));+ expect(modelsApi.installRuntime).toHaveBeenCalledTimes(1);+ });++ it('cannot resume a gateway the answer says is off', async () => {+ serve({ runtime: runtimeOf('not_started') });+ vi.mocked(modelsApi.startRuntime).mockRejectedValue(new ApiCallError('engine_down', 'down'));+ const { show } = renderScreen({ runtimeRead: readyRegion(runtimeOf('not_started')) });++ await waitFor(() => expect(gatewayCard().dataset.state).toBe('failed'));+ await userEvent.setup().click(within(gatewayCard()).getByRole('button', { name: 'Retry' }));++ // The answer comes back with the Hub turned off. A retry asks for the current+ // configuration; it carries no authorization of its own, and a stopped intent is+ // not something this screen may start around.+ await show({ gatewayEnabled: false, runtimeRead: readyRegion(runtimeOf('not_started')) });+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);+ expect(gatewayCard().dataset.state).toBe('failed');++ // Enabled again later is a new answer, not a queued press.+ await show({ gatewayEnabled: true, runtimeRead: readyRegion(runtimeOf('not_started')) });+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);+ });++ it('refuses a write against an engine nobody can read, however much else is known', async () => {+ serve();+ const { handle, show } = renderScreen();+ await settled();+ // Awaited, not read once: the scan and the inventory are two reads, and the action+ // this case starts from is the one published after both have answered.+ await waitFor(() => expect(lastAction())+ .toMatchObject({ labelKey: 'onboarding.providers.actionAdd', disabled: false }));++ // The inventory is still an answer and the stage still draws it. What stopped+ // being known is the engine the add would be written to — and a write needs that,+ // not just an idle screen and a source list.+ await show({ runtimeRead: unreadRegion<RuntimeDependency>() });+ expect(cards()).toHaveLength(3);+ await waitFor(() => expect(lastAction())+ .toMatchObject({ labelKey: 'onboarding.providers.actionAdd', disabled: true }));++ // Not through the card, and not through the footer either: one admission, wherever+ // the control is drawn.+ await userEvent.setup().click(cards()[2]);+ expect(screen.queryByRole('dialog')).toBeNull();+ await activate(handle);+ expect(screen.queryByRole('dialog')).toBeNull();+ // And the recovery is where the failure is, on the card that can do something.+ expect(within(gatewayCard()).getByRole('button', { name: 'Retry' })).toBeTruthy();+ });++ it('still asks again for the read that failed while the engine is unknown too', async () => {+ // Two unknowns, two different answers. Asking again is a read: it writes nothing,+ // so an unreadable engine is no reason to withhold it. What it may not do is turn+ // into a write once the inventory answers.+ serve();+ vi.mocked(modelsApi.listSources).mockRejectedValue(new Error('offline'));+ const { handle } = renderScreen({ runtimeRead: unreadRegion<RuntimeDependency>() });+ await settled();+ await waitFor(() => expect(lastAction()).toMatchObject({ labelKey: 'common.retry', disabled: false }));++ const before = vi.mocked(modelsApi.listSources).mock.calls.length;+ vi.mocked(modelsApi.listSources)+ .mockImplementation(async () => [source({ id: 'src_zhipu', vendor: 'zhipuai' })]);+ await activate(handle);++ await waitFor(() => expect(modelsApi.listSources).toHaveBeenCalledTimes(before + 1));+ await waitFor(() => expect(cardFor('zhipuai').dataset.state).toBe('connected'));+ expect(screen.queryByRole('dialog')).toBeNull();+ // The inventory answered; the engine still has not. So the screen names what is+ // next and goes on refusing it.+ await waitFor(() => expect(lastAction())+ .toMatchObject({ labelKey: 'onboarding.providers.actionContinue', disabled: true }));+ });++ it('refuses the write an open dialog was for when the answer beneath it changes', async () => {+ serve();+ vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValue({+ source: source({ id: 'src_new', vendor: 'custom' }),+ added_to: [],+ adopted_by: [],+ });+ const { show } = renderScreen();+ await settled();+ const user = userEvent.setup();++ await user.click(cards()[2]);+ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('button', { name: 'API Key' }));+ await user.type(within(dialog).getByLabelText('Base URL'), 'https://api.example/v1');+ await user.type(within(dialog).getByLabelText('API key'), 'sk-live-1');+ const add = () => within(screen.getByRole('dialog')).getByRole<HTMLButtonElement>(+ 'button', { name: 'Add' },+ );+ expect(add().disabled).toBe(false);++ // The engine stopped being readable while the form was being filled. Admission is+ // not only a door: the dialog stays, because what is typed in it is the person's+ // and the read behind it may come back — and the write is what stops.+ await show({ runtimeRead: unreadRegion<RuntimeDependency>() });+ expect(screen.queryByRole('dialog')).not.toBeNull();+ expect(add().disabled).toBe(true);+ await user.click(add());+ expect(modelsApi.createApiKeySource).not.toHaveBeenCalled();++ // The read comes back and says the engine is serving. Nothing was lost.+ await show({ runtimeRead: readyRegion(runtimeOf('ok')) });+ expect(add().disabled).toBe(false);+ await user.click(add());+ await waitFor(() => expect(modelsApi.createApiKeySource).toHaveBeenCalledTimes(1));+ });++ it('refuses the write of a dialog the wizard has hidden, and takes it back on return', async () => {+ serve();+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValue({+ source: source({ id: 'src_new', vendor: 'custom' }),+ added_to: [],+ adopted_by: [],+ });+ const { show } = renderScreen();+ await settled();+ const user = userEvent.setup();++ await user.click(cards()[2]);+ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('button', { name: 'API Key' }));+ await user.type(within(dialog).getByLabelText('Base URL'), 'https://api.example/v1');+ await user.type(within(dialog).getByLabelText('API key'), 'sk-live-1');+ const add = () => within(screen.getByRole('dialog')).getByRole<HTMLButtonElement>(+ 'button', { name: 'Add' },+ );++ // The wizard moved somewhere else with this open. A screen nobody is looking at+ // does not act — and a write is the strongest thing it could do, so it is the+ // first thing that stops. What was typed is still the person's.+ await show({ active: false });+ expect(add().disabled).toBe(true);+ await user.click(add());+ expect(create).not.toHaveBeenCalled();++ await show({ active: true });+ expect(add().disabled).toBe(false);+ await user.click(add());+ await waitFor(() => expect(create).toHaveBeenCalledTimes(1));+ });++ it('refuses a write the configuration does not admit, however healthy the engine is', async () => {+ serve();+ const { handle, show } = renderScreen();+ await settled();+ const user = userEvent.setup();++ // The runtime is up and the card goes on saying so, truthfully: health is a fact+ // about the machine, not a permission. What is gone is the configuration that+ // admits this flow to the Hub — and every write here is a write to the Hub.+ await show({ gatewayEnabled: false, runtimeRead: readyRegion(runtimeOf('ok')) });+ await waitFor(() => expect(lastAction())+ .toMatchObject({ labelKey: 'onboarding.providers.actionAdd', disabled: true }));+ await user.click(cards()[2]);+ expect(screen.queryByRole('dialog')).toBeNull();+ await activate(handle);+ expect(screen.queryByRole('dialog')).toBeNull();++ // Unknown is not authorization either. A capability still being read and a saved+ // intent nobody has answered are two reasons to wait, not two halves of a yes.+ await show({ capability: 'pending', gatewayEnabled: null, runtimeRead: readyRegion(runtimeOf('ok')) });+ await user.click(cards()[2]);+ expect(screen.queryByRole('dialog')).toBeNull();+ });++ it('ends a retry on the answer that failed, not on an unrelated later one', async () => {+ serve({ runtime: runtimeOf('not_started') });+ vi.mocked(modelsApi.startRuntime).mockRejectedValue(new ApiCallError('engine_down', 'down'));+ const { show } = renderScreen({ runtimeRead: readyRegion(runtimeOf('not_started')) });++ await waitFor(() => expect(gatewayCard().dataset.state).toBe('failed'));+ await userEvent.setup().click(within(gatewayCard()).getByRole('button', { name: 'Retry' }));+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);++ // The read the retry asked for fails, and one load failure takes everything with+ // it: no capability, no saved intent, an unread machine. That is a complete answer+ // — 「不知道」 — and nothing more is coming unless someone asks again. Filing it+ // under 「still unknown」 would leave the press waiting to be spent on whatever+ // read landed next, which is not the one it asked for.+ await show({ capability: 'pending', gatewayEnabled: null, runtimeRead: unreadRegion<RuntimeDependency>() });+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);++ // Something else re-reads the machine much later and finds it installed and idle.+ await show({ capability: 'enabled', gatewayEnabled: true, runtimeRead: readyRegion(runtimeOf('not_started')) });+ await waitFor(() => expect(gatewayCard()).toBeTruthy());+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);+ });++ it('refuses to continue into a screen with no engine behind it', async () => {+ // The next screen picks a model per assistant out of what the Hub supplies, so+ // arriving with a stopped engine is arriving at an empty screen with no way to+ // tell why. The label does not change; what went wrong stays on the card.+ const stopped = { ...UNSUPPORTED, status: { ...UNSUPPORTED.status, health: 'not_started' as const } };+ serve({ runtime: stopped, sources: [source({ id: 'src_zhipu', vendor: 'zhipu' })] });+ vi.mocked(modelsApi.startRuntime).mockRejectedValue(new ApiCallError('engine_down', 'down'));+ const { handle } = renderScreen({ runtimeRead: readyRegion(stopped) });+ await settled();++ await waitFor(() => expect(lastAction()).toMatchObject({+ labelKey: 'onboarding.providers.actionContinue',+ disabled: true,+ busy: false,+ }));++ await activate(handle);+ expect(navigated).toEqual([]);+ });++ it('continues once the engine is really serving', async () => {+ serve({ sources: [source({ id: 'src_zhipu', vendor: 'zhipu' })] });+ const { handle } = renderScreen();+ await settled();++ await waitFor(() => expect(lastAction()).toMatchObject({+ labelKey: 'onboarding.providers.actionContinue',+ disabled: false,+ }));++ await activate(handle);+ expect(navigated).toEqual(['assistants']);+ });++ it('treats a machine with no CLI as nothing to adopt, not as a failure', async () => {+ serve({+ agents: [supply({ backend: 'codex', cli_present: false }), supply({ backend: 'opencode', cli_present: false })],+ runtime: runtimeOf('not_installed'),+ });+ renderScreen({ runtimeRead: readyRegion(runtimeOf('not_installed')) });+ await settled();++ // The engine is ensured whatever there is to adopt. Nothing to adopt is not+ // nothing to do: the next screen picks a model per assistant out of what the Hub+ // supplies, so a machine with no CLI still arrives there needing one behind it.+ await waitFor(() => expect(modelsApi.installRuntime).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1));+ // Presence is read fresh: a CLI installed while setup was open is exactly the+ // case a cached list would get wrong.+ await waitFor(() => expect(modelsApi.refreshAgentPresence).toHaveBeenCalled());+ await waitFor(() => expect(gatewayCard().dataset.state).toBe('idle'));+ });++ it('still ensures the engine on a machine where every CLI is already adopted', async () => {+ // The other exit that used to strand this screen. `resumeGatewayAdoption` returns+ // success without touching the runtime when its backend is already in hub mode,+ // so the engine stayed missing: card idle, no retry beside it, Continue blocked+ // on a read that never moves.+ serve({+ agents: [supply({ backend: 'codex', mode: 'hub' }), supply({ backend: 'claude', mode: 'hub' })],+ runtime: runtimeOf('not_installed'),+ });+ renderScreen({ runtimeRead: readyRegion(runtimeOf('not_installed')) });+ await settled();++ await waitFor(() => expect(modelsApi.installRuntime).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(gatewayCard().dataset.state).toBe('idle'));+ });++ it('does nothing at all while the screen is hidden', async () => {+ serve({ runtime: runtimeOf('not_installed') });+ renderScreen({ active: false, runtimeRead: readyRegion(runtimeOf('not_installed')) });++ // Give every effect the chance a mounted-but-hidden screen would have.+ await act(async () => { await Promise.resolve(); });++ expect(modelsApi.scanMigration).not.toHaveBeenCalled();+ expect(modelsApi.listSources).not.toHaveBeenCalled();+ expect(modelsApi.installRuntime).not.toHaveBeenCalled();+ expect(modelsApi.startRuntime).not.toHaveBeenCalled();+ // No claim on the shell's action either: the hidden screen is not the one+ // the button belongs to.+ expect(actions).toEqual([]);+ expect(screen.queryByText(/API key to import/)).toBeNull();+ });++ it('lets an install it started finish after the wizard hides the screen', async () => {+ // The mutation is on the server either way. Abandoning the attempt when the+ // screen is merely hidden leaves the card stuck on 「正在安装」, the shell's read+ // describing a machine that has since changed, and nothing to reconcile either.+ serve({ runtime: runtimeOf('not_installed') });+ const install = deferred<RuntimeDependency>();+ vi.mocked(modelsApi.installRuntime).mockReturnValue(install.promise);+ const { show } = renderScreen({ runtimeRead: readyRegion(runtimeOf('not_installed')) });++ await waitFor(() => expect(modelsApi.installRuntime).toHaveBeenCalledTimes(1));+ await show({ active: false });++ await act(async () => { install.resolve(runtimeOf('not_started')); });+ await waitFor(() => expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1));+ // The engine moved, so the read that describes it is asked for again.+ await waitFor(() => expect(retrySetup).toHaveBeenCalled());++ // And coming back finds the finished attempt rather than launching a second+ // install over it.+ await show({ active: true });+ await act(async () => { await Promise.resolve(); });+ expect(modelsApi.installRuntime).toHaveBeenCalledTimes(1);+ expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1);+ });++ it('installs once under a StrictMode replay, and does not abandon what it started', async () => {+ // The app mounts under StrictMode, which runs every effect's cleanup and then the+ // effect again. Both halves of the attempt have to survive that: the guard, or it+ // installs twice; the attempt's identity, or the replay's cleanup discards a+ // mutation the server is performing and the card never leaves 「正在安装」.+ serve({ runtime: runtimeOf('not_installed') });+ const install = deferred<RuntimeDependency>();+ vi.mocked(modelsApi.installRuntime).mockReturnValue(install.promise);+ const handle = React.createRef<SetupScreenHandle | null>();+ render(+ <React.StrictMode>+ <Harness handle={handle} runtimeRead={readyRegion(runtimeOf('not_installed'))} />+ </React.StrictMode>,+ );++ await waitFor(() => expect(modelsApi.installRuntime).toHaveBeenCalledTimes(1));+ await act(async () => { install.resolve(runtimeOf('not_started')); });++ await waitFor(() => expect(modelsApi.startRuntime).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(gatewayCard().dataset.state).toBe('idle'));+ expect(modelsApi.installRuntime).toHaveBeenCalledTimes(1);+ });++ it('says the engine could not be read rather than showing an idle one', async () => {+ // The read failed and asking again is worth doing. Folded into 「waiting」 this+ // renders as the idle card: the engine looks fine while Continue stays disabled+ // for a reason nothing on screen gives.+ serve();+ renderScreen({ runtimeRead: unreadRegion<RuntimeDependency>() });+ await settled();++ expect(gatewayCard().dataset.state).toBe('failed');+ expect(within(gatewayCard()).getByText('Model Hub is not ready. Try again.')).toBeTruthy();+ // The runtime-unread copy, never the unsupported notice: nothing has been read+ // about this host, so nothing can be said about what it supports.+ expect(within(gatewayCard()).queryByRole('link')).toBeNull();+ expect(modelsApi.installRuntime).not.toHaveBeenCalled();++ await userEvent.setup().click(within(gatewayCard()).getByRole('button', { name: 'Retry' }));+ // The shell owns the read; this screen owns the attempt. Both are re-armed,+ // because either one could be what is stale.+ expect(retrySetup).toHaveBeenCalled();+ });++ it('stays quiet about a failed read there is nothing to ask again about', async () => {+ // The shell owns the read and has declared this one beyond retrying. A Retry+ // that cannot help is a worse answer than none.+ serve();+ renderScreen({ runtimeRead: unreadRegion<RuntimeDependency>(false) });+ await settled();++ expect(gatewayCard().dataset.state).toBe('idle');+ expect(within(gatewayCard()).queryByRole('button')).toBeNull();+ });++ it('waits rather than acting on a configuration that turned the gateway off', async () => {+ serve({ runtime: runtimeOf('not_installed', { enabled: false }) });+ renderScreen({ gatewayEnabled: false, runtimeRead: readyRegion(runtimeOf('not_installed', { enabled: false })) });++ await act(async () => { await Promise.resolve(); });++ // Setup never silently re-enables a disabled configuration, and never reads+ // the machine as if it had.+ expect(modelsApi.installRuntime).not.toHaveBeenCalled();+ expect(modelsApi.scanMigration).not.toHaveBeenCalled();+ expect(gatewayCard().dataset.state).toBe('idle');+ });+});diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.tsxnew file mode 100644index 000000000..634b35bb4--- /dev/null+++ b/ui/src/components/onboarding/providers/ProvidersScreen.tsx@@ -0,0 +1,782 @@+// Setup's second screen: where models come from, and the one picture that explains+// why that question has a single answer.+//+// The screen is a diagram, not a form. Providers at the top, the gateway in the+// middle, the assistants at the bottom, wired together — so "add a key once and every+// assistant can use it" is something you SEE before you read it. Everything on the+// stage is therefore derived from one scan and one source list; two reads of the same+// machine would let the cards, the sentence and the button disagree about it.+//+// What this file owns is composition and lifecycle. It owns no migration semantics+// (the shipped takeover does), no install-and-start sequence (`runtimeLifecycle` does),+// no adoption sequence (`gatewayAdoption` does), no credential write (the add dialog+// does), no derivation (`providerStage.ts` does) and no primary button (the shell does,+// through `onActionChange` and `activate`). Ordering those two runtime sequences is+// composition, and therefore is this file's: the engine has to be up whether or not+// there is an assistant to adopt.+import * as React from 'react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import {+ createAgentCollectionReadAuthority,+ createSourceCollectionReadAuthority,+} from '@/components/settings/models/collectionReadAuthority';+import { resumeGatewayAdoption, type GatewayAdoptionFailure } from '@/components/settings/models/gatewayAdoption';+import { MigrationDialog } from '@/components/settings/models/MigrationDialog';+import { isImportableKey } from '@/components/settings/models/migrationScan';+import { modelsApi, type SourceCreated } from '@/components/settings/models/modelsApi';+import {+ installAndStartStep,+ resumeInstallAndStartRuntime,+} from '@/components/settings/models/runtimeLifecycle';+import type { AgentBackend, RuntimeDependency, Source } from '@/components/settings/models/types';++import { ImportKeysNotice } from '../ImportKeysNotice';+import { useOnboardingMotion } from '../motion';+import {+ setupCanAttemptInstall,+ setupNavigationReady,+ type SetupScreenHandle,+ type SetupScreenProps,+} from '../setupFlow';+import { AddSourceDialog } from './AddSourceDialog';+import { DestinationRow } from './DestinationRow';+import { GatewayCard, type GatewayPhase } from './GatewayCard';+import { AddMoreCard, ProviderCard } from './ProviderCard';+import { SupplyWires } from './SupplyWires';+import {+ addedThroughMoreCount,+ adoptionBackend,+ defaultSelection,+ gatewayEvidenceSettled,+ gatewayIntent,+ offeredImportKeys,+ pendingImportRows,+ providerAction,+ providerSetupAction,+ providerSlots,+ providerSummary,+ reconcileSelection,+ slotSelected,+ toggleSlotSelection,+ unlistedDetected,+ usableSource,+ type ProviderSlot,+} from './providerStage';++// The tier tokens this screen is measured in, and the shell classes it renders+// (`.onboarding-setup`, `.onboarding-stage`, `.onboarding-heading`), are declared+// there. Today the Wizard always mounts an earlier step that imports it, so the+// dependency is satisfied by accident; a screen reached first — a handoff, a+// deep link — would render untiered without this line.+import '../onboarding.css';+import '../onboarding-providers.css';++/** The wires' first arrival, staggered so the fan-in lands before the fan-out leaves.+ * Two numbers rather than a timeline: each band's own 3-wire stagger is the CSS's. */+const INBOUND_DELAY_MS = 120;+const OUTBOUND_DELAY_MS = 570;++/** A resume attempt this screen started. `step` is the step currently being attempted:+ * it opens on what the authoritative read called for and follows the lifecycle+ * helper's own report across the install/start boundary. */+type GatewayRun =+ /** Nothing outstanding: either nothing has been attempted for the current+ * authorization, or one is about to be armed for it. */+ | { kind: 'idle' }+ | { kind: 'running'; step: 'install' | 'start' }+ /**+ * Every step reported success, and the read this screen asked for on the strength+ * of that is outstanding. Kept apart from `idle` because success is not a claim+ * that the engine is ready — only the shell's read says that — and `against` is+ * the evidence the request was made on, so the answer can be told apart from the+ * stale read the attempt itself ran against. It is a waiting room: the answer+ * turns it into one of the states above or below.+ */+ | { kind: 'settled'; against: GatewayEvidence }+ /** A dead end with a Retry beside it. `step` names the step that failed where one+ * did, and is `null` where none did — every step reported success and the machine+ * the shell then read still asks to be resumed. There is nothing to name there,+ * and naming one would be a report of a failure that did not happen. */+ | { kind: 'failed'; step: GatewayAdoptionFailure['step'] | null };++/** Everything the shell hands down that decides whether an attempt is authorized at+ * all: the runtime read and the two configuration facts beside it. A retry holds the+ * set it was pressed against, and is answered when any part of it is replaced. */+type GatewayEvidence = Pick<SetupScreenProps, 'runtimeRead' | 'gatewayEnabled' | 'capability'>;++/**+ * Whether the shell has ANSWERED a read this screen asked for.+ *+ * Two things have to be true, and they are different things. The evidence must have+ * moved off what the request was made against — the only read a request can see is+ * the one it was made from, so that read is never its answer. And what replaced it+ * must be an answer at all: the shell reports a read STARTING before it reports what+ * it found — `refreshing` over the old value, a configuration back to 「pending」 —+ * and treating one of those as the reply loses the request the person is waiting on.+ */+const gatewayReadAnswered = (against: GatewayEvidence | null, now: GatewayEvidence): boolean =>+ (against === null+ || against.runtimeRead !== now.runtimeRead+ || against.gatewayEnabled !== now.gatewayEnabled+ || against.capability !== now.capability)+ && gatewayEvidenceSettled(now);++/** Locale-correct enumeration without inventing a separator string for each language.+ * Falls back to the ASCII list on a runtime without `Intl.ListFormat`. */+const formatNames = (names: readonly string[], locale: string): string => {+ try {+ return new Intl.ListFormat(locale, { style: 'narrow', type: 'unit' }).format([...names]);+ } catch {+ return names.join(', ');+ }+};++export const ProvidersScreen = React.forwardRef<SetupScreenHandle, SetupScreenProps>(+ function ProvidersScreen({+ active,+ capability,+ gatewayEnabled,+ runtimeRead,+ onRetrySetup,+ flowState,+ setFlowState,+ onActionChange,+ onNavigate,+ }, ref) {+ const { t, i18n } = useTranslation();+ const motion = useOnboardingMotion();+ const attachMotion = motion.ref;++ // The stage is held as an ELEMENT, not a ref: `SupplyWires` measures inside it and+ // a ref object would still be empty when the children first lay out.+ const [stage, setStage] = React.useState<HTMLElement | null>(null);+ const attachStage = React.useCallback((element: HTMLDivElement | null) => {+ setStage(element);+ attachMotion(element);+ }, [attachMotion]);++ // One owner per collection, for the whole life of the screen: the add dialog+ // settles an unknown write against the same generation this screen reads.+ const [sourceReads] = React.useState(createSourceCollectionReadAuthority);+ const [agentReads] = React.useState(createAgentCollectionReadAuthority);++ const [sources, setSources] = React.useState<Source[]>([]);+ // Whether the list above is an answer. It starts as neither empty nor absent but+ // unknown, because that is what it is before the first read lands. It tracks the+ // SOURCE read alone: a scan that failed says nothing about whether a credential+ // exists, and only this read can answer that.+ const [sourceRead, setSourceRead] = React.useState<'reading' | 'unreadable' | 'read'>('reading');+ const [scanFailed, setScanFailed] = React.useState(false);+ // The sentence is about the picture, which either read can leave incomplete.+ const supplyFailed = sourceRead === 'unreadable' || scanFailed;+ const [supplyToken, setSupplyToken] = React.useState(0);+ const [gatewayRun, setGatewayRun] = React.useState<GatewayRun>({ kind: 'idle' });+ const [gatewayToken, setGatewayToken] = React.useState(0);+ const [addDialog, setAddDialog] = React.useState<{ more: boolean; vendor: string | null } | null>(null);+ const [importOpen, setImportOpen] = React.useState(false);+ const [importFailed, setImportFailed] = React.useState(false);+ const [verifying, setVerifying] = React.useState(false);+ const [pulse, setPulse] = React.useState({ inbound: false, outbound: false });++ const selection = flowState.providerSelection;+ const ready = setupNavigationReady(capability, gatewayEnabled);+ const intent = gatewayIntent({ capability, gatewayEnabled, runtimeRead });++ const slots = React.useMemo(+ () => providerSlots({ sources, scan: selection.scan }),+ [sources, selection.scan],+ );+ const detected = React.useMemo(+ () => unlistedDetected({ sources, scan: selection.scan }),+ [sources, selection.scan],+ );+ const pending = React.useMemo(() => pendingImportRows(selection), [selection]);+ // The capsule counts through the same consent grouping the cards and the dialog+ // use, so a key it advertises is always one the review can actually act on.+ const offered = React.useMemo(() => offeredImportKeys(selection), [selection]);++ // ── Supply ──────────────────────────────────────────────────────────────++ // Whether the server's own row defaults have been honoured yet. A scan is nulled+ // again once a batch lands, so 「no scan held」 alone cannot answer this: it is+ // also true for the rescan that follows an import, whose consent has just been+ // spent on purpose and must not come back ticked.+ const seededSelectionRef = React.useRef(false);+ React.useEffect(() => {+ if (!active || !ready) return;+ let cancelled = false;+ // A re-read is a read: while it is in flight the screen is back to not knowing,+ // which is what a retry means and what the action should say.+ setSourceRead('reading');+ void (async () => {+ // Settled independently, because they answer different questions. A scan that+ // fails says nothing about the sources, and discarding a source list that did+ // arrive would report providers that exist as providers that do not — leaving+ // the action offering 「添加」 on a machine that already has credentials.+ const [read, scan] = await Promise.allSettled([+ sourceReads.refresh(),+ modelsApi.scanMigration(),+ ]);+ if (cancelled) return;+ // A stale source read is neither an answer nor a failure: a newer generation+ // superseded it, and that newer one is what will settle this.+ if (read.status === 'rejected') setSourceRead('unreadable');+ else if (read.value.kind === 'current') {+ setSources(read.value.value);+ setSourceRead('read');+ }+ // Either failure is still a failure for the sentence: what the screen cannot+ // report is exactly what it and its retry exist to say.+ setScanFailed(scan.status === 'rejected');+ if (scan.status === 'rejected') return;+ const scanned = scan.value;+ // Read outside the updater and written after it: an updater has to be pure,+ // and one that flips this on its first call answers its own question+ // differently on the second.+ const first = !seededSelectionRef.current;+ setFlowState((previous) => {+ // The first scan has no prior consent to carry, so it opens on the+ // server's own defaults — the same rows the shipped dialog opens ticked.+ // Afterwards the selection is the person's, and survives only where this+ // scan asks the same question the last one did.+ const selectedBackends = first && previous.providerSelection.scan === null+ ? defaultSelection(scanned)+ : reconcileSelection(+ { scan: scanned, selectedBackends: previous.providerSelection.selectedBackends },+ previous.providerSelection.scan,+ );+ return { ...previous, providerSelection: { scan: scanned, selectedBackends } };+ });+ seededSelectionRef.current = true;+ })();+ return () => { cancelled = true; };+ }, [active, ready, supplyToken, setFlowState, sourceReads]);++ // ── Gateway ─────────────────────────────────────────────────────────────++ // Which attempt the gateway effect has already made, named by the token that+ // armed it — so it is both the guard against making it twice and the identity of+ // the live one. `gatewayToken` only ever increases, so an attempt is superseded+ // exactly when this no longer holds its token.+ //+ // One attempt per explicit retry. Not per intent change: the intent is recomputed+ // from a read the shell refreshes, and re-running on every recomputation would+ // reinstall in a loop while an install was still settling. Not per activation+ // either — an attempt outlives the screen being hidden, so re-arming on re-entry+ // could launch a second install over one still running. Coming back to a failed+ // attempt finds it on the card, with its retry.+ //+ // And nothing else supersedes one. A closure flag would be flipped by the effect's+ // cleanup, which runs when the screen is merely hidden and again on every+ // StrictMode replay — abandoning a mutation the server is still performing,+ // leaving the card stuck on 「正在安装」 and the shell's runtime read describing a+ // machine that has since changed. What supersedes an attempt is another attempt.+ const attemptedRef = React.useRef<number | null>(null);++ // Held in a ref for the same reason the publication is: a shell whose callback is+ // re-created each render would otherwise re-run the effect below, re-arming an+ // attempt that is still in flight.+ const refreshRuntimeRef = React.useRef(onRetrySetup);+ refreshRuntimeRef.current = onRetrySetup;++ const resumeStep = intent.kind === 'resume' ? intent.step : null;+ // The snapshot the step was read from, held for the same reason the callbacks are:+ // it is a new object on every read, and depending on it would re-arm an attempt+ // that is still in flight. Captured synchronously below, before any await.+ const resumeRuntimeRef = React.useRef<RuntimeDependency | null>(null);+ resumeRuntimeRef.current = intent.kind === 'resume' ? intent.runtime : null;+ // What the shell is handing down right now, for the attempt to record its own+ // refresh request against when it completes. An attempt spans awaits, so the+ // props its closure captured are a memory of the evidence rather than the+ // evidence — and the whole point of the record is which read came after it.+ const evidenceRef = React.useRef<GatewayEvidence>({ runtimeRead, gatewayEnabled, capability });+ evidenceRef.current = { runtimeRead, gatewayEnabled, capability };++ React.useEffect(() => {+ if (!active || resumeStep === null || attemptedRef.current === gatewayToken) return;+ const runtime = resumeRuntimeRef.current;+ if (runtime === null) return;+ attemptedRef.current = gatewayToken;+ const superseded = () => attemptedRef.current !== gatewayToken;+ setGatewayRun({ kind: 'running', step: resumeStep });+ void (async () => {+ try {+ // The engine first, and on its own. `resumeGatewayAdoption` is named for+ // adoption: it returns success without touching the runtime when its backend+ // is already in hub mode, and on a machine with no assistant CLI there is no+ // backend to name at all. Either exit used to leave a missing or stopped+ // engine exactly as it was — card idle, no retry beside it, Continue blocked+ // on a read that never moves, and the screen that installs assistants on the+ // far side of it.+ const started = await resumeInstallAndStartRuntime(modelsApi, runtime, (value) => {+ // Install and start are one press and two waits; the helper reports the+ // crossing, so the card can say which one it is in.+ const step = installAndStartStep(value);+ if (!superseded() && step !== 'complete') setGatewayRun({ kind: 'running', step });+ });+ if (superseded()) return;+ if (started.failedStep !== null) {+ setGatewayRun({ kind: 'failed', step: started.failedStep });+ // A failed install or start changed supervisor health; the shell's read+ // still describes the health it had before the attempt.+ refreshRuntimeRef.current();+ return;+ }+ // Then what there is to adopt, which may be nothing: no CLI on this machine+ // is not a gateway failure, and the engine is up either way.+ const agents = await agentReads.refresh();+ if (superseded()) return;+ const backend = agents.kind === 'current' ? adoptionBackend(agents.value) : null;+ const outcome = backend === null+ ? { ok: true as const }+ : await resumeGatewayAdoption(modelsApi, agentReads, backend);+ if (superseded()) return;+ setGatewayRun(outcome.ok+ // Recorded against the evidence standing NOW, in the same update that+ // ends the attempt: the refresh below is this screen asking a question,+ // and the read it is asking about is by definition the next one.+ ? { kind: 'settled', against: evidenceRef.current }+ : { kind: 'failed', step: outcome.failure.step });+ // The engine moved; the shell's read still describes where it was. Asking+ // for that read again is what turns the card from 「正在启动」 to 「运行中」+ // and unblocks Continue — without it the attempt succeeds and the screen+ // falls back to the stale intent, which is still 'resume'.+ refreshRuntimeRef.current();+ // And an engine that just came up can answer reads that failed before it did.+ if (outcome.ok) setSupplyToken((token) => token + 1);+ } catch {+ if (!superseded()) setGatewayRun({ kind: 'failed', step: 'read' });+ }+ })();+ }, [active, resumeStep, gatewayToken, agentReads]);++ // A retry that is waiting for the shell to answer. The press asks for a fresh read;+ // the ANSWER re-arms the attempt, never the press — the only read a press can see is+ // the one its failure was read from, so arming on it starts the same attempt against+ // the same snapshot, ahead of the shell and on evidence already known to be stale.+ const [resumeRequested, setResumeRequested] = React.useState(false);+ const requestedAgainstRef = React.useRef<GatewayEvidence | null>(null);++ const retryGateway = React.useCallback(() => {+ // One owner at a time: an attempt that has not reported still owns the engine, and+ // a second press over it is a second install or start on the same machine.+ if (gatewayRun.kind === 'running') return;+ requestedAgainstRef.current = { runtimeRead, gatewayEnabled, capability };+ setResumeRequested(true);+ // The shell owns the authoritative read. Asking for it is all this does.+ onRetrySetup();+ }, [gatewayRun.kind, runtimeRead, gatewayEnabled, capability, onRetrySetup]);++ React.useEffect(() => {+ if (!active || !resumeRequested) return;+ // Nothing to act on until the shell has answered the read this press asked for:+ // the same read and the same configuration it was made against is not new+ // information, and a different one that has not landed yet is not an answer+ // either. Spending the request on one loses it — the person pressed Retry, the+ // read they asked for arrives a moment later saying the engine is stopped, and+ // nothing starts it.+ if (!gatewayReadAnswered(requestedAgainstRef.current, { runtimeRead, gatewayEnabled, capability })) return;+ requestedAgainstRef.current = null;+ setResumeRequested(false);+ // Only an answer that still calls for a resume re-arms one. A configuration that+ // came back disabled ends the request instead of being overridden by it, and an+ // engine that is simply running now has nothing left to resume. Either way the+ // card goes on describing the fresh read rather than this screen's last attempt.+ if (resumeStep === null) return;+ setGatewayRun({ kind: 'idle' });+ setGatewayToken((token) => token + 1);+ }, [active, resumeRequested, runtimeRead, gatewayEnabled, capability, resumeStep]);++ // The other half of the same rule, for the refresh an ATTEMPT asks for when it+ // finishes. The answer to that one may not re-arm anything — a machine the engine+ // keeps dying on would reinstall forever without a person ever asking — so it is+ // recorded instead: a demand still standing is a dead end, and a dead end on this+ // screen is the card with the Retry on it. Recorded rather than re-derived each+ // render, because the press that follows starts another read, and a verdict+ // recomputed from a read in flight would take its own card away mid-press.+ React.useEffect(() => {+ if (gatewayRun.kind !== 'settled') return;+ if (!gatewayReadAnswered(gatewayRun.against, { runtimeRead, gatewayEnabled, capability })) return;+ setGatewayRun(resumeStep === null ? { kind: 'idle' } : { kind: 'failed', step: null });+ }, [gatewayRun, runtimeRead, gatewayEnabled, capability, resumeStep]);++ // Supply recovers on its own, because its failures are reads: a source list or a+ // scan that could not be fetched is what breaks the sentence, and the gateway+ // neither caused that nor can fix it. Rearming an install from it would be a server+ // mutation nobody asked for.+ const retrySupply = React.useCallback(() => setSupplyToken((token) => token + 1), []);++ const gatewayBusy = gatewayRun.kind === 'running';+ const gatewayPhase: GatewayPhase = gatewayBusy+ ? (gatewayRun.step === 'install' ? 'installing' : 'starting')+ : intent.kind === 'running'+ ? 'running'+ : gatewayRun.kind === 'failed'+ ? 'failed'+ : intent.kind === 'unsupported'+ ? 'unsupported'+ // A read this screen could not make wears the same not-ready line and the+ // same retry as an attempt that failed. The contract asks for exactly+ // that — the runtime-unread copy with retry, never the unsupported+ // notice — and the alternative is the idle card, which says the engine is+ // fine while Continue stays disabled for a reason nothing on screen gives.+ : intent.kind === 'unreadable'+ ? 'failed'+ : 'idle';++ // ── Write admission ─────────────────────────────────────────────────────++ // One rule for every control that can start a write, wherever it is drawn: the+ // cards, the footer, the capsule and the dialogs all admit the same thing, so a+ // control that is drawn somewhere else cannot admit what the footer refuses.+ //+ // Four separate facts, and a write needs all of them. What the machine's HEALTH is+ // (`intent.kind === 'running'`, the authoritative read rather than this screen's+ // attempt). Whether this flow is admitted to use the Hub at all (`ready`, the same+ // prerequisite C4 gates the next screen on). Whether this screen is the one the+ // person is on. And whether a write this screen already issued is still out.+ //+ // Health is not permission, and the card is right to say so: `gatewayIntent`+ // reports a running engine even while the configuration that admits the flow is+ // pending or off, on purpose — a truthful engine state is what the person needs to+ // read. It is not authorization to write to it, and reusing it as one is how a+ // Model Hub someone turned off still gets a source written into it.+ //+ // What this deliberately keeps is the case that looks like an exception and is+ // not: a healthy engine on a host that cannot INSTALL one is still a healthy+ // engine, and with the configuration enabled, writing to it is fine. That+ // boundary is about installing, not about writing.+ const hubAdmitted = ready && intent.kind === 'running';+ const writeAdmitted = active && hubAdmitted && !gatewayBusy && !verifying;++ // The one write on this screen that installs. `apply_native_migration` ensures the+ // runtime dependency before it touches a credential, and it does so unconditionally+ // — on a host whose runtime manifest resolves to unsupported that ensure fails ahead+ // of the branch that would have reused the engine already running, so the whole+ // batch comes back 422 no matter how healthy the engine is. Offering it there is+ // offering something the server has already decided to refuse.+ //+ // It narrows nothing else. A source, a key or an OAuth authorization is a write to+ // an engine that is up, and the paragraph above is why that stays available: the+ // boundary is about installing one, and this is the only button behind which an+ // install is still waiting to happen.+ const migrationAdmitted = writeAdmitted+ && setupCanAttemptInstall(capability, gatewayEnabled, runtimeRead);++ const openAdd = React.useCallback((more: boolean, vendor: string | null) => {+ if (!writeAdmitted || sourceRead !== 'read') return;+ setAddDialog({ more, vendor });+ }, [writeAdmitted, sourceRead]);++ // The takeover reads the machine for itself, and can take over a credential an+ // unreadable inventory knows nothing about; an unread source list is no reason to+ // withhold it. An engine that cannot be written to is.+ const openImport = React.useCallback(() => {+ if (!writeAdmitted) return;+ setImportOpen(true);+ }, [writeAdmitted]);++ // ── The action the shell renders ────────────────────────────────────────++ const action = providerAction({+ pendingCount: pending.length,+ importFailed,+ // What the screen knows, not what the list happens to hold: an inventory it+ // could not read is not an empty one, and 「添加」 offered against it is how a+ // credential that already exists gets written a second time.+ supply: sourceRead === 'read'+ ? { kind: 'read', hasSource: sources.some(usableSource) }+ : { kind: sourceRead },+ gatewayBusy,+ // The same admission the dialogs are opened and submitted against, so the footer+ // cannot reach a write the rest of the screen refuses. `gatewayBusy` and+ // `verifying` are answered earlier in that ordering and stay separate facts.+ hubAdmitted,+ verifying,+ });++ // Held in a ref so a shell that re-renders on every publication cannot turn this+ // into a loop: what the effect depends on is the action's VALUE.+ const publishRef = React.useRef(onActionChange);+ publishRef.current = onActionChange;+ React.useEffect(() => {+ if (!active) return;+ publishRef.current(providerSetupAction({+ kind: action.kind,+ count: action.count,+ ...(action.blocked ? { blocked: true } : {}),+ }));+ }, [active, action.kind, action.count, action.blocked]);++ React.useImperativeHandle(ref, () => ({+ activate: () => {+ // A blocked state is the right one to show and the wrong one to press. The+ // shell already renders it disabled; refusing it here too is what makes a+ // keyboard activation on a stale render unrepresentable rather than merely+ // unlikely.+ if (action.blocked) return;+ switch (action.kind) {+ case 'import':+ case 'retryImport':+ // Consent is the takeover's, always. Continuing is what the next press+ // does, once the batch has landed and the rescan has emptied the pending+ // set — an automatic navigation here would hide the report of what landed.+ openImport();+ return;+ case 'continue':+ onNavigate('assistants');+ return;+ case 'add':+ openAdd(true, null);+ return;+ case 'retrySupply':+ // Asking again is the whole action. The effect flips back to 「reading」 on+ // its way in, so the button reports the retry it just started. It is the+ // supply read that failed, so the supply read is what it asks for again.+ retrySupply();+ return;+ default:+ // Busy. The shell already renders the action disabled; ignoring the call+ // rather than trusting that is what makes it unrepresentable.+ }+ },+ }), [action.kind, action.blocked, onNavigate, openAdd, openImport, retrySupply]);++ // ── First-entry sequence ────────────────────────────────────────────────++ React.useEffect(() => {+ if (!active) {+ // Reset so a re-entry replays: the pulse is a `<g>` that has to remount.+ setPulse({ inbound: false, outbound: false });+ return;+ }+ // Paused mid-sequence keeps the frame it is on rather than snapping back —+ // `data-motion` holds the CSS side, and clearing the timers holds this one.+ if (!motion.running) return;+ const timers = [+ window.setTimeout(() => setPulse((state) => ({ ...state, inbound: true })), INBOUND_DELAY_MS),+ window.setTimeout(() => setPulse((state) => ({ ...state, outbound: true })), OUTBOUND_DELAY_MS),+ ];+ return () => timers.forEach(window.clearTimeout);+ }, [active, motion.running]);++ // ── Writes landing ──────────────────────────────────────────────────────++ const landSource = React.useCallback(async (created: SourceCreated | null, viaMore: boolean) => {+ setVerifying(true);+ try {+ try {+ const read = await sourceReads.refresh();+ if (read.kind === 'current') {+ setSources(read.value);+ setSourceRead('read');+ }+ } catch {+ // The write may well have landed; what failed is the read that would show+ // it. The dialog swallows a rejection here to stay closable, so saying so+ // is this screen's job — keeping the old list silently would report a+ // provider that exists as one that does not.+ setSourceRead('unreadable');+ }+ const id = created?.source.id;+ if (!viaMore || !id) return;+ setFlowState((previous) => (previous.addedThroughMore.includes(id)+ ? previous+ : { ...previous, addedThroughMore: [...previous.addedThroughMore, id] }));+ } finally {+ setVerifying(false);+ }+ }, [setFlowState, sourceReads]);++ const changeSelection = React.useCallback((selectedBackends: AgentBackend[]) => {+ // Editing the selection retires the verdict the server gave about the batch it+ // no longer describes.+ setImportFailed(false);+ setFlowState((previous) => ({+ ...previous,+ providerSelection: { ...previous.providerSelection, selectedBackends },+ }));+ }, [setFlowState]);++ const toggleSlot = React.useCallback((slot: ProviderSlot) => {+ setImportFailed(false);+ setFlowState((previous) => ({+ ...previous,+ providerSelection: {+ ...previous.providerSelection,+ selectedBackends: toggleSlotSelection(previous.providerSelection, slot),+ },+ }));+ }, [setFlowState]);++ // ── Sentence ────────────────────────────────────────────────────────────++ const summary = providerSummary({+ scan: selection.scan,+ sources,+ selected: selection.selectedBackends,+ failed: supplyFailed,+ });+ const summaryText = summary.kind === 'none'+ ? t('onboarding.providers.summaryNone')+ : summary.kind === 'error'+ ? t('onboarding.providers.summaryError')+ : t(+ summary.kind === 'added'+ ? 'onboarding.providers.summaryAdded'+ : 'onboarding.providers.summarySelected',+ { count: summary.count, names: formatNames(summary.names, i18n.language) },+ );++ return (+ <div className="onboarding-setup">+ <header className="onboarding-heading">+ <h2>{t('onboarding.providers.title')}</h2>+ <p>{t('onboarding.providers.subtitle')}</p>+ </header>++ <div className="onboarding-stage">+ <div+ ref={attachStage}+ className="setup-provider-stage"+ data-motion={motion.running ? 'running' : 'paused'}+ // The diagram's meaning is its arrangement, which a screen reader cannot+ // see. One group, named by what the arrangement says.+ role="group"+ aria-label={t('onboarding.providers.stageLabel')}+ >+ <div className="setup-provider-grid">+ {slots.map((slot) => (+ <ProviderCard+ key={slot.vendor}+ slot={slot}+ selected={slotSelected(slot, selection.selectedBackends)}+ onToggle={() => toggleSlot(slot)}+ // The brand, not the slot's identity: the dialog opens on a catalog+ // vendor, and a card standing for a credential the server named no+ // provider for has none to open on.+ onAdd={() => openAdd(false, slot.brand)}+ />+ ))}+ <AddMoreCard+ count={addedThroughMoreCount(flowState.addedThroughMore, sources)}+ onAdd={() => openAdd(true, null)}+ />+ </div>++ <SupplyWires+ direction="inbound"+ stage={stage}+ endpointSelector=".setup-provider-card"+ pulse={pulse.inbound}+ />++ <GatewayCard+ phase={gatewayPhase}+ failedStep={gatewayRun.kind === 'failed' ? gatewayRun.step : null}+ onRetry={gatewayPhase === 'failed' || gatewayPhase === 'unsupported' ? retryGateway : null}+ />++ <SupplyWires+ direction="outbound"+ stage={stage}+ endpointSelector=".setup-destination"+ pulse={pulse.outbound}+ />++ <DestinationRow />++ <p+ className="setup-provider-summary"+ {...(summary.kind === 'error' ? { 'data-tone': 'error' } : {})}+ role="status"+ aria-live="polite"+ >+ {summaryText}+ {summary.kind === 'error' && (+ <Button type="button" variant="outline" size="sm" className="setup-summary-retry" onClick={retrySupply}>+ {t('common.retry')}+ </Button>+ )}+ </p>++ {/* The slot is always here; only the capsule inside it comes and goes. That+ is what keeps the footer action still when someone dismisses the offer. */}+ <div className="setup-provider-offer">+ {active && (+ <ImportKeysNotice+ candidates={offered}+ imported={flowState.importedCount}+ onReview={openImport}+ />+ )}+ </div>+ </div>+ </div>++ {addDialog && (+ <AddSourceDialog+ more={addDialog.more}+ vendor={addDialog.vendor}+ detected={detected}+ pendingCount={pending.length}+ sources={sources}+ sourceReads={sourceReads}+ // Admission is not only a door: it can be withdrawn while this is open, and+ // the write is the thing that must not happen then. Closing the dialog+ // instead would take down a flow that is mid-authorization and lose the+ // report of what it landed, which is worse than the press it prevents.+ writable={writeAdmitted}+ isSelected={(slot) => slotSelected(slot, selection.selectedBackends)}+ onToggleDetected={toggleSlot}+ onReviewDetected={() => { setAddDialog(null); openImport(); }}+ onAdded={(created) => landSource(created, addDialog.more)}+ onClose={() => setAddDialog(null)}+ />+ )}++ {importOpen && (+ <MigrationDialog+ open+ scope="setup"+ eligible={isImportableKey}+ takeable={isImportableKey}+ value={selection}+ // The add dialog's admission plus the one thing only this batch needs: an+ // engine that stopped while the review was open has nothing to migrate keys+ // into, and a host that cannot install one has a server-side refusal waiting+ // behind the button. Either way the review stays readable and cancellable and+ // only the batch is refused — and Settings passes nothing and keeps writing,+ // as it always has.+ writable={migrationAdmitted}+ onChange={(next) => changeSelection(next.selectedBackends)}+ onApplied={(applied) => {+ // `onApplied(0)` is a refresh trigger, not a receipt: the takeover reports+ // a rejected batch that way, and the only observable difference between a+ // batch that landed and one that did not is this number. The count moves+ // only when something actually landed.+ //+ // The snapshot is spent on BOTH paths, in this tick. Success would+ // otherwise keep advertising rows that are now imported until the rescan+ // answers. A terminal rejection — `migration_credentials_invalid` closes+ // the dialog behind it — would otherwise leave the held scan and consent+ // looking like a batch still authorized to submit; a failed rescan must+ // not be able to revive those ids, and retrying them returns the same+ // error forever. Re-reading is what surfaces the reauthentication.+ setImportFailed(applied === 0);+ setFlowState((previous) => ({+ ...previous,+ importedCount: applied > 0 ? previous.importedCount + applied : previous.importedCount,+ providerSelection: { scan: null, selectedBackends: [] },+ }));+ setSupplyToken((token) => token + 1);+ }}+ onClose={() => setImportOpen(false)}+ />+ )}+ </div>+ );+ },+);diff --git a/ui/src/components/onboarding/providers/SupplyWires.tsx b/ui/src/components/onboarding/providers/SupplyWires.tsxnew file mode 100644index 000000000..5326a9c53--- /dev/null+++ b/ui/src/components/onboarding/providers/SupplyWires.tsx@@ -0,0 +1,125 @@+// The wires between the cards and the gateway, drawn from where those boxes+// actually are.+//+// The story's circuit can hardcode its paths because it stretches one viewBox over a+// fixed composition. This diagram cannot: its columns are percentages, its band+// heights scale with `--ob-u`, and a provider card can be missing. So the paths are+// measured — every endpoint is the real horizontal centre of a real element, read+// after layout and read again when the box changes size.+//+// The authored shape is a drop, a curve and a drop. In the reference's 976x40 band+// the wire leaves at y=12, flattens onto y=28 and lands at 40; those three numbers+// are 0.3, 0.7 and 1 of the band, so writing them as fractions of the measured+// height reproduces the frame exactly where it was drawn and holds at every tier+// without a second set of numbers.+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';+import type { CSSProperties, FC } from 'react';++/** Where the fan-in enters the gateway, as the reference's 24 scaled by the band. */+const ENTRY_SPREAD = 24 / 40;+const LEAVE = 0.3;+const FLATTEN = 0.7;++type Geometry = { width: number; height: number; paths: string[] };++/** One drop-curve-drop from `sx` at the top to `tx` at the bottom. A wire that does+ * not have to move sideways is drawn straight rather than as a flat curve. */+function wirePath(sx: number, tx: number, height: number): string {+ const round = (value: number) => Math.round(value * 100) / 100;+ if (Math.abs(sx - tx) < 0.5) return `M ${round(sx)} 0 V ${round(height)}`;+ const leave = round(height * LEAVE);+ const flatten = round(height * FLATTEN);+ return `M ${round(sx)} 0 V ${leave} Q ${round(sx)} ${flatten} ${round(tx)} ${flatten} V ${round(height)}`;+}++const centreIn = (element: Element, originX: number): number => {+ const box = element.getBoundingClientRect();+ return box.left + box.width / 2 - originX;+};++/**+ * @param direction `inbound` fans several sources into one gateway; `outbound` fans+ * one gateway out to several destinations. The reference spreads the inbound+ * landings across the gateway's top and leaves every outbound wire from its+ * centre, which is what makes the two bands read as convergence and distribution+ * rather than as one symmetric shape drawn twice.+ * @param endpointSelector the elements at the far side of the gateway.+ * @param pulse replays the arrival once when it turns true.+ * @param stage the element every measurement is taken inside. Passed as the element+ * rather than as a ref on purpose: a ref object's identity never changes, so the+ * first measurement would have to happen before the parent's own ref was attached+ * and nothing would ever ask for a second one. An element is a value — it arrives,+ * the effects re-run, and the wires appear on the frame the stage exists.+ */+export const SupplyWires: FC<{+ direction: 'inbound' | 'outbound';+ stage: HTMLElement | null;+ endpointSelector: string;+ pulse: boolean;+}> = ({ direction, stage, endpointSelector, pulse }) => {+ const bandRef = useRef<HTMLDivElement | null>(null);+ const [geometry, setGeometry] = useState<Geometry | null>(null);++ const measure = useCallback(() => {+ const band = bandRef.current;+ if (!band || !stage) return;+ const box = band.getBoundingClientRect();+ const gateway = stage.querySelector('.setup-gateway');+ const endpoints = [...stage.querySelectorAll(endpointSelector)];+ // A hidden screen has no boxes to measure. Keeping the previous geometry rather+ // than drawing a degenerate one means returning to the screen shows wires, not+ // a flat line that corrects itself a frame later.+ if (!gateway || endpoints.length === 0 || box.width === 0 || box.height === 0) return;++ const gatewayX = centreIn(gateway, box.left);+ const spread = box.height * ENTRY_SPREAD;+ const offset = (index: number) => (index - (endpoints.length - 1) / 2) * spread;+ const paths = endpoints.map((endpoint, index) => {+ const endpointX = centreIn(endpoint, box.left);+ return direction === 'inbound'+ ? wirePath(endpointX, gatewayX + offset(index), box.height)+ : wirePath(gatewayX, endpointX, box.height);+ });++ setGeometry((previous) =>+ previous+ && previous.width === box.width+ && previous.height === box.height+ && previous.paths.length === paths.length+ && previous.paths.every((path, index) => path === paths[index])+ ? previous+ : { width: box.width, height: box.height, paths });+ }, [direction, endpointSelector, stage]);++ useLayoutEffect(measure, [measure]);++ useEffect(() => {+ if (!stage || typeof ResizeObserver === 'undefined') return;+ // Watching the stage rather than the window catches the cases a resize event+ // misses: a card appearing after a scan, and a tier variable changing the band's+ // own height without the window changing at all.+ const observer = new ResizeObserver(measure);+ observer.observe(stage);+ return () => observer.disconnect();+ }, [measure, stage]);++ return (+ <div ref={bandRef} className={`setup-wires setup-wires--${direction}`} aria-hidden="true">+ {geometry && (+ <svg viewBox={`0 0 ${geometry.width} ${geometry.height}`} width={geometry.width} height={geometry.height}>+ {geometry.paths.map((path, index) => (+ <path key={`wire-${index}`} className="setup-wire" d={path} />+ ))}+ {pulse && geometry.paths.map((path, index) => (+ // The halo and the core travel together; staggering them across the fan+ // is what makes three wires read as one arrival rather than a flash.+ <g key={`pulse-${index}`} style={{ '--setup-pulse-delay': `${index * 90}ms` } as CSSProperties}>+ <path className="setup-wire-pulse setup-wire-pulse-halo" d={path} />+ <path className="setup-wire-pulse" d={path} />+ </g>+ ))}+ </svg>+ )}+ </div>+ );+};diff --git a/ui/src/components/onboarding/providers/gatewayBootstrap.test.ts b/ui/src/components/onboarding/providers/gatewayBootstrap.test.tsnew file mode 100644index 000000000..b82fcca45--- /dev/null+++ b/ui/src/components/onboarding/providers/gatewayBootstrap.test.ts@@ -0,0 +1,378 @@+// The bootstrap sequence, stated as the things it must refuse to do.+//+// Almost every case here is a plausible shortcut: retry the write that might have+// landed, believe a GET that is really an in-memory default, start a controller whose+// state nobody confirmed, install an engine the server's own recovery is already+// installing. Each one produces a green happy path and a wrong answer somewhere else.+import { describe, expect, it, vi } from 'vitest';+import type { Mock } from 'vitest';++import type { BackendConnectionState } from '@/context/ApiContext';+import type { RuntimeDependency } from '@/components/settings/models/types';++import { GatewayBootstrapError, bootstrapGateway, readSetupConfig } from './gatewayBootstrap';+import type { GatewayBootstrapDeps } from './gatewayBootstrap';++const CONFIG = {+ version: 'v2',+ setup_completed: false,+ platforms: { primary: 'avibe', enabled: [] },+ runtime: {},+ agents: {},+ capabilities: { model_hub: { enabled: true } },+ model_hub: { enabled: true },+};++const json = (body: unknown, status = 200): Response =>+ new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });++const connection = (over: Partial<BackendConnectionState> = {}): BackendConnectionState => ({+ ok: true,+ backend: 'claude',+ installed: true,+ enabled: true,+ auth: 'none',+ application: 'applied',+ ready: false,+ entry_eligible: false,+ ...over,+});++const RUNTIME = {+ contract_version: 'v3',+ manifest: {},+ status: { verified: true, health: 'ok' },+} as unknown as RuntimeDependency;++function deps(over: Partial<GatewayBootstrapDeps> = {}) {+ const fetch = vi.fn(async (_input: string, init?: RequestInit) =>+ (init?.method === 'POST' ? json({ ...CONFIG }) : json({ ...CONFIG })));+ return {+ fetch,+ getBackendConnection: vi.fn(async () => connection()),+ control: vi.fn(async () => ({ ok: true, action: 'start' })),+ getRuntimeStatus: vi.fn(async () => RUNTIME),+ ...over,+ } satisfies GatewayBootstrapDeps;+}++/** Request arguments, from a dependency the caller declared as a plain function. */+const requests = (fn: GatewayBootstrapDeps['fetch']): [string, RequestInit?][] =>+ (fn as unknown as Mock).mock.calls as [string, RequestInit?][];++/** The writes only. Every case below has something to say about how many there were. */+const writes = (fn: GatewayBootstrapDeps['fetch']): [string, RequestInit?][] =>+ requests(fn).filter(([, init]) => init?.method === 'POST');++/**+ * A server whose write outcome and read answer are set separately.+ *+ * Which is the whole subject here: a write nobody can account for and a config that+ * reads back perfectly well is not a contradiction, it is the ordinary case after a+ * dropped reply, and the two halves have to be expressible apart.+ */+const split = (+ post: () => Promise<Response>,+ get: () => Promise<Response> = async () => json(CONFIG),+) => vi.fn(async (_url: string, init?: RequestInit) => (init?.method === 'POST' ? post() : get()));++/** The two ways a write ends up unaccounted for, as a server does them. */+const DROPPED: [string, () => Promise<Response>][] = [+ ['a transport failure', async () => { throw new TypeError('network'); }],+ ['a server fault', async () => json({ error: { message: 'boom' } }, 503)],+];++const failure = async (promise: Promise<unknown>): Promise<GatewayBootstrapError> => {+ const error = await promise.then(() => null, (thrown: unknown) => thrown);+ expect(error).toBeInstanceOf(GatewayBootstrapError);+ return error as GatewayBootstrapError;+};++describe('readSetupConfig', () => {+ it('accepts the top-level config object the handlers really return', () => {+ expect(readSetupConfig(CONFIG)).toMatchObject({+ version: 'v2',+ capabilityEnabled: true,+ savedIntentEnabled: true,+ primaryPlatform: 'avibe',+ });+ });++ it('rejects the envelope shape nobody sends', () => {+ // `{ok:true, config:{...}}` reads as a success to a careless check and carries+ // none of the fields the caller then indexes into.+ expect(readSetupConfig({ ok: true, config: CONFIG })).toBeNull();+ });++ it('rejects a body that carries an error alongside a plausible payload', () => {+ expect(readSetupConfig({ ...CONFIG, error: 'config load failed' })).toBeNull();+ expect(readSetupConfig({ ...CONFIG, ok: false })).toBeNull();+ });++ it.each([+ ['version', { version: 'v1' }],+ ['setup_completed', { setup_completed: 'no' }],+ ['platforms.primary', { platforms: { enabled: [] } }],+ ['platforms.enabled', { platforms: { primary: 'avibe', enabled: 'slack' } }],+ ['runtime', { runtime: null }],+ ['agents', { agents: [] }],+ ['capabilities.model_hub', { capabilities: {} }],+ ['model_hub', { model_hub: {} }],+ ])('treats a malformed %s as unread rather than as a value', (_field, over) => {+ expect(readSetupConfig({ ...CONFIG, ...over })).toBeNull();+ });+});++describe('bootstrapGateway', () => {+ it('seeds, reads back uncached, proves persistence, and observes the runtime', async () => {+ const d = deps();++ await expect(bootstrapGateway(d, 'claude')).resolves.toMatchObject({ runtime: RUNTIME });++ const [[seedUrl, seedInit], [readUrl, readInit]] = requests(d.fetch);+ expect(seedUrl).toBe('/api/config');+ expect(seedInit).toMatchObject({ method: 'POST', body: '{}' });+ expect(new Headers(seedInit?.headers).get('Content-Type')).toBe('application/json');+ expect(readUrl).toBe('/api/config');+ expect(readInit).toMatchObject({ cache: 'no-store' });+ // One write per attempt, acknowledged or not.+ expect(writes(d.fetch)).toHaveLength(1);+ });++ it('does not start a controller that is already applied', async () => {+ const d = deps();++ await bootstrapGateway(d, 'claude');++ expect(d.control).not.toHaveBeenCalled();+ });++ it('starts only a controller confirmed stopped, then re-reads it', async () => {+ const getBackendConnection = vi.fn()+ .mockResolvedValueOnce(connection({ application: 'stopped' }))+ .mockResolvedValueOnce(connection({ application: 'applied' }));+ const d = deps({ getBackendConnection });++ await expect(bootstrapGateway(d, 'claude')).resolves.toMatchObject({ runtime: RUNTIME });+ expect(d.control).toHaveBeenCalledWith('start');+ expect(getBackendConnection).toHaveBeenCalledTimes(2);+ });++ it.each(['draining', 'failed', 'unknown'] as const)(+ 'never infers a start from %s',+ async (application) => {+ const d = deps({ getBackendConnection: vi.fn(async () => connection({ application })) });++ const error = await failure(bootstrapGateway(d, 'claude'));++ expect(d.control).not.toHaveBeenCalled();+ expect(error).toMatchObject({ step: 'start', reason: 'unknown' });+ },+ );++ it('never ensures or starts the engine itself', async () => {+ // Controller startup owns the first recovery, with the installer admission that+ // belongs on the server. A browser-side ensure here would race it.+ const d = deps();++ await bootstrapGateway(d, 'claude');++ expect(d.getRuntimeStatus).toHaveBeenCalledTimes(1);+ expect(requests(d.fetch).map(([url]) => url)).toEqual(['/api/config', '/api/config']);+ });++ it('treats a refusal as definitive and writes nothing more', async () => {+ const fetch = vi.fn(async () => json({ error: 'config is locked' }, 403));+ const d = deps({ fetch });++ const error = await failure(bootstrapGateway(d, 'claude'));++ expect(error).toMatchObject({ reason: 'refused', step: 'seed', status: 403, detail: 'config is locked' });+ expect(fetch).toHaveBeenCalledTimes(1);+ });++ it('keeps a refusal refused even where the config reads back perfectly well', async () => {+ // The read describes what exists; it does not describe what the server declined+ // to do. Letting a healthy GET clear a 403 would report a locked config as+ // prepared, and every later write would be refused the same way with no reason+ // left on screen.+ const fetch = split(async () => json({ error: 'config is locked' }, 403));+ const d = deps({ fetch });++ expect(await failure(bootstrapGateway(d, 'claude')))+ .toMatchObject({ reason: 'refused', step: 'seed', status: 403 });+ expect(d.getBackendConnection).not.toHaveBeenCalled();+ expect(d.control).not.toHaveBeenCalled();+ expect(writes(fetch)).toHaveLength(1);+ });++ it.each(DROPPED)(+ 'settles %s by reading, and starts once persistence is proven',+ async (_how, post) => {+ // The write may well have committed and lost its reply. Reading is the only+ // thing that can tell, and it is the same read an acknowledged write takes.+ const fetch = split(post);+ const getBackendConnection = vi.fn()+ .mockResolvedValueOnce(connection({ application: 'stopped' }))+ .mockResolvedValueOnce(connection({ application: 'applied' }));+ const d = deps({ fetch, getBackendConnection });++ await expect(bootstrapGateway(d, 'claude')).resolves.toMatchObject({ runtime: RUNTIME });++ // One write, and the reads that account for it.+ expect(writes(fetch)).toHaveLength(1);+ expect(requests(fetch)[1]).toMatchObject(['/api/config', { cache: 'no-store' }]);+ expect(getBackendConnection).toHaveBeenCalledTimes(2);+ expect(d.control).toHaveBeenCalledWith('start');+ },+ );++ it('treats a truncated 2xx as unaccounted for rather than as an acknowledgement', async () => {+ // A 2xx whose body is unreadable says nothing about what was written; the+ // readback is what settles it, and it is the same read either way.+ const fetch = split(async () => new Response('{"version":', { status: 200 }));+ const d = deps({ fetch });++ await expect(bootstrapGateway(d, 'claude')).resolves.toMatchObject({ runtime: RUNTIME });+ expect(fetch).toHaveBeenCalledTimes(2);+ });++ it('reports the write it cannot account for when the reads fail too', async () => {+ const fetch = split(+ async () => json({ error: { message: 'boom' } }, 503),+ async () => json({ error: 'config load failed' }, 500),+ );+ const d = deps({ fetch });++ // The server's own words about the write, kept: a read that failed adds nothing+ // a person can act on, and the write is what is still outstanding.+ expect(await failure(bootstrapGateway(d, 'claude')))+ .toMatchObject({ reason: 'unknown', step: 'seed', status: 503, detail: 'boom' });+ expect(writes(fetch)).toHaveLength(1);+ expect(d.getBackendConnection).not.toHaveBeenCalled();+ });++ it('keeps a dropped write outstanding when the readback cannot be reached', async () => {+ const fetch = split(+ async () => { throw new TypeError('network'); },+ async () => { throw new TypeError('network'); },+ );+ const d = deps({ fetch });++ // `unread` would say no write is outstanding, which is the one thing nobody knows.+ expect(await failure(bootstrapGateway(d, 'claude')))+ .toMatchObject({ reason: 'unknown', step: 'seed' });+ expect(writes(fetch)).toHaveLength(1);+ });++ it('stays blocked when the readback cannot be validated', async () => {+ const fetch = split(async () => json(CONFIG), async () => json({ version: 'v1' }));+ const d = deps({ fetch });++ expect(await failure(bootstrapGateway(d, 'claude'))).toMatchObject({ reason: 'unread', step: 'readback' });+ expect(d.getBackendConnection).not.toHaveBeenCalled();+ });++ it.each([+ ['the capability', { capabilities: { model_hub: { enabled: false } } }],+ ['saved intent', { model_hub: { enabled: false } }],+ ])('stops at the prerequisite boundary when %s is off, changing nothing', async (_which, over) => {+ const fetch = split(async () => json(CONFIG), async () => json({ ...CONFIG, ...over }));+ const d = deps({ fetch });++ expect(await failure(bootstrapGateway(d, 'claude'))).toMatchObject({ reason: 'disabled', step: 'capability' });+ expect(d.control).not.toHaveBeenCalled();+ expect(d.getRuntimeStatus).not.toHaveBeenCalled();+ // One write and no second: the preference is left exactly as it was.+ expect(writes(fetch)).toHaveLength(1);+ });++ it('stops at that boundary even holding a write it cannot account for', async () => {+ // The gateway is off by somebody's decision. What became of an empty patch has+ // stopped mattering, and reporting it would send a person to retry a write when+ // what they are owed is the setting.+ const fetch = split(+ async () => { throw new TypeError('network'); },+ async () => json({ ...CONFIG, model_hub: { enabled: false } }),+ );+ const d = deps({ fetch });++ expect(await failure(bootstrapGateway(d, 'claude')))+ .toMatchObject({ reason: 'disabled', step: 'capability' });+ expect(writes(fetch)).toHaveLength(1);+ expect(d.control).not.toHaveBeenCalled();+ });++ it('does not accept a valid GET as proof the config file exists', async () => {+ // The server answers with an in-memory default when there is no file, so the+ // connection read — whose handler really calls load_config() — is the proof.+ const d = deps({ getBackendConnection: vi.fn(async () => connection({ ok: false })) });++ expect(await failure(bootstrapGateway(d, 'claude'))).toMatchObject({ reason: 'unknown', step: 'persistence' });+ expect(d.control).not.toHaveBeenCalled();+ });++ it('stays blocked when the persistence read itself cannot be made', async () => {+ const d = deps({+ getBackendConnection: vi.fn(async () => { throw new Error('socket closed'); }),+ });++ expect(await failure(bootstrapGateway(d, 'claude'))).toMatchObject({ reason: 'unknown', step: 'persistence' });+ expect(d.control).not.toHaveBeenCalled();+ });++ it('keeps a dropped write outstanding when persistence is not proven', async () => {+ // A valid GET and an unproven config file: nothing here has settled the write,+ // so the server's own account of it is still the most specific thing to report.+ const fetch = split(async () => json({ error: { message: 'boom' } }, 503));+ const d = deps({ fetch, getBackendConnection: vi.fn(async () => connection({ ok: false })) });++ expect(await failure(bootstrapGateway(d, 'claude')))+ .toMatchObject({ reason: 'unknown', step: 'seed', status: 503 });+ expect(writes(fetch)).toHaveLength(1);+ expect(d.control).not.toHaveBeenCalled();+ });++ it('retires a dropped write once persistence is proven, and reports what fails next', async () => {+ // The empty patch's only intended effect was a config file the server can load.+ // A handler that just loaded one is that effect, observed — so a later failure is+ // its own, and reporting the seed here would blame a write that is accounted for.+ const fetch = split(async () => { throw new TypeError('network'); });+ const d = deps({ fetch, getRuntimeStatus: vi.fn(async () => ({}) as RuntimeDependency) });++ expect(await failure(bootstrapGateway(d, 'claude'))).toMatchObject({ reason: 'unread', step: 'runtime' });+ expect(writes(fetch)).toHaveLength(1);+ });++ it('keeps a rejected start unknown rather than reporting the controller up', async () => {+ const d = deps({+ getBackendConnection: vi.fn(async () => connection({ application: 'stopped' })),+ control: vi.fn(async () => { throw new Error('restart_in_progress'); }),+ });++ expect(await failure(bootstrapGateway(d, 'claude'))).toMatchObject({ reason: 'unknown', step: 'start' });+ });++ it('does not take a 2xx control body at its word', async () => {+ const d = deps({+ getBackendConnection: vi.fn(async () => connection({ application: 'stopped' })),+ control: vi.fn(async () => ({ ok: true, action: 'restart' })),+ });++ expect(await failure(bootstrapGateway(d, 'claude'))).toMatchObject({ reason: 'unknown', step: 'start' });+ });++ it('reports an unreadable runtime instead of inventing a status for it', async () => {+ const d = deps({ getRuntimeStatus: vi.fn(async () => ({}) as RuntimeDependency) });++ expect(await failure(bootstrapGateway(d, 'claude'))).toMatchObject({ reason: 'unread', step: 'runtime' });+ });++ it('asks the backend the caller named, not one of its own choosing', async () => {+ const d = deps();++ await bootstrapGateway(d, 'opencode');++ expect(d.getBackendConnection).toHaveBeenCalledWith('opencode');+ });+});diff --git a/ui/src/components/onboarding/providers/gatewayBootstrap.ts b/ui/src/components/onboarding/providers/gatewayBootstrap.tsnew file mode 100644index 000000000..e97852c34--- /dev/null+++ b/ui/src/components/onboarding/providers/gatewayBootstrap.ts@@ -0,0 +1,292 @@+// D11: making the controller answerable before the provider screen asks it anything.+//+// Hub reads are IPC-backed, so a stopped application cannot serve them and a missing+// config file means there is nothing for the controller to load. This runs once on+// active provider entry and establishes both, in the only order that can prove them:+// seed config, read it back uncached, prove it actually persisted, start a controller+// that is confirmed stopped, then observe the runtime the controller's own recovery+// has already been working on.+//+// It is deliberately stateless. The shell owns the `RegionRead` this feeds; this+// module returns one validated snapshot or throws one classified error, so the same+// sequence can be tested without a React tree and the region has exactly one owner.+//+// Two things it must not do, both of which look like improvements and are not:+//+// - Repeat the POST after an unknown outcome. The write may have landed; a blind+// retry is a second write against state the first one may already own. An unknown+// outcome is settled by reading, and only an explicit retry reseeds.+// - Ensure or start the engine. Controller startup already ran+// `_recover_runtime_owners()` with the installer admission that belongs on the+// server. This observes that outcome; asking for a second unconditional install+// would race the recovery that is still finishing.+import type { AgentBackend, RuntimeDependency } from '@/components/settings/models/types';+import type { BackendConnectionState } from '@/context/ApiContext';++/**+ * Why bootstrap could not finish, in the terms the caller has to act in.+ *+ * `disabled` is not a failure: it is C2's prerequisite boundary, and the caller+ * shows the configuration path rather than a retry. The rest differ in what is+ * outstanding — `refused` is a definitive no and blocks, `unknown` leaves a write+ * nobody can account for, `unread` means no write is outstanding and a read this+ * flow depends on did not answer.+ */+export type GatewayBootstrapReason = 'refused' | 'unknown' | 'unread' | 'disabled';++export class GatewayBootstrapError extends Error {+ readonly reason: GatewayBootstrapReason;+ /** The step that produced it, for the caller's error surface. */+ readonly step: 'seed' | 'readback' | 'capability' | 'persistence' | 'start' | 'runtime';+ readonly status?: number;+ readonly detail?: string;++ constructor(+ reason: GatewayBootstrapReason,+ step: GatewayBootstrapError['step'],+ options: { status?: number; detail?: string } = {},+ ) {+ super(`gateway bootstrap ${step}: ${reason}`);+ this.name = 'GatewayBootstrapError';+ this.reason = reason;+ this.step = step;+ this.status = options.status;+ this.detail = options.detail;+ }+}++/**+ * The fields of `/api/config` this flow is allowed to read.+ *+ * Narrow on purpose: validating the whole config would couple setup to every future+ * field, and an absent or malformed one of these is unread state rather than an+ * opt-out — which is a distinction the caller has to be able to make.+ */+export type SetupConfigSnapshot = {+ version: 'v2';+ setup_completed: boolean;+ capabilityEnabled: boolean;+ savedIntentEnabled: boolean;+ primaryPlatform: string;+ enabledPlatforms: string[];+ /** The validated body, for the shell's existing server-config state. */+ raw: Record<string, unknown>;+};++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++/** The server's error shape is a string on some handlers and an object on others. */+function errorDetail(body: unknown): string | undefined {+ if (!isRecord(body)) return undefined;+ const error = body.error;+ if (typeof error === 'string') return error;+ if (isRecord(error) && typeof error.message === 'string') return error.message;+ if (body.ok === false && typeof body.message === 'string') return body.message;+ return undefined;+}++const hasError = (body: unknown): boolean =>+ isRecord(body) && (body.ok === false || body.error !== undefined);++async function parseJson(response: Response): Promise<unknown> {+ try {+ return await response.json();+ } catch {+ return undefined;+ }+}++/**+ * Validate a config body, or explain what was missing.+ *+ * Returns `null` rather than throwing so both callers — the POST acknowledgement and+ * the GET readback — can decide for themselves what an invalid body means at their+ * own step.+ */+export function readSetupConfig(body: unknown): SetupConfigSnapshot | null {+ if (!isRecord(body) || hasError(body)) return null;+ if (body.version !== 'v2') return null;+ if (typeof body.setup_completed !== 'boolean') return null;++ const platforms = body.platforms;+ if (!isRecord(platforms)) return null;+ if (typeof platforms.primary !== 'string') return null;+ const enabled = platforms.enabled;+ if (!Array.isArray(enabled) || enabled.some((entry) => typeof entry !== 'string')) return null;++ if (!isRecord(body.runtime) || !isRecord(body.agents)) return null;++ const capabilities = body.capabilities;+ const capability = isRecord(capabilities) ? capabilities.model_hub : undefined;+ const saved = body.model_hub;+ if (!isRecord(capability) || typeof capability.enabled !== 'boolean') return null;+ if (!isRecord(saved) || typeof saved.enabled !== 'boolean') return null;++ return {+ version: 'v2',+ setup_completed: body.setup_completed,+ capabilityEnabled: capability.enabled,+ savedIntentEnabled: saved.enabled,+ primaryPlatform: platforms.primary,+ enabledPlatforms: enabled as string[],+ raw: body,+ };+}++export type GatewayBootstrapDeps = {+ /** The CSRF-aware `apiFetch`, injected so the sequence is testable as itself. */+ fetch: (input: string, init?: RequestInit) => Promise<Response>;+ getBackendConnection: (backend: AgentBackend) => Promise<BackendConnectionState>;+ /** `useStatus().control`, which already rejects a non-2xx response. */+ control: (action: string) => Promise<unknown>;+ getRuntimeStatus: () => Promise<RuntimeDependency>;+};++export type GatewayBootstrapResult = { config: SetupConfigSnapshot; runtime: RuntimeDependency };++/**+ * @param backend the assistant whose connection read proves the config file exists.+ * Any one would do — the handler calls `load_config()` either way — so the caller+ * passes the one it is about to work with rather than this module picking.+ */+export async function bootstrapGateway(+ deps: GatewayBootstrapDeps,+ backend: AgentBackend,+): Promise<GatewayBootstrapResult> {+ // 1. Seed, exactly once. A definitive refusal throws from inside it; anything else+ // leaves a write to account for, and accounting for a write is reading.+ const outstanding = await seedConfig(deps);++ // 2. Read back, uncached and directly: this POST cleared no `ApiContext` cache and+ // emitted no convergence event, so a cached read here would describe the world+ // before the write. An acknowledged write and an unaccounted one take the same+ // read, because they ask the server the same question — what does the config say+ // now — and only the answer can tell them apart.+ let readback: Response;+ try {+ readback = await deps.fetch('/api/config', { cache: 'no-store' });+ } catch {+ // An outstanding write is the more specific answer, and it is why a retry here+ // may reseed at all. Only a read that succeeds retires it.+ throw outstanding ?? new GatewayBootstrapError('unread', 'readback');+ }+ const config = readback.ok ? readSetupConfig(await parseJson(readback)) : null;+ if (!config) {+ throw outstanding ?? new GatewayBootstrapError('unread', 'readback', { status: readback.status });+ }++ // 3. The prerequisite boundary. Stop here without touching the preference: a+ // person who turned the gateway off in Settings did so deliberately, and setup+ // silently turning it back on would be the worst possible answer.+ //+ // This answers the attempt whatever became of the write. Reporting an unaccounted+ // seed instead would send someone to retry a write whose fate has stopped+ // mattering, when what they are owed is the configuration path.+ if (!config.capabilityEnabled || !config.savedIntentEnabled) {+ throw new GatewayBootstrapError('disabled', 'capability');+ }++ // 4. Prove persistence. A valid GET cannot do it alone — the server answers with an+ // in-memory default when no file exists, so the seed's outcome is still open+ // until a handler that actually calls `load_config()` succeeds.+ //+ // Which is also what retires an unaccounted seed: the empty patch's only intended+ // effect was a config file the server can load, and a handler that just loaded one+ // is that effect, observed. Everything after this line answers for itself.+ let connection: BackendConnectionState;+ try {+ connection = await readConnection(deps, backend);+ } catch (error) {+ throw outstanding ?? error;+ }++ // 5. Start, but only a controller confirmed stopped. Draining, failed or unknown+ // are somebody's existing recovery path; inferring a restart from them would+ // interrupt whatever is really happening.+ if (connection.application === 'stopped') {+ const result = await deps.control('start').catch(() => {+ throw new GatewayBootstrapError('unknown', 'start');+ });+ if (!isRecord(result) || result.ok !== true || result.action !== 'start') {+ throw new GatewayBootstrapError('unknown', 'start', { detail: errorDetail(result) });+ }+ connection = await readConnection(deps, backend);+ }+ if (connection.application !== 'applied') {+ throw new GatewayBootstrapError('unknown', 'start', { detail: connection.application });+ }++ // 6. Observe. Controller startup has already run its own recovery with the+ // installer admission the server owns; this reads what came of it.+ let runtime: RuntimeDependency;+ try {+ runtime = await deps.getRuntimeStatus();+ } catch {+ throw new GatewayBootstrapError('unread', 'runtime');+ }+ if (!isRecord(runtime) || !isRecord((runtime as unknown as Record<string, unknown>).status)) {+ throw new GatewayBootstrapError('unread', 'runtime');+ }++ return { config, runtime };+}++/**+ * Send the empty patch once, and say what is still unaccounted for afterwards.+ *+ * An empty patch, because `configMutationsToPayload` rejects an empty mutation list+ * before it ever reaches HTTP — the general validator stays as it is, and this+ * composition goes around it rather than through it.+ *+ * Returns the error that stays outstanding, or `null` when the server acknowledged+ * the write in terms this flow can read. Throws only for a definitive refusal, which+ * no later read may clear: a server that says no has answered, and reading the config+ * afterwards describes what exists, not what it declined to do.+ */+async function seedConfig(deps: GatewayBootstrapDeps): Promise<GatewayBootstrapError | null> {+ let seeded: Response;+ try {+ seeded = await deps.fetch('/api/config', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({}),+ });+ } catch {+ // The request may never have reached the server, or may have committed and lost+ // its reply on the way back. Unknown, not refused — and never sent again.+ return new GatewayBootstrapError('unknown', 'seed');+ }+ const body = await parseJson(seeded);+ if (!seeded.ok || hasError(body)) {+ const evidence = { status: seeded.status, detail: errorDetail(body) };+ // A server that says no is definitive; a server that broke is not.+ if (seeded.status < 500) throw new GatewayBootstrapError('refused', 'seed', evidence);+ return new GatewayBootstrapError('unknown', 'seed', evidence);+ }+ // A 2xx is an acknowledgement only if it carries the config these handlers return.+ // A truncated or unrecognisable body says nothing about what was written, so it is+ // reconciled by reading like any other unknown rather than believed like a success.+ // The status stays as the evidence it is: the server did answer, and this is what+ // it answered with.+ if (!readSetupConfig(body)) {+ return new GatewayBootstrapError('unknown', 'seed', { status: seeded.status });+ }+ return null;+}++async function readConnection(+ deps: GatewayBootstrapDeps,+ backend: AgentBackend,+): Promise<BackendConnectionState> {+ let connection: BackendConnectionState;+ try {+ connection = await deps.getBackendConnection(backend);+ } catch {+ throw new GatewayBootstrapError('unknown', 'persistence');+ }+ if (!connection?.ok || typeof connection.application !== 'string') {+ throw new GatewayBootstrapError('unknown', 'persistence');+ }+ return connection;+}diff --git a/ui/src/components/onboarding/providers/providerStage.test.ts b/ui/src/components/onboarding/providers/providerStage.test.tsnew file mode 100644index 000000000..2f30b85d2--- /dev/null+++ b/ui/src/components/onboarding/providers/providerStage.test.ts@@ -0,0 +1,1090 @@+// The rules the provider stage is easiest to get wrong, stated over the real shapes+// the server produces. Each case here is a mistake that would render plausibly and+// be wrong: a vendor occupying two slots because a scan and a source spell it+// differently, a connected card changing colour because someone toggled a selection,+// a summary that promises providers nobody added, a CTA that offers to continue with+// nothing to continue with.+import { describe, expect, it } from 'vitest';++import type { MigrationItem, Source, SourceStatus } from '@/components/settings/models/types';+import en from '@/i18n/en.json';+import zh from '@/i18n/zh.json';++import { readyRegion, loadingRegion, degradedRegion, unreadRegion } from '@/components/settings/models/regionRead';+import type { AgentSupply, RuntimeDependency, RuntimeHealth } from '@/components/settings/models/types';++import {+ COUNTED_LABEL,+ PLAIN_LABEL,+ PROVIDER_SLOT_COUNT,+ addedThroughMoreCount,+ adoptionBackend,+ defaultSelection,+ gatewayEvidenceSettled,+ gatewayIntent,+ offeredImportKeys,+ pendingImportRows,+ providerAction,+ providerSetupAction,+ providerSlots,+ providerSummary,+ reconcileSelection,+ slotSelected,+ toggleSlotSelection,+ unlistedDetected,+ usableSource,+} from './providerStage';++const row = (over: Partial<MigrationItem>): MigrationItem => ({+ id: 'mig_1',+ backend: 'codex',+ kind: 'api_key',+ masked_detail: 'sk-…9f21 · Codex configuration',+ masked_credential: 'sk-…9f21',+ proposed_action: 'import',+ selected: true,+ notes_key: null,+ vendor: 'openai',+ ...over,+});++const source = (over: Partial<Source> & { id: string; vendor: string }): Source => ({+ last_discovered_at: null,+ kind: 'api_key',+ display_name: over.vendor,+ protocol: 'openai_chat',+ supply_channel: 'hub',+ billing: 'metered',+ state: { status: 'active' },+ models: [],+ ...over,+});++const scanOf = (...items: MigrationItem[]) => ({ items });++describe('providerSlots', () => {+ it('fills the empty stage with the shortlist it opens with, in its order', () => {+ const slots = providerSlots({ sources: [], scan: null });++ expect(slots).toHaveLength(PROVIDER_SLOT_COUNT);+ expect(slots.map((slot) => slot.vendor)).toEqual(['openai', 'anthropic']);+ expect(slots.every((slot) => slot.kind === 'empty')).toBe(true);+ });++ it('puts what exists ahead of what was merely found, and tops up from the shortlist', () => {+ const slots = providerSlots({+ sources: [source({ id: 'src_1', vendor: 'zhipuai', display_name: 'Zhipu' })],+ scan: null,+ });++ expect(slots.map((slot) => [slot.vendor, slot.kind])).toEqual([+ ['zhipuai', 'connected'],+ ['openai', 'empty'],+ ]);+ });++ it('never seats one provider twice when the scan and the source spell it differently', () => {+ // An OpenCode row calls Gemini `google`; a source created from the catalog+ // calls it `gemini`. Without the alias both would take a slot and the stage+ // would offer to import a key for a provider already connected.+ const slots = providerSlots({+ sources: [source({ id: 'src_1', vendor: 'gemini' })],+ scan: scanOf(row({ id: 'mig_g', backend: 'opencode', kind: 'opencode_provider', vendor: 'google' })),+ });++ expect(slots.map((slot) => slot.vendor)).toEqual(['gemini', 'openai']);+ });++ it('ignores a source that cannot be used and offers the shortlist instead', () => {+ const slots = providerSlots({+ sources: [source({ id: 'src_1', vendor: 'xai', state: { status: 'needs_action', detail_key: null } })],+ scan: null,+ });++ expect(slots.map((slot) => slot.vendor)).toEqual(['openai', 'anthropic']);+ });++ it('keeps a detected candidate on the stage when its consent group is blocked, and says why', () => {+ // A backend whose linked rows include something this entry cannot import is+ // reviewed in Settings. What it is not is invisible: the key is on the machine,+ // and replacing it with an empty 「add Anthropic」 invitation is how a person+ // adds a second copy of the key they already have.+ const slots = providerSlots({+ sources: [],+ scan: scanOf(+ row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_b', backend: 'claude', vendor: 'anthropic', kind: 'oauth_native', proposed_action: 'reauth' }),+ ),+ });++ expect(slots.map((slot) => [slot.vendor, slot.kind])).toEqual([['anthropic', 'detected'], ['openai', 'empty']]);+ // Found, with a reason, and no permission: nothing in the card's `backends` is a+ // backend anything here may take over. The reason is the migration feature's own+ // note for that row — a server note nobody recognises still reads as a sentence.+ expect(slots[0].reasons).toEqual(['settings.models.migration.blocked.fallback']);+ expect(slots[0].backends).toEqual([]);+ });++ it('keeps the card and names setup’s own scope when the group holds an importable subscription', () => {+ // The harder half of the same rule, and the one that reads as working. This+ // OAuth store is importable — Settings would take it over — so nothing on the+ // server declines it. What declines it is setup's own scope: its copy names API+ // keys only. And the key beside it cannot be taken alone, because the server+ // migrates a backend whole and refuses a batch that omits one of its rows.+ const slots = providerSlots({+ sources: [],+ scan: scanOf(+ row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_b', backend: 'claude', vendor: 'anthropic', kind: 'oauth_native' }),+ ),+ });++ expect(slots.map((slot) => [slot.vendor, slot.kind])).toEqual([['anthropic', 'detected'], ['openai', 'empty']]);+ expect(slots[0].reasons).toEqual(['onboarding.import.outOfScope']);+ expect(slots[0].backends).toEqual([]);+ });++ it('keeps a blocked-only scan on the stage rather than falling back to the shortlist', () => {+ // Nothing here is takeable from setup, so the actionable count is zero. The stage+ // is still what the machine holds: an empty shortlist would say nothing was found.+ const scan = scanOf(+ row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_b', backend: 'claude', vendor: 'anthropic', kind: 'oauth_native' }),+ row({ id: 'mig_c', backend: 'opencode', kind: 'opencode_provider', vendor: 'zhipuai' }),+ row({ id: 'mig_d', backend: 'opencode', kind: 'oauth_native', proposed_action: 'keep_native', vendor: undefined }),+ );+ const slots = providerSlots({ sources: [], scan });++ expect(slots.map((slot) => [slot.vendor, slot.kind])).toEqual([+ ['anthropic', 'detected'],+ ['zhipuai', 'detected'],+ ]);+ expect(slots.every((slot) => slot.reasons.length > 0 && slot.backends.length === 0)).toBe(true);++ // Visible, and contributing nothing: no consent by default, none obtainable by+ // pressing, no rows to submit, and nothing for the capsule to advertise.+ expect(defaultSelection(scan)).toEqual([]);+ expect(slots.some((slot) => slotSelected(slot, ['claude', 'opencode']))).toBe(false);+ expect(toggleSlotSelection({ scan, selectedBackends: [] }, slots[0])).toEqual([]);+ expect(pendingImportRows({ scan, selectedBackends: ['claude', 'opencode'] })).toEqual([]);+ expect(offeredImportKeys({ scan, selectedBackends: [] })).toEqual([]);+ });++ it('does not lend one vendor’s takeable group the reason of its blocked one', () => {+ // The same brand's key sits in two backends: one this entry may take over whole,+ // one it may not. The card is the takeable one — pressing it consents to the+ // group it may — and the blocked group keeps its reason in the review it belongs+ // to. A card saying 「not from here」 that was pressable anyway contradicts itself.+ const slots = providerSlots({+ sources: [],+ scan: scanOf(+ row({ id: 'mig_a', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_b', backend: 'opencode', kind: 'opencode_provider', vendor: 'openai' }),+ row({ id: 'mig_c', backend: 'opencode', kind: 'oauth_native', proposed_action: 'keep_native' }),+ ),+ });++ expect(slots[0]).toMatchObject({ vendor: 'openai', kind: 'detected', reasons: [] });+ // Consent covers the backend that offered it, and not the one that did not.+ expect(slots[0].backends).toEqual(['codex']);+ });++ it('carries the masked credential and every consenting backend on a detected card', () => {+ const [slot] = providerSlots({+ sources: [],+ scan: scanOf(+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai', masked_credential: 'sk-…9f21' }),+ row({ id: 'mig_2', backend: 'opencode', kind: 'opencode_provider', vendor: 'openai' }),+ ),+ });++ expect(slot).toMatchObject({ vendor: 'openai', kind: 'detected', mask: 'sk-…9f21' });+ expect([...slot.backends].sort()).toEqual(['codex', 'opencode']);+ });++ it('marks a source saved but not yet verified, and nothing else', () => {+ // `save_unverified: true` is what both hosts of the key form send, so a card can+ // be connected with nothing having confirmed the key answers. Settings discloses+ // that state; a card that did not would report it as a working provider.+ const slots = providerSlots({+ sources: [+ source({ id: 'src_1', vendor: 'openai', state: { status: 'standby' }, verification_pending: 'vp_fixture' }),+ source({ id: 'src_2', vendor: 'anthropic' }),+ ],+ scan: null,+ });++ expect(slots.map((slot) => [slot.vendor, slot.kind, slot.pending])).toEqual([+ ['openai', 'connected', true],+ ['anthropic', 'connected', false],+ ]);+ });++ it('never marks a detected or empty card pending: neither has a key that was written', () => {+ const slots = providerSlots({+ sources: [],+ scan: scanOf(row({ id: 'mig_1', backend: 'codex', vendor: 'openai' })),+ });++ expect(slots.map((slot) => [slot.kind, slot.pending])).toEqual([+ ['detected', false],+ ['empty', false],+ ]);+ });++ it('names a credential the server did not name by its mask, never by a brand', () => {+ // No vendor and no display name: an older server, or a key in a file nothing+ // claims. It is still a key on this machine, so it keeps its card — named by+ // what is known about it. Naming it after the backend that held the file would+ // put 「OpenAI」 on a key that may be anything, and a brand mark would do the+ // same silently, so the card falls back to the key it is.+ const slots = providerSlots({+ sources: [],+ scan: scanOf(row({+ id: 'mig_1',+ vendor: undefined,+ display_name: undefined,+ masked_detail: 'sk-…abcd · Codex configuration',+ masked_credential: undefined,+ })),+ });++ expect(slots.map((slot) => slot.kind)).toEqual(['detected', 'empty']);+ expect(slots[0].label).toBe('sk-…abcd · Codex configuration');+ // Its own identity, so a second unnamed row is a second card rather than a+ // collision, and no brand mark: `brand` is what the glyph is filed under.+ expect(slots[0]).toMatchObject({ vendor: 'mig_1', brand: null, mask: null });+ // And takeable: nothing about it being unnamed blocks the group it belongs to.+ expect(slots[0].backends).toEqual(['codex']);+ expect(slots[0].reasons).toEqual([]);+ });+});++describe('unlistedDetected', () => {+ it('is empty when the stage is already drawing everything that was found', () => {+ // An add dialog whose first tab repeats the two cards immediately behind it+ // offers nothing — this emptiness is what takes the tab away.+ const input = {+ sources: [],+ scan: scanOf(+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_2', backend: 'claude', vendor: 'anthropic' }),+ ),+ };++ expect(providerSlots(input).map((slot) => slot.kind)).toEqual(['detected', 'detected']);+ expect(unlistedDetected(input)).toEqual([]);+ });++ it('lists what the stage ran out of room for', () => {+ const detected = unlistedDetected({+ sources: [],+ scan: scanOf(+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_2', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_3', backend: 'opencode', kind: 'opencode_provider', vendor: 'google' }),+ ),+ });++ // `google` is the scan's spelling of the brand the catalog calls `gemini`.+ expect(detected.map((slot) => slot.vendor)).toEqual(['gemini']);+ });++ it('still offers a detected credential whose brand is already connected', () => {+ // The scan reads native stores and knows nothing about what the Hub already+ // holds, so a row sharing a brand with a connected source is a second key+ // until something compares the credentials. The stage collapsing the two into+ // one card is presentation; letting that collapse answer 「is there another key+ // on this machine」 is how a row the capsule still counts disappears from the+ // stage AND from the only pane that could take it.+ const input = {+ sources: [+ source({ id: 'src_1', vendor: 'openai', masked_credential: 'sk-…1111' }),+ source({ id: 'src_2', vendor: 'anthropic', masked_credential: 'sk-…2222' }),+ ],+ scan: scanOf(row({ id: 'mig_1', backend: 'codex', vendor: 'openai' })),+ };++ // One card per brand, as before: two connected facts, no third slot.+ expect(providerSlots(input).map((slot) => [slot.vendor, slot.kind])).toEqual([+ ['openai', 'connected'],+ ['anthropic', 'connected'],+ ]);+ // And the row is reviewable, carrying its own masked credential so the person+ // can tell it apart from the key already connected under that brand.+ expect(unlistedDetected(input).map((slot) => [slot.vendor, slot.kind, slot.mask])).toEqual([+ ['openai', 'detected', 'sk-…9f21'],+ ]);+ });++ it('keeps an alias-collapsed detection reviewable behind the card that absorbed it', () => {+ // `google` and `gemini` are one brand, so the stage draws one card — the+ // connected one, because it is a fact. The detection behind it is still a+ // separate native store, and Add more is where it stays reachable.+ const input = {+ sources: [source({ id: 'src_1', vendor: 'gemini', masked_credential: 'sk-…1111' })],+ scan: scanOf(row({ id: 'mig_g', backend: 'opencode', kind: 'opencode_provider', vendor: 'google' })),+ };++ expect(providerSlots(input).map((slot) => [slot.vendor, slot.kind])).toEqual([+ ['gemini', 'connected'],+ ['openai', 'empty'],+ ]);+ expect(unlistedDetected(input).map((slot) => slot.vendor)).toEqual(['gemini']);+ });+});++describe('pendingImportRows', () => {+ it('submits nothing while nothing is consented to', () => {+ expect(pendingImportRows({+ scan: scanOf(row({ id: 'mig_1' })),+ selectedBackends: [],+ })).toEqual([]);+ });++ it('counts every importable row of a consented backend, not the cards it drew', () => {+ // Two keys, one brand, one card — and two rows in the batch. A count taken from+ // the stage would promise one import and perform two.+ const rows = pendingImportRows({+ scan: scanOf(+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_2', backend: 'codex', vendor: 'openai', masked_credential: 'sk-…0001' }),+ ),+ selectedBackends: ['codex'],+ });++ expect(rows.map((item) => item.id)).toEqual(['mig_1', 'mig_2']);+ });++ it('submits nothing for a group holding any row it cannot import', () => {+ // Consent is per group, never per row: one row the server does not propose+ // importing blocks the whole custody boundary, so the batch is empty rather+ // than partial. Settings is where a mixed group gets resolved.+ const rows = pendingImportRows({+ scan: scanOf(+ row({ id: 'mig_1', backend: 'codex' }),+ row({ id: 'mig_2', backend: 'codex', proposed_action: 'keep_native' }),+ ),+ selectedBackends: ['codex'],+ });++ expect(rows).toEqual([]);+ });++ it('refuses a backend this entry point cannot consent to, however it got selected', () => {+ // A blocked group is Settings' to resolve. Naming it in the selection must not+ // make the CTA promise a batch the dialog would decline to build.+ const rows = pendingImportRows({+ scan: scanOf(+ row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_b', backend: 'claude', kind: 'oauth_native', proposed_action: 'reauth' }),+ ),+ selectedBackends: ['claude'],+ });++ expect(rows).toEqual([]);+ });++ it('never submits a subscription store alongside the key it is linked to', () => {+ // The one that would have shipped silently: the batch is unscoped by design, so+ // a backend reaching the selection at all is what has to be impossible. If this+ // returned both rows, setup would take over an OAuth sign-in its copy never+ // mentioned; if it returned only the key, the server would refuse the batch.+ const rows = pendingImportRows({+ scan: scanOf(+ row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_b', backend: 'claude', vendor: 'anthropic', kind: 'oauth_native' }),+ ),+ selectedBackends: ['claude'],+ });++ expect(rows).toEqual([]);+ });+});++describe('offeredImportKeys', () => {+ it('advertises only what the review could really act on', () => {+ // The capsule's number and the dialog's batch come from one grouping. A count+ // taken from the raw scan would offer keys the review then refuses to build,+ // which reads as the dialog losing them.+ const offered = offeredImportKeys({+ scan: scanOf(+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_b', backend: 'claude', kind: 'oauth_native', proposed_action: 'reauth' }),+ ),+ selectedBackends: [],+ });++ expect(offered.map((item) => item.id)).toEqual(['mig_1']);+ });++ it('does not count a key it could only take by taking a subscription too', () => {+ // Counting this key would put 「发现 1 个可导入的 API Key」 above a review whose+ // only group is blocked — an offer with nothing to press.+ const offered = offeredImportKeys({+ scan: scanOf(+ row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_b', backend: 'claude', vendor: 'anthropic', kind: 'oauth_native' }),+ ),+ selectedBackends: [],+ });++ expect(offered).toEqual([]);+ });++ it('is independent of what is consented to, unlike the batch', () => {+ const scan = scanOf(row({ id: 'mig_1', backend: 'codex', vendor: 'openai' }));++ expect(offeredImportKeys({ scan, selectedBackends: [] })).toHaveLength(1);+ expect(pendingImportRows({ scan, selectedBackends: [] })).toHaveLength(0);+ });+});++describe('defaultSelection', () => {+ it('opens on the rows the server itself proposes, the way the shipped dialog does', () => {+ expect(defaultSelection(scanOf(+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_2', backend: 'opencode', kind: 'opencode_provider', vendor: 'xai' }),+ ))).toEqual(['codex', 'opencode']);+ });++ it('leaves a group the server did not tick alone', () => {+ // `selected: false` is the server declining to propose that row. Ticking it here+ // would be this screen consenting on someone's behalf.+ expect(defaultSelection(scanOf(+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_2', backend: 'opencode', kind: 'opencode_provider', vendor: 'xai', selected: false }),+ ))).toEqual(['codex']);+ });++ it('never opens on a blocked group', () => {+ expect(defaultSelection(scanOf(+ row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_b', backend: 'claude', kind: 'oauth_native', proposed_action: 'reauth' }),+ ))).toEqual([]);+ });++ it('never opens on a group setup itself cannot take whole', () => {+ // The server ticked both rows; Settings would open on them. Setup may not, and+ // opening ticked would make the CTA promise a batch it refuses to build.+ expect(defaultSelection(scanOf(+ row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_b', backend: 'claude', vendor: 'anthropic', kind: 'oauth_native' }),+ ))).toEqual([]);+ });++ it('has nothing to open on without a scan', () => {+ expect(defaultSelection(null)).toEqual([]);+ });+});++describe('toggleSlotSelection', () => {+ const stage = (...items: MigrationItem[]) => providerSlots({ sources: [], scan: scanOf(...items) });++ it('consents to the whole linked closure, not just the card that was pressed', () => {+ // Codex and OpenCode read the same credential file, so migrating one migrates+ // both. Half of that consent does not exist, so it is never representable.+ const items = [+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai', required_backends: ['codex', 'opencode'] }),+ row({ id: 'mig_2', backend: 'opencode', kind: 'opencode_provider', vendor: 'openai', required_backends: ['codex', 'opencode'] }),+ ];+ const [slot] = stage(...items);++ const next = toggleSlotSelection({ scan: scanOf(...items), selectedBackends: [] }, slot);++ expect([...next].sort()).toEqual(['codex', 'opencode']);+ });++ it('gives the whole closure back when the card is pressed again', () => {+ const items = [+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai', required_backends: ['codex', 'opencode'] }),+ row({ id: 'mig_2', backend: 'opencode', kind: 'opencode_provider', vendor: 'openai', required_backends: ['codex', 'opencode'] }),+ ];+ const [slot] = stage(...items);++ const next = toggleSlotSelection(+ { scan: scanOf(...items), selectedBackends: ['codex', 'opencode'] },+ slot,+ );++ expect(next).toEqual([]);+ });++ it('leaves another card\'s consent alone', () => {+ const items = [+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_2', backend: 'claude', vendor: 'anthropic' }),+ ];+ const [openai] = stage(...items);++ const next = toggleSlotSelection({ scan: scanOf(...items), selectedBackends: ['claude'] }, openai);++ expect([...next].sort()).toEqual(['claude', 'codex']);+ });++ it('is inert on a connected card, so a fact cannot be toggled off', () => {+ const items = [row({ id: 'mig_1', backend: 'claude', vendor: 'anthropic' })];+ const [connected] = providerSlots({+ sources: [source({ id: 'src_1', vendor: 'openai' })],+ scan: scanOf(...items),+ });++ expect(connected.kind).toBe('connected');+ expect(toggleSlotSelection({ scan: scanOf(...items), selectedBackends: ['claude'] }, connected))+ .toEqual(['claude']);+ });+});++describe('reconcileSelection', () => {+ it('keeps a consent the fresh scan still supports', () => {+ const before = scanOf(row({ id: 'mig_1', backend: 'codex' }));+ expect(reconcileSelection({+ scan: scanOf(row({ id: 'mig_1', backend: 'codex' })),+ selectedBackends: ['codex'],+ }, before)).toEqual(['codex']);+ });++ it('keeps a consent whose rows came back in a different order', () => {+ // Scan order is the server's, not a promise. Comparing the rows as a set is+ // what stops a reordered rescan from reading as changed credentials and+ // silently un-ticking a card nobody touched.+ const before = scanOf(+ row({ id: 'mig_1', backend: 'codex' }),+ row({ id: 'mig_2', backend: 'codex', vendor: 'openai' }),+ );+ expect(reconcileSelection({+ scan: scanOf(+ row({ id: 'mig_2', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_1', backend: 'codex' }),+ ),+ selectedBackends: ['codex'],+ }, before)).toEqual(['codex']);+ });++ it('drops a backend the rescan no longer offers', () => {+ // What this prevents: importing one of two consented backends, rescanning, and+ // leaving the CTA counting a batch the dialog would now build as empty.+ const before = scanOf(+ row({ id: 'mig_1', backend: 'codex' }),+ row({ id: 'mig_2', backend: 'claude', vendor: 'anthropic' }),+ );+ expect(reconcileSelection({+ scan: scanOf(row({ id: 'mig_1', backend: 'codex' })),+ selectedBackends: ['codex', 'claude'],+ }, before)).toEqual(['codex']);+ });++ it('drops a backend that gained a row nobody consented to', () => {+ // The quiet one. A key that appeared under an already-ticked backend would ride+ // into the next batch on a decision made about a different set of credentials.+ const before = scanOf(row({ id: 'mig_1', backend: 'codex' }));+ expect(reconcileSelection({+ scan: scanOf(+ row({ id: 'mig_1', backend: 'codex' }),+ row({ id: 'mig_2', backend: 'codex', vendor: 'openai' }),+ ),+ selectedBackends: ['codex'],+ }, before)).toEqual([]);+ });++ it('drops a backend whose closure grew into one that was never consented to', () => {+ // Half a custody closure is a press that always fails: the server refuses a+ // batch that migrates one backend and leaves a linked one out.+ const before = scanOf(row({ id: 'mig_1', backend: 'codex' }));+ expect(reconcileSelection({+ scan: scanOf(+ row({ id: 'mig_1', backend: 'codex', required_backends: ['codex', 'claude'] }),+ row({ id: 'mig_2', backend: 'claude', vendor: 'anthropic' }),+ ),+ selectedBackends: ['codex'],+ }, before)).toEqual([]);+ });++ it('drops a backend that became blocked between scans', () => {+ const before = scanOf(row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }));+ expect(reconcileSelection({+ scan: scanOf(+ row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_b', backend: 'claude', kind: 'oauth_native', proposed_action: 'reauth' }),+ ),+ selectedBackends: ['claude'],+ }, before)).toEqual([]);+ });++ it('empties the selection when the scan itself is gone', () => {+ expect(reconcileSelection({ scan: null, selectedBackends: ['codex'] }, null)).toEqual([]);+ });+});++const supply = (over: Partial<AgentSupply> & { backend: AgentSupply['backend'] }): AgentSupply => ({+ cli_present: true,+ mode: 'direct',+ menu_kind: 'fixed',+ ...over,+});++describe('adoptionBackend', () => {+ it('names nothing when no CLI is installed', () => {+ expect(adoptionBackend([supply({ backend: 'codex', cli_present: false })])).toBeNull();+ });++ it('names a present backend that has not been adopted yet', () => {+ expect(adoptionBackend([+ supply({ backend: 'claude', cli_present: false }),+ supply({ backend: 'codex' }),+ ])).toBe('codex');+ });++ it('prefers the unadopted backend over an adopted one earlier in the order', () => {+ // `resumeGatewayAdoption` returns early — without touching the runtime at all —+ // when the backend it is named for is already in hub mode. Naming `claude` here+ // would skip the install and start this whole screen exists to perform.+ expect(adoptionBackend([+ supply({ backend: 'claude', mode: 'hub' }),+ supply({ backend: 'codex' }),+ ])).toBe('codex');+ });++ it('falls back to the first present backend when every one is already adopted', () => {+ expect(adoptionBackend([+ supply({ backend: 'codex', mode: 'hub' }),+ supply({ backend: 'claude', mode: 'hub' }),+ ])).toBe('claude');+ });+});++const runtime = (health: RuntimeHealth, over: Partial<RuntimeDependency> = {}): RuntimeDependency => ({+ contract_version: 10,+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },+ status: { verified: true, health },+ ...over,+});++describe('gatewayIntent', () => {+ const enabled = { capability: 'enabled', gatewayEnabled: true } as const;++ it('has nothing to do about an engine that is already serving', () => {+ expect(gatewayIntent({ ...enabled, runtimeRead: readyRegion(runtime('ok')) }))+ .toEqual({ kind: 'running' });+ });++ it('treats a degraded but running engine as serving, because it still routes', () => {+ expect(gatewayIntent({ ...enabled, runtimeRead: readyRegion(runtime('degraded')) }))+ .toEqual({ kind: 'running' });+ });++ it('installs a missing engine where installation is admitted', () => {+ // The snapshot rides along: the resume starts from the state that authorized+ // it rather than reading the same runtime a second time and racing itself.+ const missing = runtime('not_installed');+ expect(gatewayIntent({ ...enabled, runtimeRead: readyRegion(missing) }))+ .toEqual({ kind: 'resume', step: 'install', runtime: missing });+ });++ it('starts an installed but stopped engine even where installation is unsupported', () => {+ // Admission gates fresh installation only. Refusing to START a Hub that is+ // already on the machine would strand a working engine on a technicality.+ const unsupported = runtime('not_started', {+ manifest: { name: 'cliproxyapi', resolution: 'unsupported', version: '1.0.0', source_sha: 'sha', assets: [] },+ });++ expect(gatewayIntent({ ...enabled, runtimeRead: readyRegion(unsupported) }))+ .toEqual({ kind: 'resume', step: 'start', runtime: unsupported });+ });++ it('reports installation as unsupported rather than attempting it', () => {+ const unsupported = runtime('not_installed', {+ manifest: { name: 'cliproxyapi', resolution: 'unsupported', version: '1.0.0', source_sha: 'sha', assets: [] },+ });++ expect(gatewayIntent({ ...enabled, runtimeRead: readyRegion(unsupported) }))+ .toEqual({ kind: 'unsupported' });+ });++ it.each([+ ['still in flight', loadingRegion<RuntimeDependency>()],+ ['already being retried', degradedRegion(runtime('ok'), 'refreshing', true)],+ ['failed with nothing to ask again', unreadRegion<RuntimeDependency>(false)],+ ['failed a second time with nothing to ask again', degradedRegion(runtime('ok'), 'read_failed', false)],+ ] as const)('authorizes nothing, and asks for nothing, on a read %s', (_label, runtimeRead) => {+ // None of these is evidence the engine is absent — acting on one would install+ // over a Hub that is merely unreachable this second — and none of them is+ // something the person can do anything about either, so the card stays quiet.+ expect(gatewayIntent({ ...enabled, runtimeRead })).toEqual({ kind: 'waiting' });+ });++ it.each([+ ['a first read that failed', unreadRegion<RuntimeDependency>()],+ ['a later read that failed', degradedRegion(runtime('ok'), 'read_failed', true)],+ ] as const)('says %s is worth asking again, rather than showing an idle engine', (_label, runtimeRead) => {+ // The distinction `waiting` cannot carry: nothing is coming unless someone asks.+ // Folded into `waiting` this renders as the idle card — the engine looks fine+ // while Continue stays disabled for a reason nothing on screen gives.+ expect(gatewayIntent({ ...enabled, runtimeRead })).toEqual({ kind: 'unreadable' });+ });++ it('holds a failed read behind the gates that have not opened yet', () => {+ // A retry here would re-read a runtime the flow is not admitted to use. The+ // pending capability is the thing to wait for, and it is the shell's to resolve.+ expect(gatewayIntent({+ capability: 'pending',+ gatewayEnabled: null,+ runtimeRead: unreadRegion<RuntimeDependency>(),+ })).toEqual({ kind: 'waiting' });+ });++ it('waits rather than re-enabling a configuration someone turned off', () => {+ expect(gatewayIntent({ ...enabled, runtimeRead: readyRegion(runtime('not_installed', { enabled: false })) }))+ .toEqual({ kind: 'waiting' });+ });++ it.each([+ ['pending capability', { capability: 'pending', gatewayEnabled: true }],+ ['disabled capability', { capability: 'disabled', gatewayEnabled: true }],+ ['config not yet read', { capability: 'enabled', gatewayEnabled: null }],+ ['config turned off', { capability: 'enabled', gatewayEnabled: false }],+ ] as const)('waits while %s', (_label, gate) => {+ expect(gatewayIntent({ ...gate, runtimeRead: readyRegion(runtime('not_installed')) }))+ .toEqual({ kind: 'waiting' });+ });++ it('still reports a running engine the flow is otherwise not ready to use', () => {+ // Running health is independent of admission: the card should say the engine is+ // up even while the configuration read that gates the flow is still pending.+ expect(gatewayIntent({+ capability: 'pending',+ gatewayEnabled: null,+ runtimeRead: readyRegion(runtime('ok')),+ })).toEqual({ kind: 'running' });+ });+});++describe('gatewayEvidenceSettled', () => {+ const enabled = { capability: 'enabled', gatewayEnabled: true } as const;++ it.each([+ ['a read in flight', loadingRegion<RuntimeDependency>()],+ ['a re-read over the last value', degradedRegion(runtime('not_started'), 'refreshing', false)],+ ] as const)('is not answered by %s', (_label, runtimeRead) => {+ // The states the shell hands down on its way to an answer. `gatewayIntent` folds+ // all of them to `waiting`, which is the right thing to draw and the wrong thing+ // to spend a pending request on.+ expect(gatewayEvidenceSettled({ ...enabled, runtimeRead })).toBe(false);+ });++ it.each([+ ['capability is still being read', { capability: 'pending', gatewayEnabled: true }],+ ['the configuration has not been read', { capability: 'enabled', gatewayEnabled: null }],+ ] as const)('is not answered while %s', (_label, gate) => {+ expect(gatewayEvidenceSettled({ ...gate, runtimeRead: readyRegion(runtime('not_started')) }))+ .toBe(false);+ });++ it.each([+ ['a read that landed', readyRegion(runtime('not_started'))],+ ['a first read that failed', unreadRegion<RuntimeDependency>()],+ ['a later read that failed', degradedRegion(runtime('ok'), 'read_failed', true)],+ ['a failure nothing can ask again about', unreadRegion<RuntimeDependency>(false)],+ ] as const)('is answered by %s', (_label, runtimeRead) => {+ // Including the failures: 「不知道」 is an answer, and terminal until someone asks+ // again. A mutation left pending on one would fire on an unrelated later read.+ expect(gatewayEvidenceSettled({ ...enabled, runtimeRead })).toBe(true);+ });++ it.each([+ ['capability says so', { capability: 'disabled', gatewayEnabled: true }],+ ['the configuration says so', { capability: 'enabled', gatewayEnabled: false }],+ ] as const)('is answered by a gateway that is off, whatever the read holds, when %s', (_label, gate) => {+ // No runtime read overrides this, so there is nothing left to wait for: the+ // request is over, refused.+ expect(gatewayEvidenceSettled({ ...gate, runtimeRead: loadingRegion<RuntimeDependency>() }))+ .toBe(true);+ });+});++describe('slotSelected', () => {+ const connected = providerSlots({+ sources: [source({ id: 'src_1', vendor: 'openai' })],+ scan: null,+ })[0];+ const detected = providerSlots({+ sources: [],+ scan: scanOf(row({ id: 'mig_1', backend: 'codex', vendor: 'openai' })),+ })[0];++ it('never reports a connected card as selected, whatever is consented to', () => {+ // A connected card states a fact. If a selection toggle could change its fill,+ // deselecting a detected key would make an existing source look disconnected.+ expect(slotSelected(connected, [])).toBe(false);+ expect(slotSelected(connected, ['claude', 'codex', 'opencode'])).toBe(false);+ });++ it('reports a detected card selected only once its whole group is consented to', () => {+ expect(slotSelected(detected, [])).toBe(false);+ expect(slotSelected(detected, ['codex'])).toBe(true);+ });++ it('does not report a two-backend card selected on half its consent', () => {+ const [both] = providerSlots({+ sources: [],+ scan: scanOf(+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_2', backend: 'opencode', kind: 'opencode_provider', vendor: 'openai' }),+ ),+ });++ expect(slotSelected(both, ['codex'])).toBe(false);+ expect(slotSelected(both, ['codex', 'opencode'])).toBe(true);+ });+});++describe('providerSummary', () => {+ it('says nothing when nothing is added or chosen', () => {+ expect(providerSummary({ scan: null, sources: [], selected: [], failed: false })).toEqual({ kind: 'none' });+ });++ it('counts every added provider, not just the two on the stage', () => {+ const sources = [+ source({ id: 'src_1', vendor: 'openai' }),+ source({ id: 'src_2', vendor: 'anthropic' }),+ source({ id: 'src_3', vendor: 'xai' }),+ ];++ expect(providerSummary({ scan: null, sources, selected: [], failed: false }))+ .toEqual({ kind: 'added', count: 3, names: ['OpenAI', 'Anthropic', 'xAI'] });+ });++ it('counts one provider once however many keys it has', () => {+ const sources = [+ source({ id: 'src_1', vendor: 'openai' }),+ source({ id: 'src_2', vendor: 'openai', display_name: 'OpenAI (work)' }),+ ];++ expect(providerSummary({ scan: null, sources, selected: [], failed: false }))+ .toMatchObject({ kind: 'added', count: 1 });+ });++ it('prefers what is really there over what is merely consented to', () => {+ const sources = [source({ id: 'src_1', vendor: 'openai' })];+ const scan = scanOf(row({ id: 'mig_1', backend: 'claude', vendor: 'anthropic' }));++ expect(providerSummary({+ scan,+ sources,+ selected: ['claude'],+ failed: false,+ })).toMatchObject({ kind: 'added' });+ });++ it('names the consented cards while nothing has been added yet', () => {+ const scan = scanOf(row({ id: 'mig_1', backend: 'claude', vendor: 'anthropic' }));++ expect(providerSummary({+ scan,+ sources: [],+ selected: ['claude'],+ failed: false,+ })).toEqual({ kind: 'selected', count: 1, names: ['Anthropic'] });+ });++ it('names a consented provider the stage had no room to show', () => {+ // Three detected backends, two slots. Reading the sentence off the slots would+ // silently drop the third from a count the person is about to act on.+ const scan = scanOf(+ row({ id: 'mig_1', backend: 'claude', vendor: 'anthropic' }),+ row({ id: 'mig_2', backend: 'codex', vendor: 'openai' }),+ row({ id: 'mig_3', backend: 'opencode', kind: 'opencode_provider', vendor: 'xai' }),+ );++ expect(providerSummary({+ scan,+ sources: [],+ selected: ['claude', 'codex', 'opencode'],+ failed: false,+ })).toMatchObject({ kind: 'selected', count: 3 });+ });++ it('reports a failure ahead of anything it could otherwise say', () => {+ const sources = [source({ id: 'src_1', vendor: 'openai' })];++ expect(providerSummary({ scan: null, sources, selected: [], failed: true })).toEqual({ kind: 'error' });+ });+});++describe('addedThroughMoreCount', () => {+ it('counts only the added sources that are still usable', () => {+ const sources = [+ source({ id: 'src_1', vendor: 'openai' }),+ source({ id: 'src_2', vendor: 'xai', state: { status: 'error', detail_key: null } }),+ ];++ expect(addedThroughMoreCount(['src_1', 'src_2', 'src_gone'], sources)).toBe(1);+ });++ it('counts a repeated id once', () => {+ expect(addedThroughMoreCount(['src_1', 'src_1'], [source({ id: 'src_1', vendor: 'openai' })])).toBe(1);+ });+});++describe('usableSource', () => {+ const cases: [SourceStatus, boolean][] = [+ ['active', true],+ ['standby', true],+ ['cooldown', false],+ ['needs_action', false],+ ['error', false],+ ];++ it.each(cases)('treats %s as usable=%s', (status, expected) => {+ expect(usableSource(source({ id: 'src_1', vendor: 'openai', state: { status, detail_key: null } }))).toBe(expected);+ });+});++describe('providerAction', () => {+ // `hasSource` stays a shorthand for the common case — a read that landed, saying+ // this — so the cases below read as what they are about. `supply` is passed whole+ // when what the case is about is the read itself.+ const state = (+ over: Partial<Parameters<typeof providerAction>[0]> & { hasSource?: boolean } = {},+ ) => {+ const { hasSource = false, ...rest } = over;+ return providerAction({+ pendingCount: 0,+ importFailed: false,+ supply: { kind: 'read', hasSource },+ gatewayBusy: false,+ hubAdmitted: true,+ verifying: false,+ ...rest,+ });+ };++ it('offers to add when there is nothing yet', () => {+ expect(state()).toEqual({ kind: 'add', count: 0, blocked: false });+ });++ it('offers to continue once a source exists', () => {+ expect(state({ hasSource: true })).toEqual({ kind: 'continue', count: 0, blocked: false });+ });++ it('keeps saying continue but refuses it while the engine is not serving', () => {+ // The next screen picks a model per assistant out of what the Hub supplies, so+ // arriving there with a stopped engine is arriving at an empty screen. Changing+ // the label instead would move that explanation off the card it belongs to.+ expect(state({ hasSource: true, hubAdmitted: false }))+ .toEqual({ kind: 'continue', count: 0, blocked: true });+ expect(providerSetupAction(state({ hasSource: true, hubAdmitted: false })))+ .toMatchObject({ labelKey: 'onboarding.providers.actionContinue', disabled: true, busy: false });+ });++ it('keeps naming the write and refuses it while the engine is not serving', () => {+ // Both of these write to the Hub — one saves a source, the other hands a batch to+ // the take-over — and a stopped, failed, unsupported or unreadable engine cannot+ // take either. Offering the press anyway is a control that reaches nothing; hiding+ // it would take away the only name for what the person came here to do.+ expect(state({ hubAdmitted: false })).toEqual({ kind: 'add', count: 0, blocked: true });+ expect(state({ hubAdmitted: false, pendingCount: 2 }))+ .toEqual({ kind: 'import', count: 2, blocked: true });+ expect(providerSetupAction(state({ hubAdmitted: false })))+ .toMatchObject({ labelKey: 'onboarding.providers.actionAdd', disabled: true, busy: false });+ });++ it('puts a pending take-over ahead of continuing, and carries its count', () => {+ expect(state({ hasSource: true, pendingCount: 3 }))+ .toEqual({ kind: 'import', count: 3, blocked: false });+ });++ it('changes what it offers after a failed batch without losing the count', () => {+ expect(state({ pendingCount: 2, importFailed: true }))+ .toEqual({ kind: 'retryImport', count: 2, blocked: false });+ });++ it('reports the engine coming up ahead of everything else', () => {+ expect(state({ gatewayBusy: true, pendingCount: 3, hasSource: true })).toEqual({ kind: 'connecting', count: 0 });+ });++ it('reports a connection being read back ahead of what it would unlock', () => {+ expect(state({ verifying: true, hasSource: true })).toEqual({ kind: 'checking', count: 0 });+ });++ it('says it is still looking rather than offering to add against an unread inventory', () => {+ // 「添加」 here is the same button on a machine that already has credentials as+ // on one that has none, which is how a second copy of an existing key gets+ // written before the first read even lands.+ expect(state({ supply: { kind: 'reading' } })).toEqual({ kind: 'checking', count: 0 });+ });++ it('offers to ask again when the inventory could not be read', () => {+ // Not 「添加」: nothing is known about what is there. Not silence either — the+ // contract keeps Retry reachable on every failed supply read.+ expect(state({ supply: { kind: 'unreadable' } })).toEqual({ kind: 'retrySupply', count: 0 });+ expect(providerSetupAction(state({ supply: { kind: 'unreadable' } })))+ // No arrow: the press stays on this screen.+ .toMatchObject({ labelKey: 'common.retry', disabled: false, busy: false, icon: 'none' });+ });++ it('still takes over a key a failed inventory read knows nothing about', () => {+ // The scan answered even though the source list did not, and taking over what+ // it found does not depend on knowing what else is already there.+ expect(state({ supply: { kind: 'unreadable' }, pendingCount: 2 }))+ .toEqual({ kind: 'import', count: 2, blocked: false });+ expect(state({ supply: { kind: 'reading' }, pendingCount: 2 }))+ .toEqual({ kind: 'import', count: 2, blocked: false });+ });+});++describe('providerSetupAction', () => {+ // The count travels with the label that needs it and with nothing else: a family+ // does not resolve without one, and a plain leaf has nothing to interpolate. The+ // only states carrying a count are the two `providerAction` builds from a positive+ // pending count, so this is the same pairing C2's type requires.+ it('carries the count with a counted label and nothing with a plain one', () => {+ expect(providerSetupAction({ kind: 'import', count: 2 })).toEqual({+ labelKey: 'onboarding.providers.actionImport',+ labelArgs: { count: 2 },+ disabled: false,+ busy: false,+ icon: 'arrow-right',+ });+ expect(providerSetupAction({ kind: 'continue', count: 0 })).not.toHaveProperty('labelArgs');+ });++ it('marks a busy state both busy and disabled, so neither alone can let a click through', () => {+ for (const kind of ['connecting', 'checking'] as const) {+ expect(providerSetupAction({ kind, count: 0 })).toMatchObject({ disabled: true, busy: true, icon: 'spinner' });+ }+ });++ it('drops the arrow on the one state that opens a dialog instead of moving on', () => {+ expect(providerSetupAction({ kind: 'add', count: 0 }).icon).toBe('none');+ });++ // Which table a label sits in is what decides whether the count travels with it,+ // and the compiler cannot check that in the e2e project, where this module is+ // compiled without the bundle augmentation. So both halves answer to the bundles+ // themselves: a counted label must be a complete family and must NOT resolve on+ // its own (a plain leaf given a count is a different string than the one C1+ // approved), and a plain label must resolve exactly as it stands.+ it('names only labels that have shipped, in the form its table claims, in both locales', () => {+ const leaf = (bundle: unknown, key: string): unknown => key+ .split('.')+ .reduce<unknown>(+ (node, part) => (node && typeof node === 'object' ? (node as Record<string, unknown>)[part] : undefined),+ bundle,+ );+ const resolves = (bundle: unknown, key: string): boolean => typeof leaf(bundle, key) === 'string';++ for (const [locale, bundle] of [['en', en], ['zh', zh]] as const) {+ for (const key of Object.values(COUNTED_LABEL)) {+ for (const suffix of ['_one', '_other']) {+ expect(resolves(bundle, `${key}${suffix}`), `${key}${suffix} in ${locale}`).toBe(true);+ }+ expect(leaf(bundle, key), `${key} in ${locale} is a family, not a leaf`).toBeUndefined();+ }+ for (const key of Object.values(PLAIN_LABEL)) {+ expect(resolves(bundle, key), `${key} in ${locale}`).toBe(true);+ }+ }+ });+});diff --git a/ui/src/components/onboarding/providers/providerStage.ts b/ui/src/components/onboarding/providers/providerStage.tsnew file mode 100644index 000000000..0fe47dbd8--- /dev/null+++ b/ui/src/components/onboarding/providers/providerStage.ts@@ -0,0 +1,789 @@+// What the provider stage is showing, derived from what the server said.+//+// Kept pure and separate from the screen because these are the decisions the+// screen is easy to get wrong and hard to inspect once it renders: which two+// brands occupy the stage, whether a card is a fact or an offer, what the+// summary sentence counts, and which of the action's states the footer button+// is in. None of it needs React, so none of it is written in React.+//+// Identity is the catalog vendor id throughout. A migration row calls Gemini+// `google` and Qwen `alibaba-cn`; a source calls them what it was created with.+// Resolving both through `providerIdentity` is what stops the same provider+// occupying two slots.+import {+ appliableItems,+ BACKEND_ORDER,+ blockedReasonKey,+ groupMigrationCandidates,+ groupSelectable,+ requiredBackends,+ takeableImportRows,+ type MigrationGroup,+ type MigrationSelection,+} from '@/components/settings/models/migrationGrouping';+import { isImportableKey } from '@/components/settings/models/migrationScan';+import { foldRegionRead, regionFailed, type RegionRead } from '@/components/settings/models/regionRead';+import { installAndStartStep } from '@/components/settings/models/runtimeLifecycle';+import type {+ AgentBackend,+ AgentSupply,+ MigrationItem,+ MigrationScan,+ RuntimeDependency,+ Source,+ SourceKind,+} from '@/components/settings/models/types';+import {+ SETUP_PRIMARY_VENDORS,+ providerBrandLabel,+ providerVendorId,+ setupPrimaryRank,+} from '@/components/settings/providers/providerIdentity';+import type { TranslationKey } from '@/i18n/types';+import {+ setupCanAttemptInstall,+ setupHubRunning,+ setupNavigationReady,+ type SetupAction,+ type SetupCapability,+} from '../setupFlow';++/** The stage draws three cards; the third is always the way to add more. */+export const PROVIDER_SLOT_COUNT = 2;++/**+ * Whether a source counts as connected.+ *+ * `active` and `standby` are the two healthy statuses; the shipped resolver already+ * routes through standby, so treating it as anything less would under-report a source+ * the gateway is in fact willing to use. A source still awaiting its first successful+ * model call is kept and disclosed as unverified rather than hidden — the credential+ * exists and the person did add it.+ */+export const usableSource = (source: Source): boolean =>+ source.state.status === 'active' || source.state.status === 'standby';++/**+ * How many of the sources added through Add more are still there.+ *+ * Filtered against the live source list rather than trusted from the flow state: the+ * badge describes what exists now, and a source removed in another tab must not keep+ * inflating it.+ */+export function addedThroughMoreCount(+ addedThroughMore: readonly string[],+ sources: readonly Source[],+): number {+ const usable = new Set(sources.filter(usableSource).map((source) => source.id));+ return new Set(addedThroughMore.filter((id) => usable.has(id))).size;+}++export type ProviderSlotKind =+ /** A source already exists. A fact, not a choice. */+ | 'connected'+ /** A scan found credentials Model Hub could take over, pending consent. */+ | 'detected'+ /** Nothing is known yet; the card offers to add this brand. */+ | 'empty';++export type ProviderSlot = {+ /**+ * The card's stable identity — for the slot it occupies, its React key and its+ * `data-provider`. The catalog vendor id whenever there is one, and a detected+ * row's own id when the server named no provider for it: that row is still one+ * credential and still needs one slot of its own.+ */+ vendor: string;+ /**+ * The catalog brand whose mark and name this card wears, `null` for a detected+ * credential the server named no provider for. Distinct from `vendor` for exactly+ * that case: an unnamed credential has an identity but no brand, and drawing one+ * from its backend or its key prefix would be a guess — the same guess the import+ * dialog refuses to make, where such a row is identified by its masked detail.+ */+ brand: string | null;+ label: string;+ kind: ProviderSlotKind;+ /**+ * The card's second line when there is a credential to describe: the separate+ * mask when the server sends one, and for a detected row the masked detail it has+ * always carried when it does not. Never secret material.+ */+ mask: string | null;+ /**+ * How a connected source arrives, and whose sign-in it is. `null` for anything+ * that is not connected.+ *+ * A subscription has no mask by construction — there is no key to mask — so a card+ * that described itself by its mask alone would fall through to the offer an EMPTY+ * card makes and invite a key for a provider already connected. What it says+ * instead is what Settings says about the same source.+ */+ supply: { kind: SourceKind; account: string | null } | null;+ /**+ * Connected, but no successful model call has been made with this credential yet.+ *+ * `save_unverified` is deliberate policy in both hosts of the key form, so a source+ * the person just added is routinely `standby` with a pending marker. It stays+ * usable — that is what `usableSource` already says — but a card that states a+ * working connection the server has never observed is a claim nobody made. This is+ * the same distinction `sourceStatePresentation` draws as 「已保存」 rather than+ * 「供应中」 on the Settings row.+ */+ pending: boolean;+ /**+ * The backends whose consent this card carries, empty unless detected.+ * One entry per consent group the card's credentials sit in — the migration+ * feature expands each to its linked group when the card is toggled, so this+ * stays the entry point rather than the closure.+ *+ * Only groups this entry point can actually take over. A card whose credential+ * sits in a blocked group carries none, which is what makes it unselectable+ * everywhere at once — and a brand holding one blocked group beside an unrelated+ * selectable one carries only the selectable one, because consent to the second+ * was never consent to the first.+ */+ backends: AgentBackend[];+ /**+ * Why this card's credentials cannot be taken over from here, empty when they+ * can. The migration feature's own reasons, deduped, so the card and the review+ * explain one blocked group with one sentence.+ */+ reasons: TranslationKey[];+};++/**+ * Every group the scan offers setup, on setup's terms.+ *+ * Both scopes are the same predicate, and that is the point: setup opens from+ * importable API keys and may take over nothing else. A backend that also carries an+ * importable subscription store therefore appears — its key is right there, and a+ * screen that silently dropped it would leave a detected credential unexplained —+ * but blocked, for review in Settings. The server migrates a backend whole and+ * refuses a batch that omits any of its rows, so there is no half of it to take.+ *+ * One helper rather than the call spelled out five times, so the cards, the capsule's+ * count, the CTA's batch, the seeded consent and the reconciliation cannot drift into+ * answering the same question two ways.+ */+const setupGroups = (items: MigrationItem[]): MigrationGroup[] =>+ groupMigrationCandidates(items, isImportableKey, isImportableKey);++/**+ * Detected cards in the order the stage should spend its two slots on them.+ *+ * Actionable before blocked, then the shortlist's own order. Both stay visible —+ * whichever does not fit is in the add dialog's 已检测到 list — but the stage has+ * two slots and a card that can be acted on has the better claim to one.+ */+const byPrimaryRank = (left: ProviderSlot, right: ProviderSlot): number => {+ if (left.reasons.length !== right.reasons.length) {+ return (left.reasons.length > 0 ? 1 : 0) - (right.reasons.length > 0 ? 1 : 0);+ }+ const leftRank = setupPrimaryRank(left.vendor);+ const rightRank = setupPrimaryRank(right.vendor);+ if (leftRank === rightRank) return 0;+ if (leftRank === null) return 1;+ if (rightRank === null) return -1;+ return leftRank - rightRank;+};++/**+ * Every API key the scan found, and for each one whether setup may take it over.+ *+ * Discovery and permission are two projections of one scan, not two scans. A key+ * inside a group this entry point cannot consent to — a linked subscription+ * sign-in, a server blocker — is still a key that is on this machine, and a stage+ * that dropped it would answer 「we found your Anthropic key」 with an empty invitation+ * to add one. So every importable key gets a card; what a blocked group does not get+ * is a backend to consent to, which is the one thing that decides selection,+ * the batch and the counts.+ *+ * A row whose provider the server did not name keeps its own identity and is+ * labelled by its masked detail, exactly as the import dialog labels it. Guessing a+ * brand from the backend that happened to hold the key is the one thing neither+ * surface does.+ */+function detectedProviders(scan: MigrationScan | null): ProviderSlot[] {+ if (!scan) return [];+ const byIdentity = new Map<string, ProviderSlot>();+ for (const group of setupGroups(scan.items)) {+ const selectable = groupSelectable(group);+ const reasons = selectable ? [] : [...new Set(group.blockedRows.map(blockedReasonKey))];+ for (const row of group.importRows) {+ const named = row.vendor?.trim();+ const brand = named ? providerVendorId(named) : null;+ const identity = brand ?? row.id;+ const existing = byIdentity.get(identity);+ if (existing) {+ if (selectable && !existing.backends.includes(group.backend)) existing.backends.push(group.backend);+ for (const reason of reasons) {+ if (!existing.reasons.includes(reason)) existing.reasons.push(reason);+ }+ continue;+ }+ byIdentity.set(identity, {+ vendor: identity,+ brand,+ label: named ? providerBrandLabel(named, row.display_name) : row.masked_detail.trim(),+ kind: 'detected',+ // `masked_credential` is the newer separate field; `masked_detail` is the one+ // every server has always sent. Falling back to it is what stops a row from an+ // older server reading as a provider with nothing detected about it. An unnamed+ // row has no second line to fill: its masked detail is already its name, and+ // saying the same string twice on one card describes nothing.+ mask: named ? row.masked_credential?.trim() || row.masked_detail?.trim() || null : null,+ supply: null,+ pending: false,+ backends: selectable ? [group.backend] : [],+ // Copied, not shared: two rows of one blocked group are two cards, and a+ // reason later pushed onto one of them is not a reason on the other.+ reasons: [...reasons],+ });+ }+ }+ // A reason is why nothing can be done, so it only belongs on a card where nothing+ // can be. One vendor found in two backends — takeable in one, blocked in the other+ // — is a takeable card: pressing it takes over the group it may, and the group it+ // may not keeps its own reason in the review. A card that read 「not from here」 and+ // was pressable anyway would contradict itself.+ return [...byIdentity.values()]+ .map((slot) => (slot.backends.length > 0 && slot.reasons.length > 0 ? { ...slot, reasons: [] } : slot))+ .sort(byPrimaryRank);+}++/**+ * The two provider cards, most settled first.+ *+ * Already-added sources come first because they are facts; detected candidates+ * follow; and when the two together do not fill the stage, the named brands the+ * shortlist opens with stand in as offers. A stage that drew one card would read+ * as a list of one rather than as providers feeding a hub.+ */+export function providerSlots(input: {+ sources: readonly Source[];+ scan: MigrationScan | null;+}): ProviderSlot[] {+ const seen = new Set<string>();+ const slots: ProviderSlot[] = [];++ for (const source of input.sources.filter(usableSource)) {+ const vendor = providerVendorId(source.vendor);+ if (seen.has(vendor)) continue;+ seen.add(vendor);+ slots.push({+ vendor,+ brand: vendor,+ label: providerBrandLabel(source.vendor, source.display_name),+ kind: 'connected',+ mask: source.masked_credential?.trim() || null,+ supply: { kind: source.kind, account: source.account_label?.trim() || null },+ pending: Boolean(source.verification_pending),+ backends: [],+ reasons: [],+ });+ }++ for (const detected of detectedProviders(input.scan)) {+ if (seen.has(detected.vendor)) continue;+ seen.add(detected.vendor);+ slots.push(detected);+ }++ for (const vendor of SETUP_PRIMARY_VENDORS) {+ if (slots.length >= PROVIDER_SLOT_COUNT) break;+ if (seen.has(vendor)) continue;+ seen.add(vendor);+ slots.push({+ vendor,+ brand: vendor,+ label: providerBrandLabel(vendor),+ kind: 'empty',+ mask: null,+ supply: null,+ pending: false,+ backends: [],+ reasons: [],+ });+ }++ return slots.slice(0, PROVIDER_SLOT_COUNT);+}++/**+ * Detected providers the stage is not already drawing.+ *+ * This is what the add dialog's 已检测到 tab lists, and whether it has anything to+ * list is what decides the tab exists at all: a tab repeating the two cards+ * immediately behind it offers nothing, and an empty tab is worse than an absent+ * one.+ *+ * What it subtracts is the detected cards, and only those. A connected card also+ * occupies its brand's slot — that collapse is presentation, and it is right — but+ * the scan has no knowledge of the Hub's inventory: it reads native stores, so a+ * row under a connected brand is a second credential until something compares the+ * two. Letting the stage's brand set answer that question is how a row the capsule+ * still counts becomes reachable from nowhere. Whether it is the same key is a+ * question about credentials, and the pane that lists it is where it is answered.+ */+export function unlistedDetected(input: {+ sources: readonly Source[];+ scan: MigrationScan | null;+}): ProviderSlot[] {+ const drawn = new Set(+ providerSlots(input).filter((slot) => slot.kind === 'detected').map((slot) => slot.vendor),+ );+ return detectedProviders(input.scan).filter((slot) => !drawn.has(slot.vendor));+}++/** Whether a detected card is currently consented to. A connected card is never+ * "selected": its fill states a fact, so a selection toggle cannot change it. */+export const slotSelected = (+ slot: ProviderSlot,+ selected: readonly AgentBackend[],+): boolean => slot.kind === 'detected'+ && slot.backends.length > 0+ && slot.backends.every((backend) => selected.includes(backend));++/**+ * The rows the current consent would submit, counted the way the dialog counts them.+ *+ * Deliberately the takeover's own computation rather than anything of this screen's:+ * the number the CTA promises and the number the batch sends have to be one number,+ * and the only way to guarantee that is to run the same grouping the dialog runs —+ * scope the scan, drop groups this entry point cannot consent to, then take every+ * importable row of the consented backends.+ */+export function pendingImportRows(selection: MigrationSelection): MigrationItem[] {+ const items = selection.scan?.items ?? [];+ const consented = new Set(+ setupGroups(items)+ .filter((group) => groupSelectable(group) && selection.selectedBackends.includes(group.backend))+ .map((group) => group.backend),+ );+ return appliableItems(items, consented);+}++/**+ * The keys the capsule offers to review.+ *+ * Not every importable key in the scan: a key whose consent group is blocked by an+ * OAuth row or a blocker cannot be consented to from here, so advertising it would+ * open a review with nothing to press. The offer is therefore built from the same+ * selectable groups the cards and the dialog are built from — already only keys,+ * because that is setup's scope, and 「发现 N 个可导入的 API Key」 is what the+ * sentence says.+ *+ * The migration feature's own projection, because the standalone capsule in+ * Settings' wizard has to count the same way and cannot reach into this screen to+ * do it.+ */+export function offeredImportKeys(selection: MigrationSelection): MigrationItem[] {+ return takeableImportRows(selection.scan?.items ?? [], isImportableKey, isImportableKey);+}++/**+ * The consent a scan arrives already carrying.+ *+ * The server marks rows `selected`, and the uncontrolled dialog has always honoured+ * that — a group whose every linked importable row is marked opens ticked. A+ * controlled caller that built its selection only from what it previously held would+ * throw those defaults away on the first scan and show a stage where nothing is+ * chosen and a capsule announcing keys to import, which is two answers to one+ * question. Seeded once, on the first scan; every later scan is reconciled instead,+ * because by then the selection is the person's rather than the server's.+ */+export function defaultSelection(scan: MigrationScan | null): AgentBackend[] {+ const items = scan?.items ?? [];+ return setupGroups(items)+ .filter((group) => groupSelectable(group) && group.linkedImportRows.every((row) => row.selected))+ .map((group) => group.backend);+}++/**+ * Consent after a card was toggled.+ *+ * A card names an entry point, not a consent group: toggling it writes its whole+ * linked closure, because migrating one backend's copy of a shared credential file+ * migrates every backend that reads it. Consent to half of that does not exist, so+ * it is never representable here.+ */+export function toggleSlotSelection(+ selection: MigrationSelection,+ slot: ProviderSlot,+): AgentBackend[] {+ const items = selection.scan?.items ?? [];+ if (slot.kind !== 'detected' || slot.backends.length === 0) return [...selection.selectedBackends];+ const next = new Set(selection.selectedBackends);+ const on = slotSelected(slot, selection.selectedBackends);+ for (const backend of requiredBackends(items, slot.backends)) {+ if (on) next.delete(backend);+ else next.add(backend);+ }+ return [...next];+}++/** A backend's rows as an order-independent identity, so two scans can be asked+ * whether they describe the same credentials rather than merely the same names. */+const backendRowIdentity = (items: readonly MigrationItem[], backend: AgentBackend): string =>+ items.filter((item) => item.backend === backend).map((item) => item.id).sort().join('\n');++/**+ * Consent a fresh scan still supports.+ *+ * Run whenever the scan is replaced, and deliberately conservative: consent was given+ * to rows that were on screen, so it survives only where the new scan asks the same+ * question. Three ways it stops doing that.+ *+ * A group that was imported, newly blocked or has lost its importable rows can no+ * longer be submitted at all, and a stale name left behind would keep the CTA+ * offering a batch the dialog would refuse to build.+ *+ * A group whose custody closure has grown can be submitted, and refused: the server+ * rejects a batch that migrates one backend while leaving a linked one out, so a+ * selection holding only part of a closure is a press that always fails.+ *+ * And a group whose rows have CHANGED is the quiet one — a key that appeared under an+ * already-consented backend would ride into the next batch on a decision made about+ * a different set of credentials. Nobody consented to that one, so the group goes+ * back for review rather than carrying its tick forward.+ */+export function reconcileSelection(+ selection: MigrationSelection,+ previous: MigrationScan | null,+): AgentBackend[] {+ const items = selection.scan?.items ?? [];+ const priorItems = previous?.items ?? [];+ const carried = new Set(selection.selectedBackends);+ const selectable = new Map(+ setupGroups(items)+ .filter(groupSelectable)+ .map((group) => [group.backend, group] as const),+ );+ return selection.selectedBackends.filter((backend) => {+ const group = selectable.get(backend);+ if (!group) return false;+ return [...group.required].every((linked) => (+ carried.has(linked)+ && backendRowIdentity(items, linked) === backendRowIdentity(priorItems, linked)+ ));+ });+}++export type ProviderSummary =+ | { kind: 'none' }+ | { kind: 'added'; count: number; names: string[] }+ | { kind: 'selected'; count: number; names: string[] }+ | { kind: 'error' };++/**+ * The sentence under the stage.+ *+ * Added wins over selected: once a provider is really there, what setup has is+ * no longer an intention. Both counts span everything, not just the two cards on+ * the stage — a person who added five through Add more has five, and one who+ * consented to a third provider inside the add dialog consented to three. The+ * sentence describes the flow's state, and the stage is only the part of it that+ * happens to be drawn.+ */+export function providerSummary(input: {+ scan: MigrationScan | null;+ sources: readonly Source[];+ selected: readonly AgentBackend[];+ failed: boolean;+}): ProviderSummary {+ if (input.failed) return { kind: 'error' };+ const added = new Map<string, string>();+ for (const source of input.sources.filter(usableSource)) {+ const vendor = providerVendorId(source.vendor);+ if (!added.has(vendor)) added.set(vendor, providerBrandLabel(source.vendor, source.display_name));+ }+ if (added.size > 0) return { kind: 'added', count: added.size, names: [...added.values()] };+ const selected = detectedProviders(input.scan)+ .filter((slot) => slotSelected(slot, input.selected))+ .map((slot) => slot.label);+ if (selected.length > 0) return { kind: 'selected', count: selected.length, names: selected };+ return { kind: 'none' };+}++/**+ * The backend whose adoption the screen resumes, or `null` when there is none.+ *+ * The engine is ensured before this is asked, so what is left to choose is what to+ * ADOPT: the first present backend not already in hub mode, in the shared backend+ * order. The choice is not cosmetic — `resumeGatewayAdoption` is named for one+ * backend and returns success immediately when that one is already in hub mode, so+ * naming an adopted backend would adopt nothing while an unadopted CLI sat beside+ * it. When every present backend is already adopted, the first present one is that+ * same no-op and correctly reports there is nothing left to do.+ *+ * Presence is the server's `cli_present`, read from a refreshed collection rather+ * than a cached list: a CLI installed while setup was open is exactly the case a+ * cached read would get wrong.+ */+export function adoptionBackend(agents: readonly AgentSupply[]): AgentBackend | null {+ const present = BACKEND_ORDER.filter((backend) =>+ agents.some((agent) => agent.backend === backend && agent.cli_present));+ const unadopted = present.find((backend) =>+ agents.find((agent) => agent.backend === backend)?.mode !== 'hub');+ return unadopted ?? present[0] ?? null;+}++export type GatewayIntent =+ /** Already serving. Nothing to do, and nothing to say beyond that. */+ | { kind: 'running' }+ /** No authoritative answer yet, or one that authorizes nothing. The shell owns+ * the read and its recovery; the card waits rather than inventing a verdict. */+ | { kind: 'waiting' }+ /** The read failed and asking again is worth doing. Distinct from `waiting`, which+ * is a read still in flight: this one has nothing coming unless someone asks. The+ * contract is explicit that a read error shows the runtime-unread copy *with+ * retry* rather than the unsupported notice, and without this kind the two are+ * the same silent `idle` card. */+ | { kind: 'unreadable' }+ /** The engine is missing or stopped and this screen may resume it. `runtime` is the+ * authoritative snapshot the step was read from, carried so the resume starts from+ * the state that authorized it rather than reading the same thing a second time. */+ | { kind: 'resume'; step: 'install' | 'start'; runtime: RuntimeDependency }+ /** Installing here is not something this deployment can do. */+ | { kind: 'unsupported' };++/**+ * What the screen should do about the engine, from the read the shell handed down.+ *+ * Two rules the ordering encodes. Installing and starting are admitted separately:+ * `setupCanAttemptInstall` gates fresh installation only, so a Hub that is installed+ * but stopped still starts on a host where new installation is unsupported —+ * refusing to start it would strand a working engine on a technicality. And nothing+ * outside `ready` authorizes anything: a loading, unread or degraded read is not+ * evidence the engine is absent, and acting on it would install over a Hub that is+ * merely unreachable this second.+ *+ * Controller startup already ran the first recovery, which is why this resumes only+ * what that recovery demonstrably left undone rather than installing unconditionally.+ */+export function gatewayIntent(input: {+ capability: SetupCapability;+ gatewayEnabled: boolean | null;+ runtimeRead: RegionRead<RuntimeDependency>;+}): GatewayIntent {+ if (setupHubRunning(input.runtimeRead)) return { kind: 'running' };+ if (!setupNavigationReady(input.capability, input.gatewayEnabled)) return { kind: 'waiting' };+ // A read that failed, asked before anything else is decided from it. `loading` and+ // a refresh-degraded read are both a read in flight and stay quiet; a first read+ // that failed (`unread`) and a later one that failed over stale data+ // (`degraded/read_failed`) are not coming back on their own. Non-retryable is left+ // waiting on purpose: the shell owns the read, and a Retry that cannot help is a+ // worse answer than none.+ const unreadable = foldRegionRead(input.runtimeRead, {+ loading: () => false,+ ready: () => false,+ unread: (retryable) => retryable,+ degraded: (_stale, cause, retryable) => cause === 'read_failed' && retryable,+ });+ if (unreadable) return { kind: 'unreadable' };+ const runtime = foldRegionRead(input.runtimeRead, {+ loading: () => null,+ unread: () => null,+ degraded: () => null,+ ready: (value: RuntimeDependency) => value,+ });+ // A runtime whose own persisted intent is off is a configuration boundary, and+ // the flow's one rule about those is that setup never silently re-enables them.+ if (!runtime || runtime.enabled === false) return { kind: 'waiting' };+ const step = installAndStartStep(runtime);+ if (step === 'complete') return { kind: 'running' };+ if (step === 'start') return { kind: 'resume', step: 'start', runtime };+ return setupCanAttemptInstall(input.capability, input.gatewayEnabled, input.runtimeRead)+ ? { kind: 'resume', step: 'install', runtime }+ : { kind: 'unsupported' };+}++/**+ * Whether the evidence above is an ANSWER, or still on its way to one.+ *+ * A retry is a request: it asks the shell to read the machine again, and the states+ * that read passes through on the way back are not answers. `beginRegionRead`+ * degrades the previous value to `refreshing`, and a configuration being re-read+ * reports `pending`/`null` before it reports what it found. `gatewayIntent` folds+ * every one of them to `waiting`, which is the right thing to DRAW and says nothing+ * about whether the request has been served — so a request spent on the first of+ * them is spent on the read's start and never sees its result.+ *+ * Three things are answers. A read that failed, which answers 「不知道」. A+ * configuration that came back off, which no runtime read can override. And a read+ * that landed.+ *+ * The failed read is asked FIRST, ahead of the configuration, because one load+ * failure usually takes both: the shell comes back with no capability, no saved+ * intent and an unread machine. That is a complete answer to the request — nothing+ * more is coming unless someone asks again — and filing it under 「configuration+ * unknown」 would leave the request pending on a read that is never arriving, to+ * fire on some unrelated later one. It is still distinguishable from a read in+ * flight: `beginRegionRead` maps a failure to `loading`, so a re-read over a+ * failure is `loading` and the failure itself is not.+ */+export function gatewayEvidenceSettled(input: {+ capability: SetupCapability;+ gatewayEnabled: boolean | null;+ runtimeRead: RegionRead<RuntimeDependency>;+}): boolean {+ if (regionFailed(input.runtimeRead)) return true;+ if (input.capability === 'disabled' || input.gatewayEnabled === false) return true;+ if (!setupNavigationReady(input.capability, input.gatewayEnabled)) return false;+ return foldRegionRead(input.runtimeRead, {+ loading: () => false,+ ready: () => true,+ unread: () => true,+ degraded: (_stale, cause) => cause === 'read_failed',+ });+}++export type ProviderActionKind =+ | 'import'+ | 'retryImport'+ | 'continue'+ | 'add'+ | 'retrySupply'+ | 'connecting'+ | 'checking';++/**+ * What the screen actually knows about the source inventory.+ *+ * An empty list and a list the screen could not read look identical once they are+ * both `Source[]`, and the difference is the whole question the primary action is+ * answering: offering 「添加」 against an answer nobody has is how a second copy of+ * a credential that already exists gets written. So the answer and the absence of+ * one are separate states here, and the absence is not silent — the contract's rule+ * for every setup supply read is that a failed result keeps Retry reachable.+ */+export type SupplyState =+ /** A read is in flight and nothing has landed yet. */+ | { kind: 'reading' }+ /** A read failed. Nothing is coming unless someone asks again. */+ | { kind: 'unreadable' }+ /** An authoritative answer, whichever way it went. */+ | { kind: 'read'; hasSource: boolean };++export type ProviderActionState = {+ kind: ProviderActionKind;+ count: number;+ /** The state is the right one to show and the wrong one to press. Distinct from a+ * busy state, which is also unpressable but is going somewhere on its own. */+ blocked?: boolean;+};++/**+ * Which of its states the primary action is in.+ *+ * Ordered by what the person can do next rather than by what is most+ * interesting: while the engine is coming up nothing else is possible, a+ * pending take-over is the shortest path to a working provider, and continuing+ * is only offered once something is really there to continue with.+ *+ * Every state that would WRITE additionally needs the engine to be serving, and+ * says so by staying visible and unpressable rather than by disappearing: adding a+ * source and taking over a key both go to the Hub, and one that is stopped, failed,+ * unsupported or simply not readable this second cannot take either. What went+ * wrong is on the gateway card with the recovery next to it, which is the one place+ * it can be acted on — so the footer keeps naming what the person came to do+ * instead of offering a press that reaches nothing.+ *+ * Continuing additionally needs the engine to be serving. C4 says as much —+ * `setupCandidateAllowed` requires `setupHubRunning` — and the reason is not+ * procedural: the next screen picks a model per assistant out of what the Hub+ * supplies, so arriving there with a source and a stopped, failed or unsupported+ * engine is arriving at an empty screen with no way to tell why. The action keeps+ * saying 「继续」 and stops being pressable; what went wrong is on the gateway card,+ * with the recovery next to it.+ */+export function providerAction(input: {+ /** Rows the current selection would submit in one batch. */+ pendingCount: number;+ /** A batch failed and has not been retried. */+ importFailed: boolean;+ /** What is known about the inventory, not what happens to be in it. */+ supply: SupplyState;+ /** The engine is installing or starting. */+ gatewayBusy: boolean;+ /** The flow is admitted to the Hub and the Hub is serving it: the configuration+ * prerequisite the next screen is gated on, plus the authoritative runtime read —+ * never this screen's own attempt, and never one without the other. Writing and+ * continuing both need exactly this, so both read the same field. */+ hubAdmitted: boolean;+ /** A source was written and its connection is being read back. */+ verifying: boolean;+}): ProviderActionState {+ if (input.gatewayBusy) return { kind: 'connecting', count: 0 };+ if (input.verifying) return { kind: 'checking', count: 0 };+ if (input.pendingCount > 0) {+ // Ahead of the inventory on purpose: a scan that arrived is an answer of its+ // own, and taking over a key it found does not depend on knowing what else is+ // already there. It does depend on the engine it would write to.+ return {+ kind: input.importFailed ? 'retryImport' : 'import',+ count: input.pendingCount,+ blocked: !input.hubAdmitted,+ };+ }+ if (input.supply.kind === 'reading') return { kind: 'checking', count: 0 };+ if (input.supply.kind === 'unreadable') return { kind: 'retrySupply', count: 0 };+ if (input.supply.hasSource) return { kind: 'continue', count: 0, blocked: !input.hubAdmitted };+ return { kind: 'add', count: 0, blocked: !input.hubAdmitted };+}++/** Kinds `providerAction` only ever produces from a positive pending count. */+type CountedActionKind = 'import' | 'retryImport';++/**+ * The counted labels, named by the base `t(base, { count })` resolves them under.+ *+ * C1 ships both as `_one`/`_other` families, which `TranslationKey` deliberately+ * cannot name — it is the leaves that resolve *without* count. C2's counted member+ * is what names them, and it requires the count in the same claim, which is why+ * these are a table of their own rather than a row in the one below.+ *+ * Typed as the claim rather than as `SetupCountedLabelKey` on purpose: the e2e+ * fidelity project compiles this module without the bundle augmentation, where the+ * derived family type collapses to `never` and nothing could satisfy it. That two+ * keys really are families is checked where the bundles are in scope —+ * `setupAction.types.test.ts` for the type and `providerStage.test.ts` for both locales.+ */+export const COUNTED_LABEL = {+ import: 'onboarding.providers.actionImport',+ retryImport: 'onboarding.providers.actionRetryImport',+} as const satisfies Record<CountedActionKind, SetupAction['labelKey']>;++/** Everything else: a label that resolves on its own, with no count to carry. */+export const PLAIN_LABEL = {+ continue: 'onboarding.providers.actionContinue',+ add: 'onboarding.providers.actionAdd',+ // The shared label, not a new one: the contract lets the active owner publish+ // Retry as the CTA while Continue is held, and this is that.+ retrySupply: 'common.retry',+ connecting: 'onboarding.providers.actionConnecting',+ checking: 'onboarding.providers.actionChecking',+} as const satisfies Record<Exclude<ProviderActionKind, CountedActionKind>, TranslationKey>;++const BUSY_ACTIONS = new Set<ProviderActionKind>(['connecting', 'checking']);++/** The arrow means the press leaves this screen. Adding a provider and asking for a+ * read again both stay here, so neither wears it. */+const STAYS_HERE = new Set<ProviderActionKind>(['add', 'retrySupply']);++/** The C2 action the shell renders. The screen never draws the button itself. */+export function providerSetupAction(state: ProviderActionState): SetupAction {+ const busy = BUSY_ACTIONS.has(state.kind);+ const chrome: Pick<SetupAction, 'disabled' | 'busy' | 'icon'> = {+ disabled: busy || state.blocked === true,+ busy,+ icon: busy ? 'spinner' : STAYS_HERE.has(state.kind) ? 'none' : 'arrow-right',+ };+ // The two counted kinds carry their count, and nothing else carries one: a family+ // without a count does not resolve, and a plain key has nothing to interpolate.+ // Narrowed rather than asserted, so the pairing is the compiler's to check.+ return state.kind === 'import' || state.kind === 'retryImport'+ ? { ...chrome, labelKey: COUNTED_LABEL[state.kind], labelArgs: { count: state.count } }+ : { ...chrome, labelKey: PLAIN_LABEL[state.kind] };+}diff --git a/ui/src/components/onboarding/providers/tsconfig.tests.json b/ui/src/components/onboarding/providers/tsconfig.tests.jsonnew file mode 100644index 000000000..15c1b391f--- /dev/null+++ b/ui/src/components/onboarding/providers/tsconfig.tests.json@@ -0,0 +1,16 @@+{+ "extends": "../../../../tsconfig.app.json",+ "compilerOptions": {+ "composite": false,+ "noEmit": true,+ "tsBuildInfoFile": "../../../../node_modules/.tmp/setup-providers-tests.tsbuildinfo"+ },+ "include": [+ "./**/*.ts",+ "./**/*.tsx",+ "../ImportKeysNotice.test.tsx",+ "../setupAction.types.test.ts",+ "../../../i18n/i18next.d.ts"+ ],+ "exclude": []+}diff --git a/ui/src/components/onboarding/setupAction.types.test.ts b/ui/src/components/onboarding/setupAction.types.test.tsnew file mode 100644index 000000000..6f5e990dc--- /dev/null+++ b/ui/src/components/onboarding/setupAction.types.test.ts@@ -0,0 +1,112 @@+/**+ * C2's action label: compiler assertions, plus the resolution they are about.+ *+ * `labelContract` is compiled and never executed — each `@ts-expect-error` IS the+ * assertion, and an unused directive fails the compile, so this is the only+ * construction in which "the type still refuses that" stays true as the type changes.+ * Same shape as `src/i18n/translationContract.test.ts`, for the same reason.+ *+ * What is pinned: a counted label names a family C1 ships as `_one`/`_other` and carries+ * the count that resolves it, a plain label carries nothing, and neither may name a string+ * the bundles do not have. The executed cases below then show the shell resolving both+ * forms through one `t` call, in both locales — the claim and its consequence in one file.+ */+import { createInstance } from 'i18next';+import type { TFunction } from 'i18next';+import { describe, expect, it } from 'vitest';+import type { SetupAction } from './setupFlow';+import en from '../../i18n/en.json';+import zh from '../../i18n/zh.json';++const CHROME = { disabled: false, busy: false, icon: 'arrow-right' } as const;++/** The counted claim: the family, and the count that makes it resolve. */+const countedAction: SetupAction = {+ ...CHROME,+ labelKey: 'onboarding.providers.actionImport',+ labelArgs: { count: 2 },+};++/** The plain claim: a leaf that resolves on its own needs no args at all. */+const plainAction: SetupAction = {+ ...CHROME,+ labelKey: 'onboarding.providers.actionContinue',+};++function labelContract() {+ /** Other interpolation rides along with the count, as `labelArgs` always allowed. */+ const countedWithMore: SetupAction = {+ ...CHROME,+ labelKey: 'onboarding.import.remaining',+ labelArgs: { count: 1, name: 'Codex' },+ };+ // @ts-expect-error a plural family resolves only with a count, so C2 will not carry it alone+ const countedWithoutCount: SetupAction = {+ ...CHROME,+ labelKey: 'onboarding.providers.actionImport',+ };+ // @ts-expect-error interpolation that is not a count cannot stand in for one+ const countedWithWrongArgs: SetupAction = {+ ...CHROME,+ labelKey: 'onboarding.providers.actionRetryImport',+ labelArgs: { name: 'Codex' },+ };+ // @ts-expect-error a count is a number; a rendered one is the bundle's business+ const countedWithText: SetupAction = {+ ...CHROME,+ labelKey: 'onboarding.providers.actionImport',+ labelArgs: { count: 'two' },+ };+ const absentKey: SetupAction = {+ ...CHROME,+ // @ts-expect-error a key that has not shipped in the bundles cannot be named either way+ labelKey: 'onboarding.providers.actionImportt',+ };+ const objectPrefix: SetupAction = {+ ...CHROME,+ // @ts-expect-error an object prefix is not a label, counted or otherwise+ labelKey: 'onboarding.providers',+ };+ /**+ * A family's own `_other` form stays a plain label, and that is correct: it is a text+ * leaf that resolves on its own. The counted member is about the base `t` needs a count+ * for; it does not take the suffixed leaves away from anyone.+ */+ const suffixedLeaf: SetupAction = {+ ...CHROME,+ labelKey: 'onboarding.providers.actionImport_other',+ };+ return [countedWithMore, countedWithoutCount, countedWithWrongArgs, countedWithText,+ absentKey, objectPrefix, suffixedLeaf];+}+void labelContract;++/**+ * The shell's side of the same claim: one `t` call, no narrowing.+ *+ * This is the whole reason the two members keep identical field names — a shell that had+ * to discriminate before rendering would be a protocol change, not a wider label type.+ */+export function renderSetupAction(t: TFunction, action: SetupAction): string {+ return t(action.labelKey, action.labelArgs);+}++const translator = (lng: 'en' | 'zh') => {+ const instance = createInstance();+ void instance.init({ lng, fallbackLng: false, resources: { en: { translation: en }, zh: { translation: zh } } });+ return instance;+};++describe('C2 action label resolution', () => {+ it.each(['en', 'zh'] as const)('resolves both label forms through one t call in %s', (lng) => {+ const bundle = lng === 'en' ? en : zh;+ const t = translator(lng).t;++ // The count is not decoration: it is what turns a family into a string. Expected text+ // comes from the bundle rather than from a copy pasted here, because which words those+ // are is the contract's business, not this file's.+ expect(renderSetupAction(t, countedAction))+ .toBe(bundle.onboarding.providers.actionImport_other.replace('{{count}}', '2'));+ expect(renderSetupAction(t, plainAction)).toBe(bundle.onboarding.providers.actionContinue);+ });+});diff --git a/ui/src/components/onboarding/setupFlow.ts b/ui/src/components/onboarding/setupFlow.tsindex 509b13299..c61bd9be0 100644--- a/ui/src/components/onboarding/setupFlow.ts+++ b/ui/src/components/onboarding/setupFlow.ts@@ -13,6 +13,7 @@* `docs/plans/setup-three-screen/copy-contract.json` (C1).*/import type { Dispatch, SetStateAction } from 'react';+import type { ParseKeys } from 'i18next';import type { TranslationKey } from '@/i18n/types';import type { AgentBackend, MigrationScan, RouteHop, RuntimeDependency } from '../settings/models/types';import { foldRegionRead, type RegionRead } from '../settings/models/regionRead';@@ -33,24 +34,46 @@ export type SetupHandoffTarget = Exclude<SetupScreenId, 'intro'>;/** The leading glyph the shell draws inside the primary action. */export type SetupActionIcon = 'none' | 'arrow-right' | 'spinner';+/** Written as a generic so the conditional distributes over the key union: the same test+ * applied to `ParseKeys` directly matches the whole union at once and yields `never`. */+type PluralBase<Key> = Key extends `${infer Base}_other` ? Base : never;++/**+ * A C1 plural family, named by the base `t(base, { count })` resolves it under.+ *+ * `TranslationKey` is deliberately the leaves that resolve WITHOUT a count, so it cannot+ * name a counted label at all — and "Review 2 selected" is exactly a counted label. This+ * widens what a screen may claim by nothing: the base is derived from the `_other` form+ * C1 already requires in both bundles, so a string that has not shipped as a family is+ * still not nameable, and the count that makes it resolvable is required below rather+ * than left to the shell to guess.+ */+export type SetupCountedLabelKey = PluralBase<ParseKeys>;++/** Interpolation values for `labelKey`, e.g. `{ count: 2 }` or `{ name: 'Codex' }`. */+export type SetupActionArgs = Record<string, string | number>;+/*** One screen's claim on the shell's primary action. The shell owns the element — that is* what makes "the button never moves" a property of the tree rather than an agreement* between two stylesheets — so a screen describes the button and never renders it.** `labelKey` is a key from C1. It is typed against the live bundle, so a screen cannot- * name a string that has not shipped.+ * name a string that has not shipped. A counted label is the second member: its family+ * resolves only with a count, so the count travels as part of the claim instead of being+ * something the shell hopes was passed. The fields and their meanings are the same in+ * both members, so a consumer reads `labelKey` and `labelArgs` without narrowing.*/export type SetupAction = {- labelKey: TranslationKey;- /** Interpolation values for `labelKey`, e.g. `{ count: 2 }` or `{ name: 'Codex' }`. */- labelArgs?: Record<string, string | number>;disabled: boolean;/** Renders the spinner glyph and suppresses the arrow. Distinct from `disabled`: a busy* action is also disabled, but a disabled one is not necessarily busy. */busy: boolean;icon: SetupActionIcon;-};+} & (+ | { labelKey: TranslationKey; labelArgs?: SetupActionArgs }+ | { labelKey: SetupCountedLabelKey; labelArgs: SetupActionArgs & { count: number } }+);/*** How the shell drives the active screen. The primary action is the shell's, so the clickdiff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsxindex 1b935c989..ca97a994a 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx@@ -4,8 +4,6 @@ import * as DialogPrimitive from '@radix-ui/react-dialog';import {CheckCircle2,CircleX,- Eye,- EyeOff,LoaderCircle,Save,TriangleAlert,@@ -14,15 +12,16 @@ import {import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';-import { Combobox, type ComboboxOption } from '@/components/ui/combobox';-import { Input } from '@/components/ui/input';-import { cn } from '@/lib/utils';-import { API_KEY_VENDOR_PRESETS, apiKeyVendorPreset, CUSTOM_VENDOR } from './apiKeyVendors';-import { classifyModelHubFailure, type ModelHubFailureClass } from './asyncLifetime';-import { Field } from './dialogFields';+import { ApiKeyField, ApiKeySourceForm } from './ApiKeySourceForm';import {- PROTOCOL_COPY_KEYS,-} from './addApiKeyState';+ apiKeySourceCreate,+ apiKeyWriteSettled,+ draftComplete,+ EMPTY_API_KEY_DRAFT,+ sourceClientNonce,+ type ApiKeySourceDraft,+} from './apiKeySourceDraft';+import { classifyModelHubFailure, type ModelHubFailureClass } from './asyncLifetime';import type { CollectionReadAuthority } from './collectionReadAuthority';import { GuardImpact } from './GuardImpact';import { apiFailure, modelsApi, type SourceCreated } from './modelsApi';@@ -38,17 +37,10 @@ import { reconcileUnknownWrite } from './reconcileUnknownWrite';import { mayHaveWritten, REPAIR_LINE_KEY, wasBlocked } from './repair';import { serverText } from './serverCopy';import {- SOURCE_DISPLAY_NAME_MAX_LENGTH,- SOURCE_PROTOCOLS,- type ApiKeySourceCreate,type RouteHopRef,type Source,- type SourceProtocol,type SupplyGap,} from './types';-import { ProtocolGlyph } from './protocolGlyph';-import { optionalTrimmedTextWithin } from './validation';-import { VendorGlyph } from './vendorGlyph';type Phase =| { kind: 'form' }@@ -57,70 +49,6 @@ type Phase =| { kind: 'save_unconfirmed' };const INITIAL_PHASE: Phase = { kind: 'form' };-type ProtocolSelection = SourceProtocol;--const ProtocolSegments: React.FC<{- id?: string;- disabled: boolean;- selection: ProtocolSelection;- onSelect: (value: ProtocolSelection) => void;-}> = ({ id, disabled, selection, onSelect }) => {- const { t } = useTranslation();- return (- <div- id={id}- role="group"- aria-label={t('settings.models.addKey.field.protocol')}- className="model-hub-add-key-segments flex max-w-full flex-wrap"- >- {SOURCE_PROTOCOLS.map((item) => (- <button- key={item}- type="button"- disabled={disabled}- aria-pressed={selection === item}- className={cn(- 'model-hub-add-key-segment',- selection === item && 'is-selected',- )}- onClick={() => onSelect(item)}- >- <ProtocolGlyph protocol={item} />- {t(PROTOCOL_COPY_KEYS[item])}- </button>- ))}- </div>- );-};--/**- * The 服务商 field's rows: the shipped catalog in the order the file ships, then- * the one entry that is not a vendor at all, each carrying its mark.- *- * File order because that order is a curated ranking, not an accident of how the- * rows were appended: the vendors most users are here to add sit at the top, and- * a name is only what you scan for once the list is long enough to have lost you.- * Re-sorting here would put the ranking in a second place and make the catalog's- * own order unobservable — so this reads the file verbatim, and moving a vendor- * up the list is an edit to `vibe/data/api_key_vendors.json` and to nothing else.- * 自定义 ranks nowhere: it is the absence of a vendor, so it sits after all of- * them rather than inside them, while staying the value the field opens on.- *- * The mark is why the field is no longer a `<select>`. A vendor is recognised by- * its logo long before its name is read, and an `<option>` holds text only — so- * the closed control could only ever show what an option could hold, dropping- * the mark exactly where the choice has already been made. What replaces it is- * this app's one picker, `Combobox`, given a mark per row; a second local- * implementation of the same trigger, panel, and keyboard would only be a place- * for the two to diverge.- */-const useVendorOptions = (): ComboboxOption[] => {- const { t } = useTranslation();- return React.useMemo(() => ([- ...API_KEY_VENDOR_PRESETS.map((preset) => ({ value: preset.id, label: preset.label })),- { value: CUSTOM_VENDOR, label: t('settings.models.addKey.field.vendor.custom') },- ].map((option) => ({ ...option, icon: <VendorGlyph vendor={option.value} /> }))), [t]);-};type ReplaceOutcome =| { kind: 'repaired' }@@ -157,13 +85,6 @@ type AddApiKeyDialogProps = {});-const sourceClientNonce = (): string => {- const uuid = globalThis.crypto.randomUUID?.();- if (uuid) return `scn_${uuid.replaceAll('-', '').toLowerCase()}`;- const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));- return `scn_${Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('')}`;-};-const failureMessageKey = (failure: ReturnType<typeof apiFailure>): string | null =>failure?.detail ?? failure?.code ?? null;@@ -173,54 +94,6 @@ const REPLACE_FAILURE_KEY: Record<ModelHubFailureClass, TranslationKey> = {'retryable-provider': 'settings.models.repair.replaceFailed',};-const ApiKeyField: React.FC<{- value: string;- revealed: boolean;- disabled: boolean;- label: React.ReactNode;- autoFocus?: boolean;- onChange: (value: string) => void;- onToggleReveal: () => void;- onEnter?: () => void;-}> = ({ value, revealed, disabled, label, autoFocus, onChange, onToggleReveal, onEnter }) => {- const { t } = useTranslation();- return (- <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={label}>- {(id) => (- <span className="model-hub-add-key-secret relative flex items-center">- <Input- id={id}- value={value}- type={revealed ? 'text' : 'password'}- disabled={disabled}- autoFocus={autoFocus}- autoComplete="off"- spellCheck={false}- onChange={(event) => onChange(event.target.value)}- onKeyDown={(event) => {- if (event.key !== 'Enter' || disabled || !onEnter) return;- event.preventDefault();- onEnter();- }}- className="model-hub-add-key-input w-full pr-10 font-mono"- />- <Button- type="button"- variant="ghost"- size="icon"- className="model-hub-ink-59 absolute right-1 size-7"- aria-label={t(`settings.models.addKey.field.apiKey.${revealed ? 'conceal' : 'reveal'}`)}- disabled={disabled}- onClick={onToggleReveal}- >- {revealed ? <EyeOff className="size-3.5" /> : <Eye className="size-3.5" />}- </Button>- </span>- )}- </Field>- );-};-export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {const { open, onClose } = props;const replaceMode = props.mode === 'replace';@@ -228,12 +101,8 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {const addOnAdded = replaceMode ? null : props.onAdded;const replaceSourceId = replaceMode ? props.source.id : null;const { t } = useTranslation();- const vendorOptions = useVendorOptions();- const [vendor, setVendor] = React.useState<string>(CUSTOM_VENDOR);- const [displayName, setDisplayName] = React.useState('');- const [baseUrl, setBaseUrl] = React.useState('');- const [apiKey, setApiKey] = React.useState('');- const [protocolSelection, setProtocolSelection] = React.useState<ProtocolSelection>('openai_chat');+ const [draft, setDraft] = React.useState<ApiKeySourceDraft>(EMPTY_API_KEY_DRAFT);+ const apiKey = draft.apiKey;const [revealed, setRevealed] = React.useState(false);const [phase, setPhase] = React.useState<Phase>(INITIAL_PHASE);const [replacePhase, setReplacePhase] = React.useState<ReplacePhase>({ kind: 'edit' });@@ -253,11 +122,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {}if (open) {clientNonce.current = sourceClientNonce();- setVendor(CUSTOM_VENDOR);- setDisplayName('');- setBaseUrl('');- setApiKey('');- setProtocolSelection('openai_chat');+ setDraft(EMPTY_API_KEY_DRAFT);setRevealed(false);setPhase(INITIAL_PHASE);setReplacePhase({ kind: 'edit' });@@ -297,25 +162,14 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {if (settle) void settle().catch(() => undefined);}, [continuation]);- const draft = React.useCallback((): ApiKeySourceCreate => ({- kind: 'api_key', vendor,- ...(displayName.trim() ? { display_name: displayName.trim() } : {}),- base_url: baseUrl.trim(), key: apiKey.trim(),- protocol: apiKeyVendorPreset(vendor)?.protocol ?? protocolSelection,- client_nonce: clientNonce.current, save_unverified: true,- }), [apiKey, baseUrl, displayName, protocolSelection, vendor]);-const persist = React.useCallback(async (seq: ContinuationTicket) => {if (continuation.settle(seq, () => setPhase({ kind: 'working' })) === 'stale') return;try {- const created = await modelsApi.createApiKeySource(draft());+ const created = await modelsApi.createApiKeySource(apiKeySourceCreate(draft, clientNonce.current));createdDelivery.settle(continuation, seq, created);} catch (error) {- const failure = apiFailure(error);- const definitive = failure?.serverNamed && failure.responseStatus !== undefined- && failure.responseStatus >= 400 && failure.responseStatus < 500 && failure.responseStatus !== 409;- continuation.settle(seq, () => setPhase(definitive- ? { kind: 'persist_failure', messageKey: failureMessageKey(failure) }+ continuation.settle(seq, () => setPhase(apiKeyWriteSettled(error)+ ? { kind: 'persist_failure', messageKey: failureMessageKey(apiFailure(error)) }: { kind: 'save_unconfirmed' }));}}, [continuation, createdDelivery, draft]);@@ -413,8 +267,6 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {createdDelivery.close();}, [continuation, createdDelivery, onClose, phase, replaceMode, replacePhase.kind]);- const vendorPreset = apiKeyVendorPreset(vendor);- const constrainedProtocol = vendorPreset?.protocol ?? protocolSelection;const retry = async () => {if (phase.kind === 'save_unconfirmed') {if (!addSourceReads) return;@@ -443,38 +295,24 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {setPhase((current) => current.kind === 'persist_failure' ? INITIAL_PHASE : current);};- const editEndpoint = (value: string) => {- setBaseUrl(value);- clearSaveFailure();- };const editKey = (value: string) => {- setApiKey(value);+ setDraft((current) => ({ ...current, apiKey: value }));if (replaceMode && replacePhase.kind === 'failure') setReplacePhase({ kind: 'edit' });clearSaveFailure();};- const editDisplayName = (value: string) => {- setDisplayName(value);- if (phase.kind === 'persist_failure') setPhase(INITIAL_PHASE);- };- const editProtocol = (value: ProtocolSelection) => {- setProtocolSelection(value);- clearSaveFailure();- };- // Re-selecting the current vendor must preserve a hand-edited endpoint and- // protocol. A different vendor starts from that vendor's defaults.- const editVendor = (value: string) => {- if (value === vendor) return;- setVendor(value);- setBaseUrl(apiKeyVendorPreset(value)?.official_base_url ?? '');- setProtocolSelection('openai_chat');- setPhase(INITIAL_PHASE);+ // A vendor change resets the phase outright rather than only clearing a save+ // failure: it restates what is being connected to, so an unsettled outcome+ // from the previous one no longer describes what the form holds.+ const editDraft = (next: ApiKeySourceDraft, field: keyof ApiKeySourceDraft) => {+ setDraft(next);+ if (field === 'vendor') setPhase(INITIAL_PHASE);+ else clearSaveFailure();};const isWorking = phase.kind === 'working';const formLocked = isWorking || phase.kind === 'save_unconfirmed';const canCancel = replaceMode ? replacePhase.kind !== 'submitting' : !isWorking;- const displayNameValid = optionalTrimmedTextWithin(displayName, SOURCE_DISPLAY_NAME_MAX_LENGTH);- const canSubmit = Boolean(baseUrl.trim() && apiKey.trim()) && displayNameValid && !formLocked;+ const canSubmit = draftComplete(draft) && !formLocked;const replaceTerminalFailure = replacePhase.kind === 'failure'&& replacePhase.failureClass === 'authoritative-terminal';const replaceFieldLocked = replacePhase.kind === 'submitting'@@ -577,65 +415,13 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {{!replaceMode && (<div className="model-hub-add-key-body flex flex-col">- {/* First, because it is the field the rest are conditioned on: it- decides what the Base URL starts as and whether the interface is- still a question. */}- <Field- className="model-hub-add-key-field"- labelClassName="model-hub-add-key-label"- hintClassName="model-hub-add-key-hint"- label={t('settings.models.addKey.field.vendor')}- hint={t('settings.models.addKey.field.vendor.hint')}- >- {(id) => (- <Combobox- id={id}- // The label points here, but a `for` association contributes- // nothing to a button's accessible name, so the field has to- // name itself. The primitive appends the selection to what is- // passed here: the label alone would replace the trigger's- // contents, and those contents are the chosen vendor — the one- // thing a picker exists to report.- ariaLabel={t('settings.models.addKey.field.vendor')}- className="model-hub-add-key-input"- options={vendorOptions}- value={vendor}- onValueChange={editVendor}- // A vendor is a catalog row, and the request sends its id: there- // is no typed value this field could accept.- allowCustomValue={false}- disabled={formLocked}- searchPlaceholder={t('settings.models.addKey.field.vendor.search')}- emptyText={t('settings.models.addKey.field.vendor.empty')}- />- )}- </Field>- <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={t('settings.models.addKey.field.name')}>- {(id) => <Input id={id} value={displayName} disabled={formLocked} aria-invalid={!displayNameValid} onChange={(event) => editDisplayName(event.target.value)} className="model-hub-add-key-input" />}- </Field>- <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" hintClassName="model-hub-add-key-hint" label={t('settings.models.addKey.field.baseUrl')} hint={t('settings.models.addKey.field.baseUrl.hint')}>- {(id) => <Input id={id} value={baseUrl} disabled={formLocked} autoComplete="url" spellCheck={false} onChange={(event) => editEndpoint(event.target.value)} className="model-hub-add-key-input font-mono" />}- </Field>- <ApiKeyField- value={apiKey}- revealed={revealed}+ <ApiKeySourceForm+ draft={draft}disabled={formLocked}- label={t('settings.models.addKey.field.apiKey')}- onChange={editKey}+ revealed={revealed}+ onChange={editDraft}onToggleReveal={() => setRevealed((value) => !value)}/>-- <div className="model-hub-add-key-protocol-area">- <span className="model-hub-add-key-label">{t('settings.models.addKey.field.protocol')}</span>- {vendorPreset ? (- <div className="model-hub-add-key-protocol-idle-row">- <span className="model-hub-add-key-protocol-active">- <ProtocolGlyph protocol={constrainedProtocol} />{t(PROTOCOL_COPY_KEYS[constrainedProtocol])}- </span>- </div>- ) : <ProtocolSegments disabled={formLocked} selection={protocolSelection} onSelect={editProtocol} />}- <p className="model-hub-add-key-hint">{t('settings.models.addKey.protocol.saveFirstHint')}</p>- </div>{isWorking && <div className="model-hub-add-key-strip model-hub-add-key-strip--working"><LoaderCircle className="model-hub-ink-mint size-3.5 animate-spin" /><span className="model-hub-add-key-strip-title">{t('settings.models.addKey.saving')}</span>diff --git a/ui/src/components/settings/models/ApiKeySourceForm.tsx b/ui/src/components/settings/models/ApiKeySourceForm.tsxnew file mode 100644index 000000000..ea270bad5--- /dev/null+++ b/ui/src/components/settings/models/ApiKeySourceForm.tsx@@ -0,0 +1,256 @@+// The fields that ask for an API key, in the one order they are asked in.+//+// Promoted out of `AddApiKeyDialog` for the reason `dialogFields.tsx` was before+// it: setup asks for the same credential inside a different frame, and two+// dialogs asking the same question must be the same question — same vendor+// picker, same endpoint default, same protocol rule, same reveal control. A+// second local copy is how they drift by a hint and a field order.+//+// It renders a fragment rather than a container: what holds these fields is the+// host's frame, and the Model Hub dialog and the setup dialog do not agree on+// that. State is the host's too — it is what setup preserves when a tab is+// switched away from and back.+import * as React from 'react';+import { Eye, EyeOff } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { Combobox, type ComboboxOption } from '@/components/ui/combobox';+import { Input } from '@/components/ui/input';+import { cn } from '@/lib/utils';++import { PROTOCOL_COPY_KEYS } from './addApiKeyState';+import { API_KEY_VENDOR_PRESETS, apiKeyVendorPreset, CUSTOM_VENDOR } from './apiKeyVendors';+import {+ draftNameValid,+ draftProtocol,+ selectVendor,+ type ApiKeySourceDraft,+} from './apiKeySourceDraft';+import { Field } from './dialogFields';+import { ProtocolGlyph } from './protocolGlyph';+import { SOURCE_PROTOCOLS, type SourceProtocol } from './types';+import { VendorGlyph } from './vendorGlyph';++// The form's own dressing travels with the form. Every class below is declared+// in this stylesheet, and its only other importer is the Model Hub page — so a+// host outside that page (setup) would otherwise render these fields naked and+// discover it visually. Vite dedupes the second import; the page keeps its own+// because it draws far more of this sheet than the form does.+import './modelHubSurface.css';++const ProtocolSegments: React.FC<{+ id?: string;+ disabled: boolean;+ selection: SourceProtocol;+ onSelect: (value: SourceProtocol) => void;+}> = ({ id, disabled, selection, onSelect }) => {+ const { t } = useTranslation();+ return (+ <div+ id={id}+ role="group"+ aria-label={t('settings.models.addKey.field.protocol')}+ className="model-hub-add-key-segments flex max-w-full flex-wrap"+ >+ {SOURCE_PROTOCOLS.map((item) => (+ <button+ key={item}+ type="button"+ disabled={disabled}+ aria-pressed={selection === item}+ className={cn(+ 'model-hub-add-key-segment',+ selection === item && 'is-selected',+ )}+ onClick={() => onSelect(item)}+ >+ <ProtocolGlyph protocol={item} />+ {t(PROTOCOL_COPY_KEYS[item])}+ </button>+ ))}+ </div>+ );+};++/**+ * The 服务商 field's rows: the shipped catalog in the order the file ships, then+ * the one entry that is not a vendor at all, each carrying its mark.+ *+ * File order because that order is a curated ranking, not an accident of how the+ * rows were appended: the vendors most users are here to add sit at the top, and+ * a name is only what you scan for once the list is long enough to have lost you.+ * Re-sorting here would put the ranking in a second place and make the catalog's+ * own order unobservable — so this reads the file verbatim, and moving a vendor+ * up the list is an edit to `vibe/data/api_key_vendors.json` and to nothing else.+ * 自定义 ranks nowhere: it is the absence of a vendor, so it sits after all of+ * them rather than inside them, while staying the value the field opens on.+ *+ * The mark is why the field is no longer a `<select>`. A vendor is recognised by+ * its logo long before its name is read, and an `<option>` holds text only — so+ * the closed control could only ever show what an option could hold, dropping+ * the mark exactly where the choice has already been made. What replaces it is+ * this app's one picker, `Combobox`, given a mark per row; a second local+ * implementation of the same trigger, panel, and keyboard would only be a place+ * for the two to diverge.+ */+const useVendorOptions = (): ComboboxOption[] => {+ const { t } = useTranslation();+ return React.useMemo(() => ([+ ...API_KEY_VENDOR_PRESETS.map((preset) => ({ value: preset.id, label: preset.label })),+ { value: CUSTOM_VENDOR, label: t('settings.models.addKey.field.vendor.custom') },+ ].map((option) => ({ ...option, icon: <VendorGlyph vendor={option.value} /> }))), [t]);+};++/**+ * The credential field, with its reveal control.+ *+ * Exported because key replacement asks for exactly this one field and nothing+ * else around it: the same input, the same masking, the same 显示/隐藏 label.+ */+export const ApiKeyField: React.FC<{+ value: string;+ revealed: boolean;+ disabled: boolean;+ label: React.ReactNode;+ autoFocus?: boolean;+ onChange: (value: string) => void;+ onToggleReveal: () => void;+ onEnter?: () => void;+}> = ({ value, revealed, disabled, label, autoFocus, onChange, onToggleReveal, onEnter }) => {+ const { t } = useTranslation();+ return (+ <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={label}>+ {(id) => (+ <span className="model-hub-add-key-secret relative flex items-center">+ <Input+ id={id}+ value={value}+ type={revealed ? 'text' : 'password'}+ disabled={disabled}+ autoFocus={autoFocus}+ autoComplete="off"+ spellCheck={false}+ onChange={(event) => onChange(event.target.value)}+ onKeyDown={(event) => {+ if (event.key !== 'Enter' || disabled || !onEnter) return;+ event.preventDefault();+ onEnter();+ }}+ className="model-hub-add-key-input w-full pr-10 font-mono"+ />+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="model-hub-ink-59 absolute right-1 size-7"+ aria-label={t(`settings.models.addKey.field.apiKey.${revealed ? 'conceal' : 'reveal'}`)}+ disabled={disabled}+ onClick={onToggleReveal}+ >+ {revealed ? <EyeOff className="size-3.5" /> : <Eye className="size-3.5" />}+ </Button>+ </span>+ )}+ </Field>+ );+};++/**+ * @param onChange receives the whole next draft and the field that moved. The+ * field is there because hosts react differently to different edits — the Model+ * Hub dialog clears a save failure on any edit but resets its phase outright on+ * a vendor change — and inferring which one changed by diffing would be the+ * same rule written twice.+ * @param onSubmit Enter in the key field, when the host has somewhere to send it.+ * @param keyLabel Names the credential field. Setup titles it by the chosen brand+ * — 「OpenAI API Key」 — because it arrives there having just been asked for that+ * brand by name; the generic label is what a form opened from nowhere says.+ */+export const ApiKeySourceForm: React.FC<{+ draft: ApiKeySourceDraft;+ disabled: boolean;+ revealed: boolean;+ autoFocusKey?: boolean;+ keyLabel?: React.ReactNode;+ onChange: (next: ApiKeySourceDraft, field: keyof ApiKeySourceDraft) => void;+ onToggleReveal: () => void;+ onSubmit?: () => void;+}> = ({ draft, disabled, revealed, autoFocusKey, keyLabel, onChange, onToggleReveal, onSubmit }) => {+ const { t } = useTranslation();+ const vendorOptions = useVendorOptions();+ const vendorPreset = apiKeyVendorPreset(draft.vendor);+ const nameValid = draftNameValid(draft);++ return (+ <>+ {/* First, because it is the field the rest are conditioned on: it+ decides what the Base URL starts as and whether the interface is+ still a question. */}+ <Field+ className="model-hub-add-key-field"+ labelClassName="model-hub-add-key-label"+ hintClassName="model-hub-add-key-hint"+ label={t('settings.models.addKey.field.vendor')}+ hint={t('settings.models.addKey.field.vendor.hint')}+ >+ {(id) => (+ <Combobox+ id={id}+ // The label points here, but a `for` association contributes+ // nothing to a button's accessible name, so the field has to+ // name itself. The primitive appends the selection to what is+ // passed here: the label alone would replace the trigger's+ // contents, and those contents are the chosen vendor — the one+ // thing a picker exists to report.+ ariaLabel={t('settings.models.addKey.field.vendor')}+ className="model-hub-add-key-input"+ options={vendorOptions}+ value={draft.vendor}+ onValueChange={(value) => onChange(selectVendor(draft, value), 'vendor')}+ // A vendor is a catalog row, and the request sends its id: there+ // is no typed value this field could accept.+ allowCustomValue={false}+ disabled={disabled}+ searchPlaceholder={t('settings.models.addKey.field.vendor.search')}+ emptyText={t('settings.models.addKey.field.vendor.empty')}+ />+ )}+ </Field>+ <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={t('settings.models.addKey.field.name')}>+ {(id) => <Input id={id} value={draft.displayName} disabled={disabled} aria-invalid={!nameValid} onChange={(event) => onChange({ ...draft, displayName: event.target.value }, 'displayName')} className="model-hub-add-key-input" />}+ </Field>+ <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" hintClassName="model-hub-add-key-hint" label={t('settings.models.addKey.field.baseUrl')} hint={t('settings.models.addKey.field.baseUrl.hint')}>+ {(id) => <Input id={id} value={draft.baseUrl} disabled={disabled} autoComplete="url" spellCheck={false} onChange={(event) => onChange({ ...draft, baseUrl: event.target.value }, 'baseUrl')} className="model-hub-add-key-input font-mono" />}+ </Field>+ <ApiKeyField+ value={draft.apiKey}+ revealed={revealed}+ disabled={disabled}+ autoFocus={autoFocusKey}+ label={keyLabel ?? t('settings.models.addKey.field.apiKey')}+ onChange={(value) => onChange({ ...draft, apiKey: value }, 'apiKey')}+ onToggleReveal={onToggleReveal}+ onEnter={onSubmit}+ />++ <div className="model-hub-add-key-protocol-area">+ <span className="model-hub-add-key-label">{t('settings.models.addKey.field.protocol')}</span>+ {vendorPreset ? (+ <div className="model-hub-add-key-protocol-idle-row">+ <span className="model-hub-add-key-protocol-active">+ <ProtocolGlyph protocol={draftProtocol(draft)} />{t(PROTOCOL_COPY_KEYS[draftProtocol(draft)])}+ </span>+ </div>+ ) : (+ <ProtocolSegments+ disabled={disabled}+ selection={draft.protocol}+ onSelect={(value) => onChange({ ...draft, protocol: value }, 'protocol')}+ />+ )}+ <p className="model-hub-add-key-hint">{t('settings.models.addKey.protocol.saveFirstHint')}</p>+ </div>+ </>+ );+};diff --git a/ui/src/components/settings/models/MigrationDialog.test.tsx b/ui/src/components/settings/models/MigrationDialog.test.tsxindex 98e26bcfe..32b250c3d 100644--- a/ui/src/components/settings/models/MigrationDialog.test.tsx+++ b/ui/src/components/settings/models/MigrationDialog.test.tsx@@ -5,6 +5,7 @@// block that CLI, while a complete backend can still migrate independently.import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';+import { useState } from 'react';import { I18nextProvider } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -15,6 +16,7 @@ const showToast = vi.hoisted(() => vi.fn());vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast }) }));import { MigrationDialog } from './MigrationDialog';+import type { MigrationSelection } from './migrationGrouping';import { isImportableKey } from './migrationScan';import { ApiCallError, modelsApi } from './modelsApi';@@ -64,6 +66,21 @@ const REAUTH: MigrationItem = {masked_credential: 'sk-ant-…4b7e',};+// Importable, and on the same backend as the subscription above: the pair is what+// setup can see but cannot take, because the server migrates a backend whole.+const CLAUDE_KEY: MigrationItem = {+ id: 'mig_claude_key',+ backend: 'claude',+ kind: 'api_key',+ masked_detail: 'sk-ant-…1c05',+ proposed_action: 'import',+ selected: true,+ notes_key: null,+ vendor: 'anthropic',+ display_name: 'Anthropic',+ masked_credential: 'sk-ant-…1c05',+};+// An older server that sends none of the presentation metadata.const LEGACY: MigrationItem = {id: 'mig_opencode_legacy',@@ -713,3 +730,334 @@ describe('MigrationDialog — shared persisted files', () => {await waitFor(() => expect(applied).toEqual([[LEGACY.id]]));});});++// ── the two entry points ────────────────────────────────────────────────+//+// Setup reuses this dialog rather than growing a second take-over, so the guard+// that matters is that Settings did not quietly change when it did: the whole+// rendered surface is asserted literally, because a copy table that resolved one+// key to the wrong scope would still render *something* and still pass a+// behaviour test.++const visibleText = (root: Element): string[] => {+ const out: string[] = [];+ const walk = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ for (let node = walk.nextNode(); node; node = walk.nextNode()) {+ const text = node.textContent?.trim();+ if (text) out.push(text);+ }+ return out;+};++const controls = (root: Element) =>+ [...root.querySelectorAll('button')].map((button) => ({+ role: button.getAttribute('role'),+ name: button.getAttribute('aria-label') ?? button.textContent?.trim() ?? '',+ disabled: button.disabled,+ }));++describe('MigrationDialog — the Settings surface the setup scope must not disturb', () => {+ it('renders exactly the copy and controls it shipped with', async () => {+ serve([SUBSCRIPTION, CODEX_KEY, REAUTH]);+ renderDialog();++ const dialog = await screen.findByRole('dialog');+ await within(dialog).findByText('OpenAI');++ expect(visibleText(dialog)).toEqual([+ 'Migrate to the Model Hub',+ 'Import authentication saved in configuration files, shell startup files, or supported credential stores, without reading runtime environment values. After migration, Model Hub will manage the selected authentication.',+ 'Claude Code',+ 'Claude Code configuration',+ 'This credential cannot be imported. Use the existing Add flow in Model Hub to add this source manually.',+ 'Anthropic',+ 'Claude 账号登录(OAuth) · Claude Code configuration',+ 'Anthropic',+ 'sk-ant-…4b7e · Claude Code configuration',+ 'Codex',+ 'OpenAI',+ 'sk-…9f21 · Codex configuration',+ 'Later',+ 'Start migration',+ 'Close',+ ]);+ expect(controls(dialog)).toEqual([+ { role: 'checkbox', name: 'Anthropic · Claude 账号登录(OAuth) · Claude Code configuration', disabled: true },+ { role: 'checkbox', name: 'Anthropic · sk-ant-…4b7e · Claude Code configuration', disabled: true },+ { role: 'checkbox', name: 'OpenAI · sk-…9f21 · Codex configuration', disabled: false },+ { role: null, name: 'Later', disabled: false },+ { role: null, name: 'Start migration', disabled: false },+ { role: null, name: 'Close', disabled: false },+ ]);+ });++ it('keeps owning its own scan and selection when no controlled value is passed', async () => {+ serve([CODEX_KEY]);+ renderDialog();++ const dialog = await screen.findByRole('dialog');+ await within(dialog).findByText('OpenAI');+ expect(modelsApi.scanMigration).toHaveBeenCalledTimes(1);+ expect(within(dialog).queryByText(/complete API-key groups only/)).toBeNull();+ });++ it('still takes a key standing beside a subscription, because its scope is everything', async () => {+ serve([SUBSCRIPTION, CLAUDE_KEY]);+ renderDialog();++ const dialog = await screen.findByRole('dialog');+ await within(dialog).findByText(/sk-ant-…1c05/);++ // No narrower scope was passed, so neither row is out of reach and the group+ // is not blocked: the whole backend migrates together, as it always has.+ expect(controls(dialog)).toEqual([+ { role: 'checkbox', name: 'Anthropic · Claude 账号登录(OAuth) · Claude Code configuration', disabled: false },+ { role: 'checkbox', name: 'Anthropic · sk-ant-…1c05 · Claude Code configuration', disabled: false },+ { role: null, name: 'Later', disabled: false },+ { role: null, name: 'Start migration', disabled: false },+ { role: null, name: 'Close', disabled: false },+ ]);+ expect(within(dialog).queryByText(/but not from here/)).toBeNull();+ });+});++const SetupHost: React.FC<{+ scan: MigrationItem[];+ /** What the caller's refreshed scan returns after each successive batch. */+ after?: MigrationItem[][];+ onClose?: () => void;+ onApplied?: (applied: number) => void;+ /** What a host that can withdraw permission mid-review passes. Settings passes+ * nothing at all, which is the default and what every case above relies on. */+ writable?: boolean;+}> = ({ scan, after = [], onClose = () => {}, onApplied, writable }) => {+ const [selection, setSelection] = useState<MigrationSelection>({+ scan: { items: scan },+ selectedBackends: [],+ });+ const [round, setRound] = useState(0);+ return (+ <MigrationDialog+ open+ scope="setup"+ eligible={isImportableKey}+ takeable={isImportableKey}+ value={selection}+ onChange={setSelection}+ writable={writable}+ onApplied={(applied) => {+ onApplied?.(applied);+ // The receipt is a refresh trigger, not a success receipt: re-read and+ // let the refreshed scan decide what is left.+ setSelection({ scan: { items: after[round] ?? [] }, selectedBackends: [] });+ setRound((prior) => prior + 1);+ }}+ onClose={onClose}+ />+ );+};++const renderSetup = (props: React.ComponentProps<typeof SetupHost>) => {+ const view = render(+ <I18nextProvider i18n={i18n}>+ <SetupHost {...props} />+ </I18nextProvider>,+ );+ /** The host changing its half of the contract without remounting the dialog. */+ const show = (next: Partial<React.ComponentProps<typeof SetupHost>>) => view.rerender(+ <I18nextProvider i18n={i18n}>+ <SetupHost {...props} {...next} />+ </I18nextProvider>,+ );+ return { ...view, show };+};++describe('MigrationDialog — the setup scope', () => {+ it('wears setup copy and never scans for a controlled caller', async () => {+ const scan = vi.spyOn(modelsApi, 'scanMigration');+ renderSetup({ scan: [CODEX_KEY, LEGACY] });++ const dialog = await screen.findByRole('dialog');+ expect(within(dialog).getByText('Migrate to Model Hub')).toBeTruthy();+ expect(within(dialog).getByText('After migration, CLI authentication will be managed entirely by Model Hub.')).toBeTruthy();+ expect(within(dialog).getByText(/complete API-key groups only/)).toBeTruthy();+ expect(within(dialog).getByRole('button', { name: 'Not now' })).toBeTruthy();+ expect(scan).not.toHaveBeenCalled();+ });++ it('starts from the caller selection and submits one atomic batch', async () => {+ serve();+ renderSetup({ scan: [CODEX_KEY, LEGACY] });+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ const confirm = within(dialog).getByRole('button', { name: 'Start migration' }) as HTMLButtonElement;+ // Nothing is consented to until the caller says so, whatever the scan+ // pre-selected on its rows.+ expect(confirm.disabled).toBe(true);++ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }));+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));++ await waitFor(() => expect(applied).toEqual([[CODEX_KEY.id]]));+ });++ it('reports what landed, offers the remainder, and re-enters selection with it', async () => {+ serve();+ renderSetup({ scan: [CODEX_KEY, LEGACY], after: [[LEGACY], []] });+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }));+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));++ await within(dialog).findByText('Migrated 1 configuration item');+ expect(within(dialog).getByText('1 item needs review. Continue any time.')).toBeTruthy();+ // The dialog stays: setup has more to say than "it closed".+ expect(within(dialog).queryByRole('button', { name: 'Start migration' })).toBeNull();++ await user.click(within(dialog).getByRole('button', { name: 'Review remaining' }));+ await within(dialog).findByRole('button', { name: 'Start migration' });+ expect(within(dialog).queryByRole('checkbox', { name: /sk-…9f21/ })).toBeNull();+ expect(within(dialog).getByRole('checkbox', { name: /自建中转/ })).toBeTruthy();+ });++ it('counts every batch of one session, not only the last', async () => {+ serve();+ renderSetup({ scan: [CODEX_KEY, LEGACY], after: [[LEGACY], []] });+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }));+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));+ await within(dialog).findByText('Migrated 1 configuration item');+ await user.click(within(dialog).getByRole('button', { name: 'Review remaining' }));++ await user.click(within(dialog).getByRole('checkbox', { name: /自建中转/ }));+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));++ await within(dialog).findByText('Migrated 2 configuration items');+ expect(within(dialog).queryByText(/needs review/)).toBeNull();+ expect(applied).toEqual([[CODEX_KEY.id], [LEGACY.id]]);+ });++ it('returns to the same selection after a failed batch', async () => {+ vi.spyOn(modelsApi, 'applyMigration').mockRejectedValue(+ new ApiCallError('migration_native_busy', 'busy'),+ );+ renderSetup({ scan: [CODEX_KEY, LEGACY] });+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }));+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));++ await waitFor(() => expect(showToast).toHaveBeenCalled());+ const confirm = await within(dialog).findByRole('button', { name: 'Start migration' });+ expect((confirm as HTMLButtonElement).disabled).toBe(false);+ expect(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }).getAttribute('aria-checked')).toBe('true');+ expect(within(dialog).queryByText(/Migrated/)).toBeNull();+ });++ it('cannot be dismissed while a batch is in flight', async () => {+ let release: (value: { applied: number; sources: [] }) => void = () => {};+ vi.spyOn(modelsApi, 'applyMigration').mockImplementation(+ () => new Promise((resolve) => { release = resolve; }),+ );+ const onClose = vi.fn();+ renderSetup({ scan: [CODEX_KEY], onClose });+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }));+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));+ await within(dialog).findByText('Migrating 1 configuration item…');++ await user.click(within(dialog).getByRole('button', { name: 'Close' }));+ fireEvent.keyDown(dialog, { key: 'Escape' });+ expect(onClose).not.toHaveBeenCalled();++ release({ applied: 1, sources: [] });+ await within(dialog).findByText('Migrated 1 configuration item');+ await user.click(within(dialog).getByRole('button', { name: 'Done' }));+ expect(onClose).toHaveBeenCalled();+ });++ it('refuses a batch its host no longer admits, and keeps the review readable', async () => {+ serve();+ const onClose = vi.fn();+ const { show } = renderSetup({ scan: [CODEX_KEY, LEGACY], onClose, writable: true });+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }));+ const confirm = () => within(dialog).getByRole<HTMLButtonElement>('button', { name: 'Start migration' });+ expect(confirm().disabled).toBe(false);++ // The host stopped admitting a write — for setup, the engine these keys would be+ // migrated INTO. Only the batch is refused: what was chosen is still chosen, still+ // readable, and still leavable, because closing this is a different answer.+ show({ writable: false });+ expect(confirm().disabled).toBe(true);+ await user.click(confirm());+ expect(modelsApi.applyMigration).not.toHaveBeenCalled();+ expect(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }).getAttribute('aria-checked')).toBe('true');+ expect(within(dialog).getByText(/sk-…9f21/)).toBeTruthy();+ expect(within(dialog).queryByText(/Migrated/)).toBeNull();++ await user.click(within(dialog).getByRole('button', { name: 'Not now' }));+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it('settles a batch it had already sent when permission goes away mid-flight', async () => {+ let release: (value: { applied: number; sources: [] }) => void = () => {};+ const apply = vi.spyOn(modelsApi, 'applyMigration').mockImplementation(+ () => new Promise((resolve) => { release = resolve; }),+ );+ const onApplied = vi.fn();+ const { show } = renderSetup({ scan: [CODEX_KEY], onApplied, writable: true });+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }));+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));+ await within(dialog).findByText('Migrating 1 configuration item…');++ // Withdrawn while that batch is on the server's side of the wire. It owns its own+ // outcome: permission governs the next write, and a report dropped here would+ // leave keys migrated with nothing on screen saying so.+ show({ writable: false });+ release({ applied: 1, sources: [] });++ await within(dialog).findByText('Migrated 1 configuration item');+ expect(onApplied).toHaveBeenCalledTimes(1);+ expect(onApplied).toHaveBeenCalledWith(1);+ expect(apply).toHaveBeenCalledTimes(1);+ // The report is the whole of what is offered: there is no second batch to send.+ expect(within(dialog).queryByRole('button', { name: 'Start migration' })).toBeNull();+ await user.click(within(dialog).getByRole('button', { name: 'Done' }));+ });++ it('shows a key it cannot take here, and says why rather than offering it', async () => {+ renderSetup({ scan: [SUBSCRIPTION, CLAUDE_KEY] });++ const dialog = await screen.findByRole('dialog');+ await within(dialog).findByText(/sk-ant-…1c05/);++ // The key stays on screen — a detected credential the screen dropped would be+ // unexplained — but its group is blocked, because taking it would take the+ // subscription beside it, which setup has no consent for.+ expect(controls(dialog)).toEqual([+ { role: 'checkbox', name: 'Anthropic · Claude 账号登录(OAuth) · Claude Code configuration', disabled: true },+ { role: 'checkbox', name: 'Anthropic · sk-ant-…1c05 · Claude Code configuration', disabled: true },+ { role: null, name: 'Not now', disabled: false },+ { role: null, name: 'Start migration', disabled: true },+ { role: null, name: 'Close', disabled: false },+ ]);+ // Not the server's "cannot be imported": it can be, just not from here.+ expect(+ within(dialog).getByText('This credential can be migrated, but not from here. Review it in Settings.'),+ ).toBeTruthy();+ expect(within(dialog).queryByText(/cannot be imported/)).toBeNull();+ });+});diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsxindex ae84dbc3d..6295f8930 100644--- a/ui/src/components/settings/models/MigrationDialog.tsx+++ b/ui/src/components/settings/models/MigrationDialog.tsx@@ -2,7 +2,7 @@// shared persisted assignments link those boundaries into one consent group.import * as React from 'react';import type { TFunction } from 'i18next';-import { ArrowDownToLine, Bot, KeyRound, Loader2, Sparkles } from 'lucide-react';+import { ArrowDownToLine, Bot, CheckCircle2, KeyRound, Loader2, Sparkles } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';@@ -18,14 +18,22 @@ import { cn } from '@/lib/utils';import { useToast } from '@/context/ToastContext';import type { TranslationKey } from '@/i18n/types';import { providerLabel, providerVendorId } from '../providers/providerIdentity';+import {+ BACKEND_ORDER,+ BLOCKED_REASON_FALLBACK_KEY,+ appliableItems,+ blockedReasonKey,+ groupMigrationCandidates,+ groupSelectable,+ isImportable,+ type MigrationSelection,+} from './migrationGrouping';import { apiFailure, modelsApi } from './modelsApi';import { serverText } from './serverCopy';import { VendorGlyph } from './vendorGlyph';import { ACCENT_ICON, ACCENT_TILE, type Accent } from './vendorMeta';import type { AgentBackend, MigrationItem } from './types';-const BACKEND_ORDER: AgentBackend[] = ['claude', 'codex', 'opencode'];-// Older payloads cannot identify the exact file or store. Name only the// backend's configuration when the server supplies no file locators.const SOURCE_KEY = {@@ -101,26 +109,6 @@ const ItemRow: React.FC<{};const DEFAULT_SCOPE = () => true;-const isImportable = (item: MigrationItem) => item.proposed_action === 'import';--function requiredBackends(items: MigrationItem[], backends: Iterable<AgentBackend>): Set<AgentBackend> {- const required = new Set(backends);- // Resolve from every row of an included backend, not just the eligible- // entry-point rows. Scope filters cannot conceal a shared-file consumer.- let expanded = true;- while (expanded) {- expanded = false;- for (const item of items) {- if (!required.has(item.backend)) continue;- for (const backend of item.required_backends ?? []) {- if (required.has(backend)) continue;- required.add(backend);- expanded = true;- }- }- }- return required;-}const MIGRATION_ERROR_KEYS: Record<string, TranslationKey> = {migration_native_busy: 'settings.models.migration.errors.nativeBusy',@@ -131,41 +119,112 @@ const MIGRATION_ERROR_KEYS: Record<string, TranslationKey> = {migration_credentials_invalid: 'settings.models.migration.errors.credentialsInvalid',migration_reauthorization_required: 'settings.models.migration.errors.reauthorizationRequired',};-const BLOCKED_NOTE_KEYS = new Set<string>([- 'settings.models.migration.blocked.config',- 'settings.models.migration.blocked.environment',- 'settings.models.migration.blocked.credential',- 'settings.models.migration.blocked.dynamic_shell',- 'settings.models.migration.blocked.ambiguous_shell',- 'settings.models.migration.blocked.unreadable',- 'settings.models.migration.blocked.reference',- 'settings.models.migration.blocked.helper',- 'settings.models.migration.blocked.token',- 'settings.models.migration.blocked.headers',- 'settings.models.migration.blocked.transport',-] satisfies TranslationKey[]);-const BLOCKED_FALLBACK_KEY = 'settings.models.migration.blocked.fallback' satisfies TranslationKey;-function blockedMessages(t: TFunction,rows: MigrationItem[],): { key: string; source: string; message: string }[] {const messages = new Map<string, { key: string; source: string; message: string }>();for (const item of rows) {- const noteKey = item.notes_key && BLOCKED_NOTE_KEYS.has(item.notes_key) ? item.notes_key : undefined;- const message = serverText(t, noteKey, BLOCKED_FALLBACK_KEY) ?? '';+ // The dedup identity stays the key the SERVER sent: two rows on one file with+ // two unrecognised notes are two answers, even though both read as the generic+ // line. What each of them says is the shared rule's business.+ const reason = isImportable(item) ? 'onboarding.import.outOfScope' : item.notes_key ?? BLOCKED_REASON_FALLBACK_KEY;+ const message = serverText(t, blockedReasonKey(item), BLOCKED_REASON_FALLBACK_KEY) ?? '';const paths = sourcePaths(item);// Older scans cannot identify a file. Keep their backend-level locator,// with each distinct reason, without duplicating an account or key title.const sources = paths.length > 0 ? paths : [t(SOURCE_KEY[item.backend])];for (const source of sources) {- const key = JSON.stringify([source, item.notes_key ?? BLOCKED_FALLBACK_KEY]);+ const key = JSON.stringify([source, reason]);messages.set(key, { key, source, message });}}return [...messages.values()];}+/**+ * What setup's take-over is doing, and what it landed.+ *+ * It reports rather than promises: the running line names the batch that is in+ * flight, and the finished line names what the refreshed scan proves was taken+ * over plus whatever is still there to come back to. Neither claims anything+ * about rollback, copies or untouched connections — the apply owns those facts,+ * and this screen is not where they are decided.+ */+const MigrationReport: React.FC<{+ phase: SetupPhase;+ completed: number;+ remaining: number;+ onContinue: () => void;+ onDone: () => void;+}> = ({ phase, completed, remaining, onContinue, onDone }) => {+ const { t } = useTranslation();+ const running = phase.kind === 'applying';+ return (+ <div className="flex flex-col gap-5">+ <div className="flex flex-col items-center gap-3.5 py-6 text-center" role="status" aria-live="polite">+ <span className="flex size-8 shrink-0 items-center justify-center">+ {running+ ? <Loader2 className="model-hub-ink-mint size-8 animate-spin" />+ : <CheckCircle2 className="model-hub-ink-mint size-8" />}+ </span>+ <span className="text-[17px] font-semibold text-foreground">+ {running+ ? t('onboarding.import.progress', { count: phase.count })+ : t('onboarding.import.done', { count: completed })}+ </span>+ <span className="text-[12px] leading-relaxed text-muted">+ {t(running ? 'onboarding.import.progressDetail' : 'onboarding.import.doneDetail')}+ </span>+ {!running && remaining > 0 && (+ <span className="text-[12px] leading-relaxed text-muted">+ {t('onboarding.import.remaining', { count: remaining })}+ </span>+ )}+ </div>+ {!running && (+ <div className="flex items-center justify-end gap-2 border-t border-border pt-4">+ {remaining > 0 && (+ <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onContinue}>+ {t('onboarding.import.remainingAction')}+ </Button>+ )}+ <Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={onDone}>+ {t('onboarding.import.done')}+ </Button>+ </div>+ )}+ </div>+ );+};++export type MigrationDialogScope = 'settings' | 'setup';++/** The chrome each entry point wears. The rows, the consent groups and the+ * apply call underneath are the same surface in both: only the words around+ * them, and setup's progress/done phases, differ. */+const SCOPE_COPY = {+ settings: {+ title: 'settings.models.migration.title',+ description: 'settings.models.migration.subtitle',+ cancel: 'settings.models.migration.later',+ confirm: 'settings.models.migration.apply',+ confirming: 'settings.models.migration.applying',+ },+ setup: {+ title: 'onboarding.import.title',+ description: 'onboarding.import.description',+ cancel: 'onboarding.import.notNow',+ confirm: 'onboarding.import.confirm',+ confirming: 'settings.models.migration.applying',+ },+} as const satisfies Record<MigrationDialogScope, Record<string, TranslationKey>>;++/** Where setup's dialog is in its own take-over: choosing, running, or reporting+ * what landed. Settings has no phases — it closes on success, as it always+ * has. */+type SetupPhase = { kind: 'select' } | { kind: 'applying'; count: number } | { kind: 'done' };+export const MigrationDialog: React.FC<{open: boolean;onClose: () => void;@@ -174,13 +233,53 @@ export const MigrationDialog: React.FC<{/** Scopes the entry point, then includes every native row and required* backend so shared-file custody and blockers remain explicit. */eligible?: (item: MigrationItem) => boolean;-}> = ({ open, onClose, onApplied, eligible }) => {+ /** Which of the rows in view this entry point may actually take over. One in view+ * that fails it blocks its group — the server migrates a backend whole — so it+ * stays visible, with its blocker, rather than riding along in someone else's+ * batch. Omitted means every row the scan proposes importing, which is Settings. */+ takeable?: (item: MigrationItem) => boolean;+ /** Which entry point this is. `settings` is the shipped surface and renders+ * exactly as it always has. */+ scope?: MigrationDialogScope;+ /** Passing `value` makes the dialog controlled: the caller owns the scan and+ * the selection, and the dialog neither scans nor remembers. Setup does this+ * because its screen already holds both (C2). */+ value?: MigrationSelection;+ onChange?: (next: MigrationSelection) => void;+ /**+ * Whether the host still admits the write this dialog would send.+ *+ * Defaults to true, which is Settings: a host that never withdraws permission never+ * passes it. Setup does withdraw it — the engine it would migrate into can stop, or+ * the read that said it was serving can fail, while this is open — and then the+ * take-over is what has to refuse. Refusing is all it does: the scan, the selection+ * and what already landed stay on screen to be read and cancelled, because closing+ * the dialog is not the same answer as declining to write and would take the report+ * with it. A batch already sent keeps its own outcome.+ */+ writable?: boolean;+}> = ({+ open,+ onClose,+ onApplied,+ eligible,+ takeable,+ scope = 'settings',+ value,+ onChange,+ writable = true,+}) => {const { t } = useTranslation();const { showToast } = useToast();+ const copy = SCOPE_COPY[scope];+ const controlled = value !== undefined;- const [items, setItems] = React.useState<MigrationItem[]>([]);- const [loading, setLoading] = React.useState(true);+ const [ownItems, setOwnItems] = React.useState<MigrationItem[]>([]);+ const [ownLoading, setOwnLoading] = React.useState(true);const [applying, setApplying] = React.useState(false);+ const [phase, setPhase] = React.useState<SetupPhase>({ kind: 'select' });+ /** Everything this dialog session has taken over, across re-entries. */+ const [completed, setCompleted] = React.useState(0);const aliveRef = React.useRef(true);React.useEffect(() => {aliveRef.current = true;@@ -191,64 +290,66 @@ export const MigrationDialog: React.FC<{React.useEffect(() => {if (!open) return;+ setPhase({ kind: 'select' });+ setCompleted(0);+ }, [open]);++ React.useEffect(() => {+ if (!open || controlled) return;let cancelled = false;- setLoading(true);+ setOwnLoading(true);// Drop any rows from a prior scan so a failed rescan can't display — or// submit — stale migration ids.- setItems([]);+ setOwnItems([]);modelsApi.scanMigration().then((scan) => {if (cancelled) return;- setItems(scan.items);- setLoading(false);+ setOwnItems(scan.items);+ setOwnLoading(false);}).catch(() => {if (cancelled) return;- setLoading(false);+ setOwnLoading(false);showToast(t('settings.models.migration.scanFailed') as string, 'error');});return () => {cancelled = true;};- }, [open, showToast, t]);+ }, [open, controlled, showToast, t]);+ const items = controlled ? (value.scan?.items ?? []) : ownItems;+ const loading = controlled ? value.scan === null : ownLoading;const scopePredicate = eligible ?? DEFAULT_SCOPE;- const scopedBackends = requiredBackends(- items,- items.filter(scopePredicate).map((item) => item.backend),- );- const candidates = items.filter((item) => scopedBackends.has(item.backend));- const grouped = BACKEND_ORDER.map((backend) => {- const rows = candidates.filter((item) => item.backend === backend);- const importRows = rows.filter(isImportable);- const required = requiredBackends(items, [backend]);- const linkedRows = candidates.filter((item) => required.has(item.backend));- const linkedImportRows = linkedRows.filter(isImportable);- const blockedRows = linkedRows.filter((item) => !isImportable(item));- return {- backend,- rows,- importRows,- required,- linkedImportRows,- blockedRows,- blocked: blockedRows.length > 0,- };- }).filter((group) => group.rows.length > 0);+ const grouped = groupMigrationCandidates(items, scopePredicate, takeable);+ // Uncontrolled selection lives on the rows, as it always has. A controlled+ // caller names backends instead, and a backend it named that this scope+ // cannot consent to selects nothing.const selectedBackends = new Set(grouped.filter((group) => (- !group.blocked- && group.importRows.length > 0- && group.linkedImportRows.every((item) => item.selected)+ groupSelectable(group)+ && (controlled+ ? value.selectedBackends.includes(group.backend)+ : group.linkedImportRows.every((item) => item.selected))))- .map((group) => group.backend)+ .map((group) => group.backend),);- const toggle = (backend: AgentBackend) =>- setItems((prev) => {- const group = grouped.find((item) => item.backend === backend);- if (!group || group.blocked || group.importRows.length === 0) return prev;+ const toggle = (backend: AgentBackend) => {+ const group = grouped.find((item) => item.backend === backend);+ if (!group || !groupSelectable(group)) return;+ if (controlled) {+ // Toggling any member selects or deselects the whole linked group.+ const next = new Set(value.selectedBackends);+ const on = selectedBackends.has(backend);+ for (const linked of group.required) {+ if (on) next.delete(linked);+ else next.add(linked);+ }+ onChange?.({ scan: value.scan, selectedBackends: [...next] });+ return;+ }+ setOwnItems((prev) => {const selected = group.linkedImportRows.every((item) => item.selected);return prev.map((item) => (group.required.has(item.backend) && isImportable(item)@@ -256,23 +357,37 @@ export const MigrationDialog: React.FC<{: item));});- const appliable = items.filter(- (item) => selectedBackends.has(item.backend) && isImportable(item),- );+ };+ const appliable = appliableItems(items, selectedBackends);const selectedCount = appliable.length;+ /** What a re-entry would still find, once a batch has landed. */+ const remaining = grouped.filter(groupSelectable)+ .reduce((total, group) => total + group.importRows.length, 0);const apply = async () => {- if (applying || selectedCount === 0) return;+ // Read here, not captured at mount: permission is whatever it is at the moment the+ // batch would be sent. The disabled button says the same thing, and this is what+ // makes it true for a press the button did not gate — a keyboard activation that+ // raced the render, or a caller invoking the confirm path some other way.+ if (!writable || applying || selectedCount === 0) return;setApplying(true);+ if (scope === 'setup') setPhase({ kind: 'applying', count: selectedCount });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');+ setCompleted((prior) => prior + result.applied);onApplied?.(result.applied);- onClose();+ // Setup reports what landed and what is left rather than vanishing; the+ // caller's refreshed scan is what the remainder is counted from.+ if (scope === 'setup') setPhase({ kind: 'done' });+ else onClose();} catch (error) {if (aliveRef.current) {+ // The selection is left exactly as it was: a failed batch is retried+ // from the same rows, not rebuilt.+ if (scope === 'setup') setPhase({ kind: 'select' });const code = apiFailure(error)?.code;const key =MIGRATION_ERROR_KEYS[code ?? ''] ??@@ -288,6 +403,8 @@ export const MigrationDialog: React.FC<{}};+ const reporting = scope === 'setup' && phase.kind !== 'select';+return (<Dialog open={open} onOpenChange={(v) => !v && !applying && onClose()}><DialogContent className="max-w-[640px] gap-5">@@ -296,17 +413,28 @@ export const MigrationDialog: React.FC<{<span className="flex size-10 shrink-0 items-center justify-center rounded-[12px] bg-mint-soft"><ArrowDownToLine className="model-hub-ink-mint size-5" /></span>- {t('settings.models.migration.title')}+ {t(copy.title)}</DialogTitle>- <DialogDescription className="sm:pl-[52px]">{t('settings.models.migration.subtitle')}</DialogDescription>+ <DialogDescription className="sm:pl-[52px]">{t(copy.description)}</DialogDescription></DialogHeader>- {loading ? (+ {reporting ? (+ <MigrationReport+ phase={phase}+ completed={completed}+ remaining={remaining}+ onContinue={() => setPhase({ kind: 'select' })}+ onDone={onClose}+ />+ ) : 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">+ {scope === 'setup' && (+ <p className="text-[12px] leading-relaxed text-muted">{t('onboarding.import.scopeNote')}</p>+ )}{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-normal text-muted">@@ -351,15 +479,17 @@ export const MigrationDialog: React.FC<{</div>)}- <div className="flex items-center justify-end gap-2 border-t border-border pt-4">- <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={applying}>- {t('settings.models.migration.later')}- </Button>- <Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={() => void apply()} disabled={selectedCount === 0 || applying}>- {applying ? <Loader2 className="size-4 animate-spin" /> : <ArrowDownToLine className="size-4" />}- {t(applying ? 'settings.models.migration.applying' : 'settings.models.migration.apply')}- </Button>- </div>+ {!reporting && (+ <div className="flex items-center justify-end gap-2 border-t border-border pt-4">+ <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={applying}>+ {t(copy.cancel)}+ </Button>+ <Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={() => void apply()} disabled={!writable || selectedCount === 0 || applying}>+ {applying ? <Loader2 className="size-4 animate-spin" /> : <ArrowDownToLine className="size-4" />}+ {t(applying ? copy.confirming : copy.confirm)}+ </Button>+ </div>+ )}</DialogContent></Dialog>);diff --git a/ui/src/components/settings/models/apiKeySourceDraft.test.ts b/ui/src/components/settings/models/apiKeySourceDraft.test.tsnew file mode 100644index 000000000..b1f1888dc--- /dev/null+++ b/ui/src/components/settings/models/apiKeySourceDraft.test.ts@@ -0,0 +1,172 @@+// The rules two different frames now share.+//+// The same fields appear in Settings' Add-API-key dialog and in setup's add-source+// dialog. Every case here is a way the two could quietly stop agreeing about what a+// key is: a vendor switch that keeps the previous vendor's endpoint, a hand-edited+// endpoint lost to a re-selection, a protocol sent that is not the one the catalog+// publishes, or a failed create classified as decided when it was not.+import { describe, expect, it, vi } from 'vitest';++import {+ EMPTY_API_KEY_DRAFT,+ apiKeySourceCreate,+ apiKeyWriteSettled,+ draftComplete,+ draftNameValid,+ draftProtocol,+ selectVendor,+ sourceClientNonce,+} from './apiKeySourceDraft';+import { apiKeyVendorPreset } from './apiKeyVendors';+import { ApiCallError } from './modelsApi';+import { SOURCE_DISPLAY_NAME_MAX_LENGTH } from './types';++describe('selectVendor', () => {+ it('opens with no vendor assumed, so nothing is filled in on the person\'s behalf', () => {+ expect(EMPTY_API_KEY_DRAFT).toMatchObject({ baseUrl: '', apiKey: '', displayName: '' });+ });++ it('fills the endpoint a catalog vendor publishes', () => {+ const draft = selectVendor(EMPTY_API_KEY_DRAFT, 'openai');++ expect(draft.vendor).toBe('openai');+ expect(draft.baseUrl).not.toBe('');+ });++ it('starts a different vendor from its own defaults, not the last one\'s leftovers', () => {+ const openai = selectVendor(EMPTY_API_KEY_DRAFT, 'openai');+ const anthropic = selectVendor({ ...openai, baseUrl: 'https://edited.example' }, 'anthropic');++ expect(anthropic.baseUrl).not.toBe('https://edited.example');+ expect(anthropic.baseUrl).not.toBe(openai.baseUrl);+ });++ it('is identity on re-selection, which is what preserves a hand-edited endpoint', () => {+ // The vendor combobox re-fires on every render of its own list. Rebuilding the+ // draft there would silently discard a proxy URL someone typed on purpose.+ const edited = { ...selectVendor(EMPTY_API_KEY_DRAFT, 'openai'), baseUrl: 'https://proxy.example/v1' };++ expect(selectVendor(edited, 'openai')).toBe(edited);+ });++ it('never touches the key, because it belongs to the person and not to the catalog', () => {+ const typed = { ...EMPTY_API_KEY_DRAFT, apiKey: 'sk-typed-by-hand' };++ expect(selectVendor(typed, 'openai').apiKey).toBe('sk-typed-by-hand');+ expect(selectVendor(selectVendor(typed, 'openai'), 'anthropic').apiKey).toBe('sk-typed-by-hand');+ });+});++describe('draftProtocol', () => {+ it('sends what a catalog vendor publishes, whatever the control was left on', () => {+ const draft = { ...selectVendor(EMPTY_API_KEY_DRAFT, 'anthropic'), protocol: 'openai_chat' as const };++ expect(draftProtocol(draft)).toBe(apiKeyVendorPreset('anthropic')?.protocol);+ expect(draftProtocol(draft)).not.toBe('openai_chat');+ });++ it('sends the chosen protocol for a vendor the catalog does not know', () => {+ expect(draftProtocol({ ...EMPTY_API_KEY_DRAFT, protocol: 'anthropic' }))+ .toBe('anthropic');+ });+});++describe('draftComplete', () => {+ const filled = { ...EMPTY_API_KEY_DRAFT, baseUrl: 'https://api.example/v1', apiKey: 'sk-1' };++ it('needs an endpoint and a key', () => {+ expect(draftComplete(filled)).toBe(true);+ expect(draftComplete({ ...filled, apiKey: '' })).toBe(false);+ expect(draftComplete({ ...filled, baseUrl: '' })).toBe(false);+ });++ it('does not accept whitespace as either one', () => {+ expect(draftComplete({ ...filled, apiKey: ' ' })).toBe(false);+ expect(draftComplete({ ...filled, baseUrl: ' \t ' })).toBe(false);+ });++ it('leaves the name optional but not unbounded', () => {+ expect(draftNameValid({ ...filled, displayName: '' })).toBe(true);+ expect(draftComplete({ ...filled, displayName: 'x'.repeat(SOURCE_DISPLAY_NAME_MAX_LENGTH) })).toBe(true);+ expect(draftComplete({ ...filled, displayName: 'x'.repeat(SOURCE_DISPLAY_NAME_MAX_LENGTH + 1) })).toBe(false);+ });+});++describe('apiKeySourceCreate', () => {+ it('trims on the way out, and omits a name that was never given', () => {+ const request = apiKeySourceCreate({+ vendor: 'openai',+ displayName: ' ',+ baseUrl: ' https://api.example/v1 ',+ apiKey: ' sk-1 ',+ protocol: 'openai_chat',+ }, 'scn_test');++ expect(request).toEqual({+ kind: 'api_key',+ vendor: 'openai',+ base_url: 'https://api.example/v1',+ key: 'sk-1',+ // The catalog's pinned protocol, not the field's leftover value.+ protocol: apiKeyVendorPreset('openai')?.protocol,+ client_nonce: 'scn_test',+ save_unverified: true,+ });+ });++ it('carries the name once one is given', () => {+ const request = apiKeySourceCreate({+ ...EMPTY_API_KEY_DRAFT, baseUrl: 'https://api.example/v1', apiKey: 'sk-1', displayName: ' Work key ',+ }, 'scn_test');++ expect(request.display_name).toBe('Work key');+ });++ it('always saves unverified, in every frame the form is hosted in', () => {+ // Deliberate product policy, not an oversight: the credential is saved on the+ // person's word and verified afterwards, so a provider that is briefly down+ // does not cost them the key they just pasted.+ expect(apiKeySourceCreate({ ...EMPTY_API_KEY_DRAFT, baseUrl: 'u', apiKey: 'k' }, 'n').save_unverified).toBe(true);+ });+});++describe('sourceClientNonce', () => {+ it('is unique per call, which is what a readback can recognise one write by', () => {+ const nonces = new Set(Array.from({ length: 32 }, sourceClientNonce));++ expect(nonces.size).toBe(32);+ for (const nonce of nonces) expect(nonce).toMatch(/^scn_[0-9a-f]{32}$/);+ });++ it('still produces one where randomUUID is unavailable', () => {+ // Not hypothetical: `crypto.randomUUID` is absent on a non-secure origin, which+ // is exactly where a local install gets opened over plain HTTP.+ vi.spyOn(globalThis.crypto, 'randomUUID').mockReturnValue(undefined as never);+ try {+ expect(sourceClientNonce()).toMatch(/^scn_[0-9a-f]{32}$/);+ } finally {+ vi.restoreAllMocks();+ }+ });+});++describe('apiKeyWriteSettled', () => {+ const failure = (status: number, code = 'source_invalid') =>+ new ApiCallError(code, 'failed', true, [], [], [], status);++ it('accepts a server-named 4xx as a decision', () => {+ expect(apiKeyWriteSettled(failure(400))).toBe(true);+ expect(apiKeyWriteSettled(failure(422))).toBe(true);+ });++ it.each([409, 500, 502, 504])('leaves %i unsettled, because the write may have landed', (status) => {+ // Repeating one of these is how a second identical source appears. An unsettled+ // write is reconciled against its nonce instead.+ expect(apiKeyWriteSettled(failure(status))).toBe(false);+ });++ it('leaves a transport failure unsettled', () => {+ expect(apiKeyWriteSettled(new TypeError('Failed to fetch'))).toBe(false);+ expect(apiKeyWriteSettled(undefined)).toBe(false);+ });+});diff --git a/ui/src/components/settings/models/apiKeySourceDraft.ts b/ui/src/components/settings/models/apiKeySourceDraft.tsnew file mode 100644index 000000000..12867ed86--- /dev/null+++ b/ui/src/components/settings/models/apiKeySourceDraft.ts@@ -0,0 +1,124 @@+// What an API-key source is, before it is a request.+//+// Split out of `AddApiKeyDialog` when setup needed the same fields inside a+// different frame. The dialog kept five `useState` calls and read them back in+// `draft()`; a second host doing the same would be a second place the vendor+// rule, the endpoint default and the submit condition could drift. So the shape+// and its rules live here, the fields that render it live in+// `ApiKeySourceForm.tsx`, and a host owns only the state and what it does with+// it — which is what lets setup preserve a half-typed key across a tab switch+// without knowing anything about what a key is.+//+// Values, not a component, because a module exporting both opts out of fast+// refresh — the same split `vendorMarks.ts` and `vendorGlyph.tsx` already make.+import { apiKeyVendorPreset, CUSTOM_VENDOR } from './apiKeyVendors';+import { apiFailure } from './modelsApi';+import {+ SOURCE_DISPLAY_NAME_MAX_LENGTH,+ type ApiKeySourceCreate,+ type SourceProtocol,+} from './types';+import { optionalTrimmedTextWithin } from './validation';++/** The fields, exactly as typed. Trimming happens once, on the way out. */+export type ApiKeySourceDraft = {+ vendor: string;+ displayName: string;+ baseUrl: string;+ apiKey: string;+ /** What the person chose; a catalog vendor overrides it (see `draftProtocol`). */+ protocol: SourceProtocol;+};++/** 自定义 is where the field opens: it is the absence of a vendor, so nothing is+ * assumed about the endpoint or the protocol until one is chosen. */+export const EMPTY_API_KEY_DRAFT: ApiKeySourceDraft = {+ vendor: CUSTOM_VENDOR,+ displayName: '',+ baseUrl: '',+ apiKey: '',+ protocol: 'openai_chat',+};++/**+ * Choose a vendor.+ *+ * Re-selecting the current one changes nothing, which is what preserves a+ * hand-edited endpoint and protocol; a different vendor starts from that+ * vendor's own defaults rather than from the last one's leftovers. The key is+ * never touched either way — it belongs to the person, not to the catalog.+ */+export function selectVendor(draft: ApiKeySourceDraft, vendor: string): ApiKeySourceDraft {+ if (vendor === draft.vendor) return draft;+ return {+ ...draft,+ vendor,+ baseUrl: apiKeyVendorPreset(vendor)?.official_base_url ?? '',+ protocol: 'openai_chat',+ };+}++/** The protocol that will actually be sent: a catalog vendor publishes one, so+ * for those the segmented control is a statement rather than a question. */+export const draftProtocol = (draft: ApiKeySourceDraft): SourceProtocol =>+ apiKeyVendorPreset(draft.vendor)?.protocol ?? draft.protocol;++/** A name is optional; one that is only too long is not. */+export const draftNameValid = (draft: ApiKeySourceDraft): boolean =>+ optionalTrimmedTextWithin(draft.displayName, SOURCE_DISPLAY_NAME_MAX_LENGTH);++/** Whether there is enough here to save. */+export const draftComplete = (draft: ApiKeySourceDraft): boolean =>+ Boolean(draft.baseUrl.trim() && draft.apiKey.trim()) && draftNameValid(draft);++/**+ * A nonce the client can recognise its own write by.+ *+ * It is what makes an unknown outcome answerable: after a timeout the source+ * list is read back and matched on this, so a write that landed is adopted+ * rather than repeated.+ */+export const sourceClientNonce = (): string => {+ const uuid = globalThis.crypto.randomUUID?.();+ if (uuid) return `scn_${uuid.replaceAll('-', '').toLowerCase()}`;+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));+ return `scn_${Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('')}`;+};++/**+ * Whether a failed create really decided the write's outcome.+ *+ * Only a server-named 4xx does, and 409 not even then: everything else — a+ * timeout, a 5xx, a dropped connection — leaves a request that may have been+ * committed. Repeating one of those is how a second identical source appears, so+ * an unsettled write is reconciled against `client_nonce` instead+ * (`reconcileUnknownWrite`). Shared because both hosts of the same form have to+ * draw the same line; a second copy is how one of them starts retrying blind.+ */+export const apiKeyWriteSettled = (error: unknown): boolean => {+ const failure = apiFailure(error);+ const status = failure?.responseStatus;+ return Boolean(failure?.serverNamed) && status !== undefined+ && status >= 400 && status < 500 && status !== 409;+};++/**+ * The request.+ *+ * `save_unverified` is deliberate and shared by both hosts: a credential is saved+ * on the person's word and verified afterwards, so a provider that is slow or+ * briefly down does not cost them the key they just pasted.+ */+export const apiKeySourceCreate = (+ draft: ApiKeySourceDraft,+ clientNonce: string,+): ApiKeySourceCreate => ({+ kind: 'api_key',+ vendor: draft.vendor,+ ...(draft.displayName.trim() ? { display_name: draft.displayName.trim() } : {}),+ base_url: draft.baseUrl.trim(),+ key: draft.apiKey.trim(),+ protocol: draftProtocol(draft),+ client_nonce: clientNonce,+ save_unverified: true,+});diff --git a/ui/src/components/settings/models/migrationGrouping.ts b/ui/src/components/settings/models/migrationGrouping.tsnew file mode 100644index 000000000..de1617ff4--- /dev/null+++ b/ui/src/components/settings/models/migrationGrouping.ts@@ -0,0 +1,188 @@+// How a migration scan divides into consent groups.+//+// Extracted from `MigrationDialog` unchanged so setup's provider screen can ask+// the same question the dialog asks — which backends may be taken over together,+// and which rows a selection actually submits — without owning a second answer.+// A group is the unit of consent, not a row: shared persisted assignments link+// backends into one custody boundary, and a single non-importable row inside a+// linked group blocks the whole group.+import type { TranslationKey } from '@/i18n/types';+import type { AgentBackend, MigrationItem, MigrationScan } from './types';++/**+ * A scan plus the backends consented to against it.+ *+ * Declared here rather than imported from the setup flow contract so the+ * dependency runs one way: setup's `SetupProviderSelection` is structurally this+ * shape, and Model Hub never has to know the onboarding module exists.+ */+export type MigrationSelection = {+ scan: MigrationScan | null;+ selectedBackends: AgentBackend[];+};++export const BACKEND_ORDER: AgentBackend[] = ['claude', 'codex', 'opencode'];++export const isImportable = (item: MigrationItem) => item.proposed_action === 'import';++/**+ * The transitive closure of backends that share persisted assignments with any+ * of `backends`.+ *+ * Resolve from every row of an included backend, not just the eligible+ * entry-point rows. Scope filters cannot conceal a shared-file consumer.+ */+export function requiredBackends(+ items: MigrationItem[],+ backends: Iterable<AgentBackend>,+): Set<AgentBackend> {+ const required = new Set(backends);+ let expanded = true;+ while (expanded) {+ expanded = false;+ for (const item of items) {+ if (!required.has(item.backend)) continue;+ for (const backend of item.required_backends ?? []) {+ if (required.has(backend)) continue;+ required.add(backend);+ expanded = true;+ }+ }+ }+ return required;+}++export type MigrationGroup = {+ backend: AgentBackend;+ /** This backend's own rows, in scan order. */+ rows: MigrationItem[];+ importRows: MigrationItem[];+ /** Every backend this one must migrate with, including itself. */+ required: Set<AgentBackend>;+ /** Rows across the whole linked group this scope may take over. */+ linkedImportRows: MigrationItem[];+ /** Linked rows it may not: a blocker, or a credential outside the scope. */+ blockedRows: MigrationItem[];+ blocked: boolean;+};++/** Backends the scope reaches, widened to whole consent groups. */+export const scopedBackends = (+ items: MigrationItem[],+ eligible: (item: MigrationItem) => boolean,+): Set<AgentBackend> =>+ requiredBackends(items, items.filter(eligible).map((item) => item.backend));++/**+ * The dialog's rows, grouped. `items` stays the complete scan so a group's+ * linked rows can include a backend the scope itself never selected.+ *+ * Two scopes, because an entry point asks two different questions. `eligible` says+ * which rows it was opened FROM: their backends, widened to their custody closures,+ * are what appears at all. `takeable` says which of the rows that appear it may+ * actually take OVER — and a row in view that fails it blocks its group rather than+ * being quietly left behind, because the server migrates a backend whole and refuses+ * any batch that omits one of its rows. There is no half of a backend to take.+ *+ * Settings may take over everything the scan proposes importing, which is the+ * default and makes the second scope invisible there. Setup may not: it is scoped to+ * API keys, and a backend whose credentials also include an importable subscription+ * store is a Settings review rather than a setup card.+ */+export function groupMigrationCandidates(+ items: MigrationItem[],+ eligible: (item: MigrationItem) => boolean,+ takeable: (item: MigrationItem) => boolean = () => true,+): MigrationGroup[] {+ const scope = scopedBackends(items, eligible);+ const candidates = items.filter((item) => scope.has(item.backend));+ const importableHere = (item: MigrationItem) => isImportable(item) && takeable(item);+ return BACKEND_ORDER.map((backend) => {+ const rows = candidates.filter((item) => item.backend === backend);+ const importRows = rows.filter(importableHere);+ const required = requiredBackends(items, [backend]);+ const linkedRows = candidates.filter((item) => required.has(item.backend));+ const linkedImportRows = linkedRows.filter(importableHere);+ const blockedRows = linkedRows.filter((item) => !importableHere(item));+ return {+ backend,+ rows,+ importRows,+ required,+ linkedImportRows,+ blockedRows,+ blocked: blockedRows.length > 0,+ };+ }).filter((group) => group.rows.length > 0);+}++/** Whether a group can be consented to at all. */+export const groupSelectable = (group: MigrationGroup): boolean =>+ !group.blocked && group.importRows.length > 0;++/**+ * The rows a scope may actually take over, group by group.+ *+ * The same question `groupSelectable` answers for the dialog, asked without+ * rendering one: a surface that counts candidates by filtering rows would count a+ * key whose group is blocked and then open a review with nothing to press. Offer+ * and batch have to come from one rule, and this is it.+ */+export const takeableImportRows = (+ items: MigrationItem[],+ eligible: (item: MigrationItem) => boolean,+ takeable: (item: MigrationItem) => boolean = () => true,+): MigrationItem[] =>+ groupMigrationCandidates(items, eligible, takeable)+ .filter(groupSelectable)+ .flatMap((group) => group.importRows);++const BLOCKED_NOTE_KEYS = new Set<string>([+ 'settings.models.migration.blocked.config',+ 'settings.models.migration.blocked.environment',+ 'settings.models.migration.blocked.credential',+ 'settings.models.migration.blocked.dynamic_shell',+ 'settings.models.migration.blocked.ambiguous_shell',+ 'settings.models.migration.blocked.unreadable',+ 'settings.models.migration.blocked.reference',+ 'settings.models.migration.blocked.helper',+ 'settings.models.migration.blocked.token',+ 'settings.models.migration.blocked.headers',+ 'settings.models.migration.blocked.transport',+] satisfies TranslationKey[]);++export const BLOCKED_REASON_FALLBACK_KEY = 'settings.models.migration.blocked.fallback' satisfies TranslationKey;++/**+ * Why a row this entry point could otherwise have taken is nonetheless blocked.+ *+ * The server's own reasons all say the credential cannot be imported at all, which+ * is untrue of a row that is importable and merely out of this scope's reach —+ * unreachable in Settings, whose scope takes over everything the scan proposes.+ *+ * `notes_key` is an open vocabulary, so a key this app does not ship copy for+ * resolves to the generic line rather than to its own machine name. Which copy+ * explains a blocked row lives with the rule that decides a row is blocked, so the+ * dialog that lists the group and any surface that has to explain one row of it+ * cannot answer the same question two ways.+ */+export const blockedReasonKey = (item: MigrationItem): TranslationKey => {+ if (isImportable(item)) return 'onboarding.import.outOfScope';+ return item.notes_key && BLOCKED_NOTE_KEYS.has(item.notes_key)+ ? (item.notes_key as TranslationKey)+ : BLOCKED_REASON_FALLBACK_KEY;+};++/**+ * The rows a selection submits: every importable row of every selected backend.+ *+ * Unscoped on purpose, and safe because a backend reaches a selection only through+ * `groupSelectable` — whose group, by the rule above, has no linked row the scope+ * cannot take. The server enforces the same completeness from its side: a batch that+ * omits a row of a backend it is migrating is refused outright.+ */+export const appliableItems = (+ items: MigrationItem[],+ selected: ReadonlySet<AgentBackend>,+): MigrationItem[] =>+ items.filter((item) => selected.has(item.backend) && isImportable(item));diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex e839b2624..04b8c25aa 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -5404,6 +5404,92 @@"name": "Avibe","tagline": "Agent OS"},+ "providers": {+ "title": "Add model providers",+ "subtitle": "Add a subscription or API Key. Model Hub handles routing.",+ "stageLabel": "Providers connect to Model Hub, which routes to assistants",+ "gatewayName": "Model Hub",+ "gatewayTagline": "Connect models once. Model Hub handles routing.",+ "gatewayInstalling": "Installing Model Hub…",+ "gatewayStarting": "Starting Model Hub…",+ "gatewayNotReady": "Model Hub is not ready. Try again.",+ "cardKeyDetected": "API key detected {{mask}}",+ "cardKeyAdded": "API Key {{mask}}",+ "cardSelected": "Selected",+ "cardUseExistingNamed": "Use existing {{name}} configuration",+ "cardAddSubscriptionNamed": "Add a {{name}} subscription or API Key",+ "cardAddKeyNamed": "Add a {{name}} API Key",+ "addMoreTitle": "Add more",+ "addMoreSubtitle": "Subscription / API Key",+ "addMoreAction": "Add a new subscription or API Key",+ "addMoreCount_one": "{{count}} added",+ "addMoreCount_other": "{{count}} added",+ "summaryNone": "No provider selected",+ "summarySelected_one": "{{count}} provider selected: {{names}}",+ "summarySelected_other": "{{count}} providers selected: {{names}}",+ "summarySelectedNote": "After migration is confirmed, Model Hub manages authentication for the selected assistants.",+ "summaryAdded_one": "{{count}} provider added: {{names}}",+ "summaryAdded_other": "{{count}} providers added: {{names}}",+ "summaryError": "Connection failed. Check your configuration and retry.",+ "actionImport_one": "Review {{count}} and continue",+ "actionImport_other": "Review {{count}} and continue",+ "actionRetryImport_one": "Review migration status for {{count}}",+ "actionRetryImport_other": "Review migration status for {{count}}",+ "actionContinue": "Continue to assistants",+ "actionAdd": "Add subscription or API Key",+ "actionConnecting": "Connecting…",+ "actionChecking": "Checking connection…",+ "addTitle": "Add subscription or API Key",+ "addTitleMore": "Add more model providers",+ "addDescription": "Add one source to get started. Model Hub handles routing.",+ "addDescriptionMore": "Review detected configurations and confirm migration without retyping.",+ "addMethodsLabel": "Add method",+ "addMethodDetected": "Detected",+ "addMethodSubscription": "Subscription",+ "addMethodApiKey": "API Key",+ "addDetectedNote": "Review all linked configurations and confirm to start migration. Unrelated settings are preserved.",+ "addDetectedGroup": "Other detected configurations",+ "addDetectedSelectNamed": "Select existing {{name}} configuration",+ "addDetectedAdded": "Added",+ "addSignInNamed": "Sign in with {{name}}",+ "addSubscriptionNote": "Authorize with the provider. You do not enter your password in Avibe.",+ "addKeyLabelNamed": "{{name}} API Key",+ "addMoreProviders": "More providers",+ "addFooterAddKey": "Add",+ "addFooterAdd_one": "Review {{count}} selected",+ "addFooterAdd_other": "Review {{count}} selected",+ "addFooterSignInNamed": "Sign in with {{name}}",+ "addFooterAdding": "Adding…",+ "addProgressSaving": "Saving configuration…",+ "addProgressChecking": "Checking the model connection…",+ "addProgressWaitingAuth": "Waiting for authorization…",+ "addErrorPreserved": "Connection failed. Your entries are preserved. Please retry.",+ "addErrorDetectedPreserved": "Completion is unconfirmed. Your selection is preserved. Check the current state before continuing recovery.",+ "gatewayUnsupported": "Model Hub cannot be installed on this device. Recheck availability or set up Avibe in a supported environment.",+ "gatewayEnvironmentHelp": "View installation guide"+ },+ "import": {+ "title": "Migrate to Model Hub",+ "description": "After migration, CLI authentication will be managed entirely by Model Hub.",+ "review": "Review migration",+ "helpBody": "Model Hub manages authentication and model connections. Migration removes replaced native authentication and switches linked assistants to Model Hub; unrelated settings are preserved.",+ "action_one": "Review {{count}} selected",+ "action_other": "Review {{count}} selected",+ "scopeNote": "This entry handles complete API-key groups only. Linked groups with subscription sign-ins or blockers cannot be taken over here; review them in Settings.",+ "outOfScope": "This credential can be migrated, but not from here. Review it in Settings.",+ "progress_one": "Migrating {{count}} configuration item…",+ "progress_other": "Migrating {{count}} configuration items…",+ "progressDetail": "Migrating authentication and updating linked assistant connections",+ "done_one": "Migrated {{count}} configuration item",+ "done_other": "Migrated {{count}} configuration items",+ "doneDetail": "Migration and native authentication cleanup are complete. Check the assistants’ model routes.",+ "remaining_one": "{{count}} item needs review. Continue any time.",+ "remaining_other": "{{count}} items need review. Continue any time.",+ "remainingAction": "Review remaining",+ "done": "Done",+ "confirm": "Start migration",+ "notNow": "Not now"+ },"flow": {"backToIntro": "Back to introduction","backToProviders": "Back to models",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex f6c17b02f..98ed50dc6 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -5404,6 +5404,92 @@"name": "Avibe","tagline": "Agent OS"},+ "providers": {+ "title": "添加模型提供商",+ "subtitle": "添加订阅或 API Key,由模型网关统一路由",+ "stageLabel": "提供商接入模型网关,再统一路由到助手",+ "gatewayName": "模型网关",+ "gatewayTagline": "模型一次接入,网关统一路由",+ "gatewayInstalling": "正在安装模型网关…",+ "gatewayStarting": "正在启动模型网关…",+ "gatewayNotReady": "模型网关未就绪,请重试",+ "cardKeyDetected": "检测到 API Key {{mask}}",+ "cardKeyAdded": "API Key {{mask}}",+ "cardSelected": "已选中",+ "cardUseExistingNamed": "使用 {{name}} 的已有配置",+ "cardAddSubscriptionNamed": "添加 {{name}} 的订阅或 API Key",+ "cardAddKeyNamed": "添加 {{name}} 的 API Key",+ "addMoreTitle": "添加更多",+ "addMoreSubtitle": "订阅 / API Key",+ "addMoreAction": "添加新的订阅或 API Key",+ "addMoreCount_one": "已添加 {{count}} 项",+ "addMoreCount_other": "已添加 {{count}} 项",+ "summaryNone": "未选择提供商",+ "summarySelected_one": "已选 {{count}} 个提供商:{{names}}",+ "summarySelected_other": "已选 {{count}} 个提供商:{{names}}",+ "summarySelectedNote": "确认迁移后,由模型网关管理所选助手的认证。",+ "summaryAdded_one": "已添加 {{count}} 个提供商:{{names}}",+ "summaryAdded_other": "已添加 {{count}} 个提供商:{{names}}",+ "summaryError": "连接未完成,请检查配置后重试。",+ "actionImport_one": "查看 {{count}} 项并继续",+ "actionImport_other": "查看 {{count}} 项并继续",+ "actionRetryImport_one": "查看 {{count}} 项迁移状态",+ "actionRetryImport_other": "查看 {{count}} 项迁移状态",+ "actionContinue": "继续,选择 AI 助手",+ "actionAdd": "添加订阅或 API Key",+ "actionConnecting": "正在连接…",+ "actionChecking": "正在检查连接…",+ "addTitle": "添加订阅或 API Key",+ "addTitleMore": "添加更多模型提供商",+ "addDescription": "添加一个来源即可开始,由模型网关统一路由。",+ "addDescriptionMore": "查看检测到的配置,确认后迁移,无需重新填写。",+ "addMethodsLabel": "添加方式",+ "addMethodDetected": "已检测到",+ "addMethodSubscription": "订阅",+ "addMethodApiKey": "API Key",+ "addDetectedNote": "查看全部关联配置并确认后开始迁移。其他无关设置会保留。",+ "addDetectedGroup": "其余已检测到的配置",+ "addDetectedSelectNamed": "选择 {{name}} 的已有配置",+ "addDetectedAdded": "已添加",+ "addSignInNamed": "通过 {{name}} 登录",+ "addSubscriptionNote": "前往服务商完成授权,无需在 Avibe 输入账号密码。",+ "addKeyLabelNamed": "{{name}} API Key",+ "addMoreProviders": "更多服务商",+ "addFooterAddKey": "添加",+ "addFooterAdd_one": "查看选中的 {{count}} 项",+ "addFooterAdd_other": "查看选中的 {{count}} 项",+ "addFooterSignInNamed": "前往 {{name}} 登录",+ "addFooterAdding": "添加中…",+ "addProgressSaving": "正在保存配置…",+ "addProgressChecking": "正在检查模型连接…",+ "addProgressWaitingAuth": "等待授权完成…",+ "addErrorPreserved": "连接未完成,输入已保留,请重试。",+ "addErrorDetectedPreserved": "操作未确认完成,选择已保留。请先检查当前状态,再继续恢复。",+ "gatewayUnsupported": "此设备无法安装模型网关。请重新检查可用性,或在受支持的环境中设置 Avibe。",+ "gatewayEnvironmentHelp": "查看安装指南"+ },+ "import": {+ "title": "迁移到模型网关",+ "description": "迁移后,CLI的认证信息将完全交由模型网关管理",+ "review": "查看并迁移",+ "helpBody": "模型网关统一管理认证和模型连接。迁移会清理已替代的原生认证,并将关联助手切换到模型网关;其他无关设置会保留。",+ "action_one": "查看选中的 {{count}} 项",+ "action_other": "查看选中的 {{count}} 项",+ "scopeNote": "此入口仅处理完整的 API Key 组。涉及订阅登录或阻塞项的关联组不可在此接管,请前往设置检查。",+ "outOfScope": "此凭据可以迁移,但不能在此入口迁移,请前往设置检查。",+ "progress_one": "正在迁移 {{count}} 项配置…",+ "progress_other": "正在迁移 {{count}} 项配置…",+ "progressDetail": "正在迁移认证并更新关联助手的连接",+ "done_one": "已迁移 {{count}} 项配置",+ "done_other": "已迁移 {{count}} 项配置",+ "doneDetail": "迁移和原生认证清理已完成。请确认助手的模型路由。",+ "remaining_one": "还有 {{count}} 项需要查看,可随时继续",+ "remaining_other": "还有 {{count}} 项需要查看,可随时继续",+ "remainingAction": "继续选择",+ "done": "完成",+ "confirm": "开始迁移",+ "notNow": "暂不迁移"+ },"flow": {"backToIntro": "返回介绍","backToProviders": "返回模型",