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): align three-screen flow with Model Hub routes (#2153)
Max90256752b364
diff --git a/docs/plans/2026-09-21-setup-three-screen-implementation-plan.md b/docs/plans/2026-09-21-setup-three-screen-implementation-plan.mdindex f0ecfece3..97790639f 100644--- a/docs/plans/2026-09-21-setup-three-screen-implementation-plan.md+++ b/docs/plans/2026-09-21-setup-three-screen-implementation-plan.md@@ -1,6 +1,9 @@# Setup three-screen rebuild — implementation plan-Status: **PR0 bounded repair; feature implementation not dispatched** (2026-09-21).+Status: **Historical implementation plan (2026-09-21), superseded by the binding+`docs/plans/setup-three-screen/contracts.md` and the current implementation.**+The PR0 dispatch, lane ownership, capsule, shared route draft, and platform recovery+instructions below record the original proposal; they are not current requirements.The owner's explicit merge authority covered #2065 only. Current orchestrator requestsfrom `ses8dhcc2zq62` authorize PR0 repair, not #2082 merge or feature implementation.The owner reaffirmed on 2026-09-21 12:56 +08 that setup uses Model Hub and disabling it@@ -48,7 +51,8 @@ The design is not a new surface bolted onto the old one: screen 1 already ships,is a restructure of what ships, and screen 2 is a new composition of Model Hub APIs thatalready ship. C6 defines explicit model-chain projection and controller/runtime orderingagainst those owners. Owner-ratified D10 adopts existing migration takeover; setup does not-implement credential migration. Discovery cards/capsule/entry remain consumers of that feature.+implement credential migration. The current screen uses its main action and the controlled+MigrationDialog to consume that feature; the proposed capsule was removed.## 2. Baseline and preconditions@@ -84,7 +88,7 @@ implement credential migration. Discovery cards/capsule/entry remain consumers o| Six access entries | `onboarding/AccessTiles.tsx` | shipped; needs `hidden`/`inert` instead of unmount || Assistant cards, install/detect/enable | `steps/AgentDetection.tsx` (606 lines), `onboarding/AssistantRow.tsx`, `settings/BackendLifecycleChip.tsx` | shipped; restructured by screen 3 || Per-assistant connection dialog | `onboarding/BackendConnectionDialog.tsx` | leaves setup; existing Settings/backend Direct support remains unchanged |-| Discovery capsule + dismissal memory | `onboarding/ImportKeysNotice.tsx`, `lib/modelHubMigrationDismiss.ts` | shipped; C6 identifies copy and scan-ownership gaps before moving it to screen 2 |+| Discovery entry + dismissal memory (historical proposal) | `onboarding/ImportKeysNotice.tsx`, `lib/modelHubMigrationDismiss.ts` | The proposed capsule move was superseded; current screen 2 uses its main action and controlled MigrationDialog. || Import batch dialog | `settings/models/MigrationDialog.tsx`, `migrationScan.ts` (`importableKeys`, `isImportableKey`, `scanMigrationWhenEnabled`) | owner-ratified D10 reuse; minimal controlled-state/copy adaptation, one migration confirmation/apply/recovery owner || Add API key: vendor picker, observe → create | `settings/models/AddApiKeyDialog.tsx` (41 KB impl, 40 KB tests), `apiKeyVendors.ts`, `vendorMarks.ts`, `vendorGlyph.tsx` | shipped; needs its form extracted so a tabbed stable frame can host it (D2) || Subscription sign-in | `modelsApi.startOAuth/getOAuthStatus/submitOAuth/cancelOAuth`, `settings/models/OAuthConnectDialog.tsx`, `settings/oauth/OAuthFlowParts.tsx` | shipped; subscription tab drives it |@@ -126,7 +130,8 @@ leaving a screen destroys its state — the class of bug the handoff §5 alreadyupdates so asynchronous completions preserve other screens' edits;- moves focus to the screen's `h1` (`tabIndex={-1}`) on every screen change and scrollsto top on phones;-- keeps platform recovery (`SetupPlatformRecovery`) and the final `setup_completed` write.+- keeps the final `setup_completed` write. The proposed `SetupPlatformRecovery`+ requirement was removed; saved invalid IM settings remain for repair in Settings.Hub model recovery follows C6; `SetupModelRecovery` remains its shipped Direct owner andis not repurposed to bypass Hub setup.@@ -139,8 +144,10 @@ instead of unmounting; the three story cards become the handoff snapshot source.### 4.3 Screen 2 — model providers (new, the bulk of the work)-Composition, top to bottom: three provider cards → inbound wires → gateway card →-outbound wires → three assistant destinations → summary line → reserved capsule slot.+Historical composition proposal, top to bottom: three provider cards → inbound wires →+gateway card → outbound wires → three assistant destinations → summary line. The+reserved capsule slot was removed; use the current binding C6 and ProvidersScreen for+the migration entry.- **Slots.** 1–2 are providers detected on this machine or already added; when fewer thantwo are known, fill with OpenAI then Anthropic. Slot 3 is always "Add more" (dashed@@ -162,13 +169,12 @@ outbound wires → three assistant destinations → summary line → reserved caconnected treatment once a provider is ready.- **Summary line** (`aria-live`): pending selection / added / error / none, with theC1 selected takeover copy; counts/status follow the existing migration owner, with no copy-only guarantee.-- **Capsule.** `ImportKeysNotice` moves here, keeping its persisted non-nagging- dismissal. Count only keys in complete unblocked key-only groups (C6), with blocked- detections still visible for explanation; give it a reserved slot so dismissing it- cannot move the primary action.+- **Migration entry (superseded proposal).** The proposed `ImportKeysNotice` capsule+ was removed. The current main action opens the controlled MigrationDialog; identity+ dismissal and complete-backend consent follow binding C6.- **Import dialog.** Follow C6's full-scan, transitive backend consent grouping. Cards,- capsule and Detected tab share `providerSelection`; L2 must adapt/extract the existing- `MigrationDialog` owner because its shipped props keep local state. Preserve blockers and+ the main action and Detected tab share selection through the existing controlled+ `MigrationDialog` owner. Preserve blockers andlinked rows outside the entry filter. API-key-only setup cannot submit mixed OAuth groups.Owner-ratified D10 delegates primary/Detected actions to that feature's review with theexact consequence and Not now / Start migration; only its explicit confirmation applies.@@ -310,8 +316,9 @@ C1 (`docs/plans/setup-three-screen/copy-contract.json`) is the proposed copy tabsource of key names; handoff §8 is where its strings came from. New namespaces:`onboarding.flow.*` (L1), `onboarding.providers.*` and `onboarding.import.*` (L2), and new`onboarding.setup.*` / `onboarding.route.*` leaves (L3). Six shipped strings change: the four-welcome/access ones are L1's, the two setup headings are L3's. The capsule keeps-`settings.models.importNotice.*` for the discovery sentence, help link and dismissal label,+welcome/access ones are L1's, the two setup headings are L3's. The proposed capsule+copy was superseded by the current main-action migration entry; legacy+`settings.models.importNotice.*` remains historical context,and the import dialog keeps `settings.models.migration.{blocked,errors,notes,source}.*` forthe explanations it renders, while setup chrome reads `onboarding.import.*`. `_migration_copy`records D10's owner-ratified takeover copy and the delegation boundary. D8 allocates setup@@ -320,7 +327,7 @@ rendering and behavior. No display string is hardcoded in a component.### 4.10 Accessibility-Focus to `h1` on screen change; `aria-live` on summary, status pill, capsule and progress;+Focus to `h1` on screen change; `aria-live` on summary, status pill and progress;`aria-pressed` on cards, tabs and provider buttons; labelled Switches and icon buttons;tooltip via `aria-describedby` + `aria-expanded`; dialog focus trap with focus restored tothe trigger; Escape and outside click close menus, tooltips and dialogs (the import dialog@@ -340,7 +347,7 @@ separate owner authorization and contracts on master; no lane may reinterpret th`setupFlow.test.ts` covering sequence, navigation and actual React consumption of sharedstate, including a late update after another screen changes the route draft.- **C3 Geometry and DOM hooks** → `contracts.md` §C3: the single shell-rendered anchor- pair, the reserved capsule slot, the class names the handoff snapshots read across+ pair, the class names the handoff snapshots read acrossscreens, and the tier rule (consume `--ob-*`, restate inside the existing bands, neverinvent a new one).- **C4 Entry gate** → `contracts.md` §C4: the correlated candidate predicate and its producers, what stays@@ -356,7 +363,7 @@ separate owner authorization and contracts on master; no lane may reinterpret th| --- | --- | --- | --- || L0 contracts | orchestrator; current repair delegated to this executor | `docs/plans/2026-09-21-setup-three-screen-*.md`, `onboarding/setupFlow.ts`, the C1 fixture | product behavior || L1 shell + intro + motion | codex | `Wizard.tsx` (flow machine region), `steps/Welcome.tsx`, `onboarding/setupHandoff.ts`, `onboarding.css` shell/tier/CTA sections, `AccessTiles.tsx`, `ui/e2e/onboarding-fidelity/{fixture.tsx,support.ts,geometry.spec.ts,loop.spec.ts}`, i18n `onboarding.flow.*` and the four changed welcome/access strings | screen 2/3 internals |-| L2 providers screen | claude | new `onboarding/providers/**`, new `onboarding-providers.css`, `ImportKeysNotice.tsx`, the `AddApiKeyDialog` form extraction, `MigrationDialog`'s minimal controlled-state/copy adaptation and shared grouping reuse, new `ui/e2e/onboarding-fidelity/{provider-support.ts,providers.spec.ts}` and `hub-ownership.spec.ts`, i18n `onboarding.providers.*` / `onboarding.import.*` | `Wizard.tsx` outside the screen registry entry it adds last, screen 3 files, migration backend/cleanup/custody/recovery semantics, `onboarding.css`, L1's `fixture.tsx` / `support.ts` / `geometry.spec.ts` |+| L2 providers screen (historical assignment) | claude | new `onboarding/providers/**`, new `onboarding-providers.css`, the `AddApiKeyDialog` form extraction, `MigrationDialog`'s controlled-state/copy adaptation and shared grouping reuse, new `ui/e2e/onboarding-fidelity/{provider-support.ts,providers.spec.ts}` and `hub-ownership.spec.ts`, i18n `onboarding.providers.*` / `onboarding.import.*`; the proposed `ImportKeysNotice` move was removed | `Wizard.tsx` outside the screen registry entry it adds last, screen 3 files, migration backend/cleanup/custody/recovery semantics, `onboarding.css`, L1's `fixture.tsx` / `support.ts` / `geometry.spec.ts` || L3 assistants + gate | codex | `AssistantRow.tsx`, `steps/AgentDetection.tsx`, new `onboarding/DefaultRouteDialog.tsx`, new `onboarding-assistants.css`, `Wizard.tsx` `complete()` region, `ui/e2e/onboarding-fidelity/connections.spec.ts`, i18n `onboarding.setup.*` / `onboarding.route.*` and the two changed setup headings | screen 2 files, `onboarding.css` shell sections || L4 scenarios + acceptance | codex | `tests/scenarios/auth_setup/**`, acceptance evidence, owner checklist | UI implementation |@@ -385,7 +392,7 @@ D1 (#2065, merged) ──► PR0 contracts ──┬─► PR1 shell+intro+motiothe anchor invariant. It ships without screen 2 and without changing readiness; the interimregistry must not expose an empty providers step just because final C2 names one.- **PR2** (L2) starts in parallel with PR1, because everything it owns — the stage, the- dialogs, the capsule move, the shared API-key form extraction — is new files plus shared-owner+ dialogs and the shared API-key form extraction — is new files plus shared-owneradaptations, and it builds against C2 with its own test harness. It declares`requires #PR1 merged first`, and its one `Wizard.tsx` registry line plus its fixtureintegration land as a final commit after PR1 is on `master`. D10 and C6 bootstrap/runtime@@ -409,13 +416,13 @@ D1 (#2065, merged) ──► PR0 contracts ──┬─► PR1 shell+intro+motio- Behavior: the onboarding fixture harness (`ui/e2e/onboarding-fidelity`) extended to mock`/api/models/sources`, `/api/models/runtime/status` and `/api/models/agents/*` beside theexisting scan/apply routes, asserting rules rather than copied numbers — anchor equality- across three screens × two languages × six viewports, capsule dismissal leaving the action+ across three screens × two languages × six viewports, migration dismissal leaving the actionin place, stable-frame tab switching, handoff bail-out under reduced motion, phonescroll-to-top, no horizontal overflow.- Cross-boundary: at least one end-to-end case that pierces shell → screen 2 → screen 3 →`complete()` with real (non-ASCII) data, since two mocked halves prove nothing about theboundary.-- Migration consumption: L2 tests cards/capsule/Detected → the existing complete-group+- Migration consumption: L2 tests cards/main action/Detected → the existing complete-groupconfirmation → confirmed receipt → refreshed source/supply presentation. Verify no applyfrom selection/navigation/runtime start, Not now preserves native state, mixed OAuth groupsremain blocked for setup, zero/error callbacks do not claim success, and Settings behavior@@ -577,7 +584,7 @@ before feature implementation and explicit authority before #2082 merge remain o| D3 — runtime setup | Existing approved `model-hub-native-takeover.md` flow, adopted by orchestrator: automatically prepare runtime on active entry; active-provider config/bootstrap, C6 support preflight and admitted ensure/install/start/readback for all modes; unsupported recovery preserves the default Hub requirement and healthy running Hub. No enable/install-confirmation dialog and no automatic credential takeover || D4 — shared model route | Orchestrator-ratified bounded technical interpretation (not owner feature approval): one designated builtin setup Agent per installed/enabled backend, explicit named target if no builtin, exact saved menu model, shared order projected through each target's reviewed exact-hop membership. Preserve other menu-model routes, default and Agent models. C6 specifies hydration, repair and partial-write retry || D5 — setup prerequisite | Owner-ratified Hub-only setup; unsupported/error/disabled config never creates Direct completion. Disabling belongs to Settings afterward. C4 retains correlated Hub readiness and healthy Hub independent of installation; C2 preserves config, retry/guide/Back and drafts. Specific known-by-design resolution, no gate waiver |-| D6 — handoff §13 | Concise recommendations: destinations logo/name, reference English wording, capsule restoration, dashed Add-more. No native Pencil inspection or design-source synchronization claimed |+| D6 — handoff §13 | Historical recommendations: destinations logo/name, reference English wording, proposed capsule restoration (superseded), dashed Add-more. No native Pencil inspection or design-source synchronization claimed || D7 — vendor list | Orchestrator decision: shipped catalog/order, no prototype Cohere; no backend catalog change || D8 — copy scope | Orchestrator decision: setup copy scope separate from Settings, with takeover copy selected by owner D10. Minimal controlled-state/copy adaptation of the existing migration owner is future L2 work || D9 — row identity | Orchestrator-ratified technical interpretation with D4. Model-ranked `(source_id, model_id)` remains required. Unapproved source-ranking substitution withdrawn. Exact menu model vs upstream model, membership projection and successful manual-override readback specified with D4; no arbitrary Agent-model changes |@@ -603,7 +610,7 @@ for ratification. Merge #2082 and feature start remain separately gated.Desktop shell loading page; Model Hub service semantics and any backend routing redesign;production credential-scan behavior beyond reusing scan/apply; macOS menu bar and other-OS-layer work; IM platform configuration in onboarding (already moved to Settings —-`SetupPlatformRecovery` remains only as a recovery path); handoff §11's adjacent changes,+OS-layer work; IM platform configuration in onboarding (already moved to Settings;+the proposed `SetupPlatformRecovery` was removed); handoff §11's adjacent changes,which landed through #2033/#2047/#2050/#2051/#2058/#2067/#2068/#2069 and are re-verifiedhere only where they touch setup.diff --git a/docs/plans/setup-three-screen/contracts.md b/docs/plans/setup-three-screen/contracts.mdindex 5b14f388e..7108f1539 100644--- a/docs/plans/setup-three-screen/contracts.md+++ b/docs/plans/setup-three-screen/contracts.md@@ -2,6 +2,8 @@Status: **PR0 interface proposal; D10 owner-ratified**, audited against head`08b82658bbbf3e3e952fa1007c13f93fbca51410`. The handoff remains unchanged user source.+The later owner-approved setup implementation edits one Model Hub route per assistant,+using the existing `RouteChainDialog`; it has no shared route draft or cross-backend writer.The approved `model-hub-native-takeover.md` supplies runtime/custody precedent; theorchestrator adopts its automatic runtime preparation and the routine decisions in plan §10.The owner reaffirmed on 2026-09-21 12:56 +08 that setup uses Model Hub; disabling it@@ -10,13 +12,13 @@ At 13:19 +08 the owner ratified D10: setup delegates migration takeover to the emigration feature. C1/C6 supersede the handoff's copy-only, unchanged-connection and atomic-rollback promises for this flow; they do not alter the source handoff.-C1–C6 now specify the selected custody behavior and concrete technical mappings. D4/D9 is-orchestrator-ratified as a bounded technical interpretation. D11 is also orchestrator-ratified-for its config transport boundary. C6 now distinguishes controller-owned startup recovery-from browser observation and conditional retry, with separate composed owner evidence. Product-ratification does not authorize feature dispatch or extend #2065 merge authority to #2082;-requested feature authorization and contracts-on-master remain gates. Current work is PR0-only. A lane reports gaps instead of inventing a parallel contract.+C1–C6 specify the selected custody behavior and concrete technical mappings. D4/D9 was+orchestrator-ratified as a bounded technical interpretation; the later owner-approved+per-assistant route design supersedes its shared-route mapping below. D11 is also+orchestrator-ratified for its config transport boundary. C6 distinguishes controller-owned+startup recovery from browser observation and conditional retry. The original PR0 did not+authorize feature dispatch or extend #2065 merge authority to #2082; this document now+records the subsequently approved implementation boundary.| Contract | Where it lives | Owner || --- | --- | --- |@@ -68,9 +70,8 @@ and the shell-owned `SetupFlowState`.Consumers use `setFlowState(previous => ({ ...previous, changedField }))`, includingasynchronous completions. Replacing captured state loses other screens' intervening work.`providerSelection` holds the complete ephemeral `MigrationScan` and selected backend- consent groups shared with the existing migration owner, not an apply/recovery journal;- `routeOrder` holds `(source_id, model_id)` rows, never source IDs alone.- Neither is a second source of truth for persisted readiness.+ consent groups shared with the existing migration owner, not an apply/recovery journal.+ The shell does not own model-route drafts; persisted routes are read from Model Hub.- The shell renders the single primary and Back actions. Each `onActionChange` and`onNavigate` callback is bound to the emitting screen and activation; the shell rejectsinactive/stale publications and clicks only the current `SetupScreenHandle.activate()`.@@ -95,8 +96,8 @@ and the shell-owned `SetupFlowState`.- Server facts (CLI presence, backend enablement, sources and routes) are re-read on activeentry and after mutations. C4/C6 require the existing Agent collection authority to deep-refreshcached CLI presence after install/path/config changes and before completion; ordinary list- reads alone cannot establish that freshness. Preserve unconfirmed drafts across those reads; C6 defines scan- reconciliation, route targets and preservation of dirty target baselines. `setupFlow.test.ts` consumes the actual+ reads alone cannot establish that freshness. Preserve unconfirmed provider drafts across those reads;+ C6 defines scan reconciliation and the per-card route read boundary. `setupFlow.test.ts` consumes the actualprops with React state and checks navigation plus a late update, not just initial values.`setupCapability(boolean | null)` maps the shell's validated config capability boolean to@@ -196,17 +197,19 @@ anchor without a layout shift.**Shared reservation.** `.onboarding-stage` remains the box both the story and the screensbelow it occupy, so the anchor's vertical position does not depend on what a screen draws.-The import capsule lives in a reserved slot inside screen 2's stage: dismissing it leaves-the slot, so the primary action cannot move (handoff §4, and the assertion #2065 already-writes for the two-step flow).+Screen 2's migration offer uses the shell's primary action and a controlled review dialog;+dismissing an offer changes neither the stage nor the action anchor.**Snapshot hooks.** The handoff reads live DOM across screens, so these class names are acontract, not styling. L1's `setupHandoff.ts` queries them; L2 and L3 must render them.-An inactive `hidden` root has no measurable box. L1 must temporarily lay out the incoming-root invisibly and inertly for measurement, without activating its effects or action feed,-then switch activity at handoff completion. Restore `hidden` after cancellation; the settled-state still has exactly one active screen. L1's geometry test must exercise this real path,-not measurements taken with every screen already visible.+An inactive `hidden` root has no measurable box. At handoff start, the incoming screen+becomes the displayed root: its heading and diagram or summary appear immediately, as in+Show session `ses36vg559de2`'s `begin` and `chooseAssistants`. Only the incoming destination+cards stay visually hidden while the cloned outgoing cards fly into place (about 900 ms).+The incoming root remains inert and its effects and action feed inactive until landing.+After cancellation, restore the inactive root's `hidden` state; the settled state still+has exactly one active screen. L1's geometry test must exercise this real path, not+measurements taken with every screen already visible.| Transition | Reads from | Lands on || --- | --- | --- |@@ -260,7 +263,7 @@ and Agent name** to backend connection/CLI reads and `AgentSupply.named_agents`.Do not read backend-level `selected_model_id` to reject a different candidate: it describesonly `selected_by_agent`. The runnable-hop owner is the server resolver; neither an unrelated-healthy source nor a client `routeOrder` proves readiness. Revalidate on the completion click.+healthy source nor a card's displayed route proves readiness. Revalidate on the completion click.**CLI freshness owner.** `Controller` caches CLI presence; an ordinary `listAgents()` cannotrefresh it after installation. Use one shared `createAgentCollectionReadAuthority(modelsApi)`@@ -286,20 +289,23 @@ ensure/start. Startuphas no assistant/source readiness prerequisite. Do not restart after an enable/config write.Preserve `default_agent_name` if it remains in the available set, including a usable custom-Agent outside the route editor's setup targets. Otherwise prefer a runnable setup target in-C6's stable order, then an available named Agent in stable backend/name order; call+Agent outside the cards' designated builtin Agents. Otherwise prefer a runnable designated+builtin Agent in card order, then an available named Agent in stable backend/name order; call`setDefaultVibeAgent` and verify a fresh Agent read. Write `setup_completed` last through`api.mutateConfig` with an explicit field mutation, then validate a fresh uncached`apiFetch('/api/config', {cache:'no-store'})` readback before navigating. Use that sameread/parse path after an unknown/failed write; cached pre-write data cannot settle it.-Unknown writes are reconciled by reads, not treated as success or blindly retried. Keep `SetupPlatformRecovery` for-existing invalid IM configuration. `SetupModelRecovery` is the shipped **Direct OpenCode**-recovery; it does not repair Hub models. C6 specifies Hub catalog/chain repair.+Unknown writes are reconciled by reads, not treated as success or blindly retried. Existing+invalid IM configuration remains saved for later repair in Settings and does not gate Model+Hub setup completion. `SetupModelRecovery` is the shipped **Direct OpenCode**+recovery; it does not repair Hub models. A missing Hub Agent model is repaired in existing+Agent/Model Hub settings, not chosen or written by Setup.The new Hub route predicate replaces credential readiness / `entry_eligible` as the *route*criterion, not the confirmed application-state or backend permission guard. Today's `Wizard.complete()` onlyfilters OpenCode routes; the all-backend named-Agent join is new L3 orchestration, not a-helper that already exists. Unrouted enabled assistants retain a configuration action (C6).+helper that already exists. Cards with a confirmed Hub model can edit its route even when+the chain is empty; cards without a model show a hint instead of creating a route target.**Known by design — setup requires Model Hub.** Owner decision, 2026-09-21 12:56 +08:“setup的契约是默认使用模型网关”; users who later need to disable it do so in Settings.@@ -319,7 +325,8 @@ Hub flow remain defects. Current-head review, unresolved-thread and CI gates sti## C5 — stable dialog frame-Applies to all three screen-2 dialogs and to screen 3's route dialog.+Applies to the three screen-2 dialogs. Screen 3 reuses Model Hub's existing+`RouteChainDialog` and its own focus, layout, guard and save behavior.- One frame per dialog across every tab and state: 568 wide, 24 padding, 16 radius, 20gaps, and a common height taken from that dialog's longer ordinary form (not from an@@ -343,20 +350,20 @@ Field names are exact. Every row names its producer and its consumer, because acontract passes both sides' unit tests while the behavior silently disagrees.Each row distinguishes a shipped owner from required setup orchestration. Reuse an owner-where its actual inputs and outputs fit; controlled state, support preflight and shared model-mapping cannot be attributed to helpers that lack them. A lane reports contradictions instead+where its actual inputs and outputs fit; controlled state, support preflight and per-assistant+route reads cannot be attributed to helpers that lack them. A lane reports contradictions insteadof silently changing either the handoff or another owner.### Screen 2 — providers| Element | Producer → consumer and rule || --- | --- |-| scan and discovery | existing migration feature `modelsApi.scanMigration().items` → full `providerSelection.scan`; `isImportableKey` identifies entry-point keys only. Keep every row; reuse its group closure/blockers before the actionable capsule count; a blocked detected key remains visible with its reason but is not advertised as importable |+| scan and discovery | existing migration feature `modelsApi.scanMigration().items` → full `providerSelection.scan`; `isImportableKey` identifies entry-point keys only. Keep every row; reuse its group closure/blockers before the primary-action count; a blocked detected key remains visible with its reason but is not advertised as importable || candidate identity | `MigrationItem.id` is selection identity, never vendor alone. Use `providerLabel` / `providerVendorId` as `MigrationDialog.ItemRow` does. Optional vendor/name/mask may be absent: generic mark plus `masked_detail`, never infer vendor from backend or fabricate a mask. Show every `source_paths` locator; only when absent use `migration.source.<backend>`. `notes_key` is an explanation, not origin || cards | slots 1–2 show detected/provider identities then existing sources, with OpenAI/Anthropic placeholders if needed; slot 3 is Add more. Vendor grouping is presentation only: multiple keys from one vendor retain separate IDs and may require whole backend selection || selected and connected | selected means complete consent group selected; a blocked group is disabled with its reason. Added/connected treatment follows confirmed source IDs from `listSources` and status `active` / `standby`; `verification_pending` is disclosed as unverified, not rejected as unusable (the shipped resolver accepts standby). One vendor's healthy source does not prove every key/card connected or a runnable assistant |-| 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 |+| counts | Primary-action count = deduplicated appliable item IDs in selected complete groups; summary provider count = distinct displayed providers of those items. There is no independent capsule count. `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 |+| migration offer | The primary action opens the controlled `MigrationDialog` for selected complete backend groups. `modelHubMigrationDismiss` persists declined `MigrationItem` identities; a newly discovered key remains visible for review, but its group is never automatically selected if another required item was declined. Only explicit consent to the complete group clears those identities. No `ImportKeysNotice` or reserved slot is mounted || 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: 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 |@@ -382,11 +389,9 @@ setup's API-key-only requirement, an otherwise importable OAuth member also blocfor this entry point; show it and explain that the full migration is available in Settings.Never silently import OAuth or drop it from a batch.-L2 makes the smallest controlled-state/copy adaptation of the existing dialog/grouping-owner so discovery cards, capsule and Detected tab consume that same feature. Current-`MigrationDialog` has only `open/onClose/onApplied/eligible` props and local `items` selection;-the shared state/copy inputs and setup key-only whole-group constraint are future adaptation-work, not already shipped props. Keep one grouping/confirmation/apply/recovery owner: no+The controlled `MigrationDialog`, discovery cards and Detected tab consume the same scan+and complete-group selection. Setup supplies the key-only eligibility and write admission;+Settings keeps its broader migration scope. Keep one grouping/confirmation/apply/recovery owner: noindependent item-ID selection engine, setup-specific migration coordinator or retry engine.Rescans invalidate old item IDs: preserve selection only for unchanged complete groups;changed membership/custody requires renewed review, and failed rescans disable apply rather@@ -418,7 +423,7 @@ key cleanup, preservation of unrelated MCP/name settings, and retained custody fafter exposure. Setup must not duplicate cleanup, custody writes, mode transition, rollbackor retry machinery, and must not send a second mode PATCH after successful apply.-Cards, capsule and Detected actions delegate to this feature's complete-group review. Keep+Cards, the primary action and Detected actions delegate to this feature's complete-group review. Keepevery required backend/file visible and show the exact consequence`迁移后,CLI的认证信息将完全交由模型网关管理`, with **Not now / Start migration**. Only the latterexplicit confirmation invokes apply. New/incomplete takeover invokes server dependency ensure@@ -484,7 +489,7 @@ retry can reseed an actually absent config without overwriting user fields.A direct `apiFetch` POST **does not clear ApiContext's 30-second config cache or emit`onConfigChanged`/configuration convergence**. L1 explicitly installs the validated freshGET into the shell's existing server-config state (`data` in today's Wizard), scoped to the-current request/activation. Feed capability, platform recovery and bootstrap decisions from+current request/activation. Feed capability and bootstrap decisions fromthat snapshot. Future authoritative setup reads use the same direct uncached read/parsepath, including unknown-write reconciliation; do not replace it with cached `api.getConfig()`or assume a global notification occurred. C2's draft state/setter remains unchanged.@@ -517,9 +522,10 @@ an explicit/active recovery attempt using fresh config and runtime evidence. A `can be the service's projection of failed demand, not proof of installed bytes. StatusProvider's`refreshStatus()` only refreshes service status and may return null; neither it nor a cachedstatus alone proves config persistence or backend readiness. Missing CLI, sources, routes-and incomplete setup do not forbid controller startup. Bad existing platform configuration-uses `SetupPlatformRecovery`; do not disable configured transports or restart after an-already-reconciled config write.+and incomplete setup do not forbid controller startup. Saved incomplete platform+configuration remains intact for repair in Settings; it does not block Model Hub setup+completion. Do not disable configured transports or restart after an already-reconciled+config write.Evidence is separated deliberately. The temporary frontend consumer imports the **actualApiProvider, serializer and apiFetch** with mocked HTTP: empty mutations reject before POST;@@ -579,7 +585,7 @@ is not universally side-effect-free. These are separate transport/server/compose| Mode change without native rows | `set_agent_mode` guards/drains native writers, rescans under lock and uses `_commit_synced`. No ensure; native rows are rejected, never silently taken over. Fresh health/config and mode readback remain required || Migration scan / apply | Full scan is discovery, not consent. New/incomplete `apply_native_migration._resume_takeover` explicitly ensures before native withdrawal and before sync/start; retain installing-path admission and journal recovery. A completed receipt replay returns before ensure. Healthy health alone cannot bypass this dependency; do not change migration semantics to remove it || Source/mode writes that change engine bindings | `_commit_synced` persists and calls adapter `sync_sources`; it waits for active transports and restarts a running engine via the existing verified disk binary, without installer ensure. Restart can fail if that binary/permissions/health is unavailable; owner restoration may also fail. Surface errors and re-read persisted config/runtime/receipts before retry, never claim atomic rollback |-| Exact route reads/preview/reorder | Pure chain reorder has unchanged bindings, so `_commit_synced` saves without restart or install. Keep exact-hop/menu-model eligibility, per-target guards and readback |+| Exact route reads/preview/reorder | Pure chain reorder has unchanged bindings, so `_commit_synced` saves without restart or install. `RouteChainDialog` owns exact-hop/menu-model eligibility, guards and readback for the selected route |Thus a usable running Hub is not disabled merely by `manifest.resolution === 'unsupported'`.New takeover can still be blocked by its real ensure dependency; manual sources, existing@@ -595,128 +601,46 @@ the default journey. Read failures authorize neither lifecycle writes nor comple| install | explicit `api.installAgent(name)` then detect the returned/configured path and await the collection authority refresh/current result. Path/agent-config changes have the same refresh requirement. Pending/stale/failed refresh holds completion and exposes Retry; retain install output and one loading indicator || enabled | existing Switch config write, followed by `getBackendConnection` and Agent reads. Saved config reconciles live backends; no second restart || upgrade | `BackendLifecycleChip.onVisual` still owns probe/write, activity-gated; update coexists with enabled state |-| route control | **every installed/enabled assistant has an action**, including Direct, empty route, missing model and read failure. Enabled-capability setup opens Hub configuration/recovery: show its own `named_agents` model when routed, otherwise `onboarding.setup.configureRoute`. Opening requires no resolved route; mutations use C6 operation-specific admission/consent. Unsupported without running Hub offers recheck/guide, not native auth as a setup bypass. A disabled configuration retains C2 configuration recovery, never a Direct setup dialog. Busy operations may temporarily disable action |-| candidate identity | use the setup target policy below; identify backend + Agent name and exact menu model, independently of the global default. C4 may preserve a runnable custom default outside these edit targets |-| add model source | `onNavigate('providers')` preserves the dirty route draft and closes the route dialog; reopening restores it. Done returns focus to the invoking chip/configure action |+| route control | Confirmed Hub cards with a designated builtin Agent model show that model's first chain hop and backup count. Enabled cards open `RouteChainDialog` for only `(backend, menu model)`; disabled cards preview the same route but cannot edit it. A current successful route read is required to open the editor; pending or failed reads do not infer an empty model or authorize editing. Route-read failure has its own Retry. A Hub card with no model shows a hint to repair it later in Agent/Model Hub settings; Setup does not choose or write an Agent model. Direct cards retain native connection actions, but Direct cannot satisfy setup completion. Unknown or conflicting Hub/Direct ownership disables configuration until a fresh read. A disabled Hub configuration retains C2 recovery, never a Direct setup-completion bypass |+| candidate identity | for each backend, read its current designated builtin Agent, including disabled Agents, and use its saved menu model; custom Agents or the global default do not substitute as that card's route target. C4 may preserve a runnable custom default independently |+| route close | close/commit refreshes the card's server-backed route and connection; `RouteChainDialog` owns the edit draft and save lifecycle, not `SetupFlowState` || all uninstalled | three install actions, workspace entry disabled, Back still available |-### Model-ranked route mapping — D4/D9 orchestrator-ratified technical interpretation--C2 keeps `RouteHop[]`: ordered `(source_id, upstream model_id)` pairs. A source with two-models yields two distinct rows. `putAgentSources` changes backend source membership and-priority; it is never the model-ranked Save operation. Existing `getAgentChain`,-`previewAgentChain`, `putAgentChain`, `putAgentModels` and `RouteChainDialog` supply the-primitives. The shared projection and multi-target coordinator are new L3 orchestration.--**Targets and scope.** Each installed/enabled backend card represents its designated builtin-default Agent. Use `listVibeAgents({cache:false})` for enabled/non-archived candidates and-`getVibeAgent(name,{cache:false})` for metadata: the brief list omits it. Match the store's-builtin selection (metadata `builtin_default` or `lock_delete`; prefer name equal to backend,-then `default`, then name order). A custom Agent merely named `claude` is not a builtin.-If none exists, keep configure reachable and require an explicit existing named-Agent target-selection; do not create or mutate an arbitrary Agent. Preserve each target Agent's exact-saved `model`; join to `AgentSupply.named_agents` by backend/name, then the exact-`catalog_models` menu id. No backend-native default or prefix-stripping inference.--The shared reorder includes the displayed setup targets, deduplicated by `(backend, menu-model)`, with their names/model identities visible before Save. It does not edit Agent model-fields, other menu-model chains, source order, disabled backends or the global default.-All Agents on the same backend/menu model necessarily share that chain: disclose their names-as affected; do not promise custom Agents with that same key are unaffected. A custom Agent-on a different menu model and a runnable global custom default are preserved. Explicit target-selection is required before adding such a custom route to the edit set.--**Fresh or unrouted target.** First ensure controller/runtime and mode as above; opening the-control itself has no route prerequisite. The server materializes recommendations for new-and legacy blank Agent models (`VibeAgentStore` creation/prefill); the UI never chooses the-first catalog row as an Agent model. Read back the actual selected model. If an anomalous-blank remains, require explicit Agent-model repair using existing Agent settings before-claiming a route target. The shipped Direct OpenCode recovery cannot perform this Hub repair.--Read the target's catalog and effective `getAgentChain`. Existing nonempty automatic or-manual chains hydrate immediately. If the exact saved menu id is absent (fresh OpenCode is-one real case), offer the existing catalog-add/manual form for **that exact id**, keeping the-current catalog as `baseline` and adding only the reviewed row through `putAgentModels`.-Use `getAgentModelCandidates` metadata for an exact matching candidate, or the existing-manual form's validated metadata/native protocol; never guess from the Agent name. If the-picker displays supplier chips, forward its `expected_suppliers` on catalog addition; a-manual row without a supplier promise omits that field. Preserve unrelated baseline rows-and read the catalog back before chain mutation. This adds a model entry, not an Agent-model-change; cancellation keeps the target unconfigured. Server admission errors remain visible.-For an empty chain, reuse the `routeCandidates`/`RouteChainDialog` exact-hop picker to select-an upstream model from an eligible source, preview it for this target, then save explicitly.-No arbitrary default hop, vendor-based cross-backend assumption or transplant from another-Agent. API-key passthrough can be an explicit manual target via the existing editor.--Example proved against the actual server: OpenCode's server-selected menu id-`openai/gpt-5.6-sol` can be admitted unchanged, then explicitly mapped to-`(source_id, 'gpt-5.6-sol')`. They are different identities. A source added on screen 2 can-supply an automatic route; it does not automatically extend a frozen manual chain. When an-existing manual route needs a new fallback, the same target-specific hop picker admits it-explicitly, then refreshes that target's membership. The shared reorder only reorders the-reviewed members; it never adds all global rows to every target.--**Initialization and reconciliation.** On the first clean open, snapshot for each target-`{ backend, modelId, agentNames, chain, manual_override }` from actual reads. Hydrate the-shared list by stable union of exact pairs: current global default's target first **only if-in the edit set**, then Claude/Codex/OpenCode and Agent name order. Preserve every target's-original membership and order as a baseline. Display the projected preferred/backup rank-for each affected target, not a claim that every row works on every backend. Divergent-existing orders remain unchanged on open/Done without an edit; show their actual orders and-the proposed outcome before an explicit shared Save. Disjoint native subscriptions retain-their disjoint subsets. A global interleaving change that alters no target is a no-op.--`routeOrder` and `routeOrderDirty` live in shell state. The single shared mounted route owner-retains target baselines, pending submissions and per-target results while hidden (local-state, not extra C2 fields or a new global store). Add source/Back closes the dialog without-unmounting this owner. Dirty re-entry retains both draft and baselines; read new server facts-separately, showing added candidates without overwriting edits. Changed Agent model, mode,-source membership or target set invalidates dependent previews and requires reconciliation.-If the owner is deliberately reset, clear the draft and baselines together, never retain an-orphaned dirty list. Refresh restores persisted truth, not an unpersisted browser draft.--**Projection, write and retry.** For each target, filter the shared order by that target's-reviewed exact-pair membership. Preserve temporarily unhealthy/stale persisted hops; the-server annotates health and admission. No empty write silently resets a chain: empty means-configuration/recovery required, because `{hops:[]}` removes the override and inherits defaults.-For changed targets preview with **`{manual_override:{hops}}`**. Server validation supplies-backend eligibility/model admission; inspect runnable/current and affected route evidence.-Do not synthesize vendor/protocol compatibility, auto-force interruption guards or hide a-failed target. A pure reorder keeps membership; actual backend eligibility changes may still-block it and require a fresh review.--Save only changed targets, in the displayed stable order, using `putAgentChain(backend,-menuModel,{hops})`. Reordering an automatic chain freezes that target as a manual override:-show the existing follows/frozen route explanation; future source additions will not silently-join it. Just opening or confirming an unchanged list never freezes an automatic chain.-Before each write re-read its Agent/model, mode and chain against the baseline. After each-write, read the exact target again and verify **manual_override and pair order**, not merely-the current healthy source. Reuse `routeChainMatchesAttempt` for identity/override matching.-A second-target failure leaves earlier confirmed writes intact and the shared draft dirty.-On retry read every attempted target: confirmed desired override/order is skipped; unchanged-baseline may be retried; any third state needs reconciliation/review. Unknown response means-read first. No cross-target rollback or atomicity claim. The API has no chain baseline/CAS;-a race after the last pre-read is an existing last-writer limitation, so the UI must detect-readback differences and must not promise exclusion of concurrent Settings writers.-Clear dirty only when every changed intended target is confirmed (or a verified no-op),-then refresh candidate supply/default readiness. A locally sorted list is never C4 evidence.--Temporary composed fixture evidence (real service persistence/preview/resolver with fake-engine, outside PR files): same source/two models remain distinct; native Claude/Codex subsets-remain separate; one builtin target edit preserves a custom Agent's different model/chain;-fresh Agent model materialization and OpenCode exact catalog/hop admission work; divergent-orders cause no opening write; second-target failure preserves the first write and retries-only the outstanding one. Existing primitive tests separately cover unknown-response-reconciliation, route guards and model prefill. Neither is a shipped setup integration test;-L3 must port these cases to its real consuming coordinator.+### Per-assistant Model Hub route mapping++Each card reads its designated builtin Agent's saved menu model, including when that Agent+is disabled, and the matching chain from `GET /api/models/agents/{backend}/chains`. Read+the backend supply and sources once per refresh, not once per card. The card displays that+chain's actual first upstream model (display name when available, otherwise ID) and the+remaining hop count. The three cards may legitimately show different routes. A route on+another menu model, another backend, or an unrelated custom Agent is not substituted.++Only a current, successful read for the active screen may supply an editor selection. A+pending or failed read may retain old values for non-operational display, but it cannot+claim an empty model, enable the route action or open an old selection. Retry refreshes the+route inventory. A confirmed Hub card with a saved menu model opens the existing Model Hub+`RouteChainDialog` for exactly that `(backend, menu model)`, including when its chain is+empty. The dialog owns its own draft, preview, save guards, unknown-write reconciliation+and readback; Setup refreshes the card after commit or close. It does not write other+backends' chains. If the Agent has no model, Setup shows a hint and leaves model selection+and catalog repair to existing Agent/Model Hub settings.++Installing or enabling an assistant never adopts another assistant's route or changes its+Agent model. An install offers automatic enablement only when the click-time action promised+it for a confirmed Hub backend, and a newer explicit disable or changed backend ownership+prevents that later enable write. Direct cards retain native connection actions; they cannot+complete the Hub setup journey. There is no shared `routeOrder`, target projection,+multi-target partial receipt or cross-assistant rollback policy in Setup.## Audit evidence and required consuming checks| Repeated root class | Whole boundary audited / remaining evidence || --- | --- |-| route identity / eligibility / readiness | refreshed current CLI presence (existing generation owner) → action availability → named Agent+backend → mode → menu model → exact chain → default readback. C4/C6 define reachable configuration, explicit targets, exact-pair projection, partial-write/readback and default preservation; composed fixtures exercise the mapping |+| route identity / eligibility / readiness | refreshed current CLI presence (existing generation owner) → action availability → named Agent+backend → mode → menu model → exact chain → default readback. C4/C6 keep completion on fresh server evidence; each card reads only its designated Agent's current route. `RouteChainDialog` owns single-route guards and readback; Setup does not coordinate cross-backend writes || lifecycle / capability / readiness | enabled setup prerequisite → active-provider persistence → controller recovery/server admission → browser observation → operation-specific recovery/consent → readback. Default Hub requirement and independent healthy-Hub use are preserved; no unsupported-to-Direct conversion. `gatewayAdoption.test.ts` proves helper scope only; it is not a screen-2 preflight test. Future L2 tests must cover unsupported with zero runtime artifact installation/start, healthy-engine source writes and restart failure, already-Hub missing/stopped, real controller recovery (external composed fixture available), start failure and native blockers || producer / consumer / state | C2 React consuming test covers cross-screen state plus a late functional update. Full scan → transitive backend groups → complete apply IDs follows `MigrationDialog` and its grouping tests; L2 still needs a consuming integration test for discovery → owner confirmation → receipt/readback, including no implicit apply and unchanged Settings behavior || duplicated instructions / copy | plan §§4/9/10, C1 metadata and C2/C4/C6 reviewed together. Automatic runtime setup reuses approved precedent; owner D10 selects existing migration takeover and supersedes the handoff promises; setup owns only discovery/context/result presentation. Task-specific design source overrides the general default; existing theme shadow token replaces the literal prescription. Source-ranking substitution and false approval/rollback claims are removed; handoff remains unchanged user source |-PR0 tests do not claim a shipped screen or an end-to-end migration/route implementation.+The original PR0 tests established interface shapes only. Current consuming tests cover+per-card route reads, current-read editor admission and model-less presentation; they do+not replace the server's route-save and migration-owner checks.diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex b260eda13..36ebf4dc8 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -72,7 +72,8 @@ capabilities:- ui/src/components/settings/models/AgentCard.test.tsx- ui/src/components/settings/models/MigrationDialog.test.tsx- ui/src/components/settings/models/migrationScan.test.ts- - ui/src/components/onboarding/ImportKeysNotice.test.tsx+ - ui/src/components/onboarding/providers/providerStage.test.ts+ - ui/src/components/onboarding/providers/ProvidersScreen.test.tsx- ui/scripts/scenarioCatalog.test.mjs- id: harness_failure_recoveryname: Harness per-Session failure recoverydiff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex ed42abb4b..159740556 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -342,7 +342,7 @@ scenarios:backend: opencodetest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_manual_provider_connection_reaches_controller_confirmed_readiness- id: AUTH-SETUP-120- name: Explicit completion preserves canonical no-IM setup and invalid legacy IM recovery+ name: Explicit completion preserves canonical no-IM setup and never gates on saved legacy IMstatus: coveredkind: historical_regressionlayer: scenariodiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex f550fa495..f9b474618 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -3883,7 +3883,7 @@ def test_manual_provider_connection_reaches_controller_confirmed_readiness(monkedef test_setup_completion_preserves_canonical_and_legacy_platform_configuration(monkeypatch, tmp_path):- """AUTH-SETUP-120: no mandatory IM; saved invalid IM remains actionable."""+ """AUTH-SETUP-120: no mandatory IM; a saved invalid IM neither gates nor is lost."""from config.v2_config import DiscordConfigfrom tests.ui_server_test_helpers import csrf_headersfrom vibe import internal_client@@ -3906,15 +3906,19 @@ def test_setup_completion_preserves_canonical_and_legacy_platform_configuration(config.platforms.enabled = ["slack"]config.slack.bot_token = ""config.save()+ # A saved messaging platform is not a gate on the workspace. Completion goes+ # through on the config it was given, and the incomplete platform stays saved,+ # enabled and repairable from settings rather than blocking the way in.result = client.post('/api/config', json={"setup_completed": True}, headers=csrf_headers(client))- assert result.status_code == 400- assert "slack" in json.dumps(result.get_json()).lower()+ assert result.status_code == 200, result.get_json()+ assert V2Config.load().setup_completedassert V2Config.load().platforms.enabled == ["slack"]- assert not V2Config.load().setup_completed+ assert V2Config.load().slack.bot_token == ""# The actual embedded form sends only changed credential leaves. Another# actor's unrelated update between read and repair must survive.config = V2Config.load()+ config.setup_completed = Falseconfig.runtime.default_cwd = str(tmp_path / "并发工作目录")config.slack.app_token = "xapp-test-app-token"config.save()diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 4f50a832b..e2b6cc6be 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -37,7 +37,8 @@ capability:# narrows, plus the one predicate that separates them.- ui/src/components/settings/models/MigrationDialog.test.tsx- ui/src/components/settings/models/migrationScan.test.ts- - ui/src/components/onboarding/ImportKeysNotice.test.tsx+ - ui/src/components/onboarding/providers/providerStage.test.ts+ - ui/src/components/onboarding/providers/ProvidersScreen.test.tsx# The gate that resolves those rows against vitest's own collection, and# its own evidence.- ui/scripts/scenarioCatalog.test.mjs@@ -753,12 +754,13 @@ scenarios:- tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_masked_credential_is_the_same_masking_the_detail_already_showed- tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_presentation_metadata_leaves_every_pre_existing_value_and_id_alone- id: MH-MIG-004- name: Setup's key-import entry counts, offers and submits one and the same set, and leaves subscriptions and reauth rows to the settings migration+ name: Setup's key-import offer, count and submitted batch agree, leaving subscriptions and reauth rows to settingsstatus: coveredkind: migrationlayer: unit- test: "ui/src/components/onboarding/ImportKeysNotice.test.tsx::MH-MIG-004: submits only the rows still ticked"+ test: "ui/src/components/onboarding/providers/ProvidersScreen.test.tsx::MH-MIG-004: submits the batch it counted, and keeps the blocked card after the rescan"related_tests:+ - ui/src/components/onboarding/providers/ProvidersScreen.test.tsx::counts the takeable group beside it, and only that one- ui/src/components/settings/models/migrationScan.test.ts::counts an OpenCode key, which never arrives as kind api_key- ui/src/components/settings/models/MigrationDialog.test.tsx::applies only complete backend groups with one migration action- id: MH-MIG-005@@ -772,6 +774,12 @@ scenarios:- tests/test_model_hub_persisted_migration.py::test_shell_saved_key_takeover_keeps_unrelated_bytes_and_runtime- tests/test_model_hub_persisted_migration.py::test_new_shell_layer_during_provision_cannot_escape_consent- tests/test_model_hub_persisted_migration.py::test_shared_shell_key_requires_both_backend_consents+ - id: MH-MIG-006+ name: Setup keeps distinct credentials even when their display masks collide with a Hub source+ status: covered+ kind: migration+ layer: unit+ test: "ui/src/components/onboarding/providers/providerStage.test.ts::MH-MIG-006: keeps a key whose display mask collides with a Hub source"- id: MH-TAKEOVER-001name: Recoverable failures walk the configured route and exhaust only at its endstatus: covereddiff --git a/tests/test_wechat_auth.py b/tests/test_wechat_auth.pyindex a08606d1e..087d8eee9 100644--- a/tests/test_wechat_auth.py+++ b/tests/test_wechat_auth.py@@ -141,8 +141,6 @@ class WeChatAuthManagerTests(unittest.IsolatedAsyncioTestCase):embedded_source = Path("ui/src/components/settings/PlatformConfigEmbed.tsx").read_text(encoding="utf-8")self.assertIn("<WeChatConfig", embedded_source)self.assertIn("autoStartLogin={false}", embedded_source)- recovery_source = Path("ui/src/components/onboarding/SetupPlatformRecovery.tsx").read_text(encoding="utf-8")- self.assertIn("<PlatformConfigEmbed", recovery_source)async def test_poll_status_refresh_preserves_local_token_list(self):manager = WeChatAuthManager()diff --git a/ui/e2e/onboarding-fidelity/geometry.spec.ts b/ui/e2e/onboarding-fidelity/geometry.spec.tsindex 553b552a1..c52eb9bb8 100644--- a/ui/e2e/onboarding-fidelity/geometry.spec.ts+++ b/ui/e2e/onboarding-fidelity/geometry.spec.ts@@ -39,8 +39,8 @@ const CARD_SHARE = 0.306352;/** The wire box is the card times the reference's own 350/300, so the handoffs stay on* the cards' midline at every tier. */const WIRE_RATIO = 350 / 300;-/** What the stage reserves beyond the card, spent by the introduction on the return band- * and by the connection on the 20 + 44 import capsule. */+/** What the stage reserves beyond the card: the band the introduction draws its return+ * wire in. */const STAGE_EXTRA = 64;const box = async (page: Page, selector: string, index = 0) => {@@ -563,6 +563,83 @@ const expectSamePair = async (page: Page, before: Pair) => {}};+/**+ * One set of coordinates for all three screens.+ *+ * The composition is centred in the window, so anything that joins the column changes+ * where the heading, the cards and the action sit — which is how the assistants step,+ * whose readiness caption is portalled under the pair, came to sit 9px above the two+ * steps before it. The slot now lives in the cell the screens share, resting on its+ * bottom edge, so this asserts both halves: the three screens agree, and filling the+ * slot leaves them agreeing.+ */+test.describe('shared screen anchors', () => {+ for (const viewport of [{ width: 1132, height: 664 }, { width: 1440, height: 900 }, { width: 1920, height: 1080 }]) {+ test(`${viewport.width} desktop captions share one horizontal line`, async ({ page }) => {+ await page.setViewportSize(viewport);+ await serveProduct(page);+ await serveModelHub(page);+ await openOnboarding(page, { lang: 'zh' });+ const center = async (selector: string) => {+ const rect = await box(page, selector);+ return rect.y + rect.height / 2;+ };+ const welcome = await center('.onboarding-story-caption');+ await page.getByRole('button', { name: '立即开始' }).click();+ await page.clock.runFor(950);+ await expect(page.locator('.setup-provider-summary')).toContainText('已选');+ const providers = await center('.setup-provider-summary');+ await page.locator('.onboarding-setup-hint button').click();+ await page.clock.runFor(950);+ const assistants = await center('.onboarding-setup-hint');+ expect(welcome).toBeCloseTo(providers, 0);+ expect(assistants).toBeCloseTo(providers, 0);+ });+ }++ test('the heading and the action keep one y on every screen, with or without an aside', async ({ page }) => {+ await page.setViewportSize({ width: 1440, height: 900 });+ const denied = await serveProduct(page);+ await serveModelHub(page);+ await openOnboarding(page, { lang: 'zh' });+ await openSetup(page, 'zh');+ await settleEffects(page);++ const anchors = () => page.evaluate(() => {+ const top = (node: Element) => Math.round(node.getBoundingClientRect().top);+ const aside = document.querySelector('.onboarding-action-aside')!.getBoundingClientRect();+ const content = [...document.querySelectorAll('[data-setup-screen-root]:not([hidden]) .onboarding-stage > *')]+ .map((node) => node.getBoundingClientRect()).filter((rect) => rect.height > 0);+ return {+ headings: [...document.querySelectorAll('[data-setup-screen-root] .onboarding-heading')].map(top),+ action: top(document.querySelector('.onboarding-primary-action')!),+ asideTop: Math.round(aside.top),+ contentBottom: Math.round(Math.max(...content.map((rect) => rect.bottom))),+ };+ });++ const before = await anchors();+ // Every screen's heading starts where the current screen's does, and the action is+ // the same distance below all of them.+ expect(new Set(before.headings).size).toBe(1);++ // The tallest thing the slot carries, on the screen with the least room for it.+ await page.evaluate(() => {+ const paragraph = document.createElement('p');+ paragraph.textContent = 'diagnostic '.repeat(60);+ document.querySelector('.onboarding-action-aside')!.append(paragraph);+ });+ await settleEffects(page);+ const after = await anchors();+ expect(after.headings).toEqual(before.headings);+ expect(after.action).toBe(before.action);+ // It grows upward into empty room and stops before the composition above it.+ expect(after.asideTop).toBeLessThan(before.action);+ expect(after.asideTop).toBeGreaterThanOrEqual(after.contentBottom);+ expect(denied).toEqual([]);+ });+});+test.describe('shared action anchor', () => {for (const viewport of ANCHOR_TIERS) {for (const lang of ['en', 'zh'] as const) {@@ -605,12 +682,15 @@ test.describe('shared action anchor', () => {await expect(page.locator('[data-setup-screen-root]:not([hidden]) h1')).toBeFocused();await expect(page.locator('[data-setup-screen-root][hidden]:not([inert])')).toHaveCount(0);}- // The last screen contributes a caption, and a caption is ancillary: it is drawn- // below the pair it explains. That placement is what lets it grow without moving- // the anchor, and what keeps it off the button it is describing.+ // The desktop hint sits in the free band above the action; phone keeps its+ // own compact placement below the pair. Neither position moves the action.const caption = await box(page, '.onboarding-setup-hint');const backRect = await box(page, '.onboarding-back-action');- expect(caption.y).toBeGreaterThanOrEqual(backRect.y + backRect.height - 1);+ if (viewport.width >= 760) {+ expect(caption.y + caption.height).toBeLessThanOrEqual(action.y - 8);+ } else {+ expect(caption.y).toBeGreaterThanOrEqual(backRect.y + backRect.height - 1);+ }await page.locator('.onboarding-primary-action').scrollIntoViewIfNeeded();await expect(page.locator('.onboarding-primary-action')).toBeInViewport();// And the last word on reachability is a real click, which Playwright refuses to@@ -724,7 +804,7 @@ test.describe('post-action aside', () => {expect(denied).toEqual([]);});- test(`${size(viewport)} ${lang} holds a refused permission write and the import offer under the pair`, async ({ page }) => {+ test(`${size(viewport)} ${lang} holds a refused permission write under the pair`, async ({ page }) => {await page.setViewportSize(viewport);const denied = await serveProduct(page);await serveModelHub(page);@@ -738,15 +818,11 @@ test.describe('post-action aside', () => {const before = await pair(page);await openSetup(page, lang);- // Co-presence: the capsule keeps its reserved slot in the stage, the permission- // callout is in the slot after the pair. Two asides, one anchor.- const notice = page.locator('.onboarding-import-notice');+ // The permission callout is in the slot after the pair: an aside under the anchor.const callout = page.locator('.onboarding-action-aside').getByText(lang === 'zh' ? '不设置时 OpenCode' : 'Without this, OpenCode');- await expect(notice).toBeVisible();await expect(callout).toBeVisible();await expectSamePair(page, before);- expect((await box(page, '.onboarding-import-notice')).y).toBeLessThan(before.primary.y);// A write that has not answered yet: the callout says so and nothing moves.const setup = page.locator('.onboarding-action-aside').getByRole('button', {@@ -773,22 +849,10 @@ test.describe('post-action aside', () => {await expectSamePair(page, before);await clearToasts(page);- // Refusing the offer is the stage's event, not the slot's: the capsule lives in- // the stage and the callout in the aside, so dismissing one may not disturb the- // other or the pair's own box. Nor may it move the pair at all — the capsule's- // place in the stage is reserved whether or not the capsule is in it, and the- // stage is floored at the taller of the two steps' cards, so a card that wraps- // past `--ob-card-h` no longer spends the offer's band on its way down.+ // The stage is floored at the tallest step's cards, so a card that wraps past+ // `--ob-card-h` cannot move the pair either.const stageBefore = await stageHeight(page);- const slotBefore = await box(page, '.onboarding-import-slot');- await page.getByRole('button', { name: lang === 'zh' ? '关闭导入提示' : 'Dismiss import notice' }).click();- await expect(notice).toHaveCount(0);await expectSamePair(page, before);- // The slot is what makes that true: refusing empties it, it does not remove it.- const slotAfter = await box(page, '.onboarding-import-slot');- expect(round(slotAfter.height)).toBe(round(slotBefore.height));- expect(round(slotAfter.y)).toBe(round(slotBefore.y));- expect(await stageHeight(page)).toBeCloseTo(stageBefore, 1);expect(await page.evaluate(() => document.documentElement.scrollWidth <= globalThis.innerWidth)).toBe(true);expect(await hitSelf(page, '.onboarding-primary-action')).toBe(true);expect(await hitSelf(page, '.onboarding-back-action')).toBe(true);@@ -803,25 +867,20 @@ test.describe('post-action aside', () => {focusable: node.querySelectorAll('a[href], button, input, select, textarea, [tabindex]').length,}))).toEqual({ children: 0, focusable: 0 });// Back is the other half of the cross-screen claim: the introduction the pair- // returns to is the one it started on, after the step it came from had spent an- // offer, a refusal and a permission write.+ // returns to is the one it started on, after the step it came from had spent a+ // permission write.await expectSamePair(page, before);- // And re-entering is not a third position. The offer stays refused, so this is- // the step at its shortest — the reading the reservation exists for. The clock- // here is frozen and only a test moves it, so the handoff is nudged until the- // screen has arrived rather than once, which races the click's own commit.+ // And re-entering is not a third position. The clock here is frozen and only a+ // test moves it, so the handoff is nudged until the screen has arrived rather+ // than once, which races the click's own commit.await page.getByRole('button', { name: lang === 'zh' ? '立即开始' : 'Get started' }).click();await expect.poll(async () => {await page.clock.runFor(950);return page.locator('[data-setup-sequence]').getAttribute('data-setup-screen');}).toBe('assistants');await page.locator('.onboarding-assistants').waitFor();- await expect(notice).toHaveCount(0);await expectSamePair(page, before);- const slotAgain = await box(page, '.onboarding-import-slot');- expect(round(slotAgain.height)).toBe(round(slotBefore.height));- expect(round(slotAgain.y)).toBe(round(slotBefore.y));expect(await stageHeight(page)).toBeCloseTo(stageBefore, 1);expect(await hitSelf(page, '.onboarding-primary-action')).toBe(true);expect(await hitSelf(page, '.onboarding-back-action')).toBe(true);@@ -908,131 +967,6 @@ test.describe('completion recovery in the slot', () => {}});-/**- * The import offer. Everything about WHICH keys it counts is a component-level rule and is- * tested there; what only a browser can show is that the capsule is an aside rather than a- * banner, that refusing it does not move the button underneath, and that its help text can- * actually be reached by a pointer, a keyboard and a finger.- */-test.describe('import capsule', () => {- test('is a centred capsule whose dismissal leaves the action where it was', async ({ page }, info) => {- await page.setViewportSize({ width: 1200, height: 800 });- const denied = await serveProduct(page);- await serveModelHub(page);- await openOnboarding(page, { lang: 'zh' });- await openSetup(page, 'zh');-- const notice = page.locator('.onboarding-import-notice');- // Three importable keys among five scanned rows: the two native subscription tokens- // are the settings migration's business, never this entry's.- await expect(notice).toHaveText(/发现 3 个可导入模型网关的 API Key/);-- const capsule = await box(page, '.onboarding-import-notice');- const slot = await box(page, '.onboarding-import-slot');- const cards = await box(page, '.onboarding-assistants');- const stage = await box(page, '.onboarding-stage');- const action = await box(page, '.onboarding-primary-action');- expect(round(capsule.height)).toBe(44);- // Content width, centred under the cards — not a full-width banner.- expect(capsule.width).toBeLessThan(cards.width);- expect(capsule.x + capsule.width / 2).toBeCloseTo(cards.x + cards.width / 2, 0);- expect(capsule.y - (cards.y + cards.height)).toBeCloseTo(20, 0);- // It sits at the top of its own slot, and the slot is the offer's reserved place in- // the stage rather than a box drawn around whatever arrived: a reservation that has- // to hold the other language's wrapped card leaves its slack under the composition,- // which is where the action's own 20 is measured from.- expect(capsule.y).toBeCloseTo(slot.y, 0);- expect(slot.height).toBeGreaterThanOrEqual(capsule.height - 0.5);- expect(action.y - (stage.y + stage.height)).toBeCloseTo(20, 0);- expect(await page.locator('.onboarding-import-notice').evaluate((node) => getComputedStyle(node).boxShadow)).toBe('none');-- await settleEffects(page);- await page.screenshot({ path: info.outputPath('import-capsule-1200x800-dark-zh.png') });-- // The layout space is reserved, so refusing the offer moves nothing: the slot keeps- // the height the capsule had, and the stage and the action keep theirs.- await page.getByRole('button', { name: '关闭导入提示' }).click();- await expect(notice).toHaveCount(0);- const emptySlot = await box(page, '.onboarding-import-slot');- const after = await box(page, '.onboarding-primary-action');- expect(round(emptySlot.height)).toBe(round(slot.height));- expect(round(emptySlot.y)).toBe(round(slot.y));- expect(round((await box(page, '.onboarding-stage')).height)).toBe(round(stage.height));- expect(round(after.y)).toBe(round(action.y));- expect(round(after.x)).toBe(round(action.x));- expect(denied).toEqual([]);- });-- test('phones put the offer and its refusal on one line and the actions on the next', async ({ page }, info) => {- await page.setViewportSize({ width: 390, height: 844 });- await serveProduct(page);- await serveModelHub(page);- await openOnboarding(page, { lang: 'zh' });- await openSetup(page, 'zh');-- const text = await box(page, '.onboarding-import-notice-text');- const dismiss = await box(page, '.onboarding-import-notice-dismiss');- const actions = await box(page, '.onboarding-import-notice-actions');- expect(dismiss.y).toBeCloseTo(text.y + text.height / 2 - dismiss.height / 2, 0);- expect(actions.y).toBeGreaterThanOrEqual(text.y + text.height);- // The full Chinese sentence at the verified width: wrapped if it must be, never cut.- const intact = await page.locator('.onboarding-import-notice-text')- .evaluate((node) => node.scrollWidth <= node.clientWidth + 1 && getComputedStyle(node).textOverflow !== 'ellipsis');- expect(intact).toBe(true);- expect(await page.evaluate(() => document.documentElement.scrollWidth <= globalThis.innerWidth)).toBe(true);- await settleEffects(page);- await page.screenshot({ path: info.outputPath('import-capsule-390x844-dark-zh.png') });- });-- // A real touch context, because the whole point of the hint's pointer handling is that- // a finger and a mouse arrive differently: Chromium only reports `pointerType: 'touch'`- // when the context actually has a touchscreen, so a synthetic event could not show that- // a tap produces one clean toggle instead of hover-open-then-click-closed.- test.describe(() => {- test.use({ hasTouch: true });-- test('the help text opens on hover, on focus and on tap, and closes on Escape or outside', async ({ page }) => {- await page.setViewportSize({ width: 1200, height: 800 });- await serveProduct(page);- await serveModelHub(page);- await openOnboarding(page, { lang: 'zh' });- await openSetup(page, 'zh');-- const help = page.getByRole('button', { name: '什么是模型网关?' });- const body = page.getByText(/模型网关管理你选择的认证信息/);-- // Pointer: the panel is portalled, so it must survive the trip from trigger to panel.- await help.hover();- await expect(body).toBeVisible();- await body.hover();- await expect(body).toBeVisible();- await page.mouse.move(10, 10);- // Leaving defers the close by 120ms, which is exactly what let the pointer make- // the trip above. The fixture's clock is frozen, so that delay has to be spent.- await expect(body).toBeVisible();- await page.clock.runFor(200);- await expect(body).toBeHidden();-- // Keyboard: focus reveals it and Escape takes it back, without trapping the tab order.- await help.focus();- await expect(body).toBeVisible();- await page.keyboard.press('Escape');- await expect(body).toBeHidden();- await expect(help).toBeFocused();-- // Touch: one clean toggle, and a tap elsewhere dismisses it.- const target = (await help.boundingBox())!;- await page.touchscreen.tap(target.x + target.width / 2, target.y + target.height / 2);- await expect(body).toBeVisible();- // The dismissable layer arms its outside listener in a zero-delay timeout, which a- // frozen clock never reaches. Spending it is the fixture's business, not a wait.- await page.clock.runFor(50);- await page.touchscreen.tap(8, 400);- await expect(body).toBeHidden();- });- });-});-/*** Narrow widths are where a card stops being a scaled copy of the design and becomes an* adaptation, so the thing to check is that the adaptation is ONE arrangement rather thandiff --git a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts b/ui/e2e/onboarding-fidelity/hub-ownership.spec.tsindex 680e7f773..b31ee308e 100644--- a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts+++ b/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts@@ -5,12 +5,8 @@ import { ORIGIN, serveProduct } from './support';// server responses are fixture-owned; the Vite server has a dead backend.// The Python connection tests separately establish the readiness producer.//-// C4 moved the assistant card's model entry into a dialog the step owns, so setup-// no longer leaves for the Hub settings page at all. This used to cover the return-// from it — going out, migrating there and coming back to the same step. There is-// nothing to come back from now, and the contract that mattered is the one that-// survives it: the Hub owns authentication, the take-over happens without the step-// ever being unmounted, and completion stays gated on a real readiness answer.+// Setup migrates a discovered key from Providers before entering Assistants.+// The Hub owns authentication, and completion stays gated on a fresh readiness answer.for (const width of [1200, 390]) {test(`Hub owns assistant authentication and its take-over completes inside setup at ${width}px`, async ({ page }, info) => {await page.setViewportSize({ width, height: 844 });@@ -138,43 +134,24 @@ for (const width of [1200, 390]) {await page.goto('/setup');await page.getByRole('button', { name: 'Get started', exact: true }).click();- // Nothing is connected yet, so the journey opens on Providers with only the- // take-over it found on offer. Saying so there is what leaves a way through to- // the screen that owns the Hub — and the take-over is still only on offer when- // it does: the credential this run imports is taken over from the Hub itself.await expect(page.locator('[data-setup-screen="providers"]')).toBeVisible();- await page.getByRole('button', { name: 'Continue to assistants', exact: true }).click();- const enter = page.getByRole('button', { name: 'Enter workspace', exact: true });- await expect(enter).toBeDisabled();- await expect.poll(() => observedReady.length).toBeGreaterThan(0);- const wizard = await page.locator('.onboarding-assistants').elementHandle();- const claude = page.getByLabel('Claude Code', { exact: true });- // The card offers no native key: whatever this backend authenticates with is- // the Hub's to hold, and the step says so rather than offering a second way.- await expect(claude.getByRole('button', { name: 'Add API Key', exact: true })).toHaveCount(0);-- // The take-over is the step's own: the notice opens the Hub's migration dialog- // in place, so nothing here navigates and there is no step to come back to.- await page.getByRole('button', { name: 'Review migration', exact: true }).click();- const migration = page.getByRole('dialog').filter({ has: page.getByRole('heading', { name: 'Migrate to the Model Hub', exact: true }) });+ await page.getByRole('button', { name: 'Migrate 1 key and continue', exact: true }).click();+ const migration = page.getByRole('dialog').filter({ has: page.getByRole('heading', { name: 'Migrate to Model Hub', exact: true }) });await expect(migration).toBeVisible();await migration.getByRole('button', { name: 'Start migration', exact: true }).click();await expect.poll(() => applied).toEqual([['mig_claude_fixture']]);+ await migration.getByRole('button', { name: 'Done', exact: true }).click();await expect(migration).toHaveCount(0);await page.screenshot({ path: info.outputPath(`hub-migrated-${width}.png`) });- // The step was never unmounted, so the same node is still the one being read.+ await page.getByRole('button', { name: 'Continue to assistants', exact: true }).click();await expect(page.locator('.onboarding-assistants')).toBeVisible();- expect(await wizard!.evaluate((node) => node.isConnected)).toBe(true);+ const enter = page.getByRole('button', { name: 'Enter workspace', exact: true });+ const claude = page.getByLabel('Claude Code', { exact: true });+ await expect(claude.getByRole('button', { name: 'Add API Key', exact: true })).toHaveCount(0);- // Readiness is re-read the way this step says it is: the caption under the pair- // offers the rescan, and the answer it gets is what opens the workspace. The- // take-over used to be followed by a return to this screen, which re-read the- // backends on the way in; completing it in place needs the rescan to do it.- await expect(enter).toBeDisabled();- await page.getByRole('button', { name: 'Re-scan', exact: true }).click();+ // Enter is admitted only after the backend reports readiness with the migrated key.await expect(enter).toBeEnabled();- await expect(page.getByRole('button', { name: 'Review migration', exact: true })).toHaveCount(0);expect(observedReady).toContain(true);await page.screenshot({ path: info.outputPath(`setup-hub-ready-${width}.png`), fullPage: true });await enter.click();diff --git a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.tsindex 86e10e585..d0d161937 100644--- a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts+++ b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts@@ -16,7 +16,7 @@ for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] asconst saved:Record<string,typeof hops>={claude:[],codex:[]};const agent=(backend:string)=>({id:`fixture-${backend}`,name:backend,backend,model:backend==='claude'?'opus-5':'gpt-5',enabled:true,archived:false,metadata:{builtin_default:true},source:'builtin',display_name:backend,description:'',system_prompt:null,reasoning_effort:null});const config=()=>({version:'v2',mode:'self_host',setup_completed:completed,setup_state:{needs_setup:!completed},capabilities:{model_hub:{enabled:true}},platforms:{primary:'slack',enabled:[]},runtime:{},agents:Object.fromEntries(['claude','codex','opencode'].map(b=>[b,{enabled:b!=='opencode',cli_path:b}])),agent:{default_cwd:'/fixture/work'},model_hub:{enabled:true,runtime_default_applied:true}});- const source={id:'src_fixture',kind:'api_key',vendor:'openai',display_name:'Fixture source',protocol:'openai_chat',supply_channel:'hub',billing:'metered',state:{status:'active'},masked_credential:'fixture-only',models:hops.map(h=>({id:h.model_id,origin:'discovered',reasoning_efforts:[],reasoning_efforts_source:null})),last_discovered_at:null};+ const source={id:'src_fixture',kind:'api_key',vendor:'openai',display_name:'Fixture source',protocol:'openai_chat',supply_channel:'hub',billing:'metered',state:{status:'active'},masked_credential:'fixture-only',models:hops.map(h=>({id:h.model_id,display_name:h.model_id==='gpt-5'?'GPT-5':undefined,origin:'discovered',reasoning_efforts:[],reasoning_efforts_source:null})),last_discovered_at:null};const supply=(b:string)=>({backend:b,cli_present:true,mode:'hub',menu_kind:'fixed',sources:{order:[source.id],eligibility:[{source_id:source.id,eligible:true}]},routes:{},builtin_models:[],catalog_models:[],menu:null,model_supply:[],named_agents:[{name:b,effective_model_id:agent(b).model,supply_status:saved[b].length?'ok':'unavailable'}],supply_status:saved[b].length?'ok':'unavailable'});const chain=(b:string,hs=saved[b])=>({contract_version:10,backend:b,model_id:agent(b).model,manual_override:hs.length?{hops:hs}:null,route_origin:hs.length?'manual':'automatic',current:hs[0]??null,chain:hs.map(h=>({...h,channel:'hub',health:'healthy',runnable:true,reason:null,retry_at:null})),supply_state:hs.length?'ok':'unavailable'});await page.addInitScript(()=>localStorage.setItem('i18nextLng','en'));@@ -37,6 +37,9 @@ for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] asif(path==='/api/models/runtime/status')return answer({ok:true,runtime:{contract_version:10,enabled:true,host_platform:'linux',manifest:{name:'cliproxyapi',resolution:'resolved',version:'fixture',source_sha:'a'.repeat(40),assets:[]},status:{installed_version:'fixture',verified:true,health:'ok'}}});if(path==='/api/models/sources')return answer({ok:true,sources:[source]});if(path==='/api/models/agents')return answer({ok:true,agents:[supply('claude'),supply('codex')]});+ if(/\/api\/models\/agents\/(claude|codex)\/chains$/.test(path)){+ const b=path.split('/')[4];return answer({ok:true,chains:[chain(b)]});+ }if(/\/api\/models\/agents\/(claude|codex)\/chain/.test(path)){const b=path.split('/')[4];if(req.method()==='PUT'){saved[b]=body?.hops??[];return answer({ok:true,chain:chain(b)});}@@ -65,12 +68,12 @@ for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] asawait add().click();await page.getByRole('option',{name:/gpt-5/}).click();await page.getByRole('button',{name:en.settings.models.routeDialog.add.confirm,exact:true}).click();await add().click();await page.getByRole('option',{name:/gpt-4.1/}).click();await page.getByRole('button',{name:en.settings.models.routeDialog.add.confirm,exact:true}).click();await page.screenshot({path:info.outputPath('route.png'),fullPage:true});- await page.getByRole('button',{name:en.onboarding.route.done,exact:true}).click();+ await page.getByRole('button',{name:en.settings.models.routeDialog.save,exact:true}).click();await expect.poll(()=>saved[chosen]).toEqual(hops);await expect(page.getByRole('dialog')).toHaveCount(0);- await card.getByRole('button',{name:en.onboarding.setup.configureRoute,exact:true}).click();- await expect(page.getByText('Fixture source · gpt-4.1',{exact:true})).toBeVisible();- await page.getByRole('button',{name:en.onboarding.route.done,exact:true}).click();+ await expect(card.getByText('GPT-5')).toBeVisible();+ expect(saved[chosen==='claude'?'codex':'claude']).toEqual([]);+ expect(writes.filter(w=>/^\/api\/agents\/(claude|codex)$/.test(w.path))).toEqual([]);await page.screenshot({path:info.outputPath('assistants.png'),fullPage:true});await page.getByRole('button',{name:'Enter workspace',exact:true}).click();await expect.poll(()=>completed).toBe(true);diff --git a/ui/e2e/onboarding-fidelity/providers.spec.ts b/ui/e2e/onboarding-fidelity/providers.spec.tsindex 7e3474a3c..17af1a270 100644--- a/ui/e2e/onboarding-fidelity/providers.spec.ts+++ b/ui/e2e/onboarding-fidelity/providers.spec.ts@@ -102,21 +102,18 @@ test.describe('providers screen', () => {expect(denied).toEqual([]);});- test('the badge, the summary and the capsule each count their own set', async ({ page }) => {+ test('the badge and the summary 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.@@ -139,13 +136,9 @@ test.describe('providers screen', () => {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);@@ -171,28 +164,6 @@ test.describe('providers screen', () => {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.diff --git a/ui/src/components/LanguageSwitcher.tsx b/ui/src/components/LanguageSwitcher.tsxindex 3a19941dd..28421d042 100644--- a/ui/src/components/LanguageSwitcher.tsx+++ b/ui/src/components/LanguageSwitcher.tsx@@ -83,10 +83,10 @@ export const LanguageSwitcher: React.FC<LanguageSwitcherProps> = ({ openUpward =aria-selected={active}onClick={() => handleSelect(lang.code)}className={clsx(- 'flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm transition-colors',- active- ? 'text-foreground'- : 'text-muted hover:bg-surface-2 hover:text-foreground'+ // `--surface-2` is white on a light theme, which is also the menu's own+ // surface: a row highlighted with it reads as no highlight at all.+ 'flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm transition-colors hover:bg-foreground/[0.06] hover:text-foreground',+ active ? 'bg-mint-soft text-foreground' : 'text-muted')}><span>{lang.label}</span>diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsxindex 68eceb9b3..13aa02b9b 100644--- a/ui/src/components/Wizard.tsx+++ b/ui/src/components/Wizard.tsx@@ -1,5 +1,5 @@import { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactElement, type Ref } from 'react';-import { ArrowLeft, ArrowRight, RefreshCw } from 'lucide-react';+import { ArrowLeft, ArrowRight, LoaderCircle, RefreshCw } from 'lucide-react';import { Button } from './ui/button';import { AccessTiles } from './onboarding/AccessTiles';import { RouteSurfaceActiveContext, useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';@@ -8,7 +8,7 @@ import { loadingRegion, readyRegion, beginRegionRead, failRegionRead } from './simport { modelsApi } from './settings/models/modelsApi';import { apiFetch } from '@/lib/apiFetch';import { INITIAL_SETUP_FLOW_STATE, setupBackTarget, setupCapability, setupNavigationReady, type SetupAction, type SetupCapability, type SetupScreenId, type SetupScreenHandle, type SetupScreenProps } from './onboarding/setupFlow';-import { mediaQuery, playSetupHandoff, setupHandoffAllowed } from './onboarding/setupHandoff';+import { captureSetupCards, mediaQuery, playSetupHandoff, setupHandoffAllowed, type SetupSnapshot } from './onboarding/setupHandoff';import { fetchSetupConfig, type SetupConfigRead, type SetupConfigSnapshot } from './onboarding/setupConfig';import { SETUP_REGISTERED_SCREENS } from './onboarding/setupScreenRegistry';import './onboarding/onboarding.css';@@ -28,8 +28,6 @@ import { LanguageSwitcher } from './LanguageSwitcher';import { useApi } from '../context/ApiContext';import { useStatus } from '../context/StatusContext';import { setConfigField } from '../lib/configMutations';-import { SetupPlatformRecovery, type SavedPlatformRecovery } from './onboarding/SetupPlatformRecovery';-import { getEnabledPlatforms, getPlatformCatalog, platformHasRunnableConfig } from '../lib/platforms';import { ASSISTANT_ORDER } from './onboarding/collaborationTimeline';import { createAgentCollectionReadAuthority } from './settings/models/collectionReadAuthority';import { admitEntry, chooseEntryDefault, readEntryEvidence, type EntryGateDeps, type EntryRefusal } from './onboarding/entryGate';@@ -123,11 +121,30 @@ export function SetupFlowShell({ sequence, capability, gatewayEnabled, onRetrySeconst current = useRef(activation);const transition = useRef<(() => void) | null>(null);const transitioning = useRef(false);+ /** A flight waiting for the screen it lands on to be on screen. */+ const flight = useRef<{ snapshot: SetupSnapshot; to: SetupScreenId } | null>(null);const ready = setupNavigationReady(capability, gatewayEnabled);const policy = useRef({ ready, sequence, locked: navigationLocked, routeActive });useLayoutEffect(() => { current.current = activation; policy.current = { ready, sequence, locked: navigationLocked, routeActive }; });useLayoutEffect(() => {+ if (handoff || !routeActive) return;roots.current[activation.id]?.querySelector<HTMLElement>('h1')?.focus({ preventScroll: true });+ }, [activation, handoff, routeActive]);+ // The screens swap first and the identities fly afterwards, onto the screen that is+ // now really there. Landing into a live diagram is what the reference does, and it+ // is what keeps the wires, the summary and the action from appearing in one jump+ // once the flight is already over.+ useLayoutEffect(() => {+ const pending = flight.current;+ const incoming = roots.current[activation.id];+ if (!pending || pending.to !== activation.id || !host.current || !incoming) return;+ flight.current = null;+ const finish = () => {+ transition.current = null;+ transitioning.current = false;+ setHandoff(false);+ };+ transition.current = playSetupHandoff(host.current, pending.snapshot, incoming, pending.to, finish);}, [activation]);useEffect(() => () => transition.current?.(), []);@@ -148,29 +165,28 @@ export function SetupFlowShell({ sequence, capability, gatewayEnabled, onRetrySeconst backwards = policy.current.sequence.indexOf(target) < policy.current.sequence.indexOf(previous.id);if (!backwards && !policy.current.ready) return;const next = { id: target, epoch: previous.epoch + 1 };- const finish = () => {- transition.current = null;- transitioning.current = false;- current.current = next;- setAction(null);- setHandoff(false);- setActivation(next);- };if (mediaQuery('(max-width: 759px)')) {host.current?.closest('.onboarding-shell')?.scrollTo({ top: 0, behavior: 'instant' });window.scrollTo({ top: 0, behavior: 'instant' });}- if (backwards || !setupHandoffAllowed(paused) || !host.current || !roots.current[previous.id] || !roots.current[target]) {- finish(); return;+ // Every arrival flies, as the reference's do: the identities that grew into+ // assistants shrink back into the diagram's destinations on the way out, and that+ // row grows back into the story cards it was folded from.+ const animated = setupHandoffAllowed(paused)+ && !!host.current && !!roots.current[previous.id] && !!roots.current[target];+ if (animated) {+ transitioning.current = true;+ flight.current = { snapshot: captureSetupCards(roots.current[previous.id]!, previous.id), to: target };}- transitioning.current = true;- setHandoff(target === 'intro' ? false : target);- transition.current = playSetupHandoff(host.current, roots.current[previous.id]!, roots.current[target]!, previous.id, target, finish);+ current.current = next;+ setAction(null);+ setHandoff(animated ? target : false);+ setActivation(next);}, [paused]);// A callback belongs to this activation, even if an asynchronous consumer saves it.const feeds = useMemo(() => Object.fromEntries(sequence.map((id) => [id, {onActionChange: (next: SetupAction) => {- if (current.current.id === id && current.current.epoch === activation.epoch && !transitioning.current) setAction(next);+ if (current.current.id === id && current.current.epoch === activation.epoch) setAction(next);},onNavigate: (target: SetupScreenId) => {if (current.current.id === id && current.current.epoch === activation.epoch) navigate(target);@@ -182,32 +198,40 @@ export function SetupFlowShell({ sequence, capability, gatewayEnabled, onRetrySereturn <div className="onboarding-step" data-setup-sequence={sequence.join(' ')} data-setup-screen={activation.id} data-handoff={handoff || undefined}><div className="onboarding-screens" ref={host}>{sequence.map((id) => {- const active = routeActive && id === activation.id;+ const active = routeActive && id === activation.id && !handoff;return <div key={id} ref={(node) => { roots.current[id] = node; }} data-setup-screen-root={id}hidden={id !== activation.id} inert={!active || !!handoff}>- <RouteSurfaceActiveContext.Provider value={active && !handoff}>+ <RouteSurfaceActiveContext.Provider value={active}><SetupScreenContent id={id} screenProps={{ active, handoff, capability, gatewayEnabled, runtimeRead,onRetrySetup, flowState, setFlowState, ...feeds[id] }} renderScreen={renderScreen}ref={(handle) => { handles.current[id] = handle; }} /></RouteSurfaceActiveContext.Provider></div>;})}+ {/* Where a screen puts what is ancillary to the pair below: in the cell the screens+ share, resting on its bottom edge and growing upward into the room the screen+ leaves above the action. In the cell rather than in the column, because the+ column is centred in the window — a caption in it would move the heading, the+ cards and the action by half of its own height, which is what made the+ assistants step sit 9px higher than the two before it. */}+ <div className="onboarding-action-aside" data-setup-action-aside="" /></div><div className="onboarding-setup-footer"><Button type="button" variant="brand" className="group onboarding-action-w onboarding-primary-action"- disabled={loading || !!handoff || navigationLocked || (!retry && (!action || action.disabled || action.busy || !ready))}+ disabled={loading || !!handoff || (!retry && (!action || action.disabled || action.busy || !ready))}onClick={() => { if (transitioning.current || policy.current.locked) return; if (retry) onRetrySetup(); else if (ready && action && !action.disabled && !action.busy) handles.current[current.current.id]?.activate(); }}>{t(loading ? 'common.loading' : retry ? 'common.retry' : action?.labelKey ?? 'common.loading', action?.labelArgs)}- {(loading || action?.busy || action?.icon === 'spinner') ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : action?.icon === 'arrow-right' && <ArrowRight size={16} />}+ {(loading || action?.busy || action?.icon === 'spinner')+ ? activation.id === 'providers'+ ? <LoaderCircle size={16} className="motion-safe:animate-spin" />+ : <RefreshCw size={16} className="motion-safe:animate-spin" />+ : action?.icon === 'arrow-right' && <ArrowRight size={16} />}</Button><Button type="button" variant="ghost" className="onboarding-action-w onboarding-back-action" style={{ visibility: back ? 'visible' : 'hidden' }}disabled={!back || !!handoff || !!action?.busy || navigationLocked} onClick={() => { if (back) navigate(back); }}><ArrowLeft size={14} />{t(back === 'providers' ? 'onboarding.flow.backToProviders' : 'onboarding.flow.backToIntro')}</Button></div>- {/* Where a screen puts what is ancillary to the pair above: below it, in normal flow,- so a caption that grows can neither move the anchor nor cover it. */}- <div className="onboarding-action-aside" data-setup-action-aside="" />{(authoritativeBlock || (!!error && !loading)) && <div className="onboarding-flow-error" role="alert"><p>{authoritativeBlock ? t('onboarding.flow.gatewayRequired') : error?.message ?? t('onboarding.connection.readFailed')}</p>{/* Same shape the detection failure already uses one screen over: the sentence@@ -244,7 +268,6 @@ const ProvidersEntry = forwardRef<SetupScreenHandle, ProvidersScreenProps & { onexport function Wizard() {const api = useApi(); const { t } = useTranslation(); const navigate = useNavigate();const { control } = useStatus();- const [platformRecovery, setPlatformRecovery] = useState<SavedPlatformRecovery | null>(null);const [data, setData] = useState<Record<string, any> | null>(null);const [error, setError] = useState<SetupReadFailure | null>(null);const [loading, setLoading] = useState(true);@@ -429,12 +452,6 @@ export function Wizard() {// Writes already issued cannot be recalled; the lease is what stops the next one.let lease = entry.lease;const holds = () => lease === configGeneration.current;- const enabledPlatforms = getEnabledPlatforms(entry.config.raw);- const missing = getPlatformCatalog(entry.config.raw).find((platform) => enabledPlatforms.includes(platform.id) && !platformHasRunnableConfig(entry.config.raw, platform.id));- if (missing) {- setPlatformRecovery({ config: entry.config.raw, descriptor: missing });- return;- }// C4. The gate is correlated over ONE assistant, so the reads that feed it are// taken together and judged together; what the browser must not do is assemble a// verdict out of three facts about three different machines.@@ -528,14 +545,13 @@ export function Wizard() {<main className="onboarding-shell-content"><SetupFlowShell sequence={SETUP_REGISTERED_SCREENS} capability={capability} gatewayEnabled={gatewayEnabled}runtimeRead={runtimeRead} loading={loading} error={error} onRetrySetup={retrySetup}- navigationLocked={Boolean(platformRecovery)} renderScreen={(id, props, ref) => id === 'intro'+ renderScreen={(id, props, ref) => id === 'intro'? <Welcome ref={ref} data={data ?? undefined} active={props.active} onActionChange={props.onActionChange}onNext={(next) => { setData((previous) => ({ ...previous, ...Object(next) })); props.onNavigate(SETUP_REGISTERED_SCREENS[1]); }} />: id === 'providers'? <ProvidersEntry ref={ref} {...props} agentReads={setupAgentReads} onEnter={enterProviders} />: <AgentDetection ref={ref} data={data ?? {}} active={props.active} onActionChange={props.onActionChange}flowState={props.flowState} setFlowState={props.setFlowState} onNavigate={props.onNavigate} agentReads={setupAgentReads}- completionRecovery={platformRecovery ? <SetupPlatformRecovery key={platformRecovery.descriptor.id} saved={platformRecovery} onRepaired={complete} onCancel={() => setPlatformRecovery(null)} /> : undefined}onNext={complete} />}/></main>diff --git a/ui/src/components/onboarding/AssistantRow.tsx b/ui/src/components/onboarding/AssistantRow.tsxindex 6487f5a81..f5d33cbf0 100644--- a/ui/src/components/onboarding/AssistantRow.tsx+++ b/ui/src/components/onboarding/AssistantRow.tsx@@ -1,5 +1,5 @@import type { ReactNode } from 'react';-import { Check, Download, KeyRound, RefreshCw, SlidersHorizontal } from 'lucide-react';+import { Check, ChevronRight, Download, KeyRound, RefreshCw, SlidersHorizontal } from 'lucide-react';import { useTranslation } from 'react-i18next';import { BackendIcon } from '../visual';import { Button } from '../ui/button';@@ -8,6 +8,11 @@ import { Card } from '../ui/card';import { getBackendUiMeta } from '@/lib/agentBackends';import type { AssistantId } from './collaborationTimeline';+/** One card's reading of its current Model Hub route. */+export type AssistantRouteView =+ | { kind: 'pending' | 'failed' | 'unavailable' | 'no-agent-model' }+ | { kind: 'route'; model: string | null; backups: number };+export interface AssistantRowProps {backend: AssistantId;status: 'unknown' | 'ok' | 'missing';@@ -24,11 +29,23 @@ export interface AssistantRowProps {onConfigure: () => void;onAddKey?: () => void;onRefreshConnection?: () => void;+ onRetryRoute?: () => void;connectionPending?: boolean;connectionError?: string;+ routeError?: string;configuringDisabled?: boolean;/** Presentation only. The connection owner must supply confirmed state. */connection?: 'subscription' | 'api_key' | 'hub';+ /** Model Hub is where this setup's models come from, whatever this card's own+ state is — including one whose CLI is not on disk yet. It decides what the+ card offers: an install that also enables, a switch to flip, or its own+ route to review. */+ hubManaged?: boolean;+ /** Whether the assistant is switched on. The pill and the note read from it, so+ the card says the same thing its own switch does. */+ enabled?: boolean;+ /** The route read's evidence; pending and failed reads cannot assert absence. */+ route?: AssistantRouteView;}/**@@ -44,9 +61,43 @@ export interface AssistantRowProps {* which is what keeps that true as either step changes.*/export function AssistantRow({ backend, status, installing, detecting, error, lifecycle, upgrade, enabledControl,- onInstall, onDetect, onConfigure, configuringDisabled = false, connection, onAddKey, onRefreshConnection, connectionPending, connectionError }: AssistantRowProps) {+ onInstall, onDetect, onConfigure, configuringDisabled = false, connection, onAddKey, onRefreshConnection, onRetryRoute, connectionPending, connectionError, routeError,+ hubManaged = false, enabled = false, route }: AssistantRowProps) {const { t } = useTranslation();const label = getBackendUiMeta(backend).label;+ // With Model Hub holding the credentials, a card has three things it can be, and+ // each one has a single next step: install it, switch it on, or look at the route+ // it owns. Anything else the card could say about connections belongs to+ // the other supply modes below.+ const hub = hubManaged || connection === 'hub';+ const native = connection === 'hub' ? undefined : connection;+ const hubState = !hub ? null+ : status === 'ok' ? (enabled ? 'enabled' : 'idle')+ : status === 'missing' ? 'missing'+ : 'checking';+ const routeModel = route?.kind === 'route' ? route.model : null;+ const routeUnknown = route?.kind === 'pending' || route?.kind === 'failed';+ const routeLead = () => (route?.kind === 'route' && route.backups ? t('onboarding.setup.defaultModelWithBackups', { count: route.backups })+ : t('onboarding.setup.defaultModel'));+ // Off, the card still shows the model the assistant would call, so switching it on+ // has no surprise in it. It is a statement then, not a control: no chevron, nothing+ // to press, and the switch above is the only thing that changes it.+ const routeChoice = (live: boolean) => (+ <button type="button" className="onboarding-model-choice" onClick={live ? onConfigure : undefined}+ aria-label={t('onboarding.setup.defaultModelNamed', { name: label })}+ aria-disabled={live ? undefined : true}+ disabled={!live || configuringDisabled || installing || detecting || !!connectionPending}>+ <span>+ <small>{routeUnknown ? t('onboarding.setup.defaultModel') : routeLead()}</small>+ {routeUnknown+ ? <strong className="onboarding-model-choice-pending" aria-hidden="true" />+ : <strong>{routeModel}</strong>}+ </span>+ {live && !routeUnknown && (connectionPending+ ? <RefreshCw size={17} className="motion-safe:animate-spin" />+ : <ChevronRight size={17} />)}+ </button>+ );return (<Card className="onboarding-assistant" aria-label={label}><div className="onboarding-card-identity">@@ -72,7 +123,7 @@ export function AssistantRow({ backend, status, installing, detecting, error, li</Badge>)}{upgrade}- {status === 'missing' && (+ {status === 'missing' && !hub && (<Button type="button" variant="secondary" className="onboarding-life-action" onClick={onInstall} disabled={installing || detecting}>{installing ? <RefreshCw size={14} className="motion-safe:animate-spin" /> : <Download size={14} />}{t(installing ? 'agentDetection.installing' : error ? 'common.retry' : 'onboarding.setup.install')}@@ -92,31 +143,52 @@ export function AssistantRow({ backend, status, installing, detecting, error, liassistant. The frames keep it to one line at every tier, which aper-state sentence is short enough to honour in both languages. */}<p className="onboarding-assistant-note">- {connection === 'hub'- ? t('settings.backends.nativeAuthHubOwned')+ {hubState+ ? t(hubState === 'missing' ? 'onboarding.setup.noteNotInstalled'+ : hubState === 'enabled' || hubState === 'idle'+ ? (route?.kind === 'no-agent-model' ? 'onboarding.setup.noteModelUnset'+ : route?.kind === 'route' && !routeModel ? 'onboarding.setup.noteNoModels'+ : hubState === 'enabled' ? 'onboarding.setup.noteEnabled' : 'onboarding.setup.noteNotEnabled')+ : 'onboarding.setup.noteNotEnabled', { name: label }): status === 'missing'? t('onboarding.setup.installFirstNamed', { name: label })- : connection- ? t(`onboarding.setup.${connection}ConnectedHint`)+ : native+ ? t(`onboarding.setup.${native}ConnectedHint`): t(`onboarding.setup.${backend}Guide`)}</p>{/* One full-width row per connection method, subscription above API Key, andthe connected state wearing the same row with a mint check. */}<div className="onboarding-assistant-actions">- {connection === 'hub' ? (- <button type="button" className="onboarding-method-connected" onClick={onConfigure}- disabled={configuringDisabled || installing || detecting || !!connectionPending}>- {connectionPending ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : <SlidersHorizontal size={16} />}- {t('onboarding.setup.configureRoute')}- </button>- ) : connection ? (+ {hubState === 'checking' ? null : hubState === 'missing' ? (+ <Button type="button" variant="secondary" className="onboarding-method-row" onClick={onInstall} disabled={installing || detecting}>+ {installing ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : <Download size={16} />}+ {t(installing ? 'agentDetection.installing' : error ? 'common.retry' : 'onboarding.setup.installAndEnable')}+ </Button>+ ) : route?.kind === 'no-agent-model' && (hubState === 'idle' || hubState === 'enabled') ? null : hubState === 'idle' ? (+ /* The model it would call, stated but not offered — or, with no route to+ state, the receipt that the binary is already there. */+ routeModel || routeUnknown ? routeChoice(false) : (+ <span className="onboarding-method-receipt"><Check size={16} />{t('onboarding.setup.installedNotEnabled')}</span>+ )+ ) : hubState === 'enabled' ? (+ /* The card shows the model this assistant will call and opens its route.+ With nothing to show yet the button keeps its box, so the card does not+ grow under the pointer when the read lands. */+ routeModel || routeUnknown ? routeChoice(!routeUnknown) : (+ <button type="button" className="onboarding-method-connected" onClick={onConfigure}+ disabled={configuringDisabled || installing || detecting || !!connectionPending}>+ {connectionPending ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : <SlidersHorizontal size={16} />}+ {t('onboarding.setup.configureRoute')}+ </button>+ )+ ) : native ? (/* A button wearing the connected row: it reads as the static receipt thedesign draws, and clicking it still reopens the connection dialog,which is the only way back into a settled connection from this card. */<button type="button" className="onboarding-method-connected" onClick={onConfigure}disabled={configuringDisabled || installing || detecting || !!connectionPending}>{connectionPending ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : <Check size={16} />}- {t(`onboarding.setup.${connection}Connected`)}+ {t(`onboarding.setup.${native}Connected`)}</button>) : (<Button type="button" variant="secondary" className="onboarding-method-row" onClick={onConfigure} disabled={configuringDisabled || installing || detecting || !!connectionPending}>@@ -124,7 +196,7 @@ export function AssistantRow({ backend, status, installing, detecting, error, li{t('onboarding.connection.addSubscription')}</Button>)}- {!connection && onAddKey && (+ {!hub && !native && onAddKey && (<Button type="button" variant="secondary" className="onboarding-method-row" onClick={onAddKey} disabled={configuringDisabled || installing || detecting || !!connectionPending}>{connectionPending ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : <KeyRound size={16} />}{t('onboarding.connection.addKey')}@@ -140,6 +212,10 @@ export function AssistantRow({ backend, status, installing, detecting, error, li{connectionError}{onRefreshConnection && <Button variant="link" size="xs" onClick={onRefreshConnection}>{t('common.retry')}</Button>}</div>}+ {routeError && <div className="onboarding-assistant-error" role="alert">+ {routeError}+ {onRetryRoute && <Button variant="link" size="xs" onClick={onRetryRoute}>{t('common.retry')}</Button>}+ </div>}{error && <div className="onboarding-assistant-error" role="alert"><p>{error.message}</p>{error.output && <details><summary>{t('onboarding.details')}</summary><pre>{error.output}</pre></details>}diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsxindex d18ea2745..f86d30a85 100644--- a/ui/src/components/onboarding/AssistantSetup.test.tsx+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx@@ -11,11 +11,12 @@ import en from '../../i18n/en.json';import type { BackendConnectionState } from '../../context/ApiContext';import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';import type { SetupAction } from './setupFlow';+import { INITIAL_SETUP_FLOW_STATE } from './setupFlow';const mock = vi.hoisted(() => ({ api: {detectCli: vi.fn(), installAgent: vi.fn(), getConfig: vi.fn(), getBackendRuntime: vi.fn(), getBackendConnection: vi.fn(), mutateConfig: vi.fn(), getClaudeAuth: vi.fn(), getCodexAuth: vi.fn(), getOpencodeProviders: vi.fn(), saveClaudeAuth: vi.fn(),listVibeAgents: vi.fn(), getVibeAgent: vi.fn(),-}, models: { getAgentChain: vi.fn(), previewAgentChain: vi.fn(), putAgentChain: vi.fn(), listSources: vi.fn() } }));+}, models: { getAgentChain: vi.fn(), getAgentChains: vi.fn(), previewAgentChain: vi.fn(), putAgentChain: vi.fn(), listSources: vi.fn() } }));vi.mock('../../context/ApiContext', () => ({ useApi: () => mock.api }));vi.mock('../settings/models/modelsApi', async (importOriginal) => {const actual = await importOriginal<typeof import('../settings/models/modelsApi')>();@@ -38,6 +39,25 @@ const next = vi.fn();const shown = (saved: ReturnType<typeof data>, active: boolean, onActionChange: (action: SetupAction) => void) =>wrap(<AgentDetection data={saved} active={active} onActionChange={onActionChange} onNext={next} />, active);const configureAction = () => row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ });+const hubAgent = (enabled = true) => ({+ id: 'claude-claude', name: 'claude', display_name: 'claude', description: null,+ backend: 'claude' as const, model: 'opus-5', reasoning_effort: null,+ enabled, archived: false, archived_at: null, source: 'file', updated_at: '',+ system_prompt: null, created_at: '', metadata: { builtin_default: true },+});+const hubChain = (modelId: string) => ({+ contract_version: 10, backend: 'claude', model_id: 'opus-5',+ manual_override: { hops: [{ source_id: 'src_a', model_id: modelId }] },+ route_origin: 'manual', current: { source_id: 'src_a', model_id: modelId },+ chain: [{ source_id: 'src_a', model_id: modelId, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],+ supply_state: 'ok',+});+const hubReads = {+ read: async () => ({ kind: 'current' as const, value: [{ backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const, named_agents: [{ name: 'claude', effective_model_id: 'opus-5', supply_status: 'ok' as const }] }] }),+ refresh: async () => ({ kind: 'current' as const, value: [] }),+ readValue: async () => [{ backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const, named_agents: [{ name: 'claude', effective_model_id: 'opus-5', supply_status: 'ok' as const }] }],+ invalidate: () => undefined,+};beforeEach(() => {vi.resetAllMocks();mock.api.getConfig.mockResolvedValue(data());@@ -52,10 +72,131 @@ beforeEach(() => {mock.api.getVibeAgent.mockResolvedValue({ ok: false, agent: null });mock.models.listSources.mockResolvedValue([]);mock.models.getAgentChain.mockRejectedValue(new Error('chain unread'));+ mock.models.getAgentChains.mockResolvedValue([]);});afterEach(cleanup);describe('assistant installation presentation', () => {+ it('enables a Hub assistant after a successful install', async () => {+ const saved = data();+ saved.agents.codex.enabled = false;+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: false, enabled: false, auth: 'none',+ application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub',+ }));+ mock.api.installAgent.mockResolvedValue({ ok: true, path: '/isolated/bin/codex', message: '' });+ render(wrap(<AgentDetection data={{ ...saved, capabilities: { model_hub: { enabled: true } } }} onNext={vi.fn()} />));+ fireEvent.click(await row('Codex').findByRole('button', { name: 'Install and enable' }));+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledWith(+ expect.arrayContaining([expect.objectContaining({ kind: 'set', path: ['agents', 'codex', 'enabled'], value: true })]),+ ));+ });+ it('does not enable a Direct assistant after the ordinary Install action', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.codex.enabled = false;+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: false, enabled: false, auth: 'none',+ application: 'applied', ready: false, entry_eligible: false, supply_mode: 'direct',+ }));+ const install = pending<{ ok: boolean; path: string; message: string }>();+ mock.api.installAgent.mockReturnValue(install.promise);+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));+ await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(3));+ fireEvent.click(row('Codex').getByRole('button', { name: 'Install' }));+ await act(async () => install.resolve({ ok: true, path: '/isolated/bin/codex', message: '' }));+ expect(row('Codex').getByRole('switch').getAttribute('aria-checked')).toBe('false');+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ });+ it.each(['unknown', 'failed'] as const)('does not promise Hub enablement when the mode read is %s', async (outcome) => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.codex.enabled = false;+ mock.api.getBackendConnection.mockImplementation(async (backend) => {+ if (backend === 'codex' && outcome === 'failed') throw new Error('unreadable');+ return { ok: true, backend, installed: false, enabled: false, auth: 'none',+ application: 'applied', ready: false, entry_eligible: false,+ supply_mode: backend === 'codex' ? undefined : 'direct' };+ });+ const install = pending<{ ok: boolean; path: string; message: string }>();+ mock.api.installAgent.mockReturnValue(install.promise);+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));+ await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(3));+ expect(row('Codex').queryByRole('button', { name: 'Install and enable' })).toBeNull();+ fireEvent.click(row('Codex').getByRole('button', { name: 'Install' }));+ await act(async () => install.resolve({ ok: true, path: '/isolated/bin/codex', message: '' }));+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ });+ it('does not auto-enable if a Hub install changes to Direct before it finishes', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.codex.enabled = false;+ let mode: 'hub' | 'direct' = 'hub';+ const install = pending<{ ok: boolean; path: string; message: string }>();+ mock.api.installAgent.mockReturnValue(install.promise);+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: false, enabled: false, auth: 'none',+ application: 'applied', ready: false, entry_eligible: false,+ supply_mode: backend === 'codex' ? mode : 'direct',+ }));+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));+ fireEvent.click(await row('Codex').findByRole('button', { name: 'Install and enable' }));+ mode = 'direct';+ await act(async () => install.resolve({ ok: true, path: '/isolated/bin/codex', message: '' }));+ expect(mock.api.getBackendConnection.mock.calls.filter(([backend]) => backend === 'codex').length).toBeGreaterThanOrEqual(4);+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ });+ it('does not enable from a stale Hub read when reentry offered ordinary Install', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.enabled = false;+ mock.api.detectCli.mockResolvedValue({ found: false, path: '' });+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: false, enabled: false, auth: 'none',+ application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub',+ }));+ const install = pending<{ ok: boolean; path: string; message: string }>();+ mock.api.installAgent.mockReturnValue(install.promise);+ let reenter = false;+ let clickedOrdinaryInstall = false;+ const onActionChange = vi.fn(() => {+ if (!reenter || clickedOrdinaryInstall) return;+ const action = row('Claude Code').getByRole<HTMLButtonElement>('button', { name: 'Install' });+ clickedOrdinaryInstall = true;+ action.click();+ });+ const props = { data: saved, onNext: vi.fn(), onActionChange };+ const view = render(wrap(<AgentDetection {...props} active />));+ await row('Claude Code').findByRole('button', { name: 'Install and enable' });+ view.rerender(wrap(<AgentDetection {...props} active={false} />, false));+ reenter = true;+ await act(async () => view.rerender(wrap(<AgentDetection {...props} active />, true)));+ expect(clickedOrdinaryInstall).toBe(true);+ expect(mock.api.installAgent).toHaveBeenCalledWith('claude');++ await act(async () => install.resolve({ ok: true, path: '/isolated/bin/claude', message: '' }));+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ });+ it('does not promise enablement when a missing assistant has conflicting Hub and Direct reads', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.enabled = false;+ mock.api.detectCli.mockResolvedValue({ found: false, path: '' });+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: false, enabled: false, auth: 'none',+ application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub',+ }));+ const listed = pending<[]>();+ mock.models.listSources.mockReturnValue(listed.promise);+ const install = pending<{ ok: boolean; path: string; message: string }>();+ mock.api.installAgent.mockReturnValue(install.promise);+ const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [+ { backend: 'claude' as const, cli_present: false, mode: 'direct' as const, menu_kind: 'fixed' as const },+ ] }) };+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));+ await waitFor(() => expect(mock.models.listSources).toHaveBeenCalled());+ await act(async () => listed.resolve([]));++ expect(row('Claude Code').queryByRole('button', { name: 'Install and enable' })).toBeNull();+ fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));+ await act(async () => install.resolve({ ok: true, path: '/isolated/bin/claude', message: '' }));+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ });it('keeps fixed row order, independent installs and retry details', async () => {let finishClaude!: (value: unknown) => void;mock.api.installAgent.mockImplementation((name) => name === 'claude'@@ -73,17 +214,42 @@ describe('assistant installation presentation', () => {}fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));fireEvent.click(row('Codex').getByRole('button', { name: 'Install' }));- await waitFor(() => expect(row('Codex').getByRole('button', { name: 'Installed' })).toBeTruthy());+ await waitFor(() => expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());await act(async () => finishClaude({ ok: false, message: 'Network unavailable', output: 'Installer exited 1' }));expect(row('Claude Code').getByText('Network unavailable')).toBeTruthy();expect(row('Claude Code').getByText('View details')).toBeTruthy();- expect(row('Codex').getByRole('button', { name: 'Installed' })).toBeTruthy();+ expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();expect(row('OpenCode').getByText('Not installed')).toBeTruthy();mock.api.installAgent.mockResolvedValue({ ok: true, path: '/isolated/bin/claude' });fireEvent.click(row('Claude Code').getByRole('button', { name: 'Retry' }));- await waitFor(() => expect(row('Claude Code').getByRole('button', { name: 'Installed' })).toBeTruthy());+ await waitFor(() => expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());expect(mock.api.detectCli).toHaveBeenCalledWith('/isolated/bin/claude');- expect(row('Codex').getByRole('button', { name: 'Installed' })).toBeTruthy();+ expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();+ });+ it('does not undo a newer disable when an install finishes', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.enabled = false;+ let enabled = false;+ let finish!: (value: unknown) => void;+ mock.api.installAgent.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ mock.api.mutateConfig.mockImplementation(async (mutations) => {+ enabled = mutations[0].value;+ return {};+ });+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: false, enabled: backend === 'claude' ? enabled : true,+ auth: 'none', application: 'applied', ready: false, entry_eligible: false,+ supply_mode: 'hub',+ }));+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={hubReads} />));+ fireEvent.click(await row('Claude Code').findByRole('button', { name: en.onboarding.setup.installAndEnable }));+ const toggle = row('Claude Code').getByRole('switch');+ fireEvent.click(toggle);+ fireEvent.click(toggle);+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2));+ await act(async () => finish({ ok: true, path: '/isolated/bin/claude' }));+ expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2);+ expect(enabled).toBe(false);});it('a failed install settlement refreshes connection state without admitting stale readiness', async () => {mock.api.getBackendConnection.mockImplementation(async (backend) => ({ ok: true, backend, installed: false, enabled: true, auth: 'none', application: 'applied', ready: false, entry_eligible: false }));@@ -137,7 +303,7 @@ describe('assistant installation presentation', () => {expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false);});it('opens the setup route editor when the backend is already Hub-owned', async () => {- const saved = data(); saved.agents.claude.status = 'ok';+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } }; saved.agents.claude.status = 'ok';mock.api.getBackendConnection.mockImplementation(async (backend) => ({ok: true,backend,@@ -157,14 +323,16 @@ describe('assistant installation presentation', () => {mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [agent], default_agent_name: 'claude' });mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent });mock.models.listSources.mockResolvedValue([]);- mock.models.getAgentChain.mockResolvedValue({+ const chain = {contract_version: 10, backend: 'claude', model_id: 'opus-5',manual_override: { hops: [{ source_id: 'src_a', model_id: 'opus-5' }] },route_origin: 'manual', current: { source_id: 'src_a', model_id: 'opus-5' },chain: [{ source_id: 'src_a', model_id: 'opus-5', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],supply_state: 'ok',- });- const flowState = { providerSelection: { scan: null, selectedBackends: [] }, importedCount: 0, addedThroughMore: [], routeOrder: [], routeOrderDirty: false };+ };+ mock.models.getAgentChains.mockResolvedValue([chain]);+ mock.models.getAgentChain.mockResolvedValue(chain);+ const flowState = INITIAL_SETUP_FLOW_STATE;const agentReads = {read: async () => ({ kind: 'current' as const, value: [{ backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const, named_agents: [{ name: 'claude', effective_model_id: 'opus-5', supply_status: 'ok' as const }] }] }),refresh: async () => ({ kind: 'current' as const, value: [] }),@@ -172,11 +340,14 @@ describe('assistant installation presentation', () => {invalidate: () => undefined,};render(wrap(<AgentDetection data={saved} onNext={vi.fn()} flowState={flowState} setFlowState={vi.fn()} onNavigate={vi.fn()} agentReads={agentReads} />));- const action = await row('Claude Code').findByRole('button', { name: en.onboarding.setup.configureRoute });+ await waitFor(() => expect(mock.api.getVibeAgent).toHaveBeenCalledWith('claude', { cache: false }));+ await waitFor(() => expect(mock.models.getAgentChains).toHaveBeenCalledWith('claude'));+ expect(await mock.models.getAgentChains.mock.results.at(-1)?.value).toEqual([chain]);+ const action = await row('Claude Code').findByRole('button', { name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code') });const enter = screen.getByRole('button', { name: 'Enter workspace' });expect(enter.hasAttribute('disabled')).toBe(true);fireEvent.click(action);- expect(await screen.findByRole('dialog', { name: en.onboarding.route.title })).toBeTruthy();+ expect(await screen.findByRole('dialog')).toBeTruthy();expect(screen.getByTestId('location').textContent).toBe('/');expect(enter.hasAttribute('disabled')).toBe(true);});@@ -203,7 +374,7 @@ describe('assistant installation presentation', () => {const back = vi.fn();render(wrap(<AgentDetection data={data()} onNext={vi.fn()} onBack={back} />));fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));- await waitFor(() => expect(row('Claude Code').getByRole('button', { name: 'Installed' })).toBeTruthy());+ await waitFor(() => expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());fireEvent.click(row('Codex').getByRole('switch'));fireEvent.click(screen.getByRole('button', { name: 'Back' }));expect(back).toHaveBeenCalledWith({ agents: expect.objectContaining({@@ -241,13 +412,13 @@ describe('assistant installation presentation', () => {? Promise.resolve({ found: true, path: '/isolated/external/claude' }): name === 'codex' ? Promise.resolve({ found: false }) : Promise.reject(new Error('Probe unavailable')));fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));- await waitFor(() => expect(row('Claude Code').getByRole('button', { name: 'Installed' })).toBeTruthy());+ await waitFor(() => expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());expect(row('Claude Code').queryByRole('alert')).toBeNull();expect(row('Claude Code').queryByText('Details claude')).toBeNull();expect(row('Codex').getByText('Failed codex')).toBeTruthy();expect(row('Codex').getByText('Details codex')).toBeTruthy();expect(row('OpenCode').getByText('Error: Probe unavailable')).toBeTruthy();- expect(row('OpenCode').queryByRole('button', { name: 'Installed' })).toBeNull();+ expect(row('OpenCode').queryByRole('button', { name: en.onboarding.setup.enabled })).toBeNull();// A rejected probe retains install evidence; a later missing result shows it again.mock.api.detectCli.mockResolvedValue({ found: false });fireEvent.click(row('OpenCode').getByRole('button', { name: 'Retry' }));@@ -268,12 +439,12 @@ describe('assistant installation presentation', () => {fireEvent.click(row('Codex').getByRole('button', { name: 'Install' }));expect(mock.api.installAgent).toHaveBeenCalledWith('codex');await act(async () => finishInstall({ ok: true, path: '/isolated/bin/codex' }));- expect(row('Codex').getByRole('button', { name: 'Installed' })).toBeTruthy();+ expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();expect(row('Codex').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }).hasAttribute('disabled')).toBe(true);expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);await act(async () => finishConfig(data()));expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false);- expect(row('Codex').getByRole('button', { name: 'Installed' })).toBeTruthy();+ expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();});it('settles an enable write that lands while the screen is away, and reads nothing from hiding', async () => {const saved = data(); saved.agents.claude.status = 'ok';@@ -351,14 +522,14 @@ describe('assistant installation presentation', () => {// retained screen mounted. That is the one probe the stale path ever gets.await waitFor(() => expect(probes('/stale/claude')).toBe(1));fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));- await waitFor(() => expect(row('Claude Code').getByRole('button', { name: 'Installed' })).toBeTruthy());+ await waitFor(() => expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());const retainedProbes = probes('/retained/claude');view.rerender(shown(saved, false, publish));view.rerender(shown(saved, true, publish));await waitFor(() => expect(probes('/retained/claude')).toBe(retainedProbes + 1));expect(probes('/stale/claude')).toBe(1);- expect(row('Claude Code').getByRole('button', { name: 'Installed' })).toBeTruthy();+ expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();});it('does not enable entry from installed, draining, failed or unknown states', async () => {for (const application of ['draining', 'failed', 'unknown']) {@@ -382,6 +553,541 @@ describe('assistant installation presentation', () => {fireEvent.click(screen.getByRole('button', { name: 'Subscription connected' }));expect(configure).toHaveBeenCalledOnce();});+ it('does not offer route repair when an installed Hub assistant has no selected model', () => {+ render(wrap(<AssistantRow backend="claude" status="ok" installing={false} detecting={false}+ lifecycle={<span>Enabled</span>} enabledControl={null} enabled hubManaged+ onInstall={vi.fn()} onDetect={vi.fn()} onConfigure={vi.fn()}+ route={{ kind: 'no-agent-model' }} />));+ expect(screen.getByText(en.onboarding.setup.noteModelUnset)).toBeTruthy();+ expect(screen.queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();+ });+ it.each([+ ['no-agent-model', en.onboarding.setup.noteModelUnset],+ ['empty-route', en.onboarding.setup.noteNoModels],+ ] as const)('shows %s on a disabled Hub card without offering an editor', (kind, note) => {+ const configure = vi.fn();+ render(wrap(<AssistantRow backend="claude" status="ok" installing={false} detecting={false}+ lifecycle={<span>Installed</span>} enabledControl={null} hubManaged+ onInstall={vi.fn()} onDetect={vi.fn()} onConfigure={configure}+ route={kind === 'no-agent-model' ? { kind } : { kind: 'route', model: null, backups: 0 }} />));+ expect(screen.getByText(note)).toBeTruthy();+ expect(screen.queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();+ expect(configure).not.toHaveBeenCalled();+ });+});++describe('Hub route refresh', () => {+ it.each(['direct', 'hub'] as const)('uses current %s route ownership when the connection read fails', async (mode) => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ mock.api.getBackendConnection.mockRejectedValue(new Error('connection unreadable'));+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });+ mock.models.getAgentChains.mockResolvedValue([hubChain('model-a')]);+ mock.models.getAgentChain.mockResolvedValue(hubChain('model-a'));+ const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [+ { backend: 'claude' as const, cli_present: true, mode, menu_kind: 'fixed' as const },+ ] }) };+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));++ if (mode === 'direct') {+ const action = await row('Claude Code').findByRole<HTMLButtonElement>('button', { name: /Add subscription/ });+ await waitFor(() => expect(action.disabled).toBe(false));+ expect(row('Claude Code').queryByRole('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ })).toBeNull();+ fireEvent.click(action);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ expect(mock.models.getAgentChains).not.toHaveBeenCalled();+ } else {+ const action = await row('Claude Code').findByRole<HTMLButtonElement>('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ });+ await waitFor(() => expect(action.disabled).toBe(false));+ fireEvent.click(action);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ expect(mock.models.getAgentChains).toHaveBeenCalledWith('claude');+ }+ });++ it.each([+ ['hub', 'direct'],+ ['direct', 'hub'],+ ] as const)('keeps conflicting connection %s and route %s ownership in an unknown state', async (connectionMode, routeMode) => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: connectionMode,+ }));+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });+ mock.models.getAgentChains.mockResolvedValue([hubChain('model-a')]);+ const listed = pending<[]>();+ mock.models.listSources.mockReturnValue(listed.promise);+ let currentSupplyMode: 'hub' | 'direct' = routeMode;+ const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [+ { backend: 'claude' as const, cli_present: true, mode: currentSupplyMode, menu_kind: 'fixed' as const },+ ] }) };+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));+ await waitFor(() => expect(mock.models.listSources).toHaveBeenCalled());+ await act(async () => listed.resolve([]));++ expect(row('Claude Code').queryByRole('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ })).toBeNull();+ const action = row('Claude Code').getByRole<HTMLButtonElement>('button', { name: /Add subscription/ });+ expect(action.disabled).toBe(true);+ action.removeAttribute('disabled');+ fireEvent.click(action);+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(row('Claude Code').getByText(en.onboarding.setup.ownershipChanged)).toBeTruthy();+ const connectionReads = mock.api.getBackendConnection.mock.calls.length;+ currentSupplyMode = connectionMode;+ fireEvent.click(row('Claude Code').getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(mock.api.getBackendConnection.mock.calls.length).toBeGreaterThan(connectionReads));+ if (connectionMode === 'hub') {+ await waitFor(() => expect(row('Claude Code').getByText('model-a')).toBeTruthy());+ } else {+ await waitFor(() => expect(row('Claude Code').getByRole<HTMLButtonElement>('button', { name: 'API Key connected' }).disabled).toBe(false));+ }+ expect(row('Claude Code').queryByText(en.onboarding.setup.ownershipChanged)).toBeNull();+ });++ it('keeps configuration disabled when neither ownership read succeeds', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ mock.api.getBackendConnection.mockRejectedValue(new Error('connection unreadable'));+ const reads = { ...hubReads, read: async () => { throw new Error('route unreadable'); } };+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));+ await row('Claude Code').findByText('Error: connection unreadable');+ const action = row('Claude Code').getByRole<HTMLButtonElement>('button', { name: /Add subscription/ });+ expect(action.disabled).toBe(true);+ action.removeAttribute('disabled');+ fireEvent.click(action);+ expect(screen.queryByRole('dialog')).toBeNull();+ });++ it('does not reuse a Direct connection while rereading Hub ownership on reentry', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ let mode: 'direct' | 'hub' = 'direct';+ const nextConnection = pending<BackendConnectionState>();+ const nextSupply = pending<Awaited<ReturnType<typeof hubReads.read>>>();+ mock.api.getBackendConnection.mockImplementation(async (backend) => backend === 'claude' && mode === 'hub'+ ? nextConnection.promise+ : { ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: mode });+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });+ mock.models.getAgentChains.mockResolvedValue([hubChain('model-a')]);+ mock.models.getAgentChain.mockResolvedValue(hubChain('model-a'));+ const reads = { ...hubReads, read: async () => mode === 'hub' ? nextSupply.promise+ : { kind: 'current' as const, value: [+ { backend: 'claude' as const, cli_present: true, mode: 'direct' as const, menu_kind: 'fixed' as const },+ ] } };+ const props = { data: saved, onNext: vi.fn(), onNavigate: vi.fn(), agentReads: reads };+ const view = render(wrap(<AgentDetection {...props} active />));+ await waitFor(() => expect(row('Claude Code').getByRole<HTMLButtonElement>('button', { name: 'API Key connected' }).disabled).toBe(false));+ view.rerender(wrap(<AgentDetection {...props} active={false} />, false));+ mode = 'hub';+ view.rerender(wrap(<AgentDetection {...props} active />, true));+ const staleAction = row('Claude Code').getByRole<HTMLButtonElement>('button', { name: /Add subscription/ });+ expect(staleAction.disabled).toBe(true);+ staleAction.removeAttribute('disabled');+ fireEvent.click(staleAction);+ expect(screen.queryByRole('dialog')).toBeNull();++ await act(async () => {+ nextConnection.resolve({ ok: true, backend: 'claude', installed: true, enabled: true,+ auth: 'none', application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub' });+ nextSupply.resolve(await hubReads.read());+ });+ const currentAction = await row('Claude Code').findByRole<HTMLButtonElement>('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ });+ await waitFor(() => expect(currentAction.disabled).toBe(false));+ fireEvent.click(currentAction);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ });++ it('keeps a failed route read visible and retries it without claiming the model is unset', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });+ mock.models.getAgentChains.mockRejectedValueOnce(new Error('offline')).mockResolvedValue([hubChain('model-a')]);+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} flowState={INITIAL_SETUP_FLOW_STATE}+ setFlowState={vi.fn()} onNavigate={vi.fn()} agentReads={hubReads} />));++ await waitFor(() => expect(row('Claude Code').getByText(en.settings.models.routeDialog.fail.reconcileRead)).toBeTruthy());+ expect(row('Claude Code').queryByText(en.onboarding.setup.noteModelUnset)).toBeNull();+ expect(row('Claude Code').queryByText(en.onboarding.setup.noteNoModels)).toBeNull();+ expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();+ expect(row('Claude Code').getByRole('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ })).toHaveProperty('disabled', true);+ const connectionReads = mock.api.getBackendConnection.mock.calls.length;+ fireEvent.click(row('Claude Code').getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(row('Claude Code').getByText('model-a')).toBeTruthy());+ expect(row('Claude Code').queryByText(en.settings.models.routeDialog.fail.reconcileRead)).toBeNull();+ expect(mock.models.getAgentChains).toHaveBeenCalledTimes(2);+ expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(connectionReads);+ });++ it.each(['chain', 'detail'] as const)('isolates a failed %s read to its assistant', async (failure) => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ saved.agents.codex.status = 'ok';+ const codexAgent = { ...hubAgent(), id: 'codex-codex', name: 'codex', backend: 'codex' as const };+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent(), codexAgent], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockImplementation(async (name) => {+ if (failure === 'detail' && name === 'claude') throw new Error('detail unreadable');+ return { ok: true, agent: name === 'codex' ? codexAgent : hubAgent() };+ });+ mock.models.getAgentChains.mockImplementation(async (backend) => {+ if (failure === 'chain' && backend === 'claude') throw new Error('chain unreadable');+ return [{ ...hubChain('model-a'), backend }];+ });+ mock.models.getAgentChain.mockResolvedValue({ ...hubChain('model-a'), backend: 'codex' });+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',+ }));+ const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [+ { backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const },+ { backend: 'codex' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'open' as const },+ ] }) };+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));+ await row('Claude Code').findByText(en.settings.models.routeDialog.fail.reconcileRead);+ expect(row('Codex').queryByText(en.settings.models.routeDialog.fail.reconcileRead)).toBeNull();+ const action = row('Codex').getByRole<HTMLButtonElement>('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Codex'),+ });+ expect(action.disabled).toBe(false);+ fireEvent.click(action);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ });++ it('lets a ready assistant edit while another chain read remains pending', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ saved.agents.codex.status = 'ok';+ const codexAgent = { ...hubAgent(), id: 'codex-codex', name: 'codex', backend: 'codex' as const };+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent(), codexAgent], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockImplementation(async (name) => ({ ok: true, agent: name === 'codex' ? codexAgent : hubAgent() }));+ const delayed = pending<ReturnType<typeof hubChain>[]>();+ mock.models.getAgentChains.mockImplementation((backend) => backend === 'claude'+ ? delayed.promise : Promise.resolve([{ ...hubChain('model-a'), backend }]));+ mock.models.getAgentChain.mockResolvedValue({ ...hubChain('model-a'), backend: 'codex' });+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',+ }));+ const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [+ { backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const },+ { backend: 'codex' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'open' as const },+ ] }) };+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));+ const action = await row('Codex').findByRole<HTMLButtonElement>('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Codex'),+ });+ await waitFor(() => expect(action.disabled).toBe(false));+ expect(row('Claude Code').getByRole('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ })).toHaveProperty('disabled', true);+ fireEvent.click(action);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ await act(async () => delayed.resolve([hubChain('model-a')]));+ });++ it('does not use an Agent archived after the brief read as a route target', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ saved.agents.codex.status = 'ok';+ const codexAgent = { ...hubAgent(), id: 'codex-codex', name: 'codex', backend: 'codex' as const };+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent(), codexAgent], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockImplementation(async (name) => ({ ok: true,+ agent: name === 'claude' ? { ...hubAgent(), archived: true } : codexAgent }));+ mock.models.getAgentChains.mockImplementation(async (backend) => [{ ...hubChain('model-a'), backend }]);+ mock.models.getAgentChain.mockResolvedValue({ ...hubChain('model-a'), backend: 'codex' });+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',+ }));+ const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [+ { backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const },+ { backend: 'codex' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'open' as const },+ ] }) };+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));+ await row('Claude Code').findByText(en.onboarding.setup.noteModelUnset);+ expect(row('Claude Code').queryByText('model-a')).toBeNull();+ expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();+ expect(mock.models.getAgentChains).not.toHaveBeenCalledWith('claude');+ const codexAction = row('Codex').getByRole<HTMLButtonElement>('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Codex'),+ });+ expect(codexAction.disabled).toBe(false);+ fireEvent.click(codexAction);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ });++ it('stops after a confirmed backend-named target, ignoring unreadable custom Agents', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ const custom = { ...hubAgent(), id: 'custom', name: 'custom' };+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [custom, hubAgent()], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockImplementation(async (name) => {+ if (name === 'custom') throw new Error('unreadable custom Agent');+ return { ok: true, agent: hubAgent() };+ });+ mock.models.getAgentChains.mockResolvedValue([hubChain('model-a')]);+ mock.models.getAgentChain.mockResolvedValue(hubChain('model-a'));+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',+ }));+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={hubReads} />));+ const action = await row('Claude Code').findByRole<HTMLButtonElement>('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ });+ await waitFor(() => expect(action.disabled).toBe(false));+ expect(mock.api.getVibeAgent.mock.calls.filter(([name]) => name === 'custom')).toHaveLength(0);+ fireEvent.click(action);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ });++ it('keeps an unreadable higher-priority target unknown instead of falling back', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ const fallback = { ...hubAgent(), id: 'fallback', name: 'default' };+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [fallback, hubAgent()], default_agent_name: 'default' });+ mock.api.getVibeAgent.mockImplementation(async (name) => {+ if (name === 'claude') throw new Error('unreadable designated Agent');+ return { ok: true, agent: fallback };+ });+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',+ }));+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={hubReads} />));+ await row('Claude Code').findByText(en.settings.models.routeDialog.fail.reconcileRead);+ expect(mock.api.getVibeAgent.mock.calls.filter(([name]) => name === 'default')).toHaveLength(0);+ expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();+ expect(mock.models.getAgentChains).not.toHaveBeenCalledWith('claude');+ });++ it('uses the next current builtin after an archived detail, in stable name order', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ const named = { ...hubAgent(), name: 'zeta', model: 'zeta-model' };+ const earlier = { ...hubAgent(), name: 'alpha', model: 'alpha-model' };+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [named, earlier, hubAgent()], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockImplementation(async (name) => ({ ok: true,+ agent: name === 'claude' ? { ...hubAgent(), archived: true } : name === 'alpha' ? earlier : named }));+ mock.models.getAgentChains.mockResolvedValue([{ ...hubChain('model-a'), model_id: 'alpha-model' }]);+ mock.models.getAgentChain.mockResolvedValue({ ...hubChain('model-a'), model_id: 'alpha-model' });+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',+ }));+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={hubReads} />));+ const action = await row('Claude Code').findByRole<HTMLButtonElement>('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ });+ await waitFor(() => expect(action.disabled).toBe(false));+ expect(mock.api.getVibeAgent.mock.calls.filter(([name]) => ['claude', 'alpha', 'zeta'].includes(name))+ .map(([name]) => name)).toEqual(['claude', 'alpha']);+ fireEvent.click(action);+ expect(within(await screen.findByRole('dialog')).getByText('alpha-model · Route chain')).toBeTruthy();+ });++ it('does not borrow a menu label from another backend for an upstream hop', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });+ mock.models.getAgentChains.mockResolvedValue([hubChain('shared-id')]);+ mock.models.listSources.mockResolvedValue([{ id: 'src_a', models: [] }]);+ const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [+ { backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const },+ { backend: 'codex' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const,+ catalog_models: [{ id: 'shared-id', display_name: 'Wrong menu label' }] },+ ] }) };+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',+ }));+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));+ await row('Claude Code').findByText('shared-id');+ expect(row('Claude Code').queryByText('Wrong menu label')).toBeNull();+ });++ it('distinguishes a confirmed missing Agent model from a configured model with an empty chain', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ let selectedModel: string | null = null;+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockImplementation(async () => ({ ok: true, agent: { ...hubAgent(), model: selectedModel } }));+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',+ }));+ mock.models.getAgentChains.mockResolvedValue([]);+ const props = { data: saved, onNext: vi.fn(), onNavigate: vi.fn(), agentReads: hubReads };+ const view = render(wrap(<AgentDetection {...props} active />));+ await row('Claude Code').findByText(en.onboarding.setup.noteModelUnset);+ expect(row('Claude Code').queryByText(en.onboarding.setup.noteNoModels)).toBeNull();+ expect(mock.models.getAgentChains).not.toHaveBeenCalled();++ view.rerender(wrap(<AgentDetection {...props} active={false} />, false));+ selectedModel = 'opus-5';+ view.rerender(wrap(<AgentDetection {...props} active />, true));+ await row('Claude Code').findByText(en.onboarding.setup.noteNoModels);+ expect(row('Claude Code').queryByText(en.onboarding.setup.noteModelUnset)).toBeNull();+ expect(mock.models.getAgentChains).toHaveBeenCalledWith('claude');+ const action = row('Claude Code').getByRole<HTMLButtonElement>('button', { name: en.onboarding.setup.configureRoute });+ expect(action.disabled).toBe(false);+ fireEvent.click(action);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ });++ it('refreshes connection and route ownership when a route dialog closes after Hub becomes Direct', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ let mode: 'hub' | 'direct' = 'hub';+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });+ mock.models.getAgentChains.mockResolvedValue([hubChain('model-a')]);+ mock.models.getAgentChain.mockResolvedValue(hubChain('model-a'));+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: mode,+ }));+ const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [+ { backend: 'claude' as const, cli_present: true, mode, menu_kind: 'fixed' as const },+ ] }) };+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));+ const routeAction = await row('Claude Code').findByRole<HTMLButtonElement>('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ });+ await waitFor(() => expect(routeAction.disabled).toBe(false));+ fireEvent.click(routeAction);+ const dialog = await screen.findByRole('dialog');+ mode = 'direct';+ const priorConnectionReads = mock.api.getBackendConnection.mock.calls.length;+ fireEvent.click(dialog.querySelector('.model-hub-route-close') as HTMLButtonElement);+ await waitFor(() => expect(mock.api.getBackendConnection.mock.calls.length).toBeGreaterThan(priorConnectionReads));+ await waitFor(() => expect(row('Claude Code').getByRole<HTMLButtonElement>('button', { name: 'API Key connected' }).disabled).toBe(false));+ expect(row('Claude Code').queryByText(en.onboarding.setup.ownershipChanged)).toBeNull();+ expect(row('Claude Code').queryByRole('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ })).toBeNull();+ });++ it('shows a disabled builtin assistant its stored route without opening the editor', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.opencode.status = 'ok';+ saved.agents.opencode.enabled = false;+ const agent = { ...hubAgent(false), id: 'opencode-opencode', name: 'opencode',+ display_name: 'opencode', backend: 'opencode' as const, model: 'gpt-5.6-sol' };+ mock.api.listVibeAgents.mockImplementation(async ({ includeDisabled }) => ({+ ok: true, agents: includeDisabled ? [agent] : [], default_agent_name: null,+ }));+ mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent });+ let opencodeEnabled = false;+ mock.api.mutateConfig.mockImplementation(async () => {+ opencodeEnabled = true;+ return {};+ });+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: backend !== 'opencode' || opencodeEnabled, auth: 'api_key',+ application: 'applied', ready: backend !== 'opencode' || opencodeEnabled,+ entry_eligible: backend !== 'opencode' || opencodeEnabled, supply_mode: 'hub',+ }));+ mock.models.listSources.mockResolvedValue([{ id: 'src_a', models: [{ id: 'gpt-5.6-sol', display_name: 'GPT-5.6-Sol' }] }]);+ mock.models.getAgentChains.mockResolvedValue([{ ...hubChain('gpt-5.6-sol'), backend: 'opencode', model_id: 'gpt-5.6-sol',+ chain: [+ { source_id: 'src_a', model_id: 'gpt-5.6-sol', channel: 'hub', health: 'healthy', runnable: true },+ { source_id: 'src_a', model_id: 'claude-opus-5-5', channel: 'hub', health: 'healthy', runnable: true },+ ],+ }]);+ const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [+ { backend: 'opencode' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'open' as const },+ ] }) };+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} flowState={INITIAL_SETUP_FLOW_STATE}+ setFlowState={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));+ const choice = await row('OpenCode').findByRole('button', { name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'OpenCode') });+ await waitFor(() => expect(row('OpenCode').getByText('GPT-5.6-Sol')).toBeTruthy());+ expect(choice.textContent).toContain('1 backup');+ expect(choice).toHaveProperty('disabled', true);+ fireEvent.click(choice);+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(mock.api.listVibeAgents).toHaveBeenCalledWith({ cache: false, includeDisabled: true });+ fireEvent.click(row('OpenCode').getByRole('switch', { name: 'Enable OpenCode' }));+ await waitFor(() => expect(row('OpenCode').getByRole('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'OpenCode'),+ })).toHaveProperty('disabled', false));+ });++ it('keeps an explicitly Direct assistant out of Hub routing', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });+ mock.models.getAgentChain.mockResolvedValue(hubChain('model-a'));+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({+ ok: true, backend, installed: true, enabled: true, auth: 'api_key',+ application: 'applied', ready: true, entry_eligible: true, supply_mode: 'direct',+ }));+ const directReads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [{ backend: 'claude' as const, cli_present: true, mode: 'direct' as const, menu_kind: 'fixed' as const }] }) };+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} flowState={INITIAL_SETUP_FLOW_STATE}+ setFlowState={vi.fn()} onNavigate={vi.fn()} agentReads={directReads} />));+ await waitFor(() => expect(mock.api.listVibeAgents).toHaveBeenCalled());+ expect(mock.models.getAgentChains).not.toHaveBeenCalled();+ expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();+ expect(row('Claude Code').queryByText(en.onboarding.setup.defaultModel)).toBeNull();+ });++ it('cannot open a stale route while re-reading a changed Agent model on reentry', async () => {+ const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };+ saved.agents.claude.status = 'ok';+ let designatedModel = 'model-A';+ const listed = { ...hubAgent(), model: designatedModel };+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [listed], default_agent_name: 'claude' });+ mock.api.getVibeAgent.mockImplementation(async () => ({ ok: true, agent: { ...listed, model: designatedModel } }));+ mock.models.getAgentChains.mockResolvedValue([{ ...hubChain('hop-A'), model_id: 'model-A' }]);+ const flowState = { ...INITIAL_SETUP_FLOW_STATE };+ const setFlowState = vi.fn();+ const props = { data: saved, onNext: vi.fn(), flowState, setFlowState, onNavigate: vi.fn(), agentReads: hubReads };+ const view = render(wrap(<AgentDetection {...props} active />));+ const routeAction = () => row('Claude Code').getByRole<HTMLButtonElement>('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ });+ await waitFor(() => expect(row('Claude Code').getByText('hop-A')).toBeTruthy());+ expect(routeAction().disabled).toBe(false);+ view.rerender(wrap(<AgentDetection {...props} active={false} />, false));+ designatedModel = 'model-B';+ const delayed = pending<ReturnType<typeof hubChain>[]>();+ mock.models.getAgentChains.mockReturnValue(delayed.promise);+ view.rerender(wrap(<AgentDetection {...props} active />));+ await waitFor(() => expect(mock.models.getAgentChains).toHaveBeenCalledTimes(2));+ const pendingAction = row('Claude Code').getByRole<HTMLButtonElement>('button', {+ name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),+ });+ expect(pendingAction.disabled).toBe(true);+ expect(row('Claude Code').queryByText(en.onboarding.setup.noteNoModels)).toBeNull();+ pendingAction.removeAttribute('disabled');+ fireEvent.click(pendingAction);+ expect(screen.queryByRole('dialog')).toBeNull();++ await act(async () => delayed.resolve([{ ...hubChain('hop-B'), model_id: 'model-B' }]));+ await waitFor(() => expect(row('Claude Code').getByText('hop-B')).toBeTruthy());+ expect(routeAction().disabled).toBe(false);+ fireEvent.click(routeAction());+ expect(within(await screen.findByRole('dialog')).getByText('model-B · Route chain')).toBeTruthy();+ });+});const pending = <T,>() => { let resolve!: (value: T) => void; let reject!: (reason: Error) => void; const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; };diff --git a/ui/src/components/onboarding/DefaultRouteDialog.test.tsx b/ui/src/components/onboarding/DefaultRouteDialog.test.tsxdeleted file mode 100644index 1c819d076..000000000--- a/ui/src/components/onboarding/DefaultRouteDialog.test.tsx+++ /dev/null@@ -1,264 +0,0 @@-// @vitest-environment jsdom-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';-import userEvent from '@testing-library/user-event';-import { createInstance } from 'i18next';-import { useState } from 'react';-import { I18nextProvider } from 'react-i18next';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import en from '../../i18n/en.json';-import type { CollectionReadAuthority } from '../settings/models/collectionReadAuthority';-import type { AgentChain, AgentSupply, RouteHop, Source } from '../settings/models/types';-import { DefaultRouteDialog } from './DefaultRouteDialog';-import { INITIAL_SETUP_FLOW_STATE, type SetupFlowState, type SetupScreenId } from './setupFlow';-import type { SetupRouteFocus } from './setupRoute';--const mock = vi.hoisted(() => ({- api: {- listVibeAgents: vi.fn(),- getVibeAgent: vi.fn(),- },- models: {- listSources: vi.fn(),- getAgentChain: vi.fn(),- previewAgentChain: vi.fn(),- putAgentChain: vi.fn(),- },-}));--vi.mock('../../context/ApiContext', async (importOriginal) => ({- ...await importOriginal<typeof import('../../context/ApiContext')>(),- useApi: () => mock.api,-}));-vi.mock('../settings/models/modelsApi', async (importOriginal) => {- const actual = await importOriginal<typeof import('../settings/models/modelsApi')>();- return { ...actual, modelsApi: { ...actual.modelsApi, ...mock.models } };-});--const i18n = createInstance();-await i18n.init({ lng: 'en', fallbackLng: 'en', resources: { en: { translation: en } } });--const A: RouteHop = { source_id: 'src_a', model_id: 'opus-5' };-const B: RouteHop = { source_id: 'src_b', model_id: 'sonnet-4' };--const chainOf = (hops: RouteHop[], origin: AgentChain['route_origin'] = 'manual'): AgentChain => ({- contract_version: 10,- backend: 'claude',- model_id: 'opus-5',- manual_override: origin === 'manual' ? { hops } : null,- route_origin: origin,- current: hops[0] ?? null,- chain: hops.map((hop) => ({- source_id: hop.source_id,- model_id: hop.model_id,- channel: 'hub',- health: 'healthy',- runnable: true,- reason: null,- retry_at: null,- })),- supply_state: 'ok',-});--const sources: Source[] = [- {- id: 'src_a', vendor: 'anthropic', display_name: 'Anthropic', kind: 'api_key', protocol: 'anthropic',- supply_channel: 'hub', billing: 'metered', state: { status: 'active' }, last_discovered_at: null,- models: [{ id: 'opus-5', origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null }],- },- {- id: 'src_b', vendor: 'anthropic', display_name: 'Claude subscription', kind: 'subscription', protocol: 'anthropic',- supply_channel: 'hub', billing: 'monthly', state: { status: 'active' }, last_discovered_at: null,- models: [{ id: 'sonnet-4', origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null }],- },-];--const agent = {- id: 'claude-claude', name: 'claude', display_name: 'claude', description: null, backend: 'claude' as const,- model: 'opus-5', reasoning_effort: null, enabled: true, archived: false, archived_at: null, source: 'file',- updated_at: '', system_prompt: null, created_at: '', metadata: { builtin_default: true },-};--const supplies: AgentSupply[] = [{- backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed',- named_agents: [{ name: 'claude', effective_model_id: 'opus-5', supply_status: 'ok' }],- sources: {- order: ['src_a', 'src_b'],- eligibility: [- { source_id: 'src_a', eligible: true },- { source_id: 'src_b', eligible: true },- ],- },-}];--const agentReads: CollectionReadAuthority<AgentSupply[]> = {- read: async () => ({ kind: 'current', value: supplies }),- refresh: async () => ({ kind: 'current', value: supplies }),- readValue: async () => supplies,- invalidate: () => undefined,-};--function Host({- onNavigate = vi.fn(),- focus,- onSaved,- reads = agentReads,-}: {- onNavigate?: (screen: SetupScreenId) => void;- focus?: SetupRouteFocus;- onSaved?: (focus: SetupRouteFocus) => void;- reads?: CollectionReadAuthority<AgentSupply[]>;-}) {- const [flowState, setFlowState] = useState<SetupFlowState>(INITIAL_SETUP_FLOW_STATE);- const [open, setOpen] = useState(true);- return (- <I18nextProvider i18n={i18n}>- <button type="button" onClick={() => setOpen(true)}>reopen</button>- <DefaultRouteDialog- open={open}- onClose={() => setOpen(false)}- flowState={flowState}- setFlowState={setFlowState}- onNavigate={(screen) => { setOpen(false); onNavigate(screen); }}- agentReads={reads}- focus={focus}- onSaved={onSaved}- />- </I18nextProvider>- );-}--describe('DefaultRouteDialog', () => {- beforeEach(() => {- vi.resetAllMocks();- vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });- Element.prototype.scrollIntoView = vi.fn();- mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [agent], default_agent_name: 'claude' });- mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent });- mock.models.listSources.mockResolvedValue(sources);- mock.models.getAgentChain.mockResolvedValue(chainOf([A, B]));- mock.models.previewAgentChain.mockImplementation(async (_backend, _model, body) =>- chainOf(body.manual_override?.hops ?? []));- mock.models.putAgentChain.mockImplementation(async (_backend, _model, body) => {- const next = chainOf(body.hops);- mock.models.getAgentChain.mockResolvedValue(next);- return { chain: next };- });- });- afterEach(cleanup);-- it('saves a reordered exact chain and shows that order on reopen', async () => {- render(<Host />);- fireEvent.click(await screen.findByRole('button', { name: en.onboarding.route.moveDownNamed.replace('{{name}}', 'Anthropic · opus-5') }));- fireEvent.click(screen.getByRole('button', { name: en.onboarding.route.done }));- await waitFor(() => expect(mock.models.putAgentChain).toHaveBeenCalledWith('claude', 'opus-5', { hops: [B, A] }));- fireEvent.click(screen.getByRole('button', { name: 'reopen' }));- expect((await screen.findByText(en.onboarding.route.preferred)).closest('.setup-add-row')?.textContent).toContain('sonnet-4');- });-- it('does not write when Done is pressed on an unchanged opening', async () => {- render(<Host />);- fireEvent.click(await screen.findByRole('button', { name: en.onboarding.route.done }));- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());- expect(mock.models.putAgentChain).not.toHaveBeenCalled();- });-- it('keeps a dirty draft when adding a source and returning', async () => {- const onNavigate = vi.fn();- render(<Host onNavigate={onNavigate} />);- fireEvent.click(await screen.findByRole('button', { name: en.onboarding.route.moveDownNamed.replace('{{name}}', 'Anthropic · opus-5') }));- fireEvent.click(screen.getByRole('button', { name: en.onboarding.route.addSource }));- expect(onNavigate).toHaveBeenCalledWith('providers');- expect(mock.models.putAgentChain).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('button', { name: 'reopen' }));- expect(await screen.findByText('Claude subscription · sonnet-4')).toBeTruthy();- const preferred = screen.getByText(en.onboarding.route.preferred);- expect(preferred.closest('.setup-add-row')?.textContent).toContain('sonnet-4');- });-- it('selects the first exact hop on an empty route and shows it on reopen', async () => {- const user = userEvent.setup();- mock.models.getAgentChain.mockResolvedValue(chainOf([], 'automatic'));- render(<Host />);- await user.click(await screen.findByRole('button', { name: en.settings.models.routeDialog.addHop }));- await user.click(screen.getByRole('option', { name: /opus-5/ }));- await user.click(screen.getByRole('button', { name: en.settings.models.routeDialog.add.confirm }));- await user.click(screen.getByRole('button', { name: en.onboarding.route.done }));- await waitFor(() => expect(mock.models.putAgentChain).toHaveBeenCalledWith('claude', 'opus-5', { hops: [A] }));- fireEvent.click(screen.getByRole('button', { name: 'reopen' }));- expect((await screen.findByText(en.onboarding.route.preferred)).closest('.setup-add-row')?.textContent).toContain('opus-5');- });-- it('adds a backup hop to a one-hop route and reads both back', async () => {- const user = userEvent.setup();- mock.models.getAgentChain.mockResolvedValue(chainOf([A]));- render(<Host />);- await user.click(await screen.findByRole('button', { name: en.settings.models.routeDialog.addHop }));- await user.click(screen.getByRole('option', { name: /sonnet-4/ }));- await user.click(screen.getByRole('button', { name: en.settings.models.routeDialog.add.confirm }));- await user.click(screen.getByRole('button', { name: en.onboarding.route.done }));- await waitFor(() => expect(mock.models.putAgentChain).toHaveBeenCalledWith('claude', 'opus-5', { hops: [A, B] }));- fireEvent.click(screen.getByRole('button', { name: 'reopen' }));- expect((await screen.findByText(en.onboarding.route.preferred)).closest('.setup-add-row')?.textContent).toContain('opus-5');- expect(screen.getByText(en.onboarding.route.backup.replace('{{index}}', '1')).closest('.setup-add-row')?.textContent).toContain('sonnet-4');- });-- it('saves the focused Codex card onto Codex, not the default Claude target', async () => {- const user = userEvent.setup();- const onSaved = vi.fn();- const codex = {- ...agent,- id: 'codex-codex',- name: 'codex',- display_name: 'codex',- backend: 'codex' as const,- model: 'gpt-5',- };- const empty = (backend: 'claude' | 'codex', model: string): AgentChain => ({- ...chainOf([], 'automatic'),- backend,- model_id: model,- });- mock.api.listVibeAgents.mockResolvedValue({- ok: true,- agents: [agent, codex],- default_agent_name: 'claude',- });- mock.api.getVibeAgent.mockImplementation(async (name: string) => ({- ok: true,- agent: name === 'codex' ? codex : agent,- }));- mock.models.getAgentChain.mockImplementation(async (backend: string, model: string) => (- backend === 'codex' ? empty('codex', model) : empty('claude', model)- ));- mock.models.previewAgentChain.mockImplementation(async (backend, model, body) => ({- ...chainOf(body.manual_override?.hops ?? [], 'manual'),- backend,- model_id: model,- }));- mock.models.putAgentChain.mockImplementation(async (backend, model, body) => {- const next = { ...chainOf(body.hops), backend, model_id: model };- mock.models.getAgentChain.mockImplementation(async (nextBackend: string, nextModel: string) => (- nextBackend === backend && nextModel === model ? next : empty(nextBackend as 'claude' | 'codex', nextModel)- ));- return { chain: next };- });- const both = [- ...supplies,- { ...supplies[0]!, backend: 'codex' as const, named_agents: [{ name: 'codex', effective_model_id: 'gpt-5', supply_status: 'ok' as const }] },- ];- const bothReads: CollectionReadAuthority<AgentSupply[]> = {- read: async () => ({ kind: 'current', value: both }),- refresh: async () => ({ kind: 'current', value: both }),- readValue: async () => both,- invalidate: () => undefined,- };- render(<Host focus={{ backend: 'codex', agentName: 'codex' }} onSaved={onSaved} reads={bothReads} />);- await user.click(await screen.findByRole('button', { name: en.settings.models.routeDialog.addHop }));- await user.click(screen.getByRole('option', { name: /opus-5/ }));- await user.click(screen.getByRole('button', { name: en.settings.models.routeDialog.add.confirm }));- await user.click(screen.getByRole('button', { name: en.onboarding.route.done }));- await waitFor(() => expect(mock.models.putAgentChain).toHaveBeenCalledWith('codex', 'gpt-5', { hops: [A] }));- expect(mock.models.putAgentChain).not.toHaveBeenCalledWith('claude', 'opus-5', expect.anything());- await waitFor(() => expect(onSaved).toHaveBeenCalledWith({ backend: 'codex', agentName: 'codex' }));- });-});diff --git a/ui/src/components/onboarding/DefaultRouteDialog.tsx b/ui/src/components/onboarding/DefaultRouteDialog.tsxdeleted file mode 100644index b3dc04f88..000000000--- a/ui/src/components/onboarding/DefaultRouteDialog.tsx+++ /dev/null@@ -1,374 +0,0 @@-import * as React from 'react';-import * as DialogPrimitive from '@radix-ui/react-dialog';-import { ArrowDown, ArrowUp, CircleX, LoaderCircle, Plus, X } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { Button } from '@/components/ui/button';-import { DialogOverlay } from '@/components/ui/dialog';-import { useApi } from '@/context/ApiContext';-import type { CollectionReadAuthority } from '@/components/settings/models/collectionReadAuthority';-import { eligibleSources } from '@/components/settings/models/eligibility';-import { modelsApi } from '@/components/settings/models/modelsApi';-import { RouteCandidatePopover } from '@/components/settings/models/RouteCandidatePopover';-import { RouteOriginBadge } from '@/components/settings/models/RouteOriginBadge';-import { routeCandidates, type RouteCandidate } from '@/components/settings/models/routeChainDraft';-import type { AgentSupply, RouteHop, Source } from '@/components/settings/models/types';--import type { SetupFlowState, SetupScreenId } from './setupFlow';-import {- appendSharedHop,- hopsFor,- hydrateSetupRoutes,- moveRouteHop,- retrySetupRoutes,- saveNeedsRetry,- saveSetupRoutes,- selectSetupRouteTarget,- targetKey,- withMembershipHop,- type SetupRouteFocus,- type SetupRouteTargetSnapshot,- type TargetSaveResult,-} from './setupRoute';--import './onboarding-providers.css';--type DefaultRouteDialogProps = {- open: boolean;- onClose: () => void;- flowState: SetupFlowState;- setFlowState: React.Dispatch<React.SetStateAction<SetupFlowState>>;- onNavigate: (screen: SetupScreenId) => void;- agentReads: CollectionReadAuthority<AgentSupply[]>;- focus?: SetupRouteFocus | null;- onSaved?: (focus: SetupRouteFocus) => void | Promise<void>;-};--const hopLabel = (hop: RouteHop, sources: Source[]): string => {- const source = sources.find((row) => row.id === hop.source_id);- return source ? `${source.display_name} · ${hop.model_id}` : hop.model_id;-};--export function DefaultRouteDialog({- open,- onClose,- flowState,- setFlowState,- onNavigate,- agentReads,- focus = null,- onSaved,-}: DefaultRouteDialogProps) {- const { t } = useTranslation();- const api = useApi();- const [phase, setPhase] = React.useState<'idle' | 'loading' | 'saving' | 'failed'>('idle');- const [status, setStatus] = React.useState('');- const [sources, setSources] = React.useState<Source[]>([]);- const [supplies, setSupplies] = React.useState<AgentSupply[]>([]);- const [targets, setTargets] = React.useState<SetupRouteTargetSnapshot[]>([]);- const [receipts, setReceipts] = React.useState<TargetSaveResult[]>([]);- const baselines = React.useRef<SetupRouteTargetSnapshot[]>([]);- const addButtonRef = React.useRef<HTMLButtonElement>(null);- const loadToken = React.useRef(0);- const dirtyRef = React.useRef(flowState.routeOrderDirty);-- React.useLayoutEffect(() => {- dirtyRef.current = flowState.routeOrderDirty;- }, [flowState.routeOrderDirty]);-- const writes = React.useMemo(() => ({- getVibeAgent: (name: string, params?: { cache?: boolean }) => api.getVibeAgent(name, params),- listAgents: () => agentReads.readValue(),- getAgentChain: modelsApi.getAgentChain,- previewAgentChain: modelsApi.previewAgentChain,- putAgentChain: modelsApi.putAgentChain,- getAgentModelCandidates: modelsApi.getAgentModelCandidates,- putAgentModels: modelsApi.putAgentModels,- }), [api, agentReads]);-- const load = React.useCallback(async () => {- const token = ++loadToken.current;- setPhase('loading');- setStatus('');- try {- const [supplyRead, listed] = await Promise.all([- agentReads.read(),- modelsApi.listSources().catch(() => [] as Source[]),- ]);- if (token !== loadToken.current) return;- const nextSupplies = supplyRead.kind === 'current' ? supplyRead.value : [];- setSources(Array.isArray(listed) ? listed : []);- setSupplies(nextSupplies);- const hydration = await hydrateSetupRoutes({- listVibeAgents: (params) => api.listVibeAgents(params),- getVibeAgent: (name, params) => api.getVibeAgent(name, params),- getAgentChain: modelsApi.getAgentChain,- }, nextSupplies);- if (token !== loadToken.current) return;- if (!dirtyRef.current || baselines.current.length === 0) {- baselines.current = hydration.targets;- setTargets(hydration.targets);- setFlowState((current) => (- current.routeOrderDirty- ? current- : { ...current, routeOrder: hydration.union, routeOrderDirty: false }- ));- }- setPhase('idle');- } catch (error) {- if (token !== loadToken.current) return;- setPhase('failed');- setStatus(error instanceof Error ? error.message : String(error));- }- }, [agentReads, api, setFlowState]);-- React.useEffect(() => {- if (!open) return;- void load();- }, [open, load]);-- const close = () => {- if (phase === 'saving') return;- onClose();- };-- const addSource = () => {- onClose();- onNavigate('providers');- };-- const persist = async (retry: boolean) => {- if (phase === 'saving') return;- if (!flowState.routeOrderDirty) {- onClose();- return;- }- setPhase('saving');- setStatus('');- try {- const persistTargets = focus- ? [selectSetupRouteTarget(targets, focus)].filter((row): row is SetupRouteTargetSnapshot => row !== null)- : targets;- const next = retry- ? await retrySetupRoutes(flowState.routeOrder, persistTargets, receipts, writes)- : await saveSetupRoutes(flowState.routeOrder, persistTargets, writes, { dirty: true });- setReceipts(next);- if (saveNeedsRetry(next)) {- setPhase('failed');- const failed = next.find((row) => row.kind === 'failed' || row.kind === 'reconcile');- setStatus(failed && failed.kind === 'failed' ? failed.error : t('common.retry'));- return;- }- const confirmed = next.flatMap((row) => {- if (row.kind !== 'confirmed') return [];- const live = targets.find((target) => targetKey(target.backend, target.modelId) === row.key);- if (!live) return [];- return [{- ...live,- chain: row.chain,- membership: row.chain.manual_override?.hops.length- ? row.chain.manual_override.hops- : live.membership,- }];- });- if (confirmed.length) {- const nextTargets = targets.map((target) =>- confirmed.find((row) => row.backend === target.backend && row.modelId === target.modelId) ?? target);- baselines.current = nextTargets;- setTargets(nextTargets);- }- setFlowState((current) => ({ ...current, routeOrderDirty: false }));- setPhase('idle');- const selected = selectSetupRouteTarget(targets, focus);- const savedFocus = focus ?? (selected- ? { backend: selected.backend, agentName: selected.agentNames[0] }- : null);- onClose();- if (savedFocus) await onSaved?.(savedFocus);- } catch (error) {- setPhase('failed');- setStatus(error instanceof Error ? error.message : String(error));- }- };-- const pickerTarget = selectSetupRouteTarget(targets, focus);- const origin = (pickerTarget?.chain.route_origin === 'manual' || flowState.routeOrderDirty)- ? 'manual' as const- : pickerTarget?.chain.route_origin ?? null;-- const rows = flowState.routeOrder;- const pickerSupply = pickerTarget- ? supplies.find((row) => row.backend === pickerTarget.backend && row.mode === 'hub') ?? null- : null;- const addCandidates = pickerSupply- ? routeCandidates(pickerSupply, sources, pickerTarget?.membership ?? [])- : [];- const targetSources = pickerSupply ? eligibleSources(sources, pickerSupply) : [];- const canAddHop = Boolean(pickerTarget)- && (addCandidates.length > 0 || targetSources.some((source) => source.kind === 'api_key'));-- const applyHop = (candidate: RouteCandidate) => {- if (!pickerTarget || phase === 'saving') return;- setTargets((current) => current.map((target) => (- target.backend === pickerTarget.backend && target.modelId === pickerTarget.modelId- ? { ...target, membership: withMembershipHop(target.membership, candidate.hop) }- : target- )));- setFlowState((current) => ({- ...current,- routeOrder: appendSharedHop(current.routeOrder, candidate.hop),- routeOrderDirty: true,- }));- };-- return (- <DialogPrimitive.Root open={open} onOpenChange={(next) => { if (!next) close(); }}>- <DialogPrimitive.Portal>- <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 (phase === 'saving') event.preventDefault(); }}- onPointerDownOutside={(event) => { if (phase === 'saving') event.preventDefault(); }}- >- <header className="setup-add-head">- <div className="flex items-start justify-between gap-3">- <DialogPrimitive.Title className="setup-add-title">- {t('onboarding.route.title')}- </DialogPrimitive.Title>- <Button- type="button"- variant="ghost"- size="icon"- className="setup-add-close size-7 shrink-0"- aria-label={t('common.close')}- disabled={phase === 'saving'}- onClick={close}- >- <X className="size-[15px]" />- </Button>- </div>- <DialogPrimitive.Description className="setup-add-subtitle">- {t('onboarding.route.description')}- </DialogPrimitive.Description>- {pickerTarget && (- <RouteOriginBadge origin={origin} backend={pickerTarget.backend} interactive={false} />- )}- </header>-- <div className="setup-add-body">- {phase === 'loading' && (- <p className="setup-add-note">{t('common.loading')}</p>- )}- {rows.length === 0 && phase !== 'loading' && (- <p className="setup-add-note">{t('settings.models.routing.draftEmpty')}</p>- )}- {rows.length === 1 && (- <p className="setup-add-note">{t('onboarding.route.singleNote')}</p>- )}- {rows.map((hop, index) => {- const names = hopsFor(targets, hop);- return (- <div key={`${hop.source_id}:${hop.model_id}:${index}`} className="setup-add-row">- <div className="setup-add-row-copy">- <span className="setup-add-row-tag">- {index === 0- ? t('onboarding.route.preferred')- : t('onboarding.route.backup', { index })}- </span>- <span className="setup-add-row-name">{hopLabel(hop, sources)}</span>- {names.length > 0 && (- <span className="setup-add-row-detail">{names.join(', ')}</span>- )}- </div>- <div className="flex shrink-0 gap-1">- <Button- type="button"- variant="ghost"- size="icon"- className="size-7"- aria-label={t('onboarding.route.moveUpNamed', { name: hopLabel(hop, sources) })}- disabled={phase === 'saving' || index === 0}- onClick={() => setFlowState((current) => ({- ...current,- routeOrder: moveRouteHop(current.routeOrder, index, -1),- routeOrderDirty: true,- }))}- >- <ArrowUp className="size-3.5" />- </Button>- <Button- type="button"- variant="ghost"- size="icon"- className="size-7"- aria-label={t('onboarding.route.moveDownNamed', { name: hopLabel(hop, sources) })}- disabled={phase === 'saving' || index === rows.length - 1}- onClick={() => setFlowState((current) => ({- ...current,- routeOrder: moveRouteHop(current.routeOrder, index, 1),- routeOrderDirty: true,- }))}- >- <ArrowDown className="size-3.5" />- </Button>- </div>- </div>- );- })}- {canAddHop && pickerTarget && (- <RouteCandidatePopover- candidates={addCandidates}- sources={targetSources}- confirmLabel={t('settings.models.routeDialog.add.confirm')}- label={t('settings.models.routeDialog.addHop')}- width="trigger"- onApply={applyHop}- onReturnFocus={() => addButtonRef.current?.focus()}- trigger={- <button- ref={addButtonRef}- type="button"- disabled={phase === 'saving' || phase === 'loading'}- className="setup-add-row flex w-full items-center justify-center gap-1.5"- >- <Plus className="size-3.5" aria-hidden="true" />- {t('settings.models.routeDialog.addHop')}- </button>- }- />- )}- </div>-- <footer className="setup-add-foot">- <span className="setup-add-status" role="status" aria-live="polite">- {phase === 'saving' && (- <>- <LoaderCircle className="setup-add-status-icon motion-safe:animate-spin" aria-hidden="true" />- {t('common.loading')}- </>- )}- {phase === 'failed' && (- <>- <CircleX className="setup-add-status-icon setup-add-status-icon--error" aria-hidden="true" />- <span className="setup-add-status-error">{status}</span>- </>- )}- </span>- <Button type="button" variant="outline" size="sm" disabled={phase === 'saving'} onClick={addSource}>- {t('onboarding.route.addSource')}- </Button>- <Button- type="button"- variant="brand"- size="sm"- disabled={phase === 'loading' || phase === 'saving'}- onClick={() => void persist(phase === 'failed')}- >- {phase === 'failed' ? t('common.retry') : t('onboarding.route.done')}- </Button>- </footer>- </DialogPrimitive.Content>- </DialogPrimitive.Portal>- </DialogPrimitive.Root>- );-}diff --git a/ui/src/components/onboarding/ImportKeysNotice.test.tsx b/ui/src/components/onboarding/ImportKeysNotice.test.tsxdeleted file mode 100644index 5501f05f1..000000000--- a/ui/src/components/onboarding/ImportKeysNotice.test.tsx+++ /dev/null@@ -1,481 +0,0 @@-// @vitest-environment jsdom-//-// The setup import entry, driven through the real dialog it opens. Only the two-// boundaries are stubbed — the HTTP calls and the capability probe — so what is-// under test is the thing that actually matters here: that the number in the-// sentence, the rows a person is offered, and the ids finally submitted are all-// the same set. A count computed from one rule and rows rendered from another is-// the failure this fixture exists to catch.-//-// The scan fixture carries the shapes `migration.py` really produces, including-// a row with no presentation metadata at all (an older server) and non-ASCII-// detail text.-import { cleanup, render, screen, waitFor, within } from '@testing-library/react';-import userEvent from '@testing-library/user-event';-import { I18nextProvider } from 'react-i18next';-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());-const capability = vi.hoisted(() => ({ value: true as boolean | null }));--vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast }) }));-vi.mock('@/components/settings/models/useModelHubCapability', () => ({- useModelHubCapability: () => capability.value,-}));--import { modelsApi } from '@/components/settings/models/modelsApi';-import { ImportKeysNotice } from './ImportKeysNotice';--const CLAUDE_KEY: MigrationItem = {- id: 'mig_claude_key',- backend: 'claude',- kind: 'api_key',- masked_detail: 'sk-…dd3c',- proposed_action: 'import',- selected: true,- notes_key: null,- vendor: 'anthropic',- display_name: 'Anthropic',- masked_credential: 'sk-…dd3c',-};--// A native subscription. Legitimately applied by the settings migration; never-// part of this entry.-const CLAUDE_SUBSCRIPTION: MigrationItem = {- id: 'mig_claude_oauth',- backend: 'claude',- kind: 'oauth_native',- masked_detail: 'Claude 账号登录(OAuth)',- proposed_action: 'keep_native',- selected: true,- notes_key: null,- vendor: 'anthropic',- display_name: 'Anthropic',- masked_credential: null,-};--// Key-shaped, but needs the interactive browser flow — not batchable.-const CODEX_REAUTH: MigrationItem = {- id: 'mig_codex_reauth',- backend: 'codex',- kind: 'api_key',- masked_detail: 'sk-…9f21',- proposed_action: 'reauth',- selected: true,- notes_key: null,- vendor: 'openai',- display_name: 'OpenAI',- 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 = {- id: 'mig_opencode_zhipu',- backend: 'opencode',- kind: 'opencode_provider',- masked_detail: 'zhipu · sk-…3456',- proposed_action: 'import',- selected: true,- notes_key: null,- vendor: 'zhipu',- display_name: 'zhipu',- masked_credential: 'sk-…3456',-};--// An older server, or a provider nothing recognises: no presentation metadata at-// all, so the row has only its composed detail to show.-const OPENCODE_LEGACY: MigrationItem = {- id: 'mig_opencode_legacy',- backend: 'opencode',- kind: 'opencode_provider',- masked_detail: '自建中转 · sk-…abcd',- proposed_action: 'import',- selected: true,- notes_key: null,-};--const FULL_SCAN = [CLAUDE_KEY, CLAUDE_SUBSCRIPTION, CODEX_REAUTH, OPENCODE_ZHIPU, OPENCODE_LEGACY];--// A fake server rather than a queue of canned replies: the notice and the dialog-// it opens each scan on their own schedule, so a fixed reply order would decide-// which surface saw what. Applying removes the imported rows, which is what makes-// the notice's post-import remainder a real answer instead of arithmetic.-let stored: MigrationItem[] = [];-const applied: string[][] = [];--const serve = (items: MigrationItem[]) => {- stored = items.map((i) => ({ ...i }));- vi.spyOn(modelsApi, 'scanMigration').mockImplementation(async () => ({- items: stored.map((i) => ({ ...i })),- }));- vi.spyOn(modelsApi, 'applyMigration').mockImplementation(async (ids) => {- applied.push([...ids]);- stored = stored.filter((i) => !ids.includes(i.id));- return { applied: ids.length, sources: [] };- });-};--const renderNotice = (onApplied?: (applied: number) => void) =>- render(- <I18nextProvider i18n={i18n}>- <ImportKeysNotice onApplied={onApplied} />- </I18nextProvider>,- );--const openDialog = async (user: ReturnType<typeof userEvent.setup>) => {- await user.click(await screen.findByRole('button', { name: 'Review migration' }));- return screen.findByRole('dialog');-};--beforeEach(async () => {- capability.value = true;- applied.length = 0;- window.localStorage.clear();- await i18n.changeLanguage('en');-});--afterEach(() => {- cleanup();- vi.restoreAllMocks();- showToast.mockReset();-});--describe('ImportKeysNotice', () => {- it('rescans on return from Settings without remounting the setup notice', async () => {- serve([CLAUDE_KEY]);- const notice = (active: boolean) => (- <I18nextProvider i18n={i18n}>- <RouteSurfaceActiveContext.Provider value={active}>- <ImportKeysNotice />- </RouteSurfaceActiveContext.Provider>- </I18nextProvider>- );- const view = render(notice(true));- expect(await screen.findByText('Found 1 API key to import into Model Hub')).toBeTruthy();- view.rerender(notice(false));- stored = [];- expect(modelsApi.scanMigration).toHaveBeenCalledTimes(1);- view.rerender(notice(true));- await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalledTimes(2));- await waitFor(() => expect(screen.queryByRole('button', { name: 'Review migration' })).toBeNull());- expect(modelsApi.applyMigration).not.toHaveBeenCalled();- });-- it('counts the keys its own review can act on, not every importable row', async () => {- serve(FULL_SCAN);- renderNotice();- const user = userEvent.setup();-- // 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 () => {- serve(FULL_SCAN);- renderNotice();- const user = userEvent.setup();-- const dialog = await openDialog(user);-- expect(within(dialog).getAllByText('Anthropic').length).toBeGreaterThan(0);- // `display_name` was only the provider id; the shared brand mapping names it.- expect(within(dialog).getByText('Zhipu AI')).toBeTruthy();- // No metadata at all: the composed detail stays the title rather than a- // provider guessed from the backend that held the key.- expect(within(dialog).getByText('自建中转 · sk-…abcd')).toBeTruthy();-- expect(within(dialog).getByText(/Claude 账号登录/)).toBeTruthy();- expect(- (within(dialog).getByRole('checkbox', { name: /Claude 账号登录/ }) as HTMLButtonElement).disabled,- ).toBe(true);- expect(within(dialog).queryByText(/Re-authorize/)).toBeNull();- expect(within(dialog).getByRole('button', { name: 'Start migration' })).toBeTruthy();- });-- it('MH-MIG-004: submits only the rows still ticked', async () => {- serve(FULL_SCAN);- const onApplied = vi.fn();- renderNotice(onApplied);- 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('button', { name: 'Start migration' }));-- await waitFor(() => expect(applied).toHaveLength(1));- expect(applied[0]).toEqual(['mig_opencode_zhipu', 'mig_opencode_legacy']);- expect(onApplied).toHaveBeenCalledWith(2);- });-- it('stays to report what was imported and what is still available', async () => {- // 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-…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 migration' })).toBeTruthy();- });-- it('reports the outcome without offering a review of what it may not take', async () => {- serve(FULL_SCAN);- renderNotice();- const user = userEvent.setup();-- const dialog = await openDialog(user);- await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));-- // 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',- 'mig_codex_reauth',- ]);- });-- it('remembers a dismissal so the same keys do not ask again', async () => {- serve(FULL_SCAN);- const { unmount } = renderNotice();- const user = userEvent.setup();-- await user.click(await screen.findByRole('button', { name: 'Dismiss import notice' }));- expect(screen.queryByText(/API keys to import/)).toBeNull();-- unmount();- cleanup();- renderNotice();- await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalledTimes(2));- expect(screen.queryByText(/API keys to import/)).toBeNull();- });-- it('asks again when a genuinely new key appears', async () => {- serve(FULL_SCAN);- const { unmount } = renderNotice();- const user = userEvent.setup();-- 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();-- 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 () => {- serve([CLAUDE_SUBSCRIPTION, CODEX_REAUTH]);- renderNotice();-- await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalled());- expect(screen.queryByText(/Model Gateway/)).toBeNull();- });-- it('says nothing when the scan fails', async () => {- // Advertising rows after a failed scan would open a dialog that rescans,- // fails again and shows nothing.- vi.spyOn(modelsApi, 'scanMigration').mockRejectedValue(new Error('offline'));- renderNotice();-- await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalled());- expect(screen.queryByText(/Model Gateway/)).toBeNull();- });-- it('does not scan at all when the gateway capability is off', async () => {- capability.value = false;- serve(FULL_SCAN);- renderNotice();-- await Promise.resolve();- expect(modelsApi.scanMigration).not.toHaveBeenCalled();- 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.tsxdeleted file mode 100644index 25dbefd99..000000000--- a/ui/src/components/onboarding/ImportKeysNotice.tsx+++ /dev/null@@ -1,210 +0,0 @@-// Setup's API-key import offer: one line under the assistant list saying how many-// keys already on this machine Model Hub can take over, with a way to look-// at them before anything happens.-//-// 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 — 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.-import * as React from 'react';-import { KeyRound, X } from 'lucide-react';-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 { 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';-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;- /**- * 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 [ownCandidates, setCandidates] = React.useState<MigrationItem[]>([]);- const [ownImported, setImported] = React.useState(0);- const [dialogOpen, setDialogOpen] = 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;- return () => {- aliveRef.current = false;- };- }, []);-- React.useEffect(() => {- if (hosted) return;- if (modelHubEnabled !== true) {- setCandidates([]);- return;- }- // Settings retains the wizard. Refresh its offer when it becomes visible- // again, including migrations performed outside this notice's dialog.- if (!routeSurfaceActive) return;- let cancelled = false;- scanMigrationWhenEnabled(true)- .then((scan) => {- if (cancelled || !aliveRef.current || scan === null) return;- // 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) {- // 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- // opens would rescan too, and land on its own error with nothing to show.- if (!cancelled && aliveRef.current) setCandidates([]);- });- return () => {- cancelled = true;- };- }, [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;- // 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;-- const dismiss = () => {- // An empty set would overwrite the remembered signature with nothing, so a batch- // 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);- setDismissedAt(imported);- };-- const message = imported === 0- ? t('settings.models.importNotice.found', { count: remaining })- : remaining > 0- ? t('settings.models.importNotice.importedRemaining', { imported, count: remaining })- : t('settings.models.importNotice.imported', { count: imported });-- return (- <>- <div className="onboarding-import-notice">- <KeyRound size={16} className="onboarding-import-notice-icon" aria-hidden="true" />- <span className="onboarding-import-notice-text">{message}</span>- <div className="onboarding-import-notice-actions">- {remaining > 0 && (- // 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={() => (onReview ? onReview() : setDialogOpen(true))}>- {t('onboarding.import.review')}- </Button>- )}- <InfoHint- align="end"- hover- className="onboarding-import-notice-help"- label={t('settings.models.importNotice.help') as string}- trigger={t('settings.models.importNotice.help')}- content={t('onboarding.import.helpBody')}- contentClassName="w-72"- />- </div>- <button- type="button"- className="onboarding-import-notice-dismiss"- aria-label={t('settings.models.importNotice.dismiss') as string}- onClick={dismiss}- >- <X size={14} aria-hidden="true" />- </button>- </div>-- {dialogOpen && !hosted && (- <MigrationDialog- open- eligible={isImportableKey}- takeable={isImportableKey}- onClose={() => setDialogOpen(false)}- onApplied={(applied) => {- setDialogOpen(false);- setImported((total) => total + applied);- // Rescan so "what is left" is the server's answer, not arithmetic on a- // count this component happened to be holding.- setScanToken((n) => n + 1);- onApplied?.(applied);- }}- />- )}- </>- );-};diff --git a/ui/src/components/onboarding/SetupFlowShell.test.tsx b/ui/src/components/onboarding/SetupFlowShell.test.tsxindex dd71861cf..93aa48a52 100644--- a/ui/src/components/onboarding/SetupFlowShell.test.tsx+++ b/ui/src/components/onboarding/SetupFlowShell.test.tsx@@ -22,7 +22,11 @@ function Screen({ id, ref, ...props }: SetupScreenProps & { id: SetupScreenId; r}}, [props.active, props.onActionChange]);useImperativeHandle(ref, () => ({ activate: () => props.onNavigate(id === 'intro' ? 'providers' : 'assistants') }));- return <><h1 tabIndex={-1}>{id}</h1><input aria-label={`${id} draft`} value={value} onChange={(event) => setValue(event.target.value)} /></>;+ return <><h1 tabIndex={-1}>{id}</h1>+ {id === 'providers' && <><div className="setup-provider-stage" data-testid="incoming-diagram" />+ <div className="setup-destinations" data-testid="incoming-destinations" /></>}+ {id === 'assistants' && <div className="onboarding-assistant" data-testid="incoming-assistant" />}+ <input aria-label={`${id} draft`} value={value} onChange={(event) => setValue(event.target.value)} /></>;}const show = (capability: SetupScreenProps['capability'] = 'enabled', gatewayEnabled: boolean | null = true,extra: { navigationLocked?: boolean; onRetrySetup?: () => void } = {}) =>@@ -54,7 +58,7 @@ it.each(['pending', 'disabled', 'enabled'] as const)('policy %s never removes ait('a held journey refuses the screen own navigate, not only the buttons', () => {const { container, rerender } = render(show('enabled', true, { navigationLocked: true }));const current = () => container.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen');- expect(screen.getByRole('button', { name: 'Get started' }).hasAttribute('disabled')).toBe(true);+ expect(screen.getByRole('button', { name: 'Get started' }).hasAttribute('disabled')).toBe(false);// Held, not busy: nothing is running, so nothing spins. The spinner carries Tailwind's// `motion-safe:` variant, so the token in the DOM is the whole `motion-safe:animate-spin`// — feeding a genuinely busy action proves this selector can find one, which is what@@ -74,7 +78,7 @@ it('a held journey does not hand the shared primary to the config retry either',const onRetrySetup = vi.fn();render(show('disabled', false, { navigationLocked: true, onRetrySetup }));const primary = screen.getByRole('button', { name: en.common.retry });- expect(primary.hasAttribute('disabled')).toBe(true);+ expect(primary.hasAttribute('disabled')).toBe(false);fireEvent.click(primary);expect(onRetrySetup).not.toHaveBeenCalled();});@@ -102,3 +106,34 @@ it('keeps drafts and DOM identity, focuses each heading, and rejects old activatexpect(container.querySelectorAll('.onboarding-setup-footer')).toHaveLength(1);expect(container.querySelectorAll('.onboarding-primary-action')).toHaveLength(1);});++it('focuses the arriving heading only after its animated handoff clears inert', () => {+ vi.useFakeTimers();+ const originalAnimate = HTMLElement.prototype.animate;+ Object.defineProperty(HTMLElement.prototype, 'animate', {+ configurable: true,+ value: vi.fn(() => ({ cancel: vi.fn() })),+ });+ try {+ const { container } = render(show());+ expect(document.activeElement).toBe(screen.getByRole('heading', { name: 'intro' }));+ fireEvent.click(screen.getByRole('button', { name: 'Get started' }));+ const arriving = container.querySelector<HTMLElement>('[data-setup-screen-root="providers"]')!;+ expect(arriving.hasAttribute('hidden')).toBe(false);+ expect(arriving.querySelector('h1')?.textContent).toBe('providers');+ expect(arriving.querySelector('[data-testid="incoming-diagram"]')).toBeTruthy();+ expect(container.querySelector('[data-handoff="providers"] .setup-destinations')).toBeTruthy();+ expect(arriving.hasAttribute('inert')).toBe(true);+ expect(savedFeeds).toHaveLength(1);+ expect(document.activeElement).not.toBe(arriving.querySelector('h1'));+ act(() => vi.advanceTimersByTime(900));+ expect(container.querySelector('[data-handoff]')).toBeNull();+ expect(arriving.querySelector('[data-testid="incoming-destinations"]')).toBeTruthy();+ expect(arriving.hasAttribute('inert')).toBe(false);+ expect(document.activeElement).toBe(arriving.querySelector('h1'));+ } finally {+ vi.useRealTimers();+ if (originalAnimate) Object.defineProperty(HTMLElement.prototype, 'animate', { configurable: true, value: originalAnimate });+ else Reflect.deleteProperty(HTMLElement.prototype, 'animate');+ }+});diff --git a/ui/src/components/onboarding/SetupPlatformRecovery.tsx b/ui/src/components/onboarding/SetupPlatformRecovery.tsxdeleted file mode 100644index 33609d031..000000000--- a/ui/src/components/onboarding/SetupPlatformRecovery.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';-import { useApi } from '@/context/ApiContext';-import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';-import { configChanges } from '@/lib/configMutations';-import { errorMessage } from '@/lib/errorMessage';-import { platformText, type PlatformDescriptor } from '@/lib/platforms';-import { PlatformConfigEmbed } from '../settings/PlatformConfigEmbed';-import { savePlatformSettings } from '../settings/shared/savePlatformSettings';-import { Button } from '../ui/button';--export type SavedPlatformRecovery = { config: Record<string, unknown>; descriptor: PlatformDescriptor };--export function SetupPlatformRecovery({ saved, onRepaired, onCancel }: {- saved: SavedPlatformRecovery; onRepaired: () => Promise<void>; onCancel: () => void;-}) {- const api = useApi(); const { t } = useTranslation();- const { capabilities } = useInstanceAuthorization();- const [editing, setEditing] = useState(false);- const [error, setError] = useState('');- const busy = useRef(false);- const { config, descriptor } = saved;- const key = descriptor.config_key || descriptor.id;- const apply = async (next: Record<string, unknown>) => {- if (busy.current) return;- busy.current = true; setError('');- try {- const result = await api.mutateConfig(configChanges(config[key], next[key], [key]));- const runtime = result?.platform_runtime;- if (runtime?.hot_reconciled === false && !runtime.restart_scheduled) throw new Error(runtime.restart_error || runtime.error || t('platform.restartFailed'));- await savePlatformSettings(api, descriptor.id, next, capabilities.can_manage_access_members);- await onRepaired();- } catch (cause) { setError(errorMessage(cause) || t('common.saveFailed')); }- finally { busy.current = false; }- };- return <section className="onboarding-model-recovery" aria-label={t('onboarding.connection.platformRepair')}>- <p role="alert">{t('onboarding.connection.platformRepairHint', { platform: platformText(t, descriptor.id, 'title', descriptor.title_key) })}</p>- {error && <p role="alert" className="connection-error">{error}</p>}- {editing ? <PlatformConfigEmbed platform={descriptor.id} config={config} onApply={apply} onCancel={onCancel} />- : <div className="flex flex-wrap gap-2"><Button variant="secondary" onClick={() => setEditing(true)}>{t('onboarding.connection.platformRepair')}</Button><Button variant="ghost" onClick={onCancel}>{t('common.cancel')}</Button></div>}- </section>;-}diff --git a/ui/src/components/onboarding/Welcome.test.tsx b/ui/src/components/onboarding/Welcome.test.tsxindex d5852fdd0..6086185dc 100644--- a/ui/src/components/onboarding/Welcome.test.tsx+++ b/ui/src/components/onboarding/Welcome.test.tsx@@ -111,9 +111,10 @@ describe('Welcome', () => {const footer = container.querySelector('.onboarding-setup-footer') as HTMLElement;expect(aside.contains(alert)).toBe(true);expect(container.querySelector('[data-setup-screen-root="intro"]')!.contains(alert)).toBe(false);- // Order, not just ownership: only content after the footer is content the anchor- // cannot feel.- expect(footer.compareDocumentPosition(aside) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ // Placement, not just ownership: the slot lives in the cell the screens share, above+ // the footer and out of the centred column, so what it holds cannot move the pair.+ expect(aside.parentElement?.classList.contains('onboarding-screens')).toBe(true);+ expect(footer.compareDocumentPosition(aside) & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy();expect(screen.getByRole('button', { name: 'Retry' }).closest('.onboarding-primary-action')).toBeTruthy();});// e-Dq: detection awaits three CLI probes and only then asks to move. Thatdiff --git a/ui/src/components/onboarding/WizardCompletion.test.tsx b/ui/src/components/onboarding/WizardCompletion.test.tsxindex 4a638adce..17802db20 100644--- a/ui/src/components/onboarding/WizardCompletion.test.tsx+++ b/ui/src/components/onboarding/WizardCompletion.test.tsx@@ -1,6 +1,5 @@// @vitest-environment jsdom-import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';-import userEvent from '@testing-library/user-event';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { createInstance } from 'i18next';import { I18nextProvider } from 'react-i18next';import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';@@ -11,7 +10,7 @@ import en from '../../i18n/en.json';const mock = vi.hoisted(() => ({ control: vi.fn(), toast: vi.fn(), permission: vi.fn(), manageAccess: true, apiFetch: vi.fn(), api: {saveSettings: vi.fn(), discordAuthTest: vi.fn(), discordGuilds: vi.fn(), slackManifest: vi.fn(), slackAuthTest: vi.fn(), getConfig: vi.fn(), detectCli: vi.fn(), getBackendRuntime: vi.fn(), getBackendConnection: vi.fn(),- readModelHubAgentCatalogForModelPicker: vi.fn(), listVibeAgents: vi.fn(), getVibeAgent: vi.fn(), setDefaultVibeAgent: vi.fn(), mutateConfig: vi.fn(),+ readModelHubAgentCatalogForModelPicker: vi.fn(), listVibeAgents: vi.fn(), getVibeAgent: vi.fn(), updateVibeAgent: vi.fn(), setDefaultVibeAgent: vi.fn(), mutateConfig: vi.fn(),},// The endpoints the second screen reads, and — through the one Agent-supply authority// the shell shares with it — the endpoints the entry gate judges. Only the endpoints:@@ -194,8 +193,8 @@ describe('explicit any-one-ready completion', () => {fireEvent.click(await setup()); await screen.findByTestId('destination');expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();});- it.each(['start', 'legacy IM'])('keeps failed completion recoverable (%s)', async (failure) => {- if (failure !== 'start') mock.api.mutateConfig.mockRejectedValue(new Error("Config 'slack.bot_token' must be provided"));+ it.each(['start', 'config write'])('keeps failed completion recoverable (%s)', async (failure) => {+ if (failure !== 'start') mock.api.mutateConfig.mockRejectedValue(new Error('Config write unavailable'));const enter = await setup({ stopped: failure === 'start' });if (failure === 'start') mock.control.mockRejectedValue(new Error('Start unavailable'));fireEvent.click(enter);@@ -238,10 +237,7 @@ describe('the correlated entry gate', () => {// binary detectCli does not find. Every condition is satisfied somewhere and none// of them meet. `connection.installed` is not the detector.allConnected();- mock.api.listVibeAgents.mockResolvedValue({- ok: true, default_agent_name: null,- agents: [CLAUDE_AGENT, { name: 'codex-agent', backend: 'codex', enabled: true, archived: false, source: 'builtin' }],- });+ serveAgents(null, [CLAUDE_AGENT, { name: 'codex-agent', backend: 'codex', enabled: true, archived: false, source: 'builtin' }]);mock.models.listAgents.mockResolvedValue([hubSupply('claude', []), hubSupply('codex', [route('codex-agent')])]);const enter = await setup();mock.api.detectCli.mockImplementation(async (binary: string) => ({ found: binary !== 'codex', path: binary }));@@ -518,8 +514,8 @@ describe('the correlated entry gate', () => {});});-/** A saved platform whose required credential is gone: the shape that stops completion- * and hands the slot a repair form. Shared with the navigation-ownership cases below. */+/** A saved platform whose required credential is gone: the shape that used to stop+ * completion. Shared with the navigation cases below. */function incompleteSlack() {const config = baseConfig({ platforms: { primary: 'slack', enabled: ['slack'] }, platform_catalog: [{ id: 'slack', config_key: 'slack', credential_fields: ['bot_token', 'app_token'] }], slack: { bot_token: '', app_token: '', has_bot_token: false, has_app_token: true, proxy_url: '' }, agent: { default_cwd: '/original' } }) as ReturnType<typeof baseConfig> & { slack: Record<string, unknown>; platform_catalog: Record<string, unknown>[] };serveConfig(config);@@ -527,41 +523,16 @@ function incompleteSlack() {return config;}-// AUTH-SETUP-120: the actual Wizard consumes legacy-IM recovery and narrow mutations.-describe('saved messaging recovery', () => {- it('mounts only after explicit repair, saves changed credentials only, then rechecks and completes', async () => {- const config = incompleteSlack();+// AUTH-SETUP-120: a saved platform is no longer a gate. The Wizard finishes on the+// config it was given and writes nothing on the platform's behalf.+describe('saved messaging no longer gates the workspace', () => {+ it('completes with an enabled platform whose saved credential is gone', async () => {+ incompleteSlack();fireEvent.click(await setup({ stopped: true }));- await screen.findByRole('region', { name: en.onboarding.connection.platformRepair });- expect(mock.control).not.toHaveBeenCalled(); expect(mock.api.slackManifest).not.toHaveBeenCalled();- mock.api.mutateConfig.mockImplementation(async (mutations) => {- if (mutations[0].path[0] === 'slack') {- serveConfig({ ...config, slack: { ...config.slack, has_bot_token: true }, agent: { default_cwd: '/concurrent' } });- return {};- }- persistConfig(mutations);- return {};- });- fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.platformRepair }));- fireEvent.click(await screen.findByRole('button', { name: new RegExp(en.slackConfig.step2Title) }));- fireEvent.change(await screen.findByPlaceholderText(en.slackConfig.botTokenPlaceholder), { target: { value: 'xoxb-fixture-only' } });- fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));- await screen.findByTestId('destination');- expect(mock.api.mutateConfig.mock.calls[0][0]).toEqual([{ kind: 'set', path: ['slack', 'bot_token'], value: 'xoxb-fixture-only' }]);- expect(mock.api.mutateConfig.mock.calls[1][0]).toEqual([{ kind: 'set', path: ['setup_completed'], value: true }]);- expect(mock.api.slackAuthTest).not.toHaveBeenCalled(); expect(mock.control).toHaveBeenCalledExactlyOnceWith('start');- });- it('keeps failed repair drafts editable and cancel preserves credentials', async () => {- incompleteSlack(); mock.api.mutateConfig.mockRejectedValue(new Error('Platform apply failed'));- fireEvent.click(await setup()); fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.platformRepair }));- fireEvent.click(await screen.findByRole('button', { name: new RegExp(en.slackConfig.step2Title) }));- const input = await screen.findByPlaceholderText(en.slackConfig.botTokenPlaceholder);- fireEvent.change(input, { target: { value: 'xoxb-retained-draft' } });- fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));- await screen.findByText('Platform apply failed');- expect((input as HTMLInputElement).value).toBe('xoxb-retained-draft'); expect(screen.queryByTestId('destination')).toBeNull();- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));- expect(mock.api.mutateConfig).toHaveBeenCalledOnce();+ expect(await screen.findByTestId('destination')).toBeTruthy();+ expect(mock.api.mutateConfig.mock.lastCall![0]).toEqual([{ kind: 'set', path: ['setup_completed'], value: true }]);+ expect(mock.api.slackManifest).not.toHaveBeenCalled(); expect(mock.api.slackAuthTest).not.toHaveBeenCalled();+ expect(mock.control).toHaveBeenCalledExactlyOnceWith('start');});it('honors redacted credential markers and the WeChat runnable exception', async () => {const config = incompleteSlack();@@ -571,68 +542,6 @@ describe('saved messaging recovery', () => {});});--// AUTH-SETUP-120: Discord's existing form emits credential and auxiliary settings.-describe('saved Discord recovery', () => {- async function repairDiscord() {- const config = baseConfig({ agents: { claude: { enabled: true } }, platforms: { primary: 'discord', enabled: ['discord'] }, platform_catalog: [{ id: 'discord', config_key: 'discord', credential_fields: ['bot_token'] }], discord: { bot_token: '', has_bot_token: false } });- serveConfig(config);- mock.api.discordAuthTest.mockResolvedValue({ ok: true });- mock.api.discordGuilds.mockResolvedValue({ ok: true, guilds: [{ id: 'g-one', name: 'Guild One' }, { id: 'g-two', name: 'Guild Two' }] });- mock.api.mutateConfig.mockImplementation(async (changes) => {- if (changes[0].path[0] === 'discord') {- serveConfig({ ...config, discord: { bot_token: '', has_bot_token: true } });- return {};- }- persistConfig(changes);- return {};- });- fireEvent.click(await setup());- fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.platformRepair }));- fireEvent.click(await screen.findByRole('button', { name: new RegExp(en.discordConfig.step4Title) }));- const input = await screen.findByPlaceholderText(en.discordConfig.botTokenPlaceholder);- fireEvent.change(input, { target: { value: 'fixture-discord-token' } });- fireEvent.click(screen.getByRole('button', { name: en.discordConfig.validateToken }));- await screen.findByRole('checkbox', { name: 'Guild One' });- return input;- }- it.each(['selected', 'cleared', 'unchanged', 'excluded'] as const)('persists only the intended guild selection (%s)', async (mode) => {- mock.manageAccess = mode !== 'excluded';- await repairDiscord();- if (mode === 'selected' || mode === 'cleared') fireEvent.click(screen.getByRole('checkbox', { name: 'Guild One' }));- if (mode === 'cleared') fireEvent.click(screen.getByRole('button', { name: en.discordConfig.clearGuilds }));- if (mode === 'excluded') expect(screen.getByRole('checkbox', { name: 'Guild One' }).hasAttribute('disabled')).toBe(true);- fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));- await screen.findByTestId('destination');- if (mode === 'selected' || mode === 'cleared') {- expect(mock.api.saveSettings).toHaveBeenCalledExactlyOnceWith({ guilds: mode === 'selected' ? { 'g-one': { enabled: true } } : {} }, 'discord');- expect(mock.api.saveSettings.mock.invocationCallOrder[0]).toBeLessThan(mock.api.mutateConfig.mock.invocationCallOrder[1]);- } else expect(mock.api.saveSettings).not.toHaveBeenCalled();- expect(mock.api.mutateConfig.mock.calls[0][0]).toEqual([{ kind: 'set', path: ['discord', 'bot_token'], value: 'fixture-discord-token' }]);- });- it('retains selected guild and credential draft after partial save failure, then retries before completion', async () => {- const input = await repairDiscord();- fireEvent.click(screen.getByRole('checkbox', { name: 'Guild Two' }));- mock.api.saveSettings.mockRejectedValueOnce(new Error('Guild settings failed'));- fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));- await screen.findByText('Guild settings failed');- expect(screen.queryByTestId('destination')).toBeNull();- expect((screen.getByRole('checkbox', { name: 'Guild Two' }) as HTMLInputElement).checked).toBe(true);- expect((input as HTMLInputElement).value).toBe('fixture-discord-token');- expect(mock.api.mutateConfig).toHaveBeenCalledOnce();- fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));- await screen.findByTestId('destination');- expect(mock.api.saveSettings).toHaveBeenCalledTimes(2);- expect(mock.api.saveSettings).toHaveBeenLastCalledWith({ guilds: { 'g-two': { enabled: true } } }, 'discord');- });- it('cancelled selection writes neither credentials nor settings', async () => {- await repairDiscord(); fireEvent.click(screen.getByRole('checkbox', { name: 'Guild One' }));- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));- expect(mock.api.saveSettings).not.toHaveBeenCalled(); expect(mock.api.mutateConfig).not.toHaveBeenCalled();- expect(screen.queryByTestId('destination')).toBeNull();- });-});-// e-Da: the block holds two different kinds of string. `flowError` is the sentence a// person reads, which is always a bundle key; the disclosure below it is whatever the// server or the transport said. Reading them apart is what makes "the raw detail is not@@ -644,13 +553,7 @@ const flowErrorDetail = () => {return (disclosure.textContent ?? '').slice((disclosure.querySelector('summary')?.textContent ?? '').length);};const primaryAction = () => document.querySelector('.onboarding-primary-action') as HTMLButtonElement;-const assistantsRoot = () => document.querySelector('[data-setup-screen-root="assistants"]') as HTMLElement;-const assistantCard = (name: string) => within(within(assistantsRoot()).getByLabelText(name));const backAction = () => document.querySelector('.onboarding-back-action') as HTMLButtonElement;-// The footer's spinner carries Tailwind's `motion-safe:` variant, so the token in the-// DOM is the whole `motion-safe:animate-spin`. A bare `.animate-spin` matches nothing-// here whatever the shell renders, which would make every "not busy" check vacuous.-const spinners = () => primaryAction().querySelectorAll('[class~="motion-safe:animate-spin"]').length;/** Nothing that ends setup, and nothing that leaves the screen. */function expectNoForwardWrite() {expect(mock.api.mutateConfig).not.toHaveBeenCalled();@@ -859,86 +762,11 @@ describe('fresh prerequisite boundary', () => {await act(async () => { release({ ok: true }); });expect(mock.api.mutateConfig).not.toHaveBeenCalled();});- it('a recovery completion callback passes the same boundary', async () => {- // A repair that succeeded still re-enters the completion, and re-entering is not a- // pass: the gateway went off while the repair was being written.- const config = incompleteSlack();- fireEvent.click(await setup());- fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.platformRepair }));- fireEvent.click(await screen.findByRole('button', { name: new RegExp(en.slackConfig.step2Title) }));- fireEvent.change(await screen.findByPlaceholderText(en.slackConfig.botTokenPlaceholder), { target: { value: 'xoxb-fixture-only' } });- mock.api.mutateConfig.mockImplementation(async () => {- serveConfig({ ...config, slack: { ...config.slack, has_bot_token: true } });- serveFreshOnly(async () => jsonResponse(baseConfig({ model_hub: { enabled: false } })));- return {};- });- fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));- await waitFor(() => expect(flowError()).toBe(en.onboarding.flow.gatewayRequired));- expect(mock.api.mutateConfig).toHaveBeenCalledOnce();- expect(screen.queryByTestId('destination')).toBeNull();- });});-// XpVU: a recovery owns the journey while it is open, and says so by holding the-// shared pair — not by pretending work is running.-describe('recovery navigation ownership', () => {- // A saved platform's repair is offered, not started: until somebody asks for it- // nothing runs, so the pair is held rather than busy, and refusing it returns- // the journey untouched.- it('a platform repair holds both controls without a busy spinner, and gives them back on cancel', async () => {- incompleteSlack();- fireEvent.click(await setup({ stopped: true }));- await screen.findByRole('region', { name: en.onboarding.connection.platformRepair });- expect(backAction().hasAttribute('disabled')).toBe(true);- expect(primaryAction().hasAttribute('disabled')).toBe(true);- expect(spinners()).toBe(0);- expect(mock.api.slackManifest).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));- await waitFor(() => expect(backAction().hasAttribute('disabled')).toBe(false));- expect(screen.queryByRole('region', { name: en.onboarding.connection.platformRepair })).toBeNull();- expect(mock.api.mutateConfig).not.toHaveBeenCalled();- expect(screen.queryByTestId('destination')).toBeNull();- });- it('keeps the journey put while a deferred platform repair is unsettled, survives its failure, and completes on a later success', async () => {- const config = incompleteSlack();- let releaseApply!: (ok: boolean) => void;- mock.api.mutateConfig.mockImplementation(async (mutations: { path: string[]; value: unknown }[]) => {- if (mutations[0].path[0] !== 'slack') {- persistConfig(mutations);- return {};- }- if (!await new Promise<boolean>((resolve) => { releaseApply = resolve; })) throw new Error('Platform apply failed');- serveConfig({ ...config, slack: { ...config.slack, has_bot_token: true } });- return {};- });- fireEvent.click(await setup({ stopped: true }));- fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.platformRepair }));- fireEvent.click(await screen.findByRole('button', { name: new RegExp(en.slackConfig.step2Title) }));- const input = await screen.findByPlaceholderText(en.slackConfig.botTokenPlaceholder);- fireEvent.change(input, { target: { value: 'xoxb-deferred' } });- fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));- await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());- // Unsettled: the write is out and the answer is not in, so the journey neither- // leaves nor arrives on its own.- fireEvent.click(backAction());- expect(document.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen')).toBe('assistants');- expect(screen.queryByTestId('destination')).toBeNull();-- // A refused write is not a finished recovery: the form stays, with its draft.- await act(async () => { releaseApply(false); });- await screen.findByText('Platform apply failed');- await screen.findByRole('region', { name: en.onboarding.connection.platformRepair });- expect(screen.queryByTestId('destination')).toBeNull();- expect((input as HTMLInputElement).value).toBe('xoxb-deferred');- expect(backAction().hasAttribute('disabled')).toBe(true);-- // And an explicit second attempt, settling for real, is what finishes setup.- fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));- await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2));- await act(async () => { releaseApply(true); });- expect(await screen.findByTestId('destination')).toBeTruthy();- expect(mock.api.mutateConfig.mock.lastCall![0]).toEqual([{ kind: 'set', path: ['setup_completed'], value: true }]);- });+// XpVU: a screen that is waiting on its own answer holds the shared pair while it+// waits — without pretending separate work is running.+describe('journey navigation ownership', () => {it('an ordinary not-yet-ready primary still lets the journey go back', async () => {await arriveAtProviders();// Only now: the second screen's own admission needs a connection answer, so hanging@@ -1060,166 +888,3 @@ describe('the registered journey', () => {expect(await screen.findByTestId('destination')).toBeTruthy();});});--describe('setup route editor on the registered journey', () => {- const hops = [- { source_id: 'src_openai', model_id: 'gpt-5' },- { source_id: 'src_openai', model_id: 'gpt-4.1' },- ];- const chainOf = (order = hops) => ({- contract_version: 10,- backend: 'claude' as const,- model_id: 'opus-5',- manual_override: { hops: order },- route_origin: 'manual' as const,- current: order[0],- chain: order.map((hop) => ({- ...hop,- channel: 'hub' as const,- health: 'healthy' as const,- runnable: true,- reason: null,- retry_at: null,- })),- supply_state: 'ok' as const,- });-- it('reorders the exact saved chain, keeps the draft through add-source, then enters', async () => {- serveAgents('claude-agent', [{ ...CLAUDE_AGENT, model: 'opus-5' }]);- mock.models.listAgents.mockResolvedValue([- hubSupply('claude', [route('claude-agent', { effective_model_id: 'opus-5' })]),- ]);- mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({- ok: true, backend, enabled: true, installed: true, auth: 'none',- application: 'applied', ready: backend === 'claude', entry_eligible: backend === 'claude',- supply_mode: backend === 'claude' ? 'hub' : undefined,- }));- mock.models.getAgentChain.mockResolvedValue(chainOf());- mock.models.previewAgentChain.mockImplementation(async (_backend, _model, body) =>- chainOf(body.manual_override?.hops ?? hops));- mock.models.putAgentChain.mockImplementation(async (_backend, _model, body) => {- const next = chainOf(body.hops);- mock.models.getAgentChain.mockResolvedValue(next);- return { chain: next };- });-- await setup();- fireEvent.click(await assistantCard('Claude Code').findByRole('button', { name: en.onboarding.setup.configureRoute }));- fireEvent.click(await screen.findByRole('button', { name: en.onboarding.route.moveDownNamed.replace('{{name}}', 'OpenAI · gpt-5') }));- fireEvent.click(screen.getByRole('button', { name: en.onboarding.route.addSource }));- await waitFor(() => expect(document.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen')).toBe('providers'));- expect(mock.models.putAgentChain).not.toHaveBeenCalled();-- await waitFor(() => expect(primaryAction().textContent).toContain(en.onboarding.providers.actionContinue));- await waitFor(() => expect(primaryAction().hasAttribute('disabled')).toBe(false));- fireEvent.click(primaryAction());- await screen.findByRole('button', { name: 'Enter workspace' });- fireEvent.click(assistantCard('Claude Code').getByRole('button', { name: en.onboarding.setup.configureRoute }));- expect((await screen.findByText(en.onboarding.route.preferred)).closest('.setup-add-row')?.textContent).toContain('gpt-4.1');-- fireEvent.click(screen.getByRole('button', { name: en.onboarding.route.done }));- await waitFor(() => expect(mock.models.putAgentChain).toHaveBeenCalledWith('claude', 'opus-5', { hops: [hops[1], hops[0]] }));- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());-- fireEvent.click(assistantCard('Claude Code').getByRole('button', { name: en.onboarding.setup.configureRoute }));- expect((await screen.findByText(en.onboarding.route.preferred)).closest('.setup-add-row')?.textContent).toContain('gpt-4.1');- fireEvent.click(screen.getByRole('button', { name: en.onboarding.route.done }));- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());-- fireEvent.click(screen.getByRole('button', { name: 'Enter workspace' }));- expect(await screen.findByTestId('destination')).toBeTruthy();- expect(mock.api.mutateConfig).toHaveBeenCalledExactlyOnceWith([{ kind: 'set', path: ['setup_completed'], value: true }]);- expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();- });-- it('selects the first exact hop on an empty route, then enters', async () => {- const user = userEvent.setup();- let routed = false;- serveAgents('claude-agent', [{ ...CLAUDE_AGENT, model: 'opus-5' }]);- mock.models.listAgents.mockResolvedValue([- hubSupply('claude', [route('claude-agent', { effective_model_id: 'opus-5' })]),- ]);- mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({- ok: true, backend, enabled: true, installed: true, auth: 'none',- application: 'applied', ready: backend === 'claude' && routed, entry_eligible: backend === 'claude' && routed,- supply_mode: backend === 'claude' ? 'hub' : undefined,- }));- mock.models.getAgentChain.mockResolvedValue(chainOf([]));- mock.models.previewAgentChain.mockImplementation(async (_backend, _model, body) =>- chainOf(body.manual_override?.hops ?? []));- mock.models.putAgentChain.mockImplementation(async (_backend, _model, body) => {- routed = true;- const next = chainOf(body.hops);- mock.models.getAgentChain.mockResolvedValue(next);- return { chain: next };- });-- await arriveAtProviders();- fireEvent.click(primaryAction());- const enter = await screen.findByRole('button', { name: 'Enter workspace' });- await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(true));- fireEvent.click(await assistantCard('Claude Code').findByRole('button', { name: en.onboarding.setup.configureRoute }));- await user.click(await screen.findByRole('button', { name: en.settings.models.routeDialog.addHop }));- await user.click(screen.getByRole('option', { name: /gpt-5/ }));- await user.click(screen.getByRole('button', { name: en.settings.models.routeDialog.add.confirm }));- await user.click(screen.getByRole('button', { name: en.onboarding.route.done }));- await waitFor(() => expect(mock.models.putAgentChain).toHaveBeenCalledWith('claude', 'opus-5', { hops: [hops[0]] }));- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());- await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(false));-- fireEvent.click(enter);- expect(await screen.findByTestId('destination')).toBeTruthy();- expect(mock.api.mutateConfig).toHaveBeenCalledExactlyOnceWith([{ kind: 'set', path: ['setup_completed'], value: true }]);- expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();- });-- it('saves the Codex card onto Codex and refreshes Enter after the real PUT', async () => {- const user = userEvent.setup();- const saved: Record<string, typeof hops> = { claude: [], codex: [] };- serveAgents('claude-agent', [- { ...CLAUDE_AGENT, model: 'opus-5' },- { name: 'codex', backend: 'codex', model: 'gpt-5' },- ]);- mock.models.listAgents.mockResolvedValue([- hubSupply('claude', [route('claude-agent', { effective_model_id: 'opus-5' })]),- hubSupply('codex', [route('codex', { effective_model_id: 'gpt-5' })]),- ]);- mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({- ok: true, backend, enabled: true, installed: true, auth: 'none',- application: 'applied',- ready: Boolean(saved[backend]?.length),- entry_eligible: Boolean(saved[backend]?.length),- supply_mode: 'hub',- }));- mock.models.getAgentChain.mockImplementation(async (backend: AgentBackend, model: string) => ({- ...chainOf(saved[backend] ?? []),- backend,- model_id: model,- }));- mock.models.previewAgentChain.mockImplementation(async (backend, model, body) => ({- ...chainOf(body.manual_override?.hops ?? []),- backend,- model_id: model,- }));- mock.models.putAgentChain.mockImplementation(async (backend, model, body) => {- saved[backend] = body.hops;- return { chain: { ...chainOf(body.hops), backend, model_id: model } };- });-- await arriveAtProviders();- fireEvent.click(primaryAction());- const enter = await screen.findByRole('button', { name: 'Enter workspace' });- await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(true));- fireEvent.click(await assistantCard('Codex').findByRole('button', { name: en.onboarding.setup.configureRoute }));- await user.click(await screen.findByRole('button', { name: en.settings.models.routeDialog.addHop }));- await user.click(screen.getByRole('option', { name: /gpt-5/ }));- await user.click(screen.getByRole('button', { name: en.settings.models.routeDialog.add.confirm }));- await user.click(screen.getByRole('button', { name: en.onboarding.route.done }));- await waitFor(() => expect(mock.models.putAgentChain).toHaveBeenCalledWith('codex', 'gpt-5', { hops: [hops[0]] }));- expect(mock.models.putAgentChain).not.toHaveBeenCalledWith('claude', expect.anything(), expect.anything());- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());- await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(false));- fireEvent.click(enter);- expect(await screen.findByTestId('destination')).toBeTruthy();- });-});diff --git a/ui/src/components/onboarding/onboarding-providers.css b/ui/src/components/onboarding/onboarding-providers.cssindex 45a862819..f0587a42e 100644--- a/ui/src/components/onboarding/onboarding-providers.css+++ b/ui/src/components/onboarding/onboarding-providers.css@@ -31,24 +31,38 @@* the story's `--ob-wire` family. Active and hover wear `--ob-active-shadow`.*/-.setup-provider-stage {+/* The handoff layer holds clones of this stage's own parts, and it hangs off the+ shared screens region rather than off the stage — so without this it resolves none+ of the names below. A `width: var(--obp-logo) !important` that cannot resolve is not+ ignored: it computes to `auto` and outranks the inline size the flight measured,+ which is what drew a 32px mark at 200px mid-flight. */+.setup-provider-stage,+.onboarding-handoff-layer {/* Behind every `--ob-*` name L1 owns or may promote, the value this screen wasmeasured at. Reading through the token first means a promotion upstream landshere 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)));+ /* L1 authors one inset per tier for this card — the reference pads all four sides+ equally — so both axes read that token and only fall back to the scaled default. */+ --obp-card-pv: var(--ob-provider-card-pad, calc(14 * var(--ob-u)));+ --obp-card-ph: var(--ob-provider-card-pad, calc(14 * var(--ob-u)));--obp-card-gap: var(--ob-provider-card-gap, calc(10 * var(--ob-u)));+ /* L1 authors this tier by tier — 18 here, 20 on the tall tier, 13 on phones, which+ is the reference's own ladder. Reading the story's `--ob-card-name` instead left+ every name on this stage two pixels short of the frame it was measured against. */+ --obp-card-name: var(--ob-provider-card-name, var(--ob-card-name));--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-logo: var(--ob-provider-card-logo, calc(32 * 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-destination-h: var(--ob-destination-h, calc(76 * 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)));+}+.setup-provider-stage {width: 100%;display: flex;flex-direction: column;@@ -57,6 +71,10 @@gap: 0;}+.onboarding-step[data-setup-screen="providers"] .onboarding-primary-action:disabled {+ opacity: 0.4;+}+/* ---- Provider sources ---------------------------------------------------- *//* The same three tracks the story's cards use, so the diagram's columns and the@@ -86,24 +104,33 @@.setup-provider-card[data-state='connected'],.setup-provider-card[aria-pressed='true'] {border-color: var(--mint);- background: var(--card-wash);+ background: var(--mint-soft);+ box-shadow: var(--ob-active-shadow, var(--shadow-glow-onboarding-mint));}.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));}+/* Greying a card out and showing the no-entry cursor says the person is being kept+ from acting. A connected card is disabled for a purely mechanical reason — there is+ nothing left to press — and the reference draws it at full strength beside the rest.+ Only a blocked card, which the person really is being held out of, wears the denial. */.setup-provider-card:disabled {+ cursor: default;+}+.setup-provider-card[data-blocked]: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. */+/* The third card is an invitation rather than a thing that exists, but it is one of+ the row's three cards: the reference gives it the same shell as the two beside it,+ so it carries the same surface as the two beside it and says what it is on its+ edge: the reference keeps this one card's border dashed. */.setup-provider-card[data-state='add'] {border-style: dashed;- border-color: var(--border-strong);- background: transparent;+ border-color: var(--ob-card-border);+ background: var(--ob-card);}.setup-provider-card[data-state='add']:hover,.setup-provider-card[data-state='add']:focus-visible {@@ -127,8 +154,8 @@.setup-provider-logo,.setup-destination-logo,.setup-destination-logo > span {- width: var(--ob-card-logo) !important;- height: var(--ob-card-logo) !important;+ width: var(--obp-logo) !important;+ height: var(--obp-logo) !important;}/* The destination's mark is a full-bleed brand path and fills its box, exactly asthe story card it morphs out of does. */@@ -137,18 +164,13 @@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+/* A bare mark, like the destination's and like the reference's: no well, no border+ and no second scale inside the box. The descendant selector also settles the sizewithout 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;+ width: 100%;+ height: 100%;+ object-fit: contain;display: block;color: var(--foreground);}@@ -156,7 +178,7 @@flex-shrink: 0;width: var(--obp-add);height: var(--obp-add);- color: var(--muted-foreground);+ color: var(--muted);}.setup-provider-copy {flex: 1 1 0;@@ -166,9 +188,9 @@gap: calc(3 * var(--ob-u));}.setup-provider-name {- font-size: var(--ob-card-name);- font-weight: 600;- line-height: 1.45;+ font-size: var(--obp-card-name);+ font-weight: 550;+ line-height: 1.3333;color: var(--foreground);overflow: hidden;text-overflow: ellipsis;@@ -177,17 +199,21 @@.setup-provider-key {font-size: var(--obp-card-key);line-height: 1.45;- color: var(--muted-foreground);+ color: var(--muted);overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}-.setup-provider-check {+.setup-provider-check,+.setup-provider-add-mark {flex-shrink: 0;width: var(--obp-check);height: var(--obp-check);- color: var(--mint-ink);}+.setup-provider-check { color: var(--mint-ink); }+/* The plus states an offer, not a decision, so it is drawn in the same quiet ink the+ third card's plus wears rather than in the mint the check owns. */+.setup-provider-add-mark { color: var(--muted); }/* The count of what was added through Add more rides the card it describes. */.setup-provider-badge {flex-shrink: 0;@@ -204,6 +230,15 @@real cards. Stretching one viewBox over the whole diagram — which is how thestory draws its fixed circuit — would skew every curve the moment the columnwidth changed. */+/* The reference overrides the story's port fill for the setup screens — `setup-flow`+ sets `#D6EEE5` over `welcome`'s translucent mint — because a translucent dot on a+ card edge reads as a hole in the wire rather than as a terminal. Same token, this+ screen's scope; the story's own circuit keeps the value it was measured at. */+@media (prefers-color-scheme: light) {+ :root:not([data-theme="dark"]) .setup-provider-stage { --ob-port: #d6eee5; }+}+[data-theme="light"] .setup-provider-stage { --ob-port: #d6eee5; }+.setup-wires {position: relative;width: 100%;@@ -214,37 +249,33 @@display: block;width: 100%;height: 100%;- overflow: visible;+ /* The reference clips its band (`.gateway-lines`): a port sits on the edge the+ wire leaves from, and the half outside the band is meant to be cut rather than+ to ring above the card it hangs from. */+ overflow: hidden;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; }+/* What a wire, a port and a pulse *are* is the story's, by class. This band only says+ where they run and when they move: one 3.8s cycle carries the arrival at the gateway+ and the departure from it, so the two bands read as one route rather than two loops+ that happen to overlap. Paused holds the frame; `.onboarding-shell`'s reduced-motion+ rule stops it outright, and a stopped pulse is already invisible. */+.setup-wires .onboarding-pulse-core {+ /* The reference's own weight for this band: one 2-unit stroke carrying a 14-of-100+ segment. The story's 1.6 is sized to a taller diagram; here it arrives with a+ wider glow beneath it, and the two together blur the moment of arrival that this+ screen exists to show. */+ --ob-pulse-dash: 14;+ stroke-width: 2;+ animation-duration: 3800ms;+ animation-timing-function: linear;+ animation-iteration-count: infinite;+ animation-play-state: paused;+}+.setup-wires--inbound .onboarding-pulse-core { animation-name: onboarding-pulse-converge; }+.setup-wires--outbound .onboarding-pulse-core { animation-name: onboarding-pulse-distribute; }+.setup-provider-stage[data-motion='running'] .setup-wires .onboarding-pulse-core {+ animation-play-state: running;}/* ---- Gateway ------------------------------------------------------------- */@@ -265,12 +296,7 @@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);+ transition: border-color 150ms, box-shadow 150ms;}/* The one place the band's fixed height gives way, because what replaces the taglineis two sentences and a way out of them. The wires re-measure on the stage's resize,@@ -309,7 +335,7 @@max-width: 100%;font-size: var(--obp-card-key);line-height: 1.45;- color: var(--muted-foreground);+ color: var(--muted);overflow: hidden;text-overflow: ellipsis;white-space: nowrap;@@ -344,22 +370,21 @@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;+ border-radius: 9px;+ border: 1px solid var(--ob-card-border);+ background: var(--ob-card);}.setup-destination-name {- font-size: var(--ob-card-name);- font-weight: 600;- line-height: 1.45;+ font-size: var(--obp-card-name);+ font-weight: 550;+ line-height: 1.3333;color: var(--foreground);overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}-/* ---- Summary and the offer's reserved slot ------------------------------- */+/* ---- Summary ------------------------------------------------------------- */.setup-provider-summary {height: var(--obp-summary-h);@@ -368,23 +393,12 @@justify-content: center;padding: 0 var(--obp-card-ph);font-size: var(--ob-cap-fs);- line-height: 1.45;- color: var(--muted-foreground);+ line-height: 1.5;+ color: var(--muted);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@@ -438,7 +452,7 @@.setup-add-subtitle {font-size: 12.5px;line-height: 1.5;- color: var(--muted-foreground);+ color: var(--muted);}/* The same segmented control `ApiKeySourceForm` uses for protocol, at this@@ -460,7 +474,7 @@border-radius: 7px;font-size: 12.5px;font-weight: 500;- color: var(--muted-foreground);+ color: var(--muted);transition: background 0.15s ease, color 0.15s ease;}.setup-add-method:hover:not(:disabled) { color: var(--foreground); }@@ -484,13 +498,13 @@.setup-add-note {font-size: 12px;line-height: 1.55;- color: var(--muted-foreground);+ color: var(--muted);}.setup-add-group {font-size: 11.5px;font-weight: 600;- color: var(--muted-foreground);+ color: var(--muted);}.setup-add-row {@@ -549,7 +563,7 @@.setup-add-row-detail {font-family: "JetBrains Mono", ui-monospace, monospace;font-size: 11px;- color: var(--muted-foreground);+ color: var(--muted);overflow: hidden;text-overflow: ellipsis;white-space: nowrap;@@ -565,7 +579,7 @@.setup-add-row-tag {flex: none;font-size: 11px;- color: var(--muted-foreground);+ color: var(--muted);}.setup-add-foot {@@ -588,7 +602,7 @@gap: 6px;font-size: 11.5px;line-height: 1.4;- color: var(--muted-foreground);+ color: var(--muted);}.setup-add-status-icon {@@ -628,7 +642,6 @@.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 andstays independent of the method — clamped harder against a short viewport,@@ -640,6 +653,3 @@max-height: calc(100dvh - 32px);}}-@media (prefers-reduced-motion: reduce) {- .setup-wire-pulse { animation: none !important; }-}diff --git a/ui/src/components/onboarding/onboarding.css b/ui/src/components/onboarding/onboarding.cssindex ec77d599b..a20775990 100644--- a/ui/src/components/onboarding/onboarding.css+++ b/ui/src/components/onboarding/onboarding.css@@ -35,8 +35,6 @@/* The enable switch the connection puts in the role's slot: a 42x24 track witha 2px border and a 16px thumb, drawn per theme by the reference (eq9QT) —dark keeps a lit border on the on-state, light keeps none. */- --ob-notice-fg: #d0ddd6;- --ob-notice-link: #3fe0e5;--ob-idle-dot: #4c5060;--ob-skeleton: #ffffff12;--ob-skeleton-strong: #ffffff28;@@ -60,8 +58,6 @@--ob-tile-label: #d3d7e2;/* The import notice, drawn as its own mint-tinted plate rather than a variant ofthe assistant row: it is an offer, not part of the list it sits under. */- --ob-notice-bg: #172f27;- --ob-notice-border: #30473e;/* The middle band — a 900px-tall window — is the base tier; the bands belowrestate only what their frame draws differently. */@@ -89,11 +85,16 @@--ob-sub-lh: 24px;--ob-heading-gap: 8px;/* The heading block reserves its tier's own height — the two lines of type plus- the slack the frame draws under them — and then sits its tier's own distance- above the stage. Both numbers come from the frames' heading boxes: 71 and 15- under an 800px window, 88 and 12 under 900, 132 and 18 at 1920x1080. */+ the slack the frame draws under them. The number comes from the frames' heading+ boxes: 71 under an 800px window, 88 under 900, 132 at 1920x1080. */--ob-heading-h: 88px;- --ob-heading-mb: 12px;+ /* One breathing distance, spent twice: under the heading and under the stage.+ The reference gives its heading 38 (`flow-heading{margin-bottom:38px}`) and+ leaves comparable air above the action, so the composition reads as one band+ with the same margin top and bottom instead of content pinned under the title+ with the slack dumped above the button. Authored per tier like the type around+ it: 40 standard, 32 on a short window, 48 at the large reading, 27 stacked. */+ --ob-band-gap: 40px;--ob-main-top: 16px;--ob-access-w: 740px;--ob-access-pad: 28px;@@ -137,21 +138,21 @@the note at its clamp, and the two method rows. A tier that restates itspadding or its rows restates this with them. */--ob-assistant-wrap: 0px;- --ob-assistant-h: calc(2px + var(--ob-card-pv) * 2 + var(--ob-id-h) + var(--ob-card-gap) * 2+ --ob-assistant-h: calc(2px + var(--ob-card-pv) + var(--ob-card-ph) + var(--ob-id-h) + var(--ob-card-gap) * 2+ var(--ob-life-h) + var(--ob-note-lh) * 2 + var(--ob-spacer-2)+ var(--ob-method-h) * 2 + var(--ob-method-gap) + var(--ob-assistant-wrap));- --ob-import-gap: 20px;- /* What the capsule's slot holds whether the offer is absent, still loading,- arrived or dismissed: the reference's own 44-tall line on a desktop. */- --ob-import-h: 44px;- /* One reservation, spent by both steps: the taller of the two cards, the gap- under it, and the capsule's slot. */- --ob-stage-h: calc(max(var(--ob-card-h), var(--ob-assistant-h)) + var(--ob-import-gap) + var(--ob-import-h));- /* The diagram keeps the box the reference draws it in — the story's own card- plus the same band — so a reservation that has to hold a wrapped sentence on- the other step does not redraw the story. What it takes instead is slack- under the diagram, which is what the shorter step was already given. */- --ob-diagram-h: calc(var(--ob-card-h) + var(--ob-import-gap) + var(--ob-import-h));+ /* One floor under the cards, so a card that grows while its step is read — a+ sentence that wraps in one language, a state row that arrives with detection —+ cannot move the action. It reserves the cards only; whatever a step draws under+ them adds its own height on top, and the shared cell (see `.onboarding-screens`)+ is what then holds the three steps level. */+ --ob-stage-h: max(var(--ob-diagram-h), var(--ob-assistant-h));+ /* The diagram keeps the box the reference draws it in: the story's card plus the+ band the return wire needs under it — 296 around a 232-tall card, 326 around a+ 262, 394 around a 330, the card plus 64 at every reading. A reservation that+ has to hold a wrapped sentence on another step does not redraw the story. */+ --ob-story-band: 64px;+ --ob-diagram-h: calc(var(--ob-card-h) + var(--ob-story-band));background: var(--background);color: var(--foreground);@@ -176,8 +177,6 @@--ob-active-border: #10b981;--ob-active-shadow: var(--shadow-glow-onboarding-mint);--ob-divider: #08081214;- --ob-notice-fg: #435f52;- --ob-notice-link: #0e7490;--ob-idle-dot: #5c6079;--ob-skeleton: #08081214;--ob-skeleton-strong: #08081224;@@ -200,9 +199,7 @@--ob-tile-hover: #0808120a;--ob-well: #eef1f780;--ob-tile-label: #5c6079;- --ob-notice-bg: #edf7f1;- --ob-notice-border: #cedfd5;- }+ }}[data-theme="light"] .onboarding-shell {--ob-card: #ffffff;@@ -210,8 +207,6 @@--ob-active-border: #10b981;--ob-active-shadow: var(--shadow-glow-onboarding-mint);--ob-divider: #08081214;- --ob-notice-fg: #435f52;- --ob-notice-link: #0e7490;--ob-idle-dot: #5c6079;--ob-skeleton: #08081214;--ob-skeleton-strong: #08081224;@@ -233,8 +228,6 @@--ob-tile-hover: #0808120a;--ob-well: #eef1f780;--ob-tile-label: #5c6079;- --ob-notice-bg: #edf7f1;- --ob-notice-border: #cedfd5;}/* ---- Design tiers ---------------------------------------------------------@@ -263,7 +256,7 @@--ob-sub-lh: 22px;--ob-heading-gap: 6px;--ob-heading-h: 72px;- --ob-heading-mb: 15px;+ --ob-band-gap: 32px;--ob-main-top: 6px;--ob-access-pad: 22px;--ob-access-lead-fs: 13px;@@ -303,8 +296,11 @@--ob-sub-lh: 31px;--ob-heading-gap: 12px;--ob-heading-h: 132px;- --ob-heading-mb: 18px;- --ob-main-top: 90px;+ --ob-band-gap: 48px;+ /* Only the floor under the header now: the composition is centred in the room+ the window leaves, so a large screen no longer needs the offset that used to+ push a top-anchored frame down into view. */+ --ob-main-top: 20px;--ob-access-w: 830px;--ob-access-lead-fs: 17px;}@@ -391,6 +387,8 @@color: var(--popover-foreground);box-shadow: 0 8px 24px rgb(0 0 0 / 0.13);}+/* The row's frame is the onboarding header's; its hover and selected fills come from+ the switcher itself, so both variants of the menu answer for them in one place. */.onboarding-language-menu button {display: flex;align-items: center;@@ -400,12 +398,9 @@padding: 10px;border: 0;border-radius: 6px;- background: transparent;- color: inherit;font-size: 14px;text-align: left;}-.onboarding-language-menu button:hover { background: var(--surface-2); }/* `1 0 auto`: this box is never shorter than what it holds, so a composition tallerthan the window pushes the shell into its own scroll rather than being clipped above@@ -420,6 +415,14 @@guard resolves. A percentage cannot: `min-height: %` resolves against height. */container-type: inline-size;}+/* The composition sits in the middle of whatever room the window leaves under the+ header, so a tall window reads as one centred frame instead of a screenful of+ content with an empty half below it. Auto margins rather than `align-items:+ center`: when the composition is taller than the box, an auto margin resolves to+ zero, which keeps the top edge reachable and lets the shell scroll as before. */+.onboarding-shell-content > * {+ margin-block: auto;+}/* Owner amendment, 2026-09-18: both steps share the same top anchor.Normal flow scrolls on short windows; only the lower composition changes. */.onboarding-welcome, .onboarding-setup {@@ -429,26 +432,27 @@width: 100%;max-width: var(--ob-content-w);margin: 0 auto;- /* Spacing is carried by margins, not by one flex gap: the heading's distance to- the stage is a tier number (15 / 12 / 18 / 27) while the stage's distance to- the action is 20 in every row, and the access block sits 40 under the action. */-}-/* The block between the heading and the action, in both steps, and the one owner of- every layout reservation this screen makes. Its floor is `--ob-stage-h`: the taller- of the two steps' cards plus the band the reference draws under it — so the shorter- step is padded to exactly the taller one's height instead of both being given a- number to keep in sync by hand. That is what puts "Get started" and "Enter- Workbench" on identical coordinates: same heading above, same stage height, same- action width below.- The same floor is what keeps the action still when the import notice is dismissed:- the notice lives inside this box, in a slot that keeps its height either way (see- `.onboarding-import-slot`), so refusing the offer changes what is drawn in the box,- not the height of the box or of anything under it.+ /* Spacing is carried by margins, not by one flex gap: the heading and the stage+ each sit `--ob-band-gap` from what follows them, and the access block sits 40+ under the action.+ `min-height: 100%` is what lets a short step spend the cell it shares: the cell+ is as tall as the tallest step, so this step is stretched to the same height and+ its stage (below, `flex: 1`) is given the difference to centre its content in+ instead of leaving all of it above the action. */+ min-height: 100%;+}+/* The block between the heading and the action, in every step, and the one owner of+ the layout reservations this screen makes.+ What holds "Get started", "Continue" and "Enter Workbench" on identical coordinates+ is the cell the three steps share: it is as tall as the tallest of them, each step+ is stretched to it, and the action pair sits below the cell. `--ob-stage-h` is not+ that guarantee; it is the floor under the cards, so a card growing while its own+ step is read cannot move the action either. Whatever a step draws under the cards+ adds itself on top and is held level the same way.It applies at every width, phones included: the stack band re-derives the same floor- from the stacked card instead of the side-by-side one (see the 759 band), so the- invariant holds there too. Matching the two costs slack at the bottom of whichever- step is shorter — accepted, because a person moving between the two steps, or- refusing the offer, should not have the button move out from under their finger. */+ from the stacked card instead of the side-by-side one (see the 759 band). The steps+ that are shorter than the tallest spend the difference around their composition+ rather than under it, which is the `justify-content` below. */.onboarding-stage {width: 100%;display: flex;@@ -456,7 +460,14 @@align-items: center;gap: 20px;min-height: var(--ob-stage-h);- margin-bottom: 20px;+ margin-bottom: var(--ob-band-gap);+ /* The composition is centred in the band between the heading and the action, so a+ step shorter than the tallest one reads as one frame with equal air above and+ below rather than as content pushed against its title. The tallest step has no+ slack to spend, which is what makes `--ob-band-gap` its own exact distance both+ ways; every shorter step can only be further from its heading, never nearer. */+ flex: 1;+ justify-content: center;}/* The reference swaps the two screens as one composition: the outgoing layer@@ -482,7 +493,7 @@text-align: center;width: 100%;min-height: var(--ob-heading-h);- margin-bottom: var(--ob-heading-mb);+ margin-bottom: var(--ob-band-gap);}/* The heading block reserves its tier's own two lines of type, so a title that wrapsin one step or one language and not the other cannot move the stage below it. On@@ -543,7 +554,10 @@border-radius: 18px;border: 1px solid var(--ob-card-border);background: var(--ob-card);- padding: var(--ob-card-pv) var(--ob-card-ph);+ /* The bottom inset is the side inset, not the top one: what sits on the bottom edge+ is a full-width row of actions, and a row that stops 20 from the sides and 70 from+ the floor reads as floating rather than as the card's own last line. */+ padding: var(--ob-card-pv) var(--ob-card-ph) var(--ob-card-ph);gap: var(--ob-card-gap);transition: border-color 650ms, box-shadow 650ms;}@@ -610,6 +624,9 @@color: var(--muted);white-space: nowrap;}+/* The reference sets the role in bold (`.flow-role`, 700): at 11px on a muted grey it+ is the one label on the card that has to read as a tag rather than as running text. */+.onboarding-card-role { font-weight: 700; }.onboarding-assistant-enable { display: flex; align-items: center; }/* The enable switch: a real `role="switch"` in the reference's own geometry — a 42x24track, a 2px border and a 16px thumb that travels 18px. The invisible ring around it@@ -796,16 +813,38 @@}.onboarding-wire { stroke: var(--ob-wire); stroke-width: 1; }.onboarding-port { fill: var(--ob-port); stroke: var(--ob-port-border); stroke-width: 1; }-/* A single 16-unit segment of a 100-unit path: the pulse crosses once and leaves. */+/* A single segment of a 100-unit path: the pulse crosses once and leaves. How long+ that segment is belongs to the surface drawing it — the story runs it at 16, the+ setup band at the reference's 14 — so the length is a variable the keyframes read+ too, and a scope changes the pulse by changing one number rather than by owning a+ second pair of keyframes that would then have to be kept in step with these. */.onboarding-pulse-core, .onboarding-pulse-halo {- stroke-dasharray: 16 116;- stroke-dashoffset: 16;+ --ob-pulse-dash: 16;+ stroke-dasharray: var(--ob-pulse-dash) calc(var(--ob-pulse-dash) + 100);+ stroke-dashoffset: var(--ob-pulse-dash);stroke-linecap: round;opacity: 0;}.onboarding-pulse-core { stroke: var(--ob-pulse); stroke-width: 1.6; }.onboarding-pulse-halo { stroke: var(--ob-pulse-glow); stroke-width: 4; }+/* The same crossing, on a clock instead of a handoff. The story plays one per event,+ because there the pulse *is* the event; a standing route has no event to play, so+ it runs a cycle — and the two halves of that cycle are one relay, arriving at the+ gateway before anything leaves it. The offsets belong beside the dasharray above:+ the dash length is the segment entering, -100 is a full path length past the far+ end, and reading either one anywhere else would be reading half of a pair. */+@keyframes onboarding-pulse-converge {+ 0% { stroke-dashoffset: var(--ob-pulse-dash); opacity: 0; }+ 5%, 34% { opacity: 1; }+ 40%, 100% { stroke-dashoffset: -100; opacity: 0; }+}+@keyframes onboarding-pulse-distribute {+ 0%, 48% { stroke-dashoffset: var(--ob-pulse-dash); opacity: 0; }+ 53%, 86% { opacity: 1; }+ 92%, 100% { stroke-dashoffset: -100; opacity: 0; }+}+/* The caption rides the return wire rather than the container floor: the wire'shorizontal run is at y=338 of the wire box, whose height is the card times 350/300,so this is the same line at every tier. Centring on it (rather than sitting under@@ -1039,6 +1078,74 @@card's min-height absorbs the extra line the way it absorbs an error line. */.onboarding-method-row > span, .onboarding-method-connected > span { min-width: 0; }.onboarding-method-connected > svg { color: var(--mint-ink); flex-shrink: 0; }+/* The shared route, drawn on the card: a label over the model it currently resolves+ to, and the chevron that says the dialog is behind it. Two lines of type where the+ method rows carry one, so it takes the method row's height plus a line — still+ inside the two rows the card's floor reserves, which is what keeps the three cards+ and the action below them where they were. */+.onboarding-model-choice {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ width: 100%;+ min-height: calc(var(--ob-method-h) + 16px);+ padding: 8px 11px;+ border: 1px solid var(--border-strong);+ border-radius: 8px;+ background: var(--ob-card);+ color: var(--foreground);+ font-family: inherit;+ text-align: left;+ cursor: pointer;+}+.onboarding-model-choice:hover:not(:disabled) { border-color: var(--ob-active-border); }+.onboarding-model-choice:disabled { cursor: default; color: var(--muted); }+/* Switched off, the row is a statement rather than a control, so it steps back to the+ note's weight instead of wearing the dimming that means "blocked". */+.onboarding-model-choice:disabled { border-color: var(--border); }+/* The read has not landed: the box, the label and a bar where the model will be. A+ spinner here would say the card is working; the bar says the name is on its way. */+.onboarding-model-choice-pending {+ display: block;+ width: 110px;+ height: 13px;+ border-radius: 4px;+ background: color-mix(in srgb, var(--muted) 22%, transparent);+}+@media (prefers-reduced-motion: no-preference) {+ .onboarding-model-choice-pending { animation: onboarding-choice-pulse 1.4s ease-in-out infinite; }+}+@keyframes onboarding-choice-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.45; } }+.onboarding-model-choice > span { display: flex; flex-direction: column; gap: 3px; min-width: 0; }+.onboarding-model-choice small {+ font-size: 11px;+ line-height: 14px;+ color: var(--muted);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.onboarding-model-choice strong {+ font-size: var(--ob-method-fs);+ line-height: 18px;+ font-weight: 500;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.onboarding-model-choice > svg { flex-shrink: 0; color: var(--muted); }+/* Installed but off: a line, not a control. The switch above is the only thing to+ press, and this says the binary is already there. */+.onboarding-method-receipt {+ display: flex;+ align-items: center;+ gap: 7px;+ min-height: var(--ob-method-h);+ font-size: var(--ob-method-fs);+ color: var(--muted);+}+.onboarding-method-receipt > svg { color: var(--mint-ink); flex-shrink: 0; }/* The card's body reads top to bottom the way the story's does: the identity header,then the state line, then the note and the work. The body is the flexible one, so anerror or a wrapped action grows downward and the three identity headers stay level@@ -1067,7 +1174,11 @@the reference stacks them, left-aligned with their icon leading, and the connectedstate wears the same row with a mint check. A wrapped horizontal pair read as twochips competing for one line. */+/* On the card's bottom edge, which is where the reference draws them: the note above+ is what varies in length — one line in Chinese, two in English — and letting that+ decide where the methods start leaves three cards with three different floors. */.onboarding-assistant-actions {+ margin-top: auto;display: flex;flex-direction: column;align-items: stretch;@@ -1098,87 +1209,6 @@under a 299 one. The reference's 10 between the two rows is this gap. */.onboarding-setup-footer { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 10px; }-/* ---- Import notice ------------------------------------------------------- */--/* The capsule's own place in the stage, kept whether or not anything is drawn in it:- the offer arrives after a read that the rest of the step does not wait for, and it- can be refused. A slot that is always there makes all four states — absent, still- loading, arrived, dismissed — cost the same height, so none of them can move the- action under the person's pointer. It is the stage's gap that puts the 20 above it,- and the stage's own floor holds the same total when the cards below the frame grow,- which is why this reserves a height and nothing else. The capsule sits at the top of- it: slack belongs under the composition, not between it and the offer. */-.onboarding-import-slot {- width: 100%;- min-height: var(--ob-import-h);- display: flex;- align-items: flex-start;- justify-content: center;-}--/* An offer, not a row of the list above it: a capsule that takes the width of what it- says and sits centred under the cards, flat and one line tall. A full-width banner- read as a fourth row of the list and as the loudest thing on a step whose subject is- the three assistants; a capsule is an aside.- The reference gives it 20 above, 44 of its own and 20 below, which is exactly the 64- the stage reserves beyond the card — so the offer costs the composition nothing it- was not already spending. Its own height stays the reference's line at every tier;- what the tier restates is the slot that holds it. */-.onboarding-import-notice {- max-width: 100%;- min-height: 44px;- display: flex;- align-items: center;- gap: 12px;- padding: 0 8px 0 14px;- border: 1px solid var(--ob-notice-border);- border-radius: 999px;- background: var(--ob-notice-bg);- box-shadow: none;-}-.onboarding-import-notice-icon { flex-shrink: 0; color: var(--mint-ink); }-.onboarding-import-notice-text {- min-width: 0;- font-size: 13px;- line-height: 20px;- color: var(--ob-notice-fg);-}-.onboarding-import-notice-actions { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }-/* A light control rather than a green word: the sentence already carries the mint, and- an action a person is meant to press should look pressable. The reference draws it- as a small 6-radius button inside the capsule, 28 tall. */-.onboarding-import-notice-action {- height: 28px;- border-radius: 6px;- padding: 0 10px;- font-size: 12px;- white-space: nowrap;-}-.onboarding-import-notice-help {- font-size: 12px;- color: var(--ob-notice-link);- white-space: nowrap;- text-decoration: underline;- text-decoration-style: dotted;- text-underline-offset: 4px;-}-.onboarding-import-notice-help:hover, .onboarding-import-notice-help:focus-visible { color: var(--foreground); }-.onboarding-import-notice-dismiss {- flex-shrink: 0;- display: grid;- place-items: center;- width: 28px;- height: 28px;- margin-right: -4px;- border-radius: 999px;- color: var(--ob-notice-fg);- transition: color 150ms, background 150ms;-}-.onboarding-import-notice-dismiss:hover, .onboarding-import-notice-dismiss:focus-visible {- color: var(--foreground);- background: var(--ob-tile-hover);-}-/* ---- Bands --------------------------------------------------------------- *//* The gutter is the only thing a mid-sized window changes. There is nothing between the@@ -1236,21 +1266,15 @@--ob-heading-h: 138px;--ob-h1-min: calc(2 * var(--ob-h1-lh));--ob-p-min: var(--ob-sub-lh);- --ob-heading-mb: 27px;+ --ob-band-gap: 27px;/* Stacked, the cards are one above another and nothing is narrow enough towrap a name or a method row: the card's own composition answers for thetier again. */--ob-assistant-wrap: 0px;--ob-stack-gap: 16px;- /* Four things do not fit on one line here, so the capsule folds (see the rule- below) and its slot reserves the fold: two rows of type for the sentence,- the row gap, and the two actions on a row of their own — which is what a- 320px reading of the offer actually draws. */- --ob-import-h: 126px;/* The same reservation as the desktop rows, re-derived from the stack: three- of the taller card, the two gaps between them, and the capsule's band. */- --ob-stage-h: calc(max(var(--ob-card-h), var(--ob-assistant-h)) * 3 + var(--ob-stack-gap) * 2- + var(--ob-import-gap) + var(--ob-import-h));+ of the taller card and the two gaps between them. */+ --ob-stage-h: calc(max(var(--ob-card-h), var(--ob-assistant-h)) * 3 + var(--ob-stack-gap) * 2);--ob-main-top: 0px;--ob-access-w: 100%;--ob-access-pad: 24px;@@ -1291,23 +1315,6 @@middle of the screen. The column it was aligned to is stacked away here, so thefraction has nothing left to point at and the action takes the width instead. */.onboarding-action-w { width: 100%; }- /* Four things do not fit on one 44px line at this width. The sentence and its- dismiss keep the first row — a person must be able to read the offer and refuse- it without scanning further — and the two actions take the second. Placement is- explicit so it does not depend on the order the component happens to render in. */- .onboarding-import-notice {- display: grid;- grid-template-columns: auto minmax(0, 1fr) auto;- align-items: center;- row-gap: 8px;- padding: 10px 12px;- /* Two rows is not a capsule: the pill radius would bow the long sides. */- border-radius: 14px;- }- .onboarding-import-notice-icon { grid-area: 1 / 1; }- .onboarding-import-notice-text { grid-area: 1 / 2; }- .onboarding-import-notice-dismiss { grid-area: 1 / 3; }- .onboarding-import-notice-actions { grid-area: 2 / 1 / 2 / -1; flex-wrap: wrap; }}/* A short window scrolls. The card answers to the window through the tiers above, soa short window gets the shorter authored card instead of a compressed composition;@@ -1348,17 +1355,31 @@/* C2/C3: persistent screens share one reservation and one shell-owned action pair. */.onboarding-step { max-width: var(--ob-content-w); }-.onboarding-screens { position: relative; width: 100%; }-.onboarding-screens [hidden], .onboarding-access[hidden] { display: none !important; }+/* The three screens share one cell, so the region is always as tall as the tallest of+ them and the action pair below it never moves between screens — the reference holds+ its stage at one height for the same reason. A screen that is not the current one+ keeps its `hidden` attribute, and with it its place outside the accessibility tree+ and out of reach of a pointer; what it gives up is only the right to collapse the+ region it shares. */+.onboarding-screens { position: relative; width: 100%; display: grid; }+.onboarding-screens > [data-setup-screen-root] { grid-area: 1 / 1; min-width: 0; }+/* Inside the base layer, and important, because that is the weight the framework hides+ `[hidden]` with: a screen keeps the attribute — and with it its place outside the+ accessibility tree and out of tab order — while still holding its share of the cell. */+@layer base {+ .onboarding-screens > [data-setup-screen-root][hidden] { display: block !important; }+}+.onboarding-screens > [data-setup-screen-root][hidden] { visibility: hidden; pointer-events: none; }+.onboarding-screens [hidden]:not([data-setup-screen-root]), .onboarding-access[hidden] { display: none !important; }.onboarding-handoff-layer { position: absolute; inset: 0; pointer-events: none; z-index: 3; }.onboarding-handoff-layer * { animation-play-state: paused !important; }.onboarding-handoff-card { position: absolute; pointer-events: none; }-.onboarding-handoff-surface { position: absolute; inset: 0; border: 1px solid; transform-origin: top left;- /* The halo a working card wears is a token, so the flight borrows it through the same- name and fades it out on the token's own terms rather than carrying a computed- shadow string through the animation. */- transition: box-shadow 360ms ease 480ms; }-.onboarding-handoff-surface[data-glow="true"] { box-shadow: var(--ob-active-shadow); }+.onboarding-handoff-surface { position: absolute; inset: 0; border: 1px solid; transform-origin: top left; }+/* The card an identity is flying onto is held until it lands: the moving shell is the+ one that should be seen crossing, and the two drawn at once read as a double. */+.onboarding-step[data-handoff="providers"] .setup-destinations,+.onboarding-step[data-handoff="intro"] .onboarding-collaboration-card,+.onboarding-step[data-handoff="assistants"] .onboarding-assistant { visibility: hidden; }.onboarding-step[data-handoff] .onboarding-primary-action:disabled { opacity: 1; }.onboarding-heading h1:focus { outline: none; }.onboarding-flow-error { width: 100%; margin-top: 16px; text-align: center; color: var(--destructive-ink); overflow-wrap: anywhere; }@@ -1368,23 +1389,79 @@cannot intercept a tap meant for the buttons — which is what it did while it waslifted out of flow and offset back over the footer. The slot itself costs nothingwhen no screen is contributing one; the caption brings its own gap. */-.onboarding-action-aside { width: 100%; display: flex; flex-direction: column; gap: 16px; }-/* The slot costs nothing while no screen contributes to it, and pays for its own- distance from the pair the moment one does — so the gap belongs here rather than on- whichever node happens to be first. */-.onboarding-action-aside:not(:empty) { margin-top: 16px; }+/* The slot sits in the screens' shared cell, on its bottom edge, and grows upward into+ the room the screen leaves above the action.+ It is in the cell rather than in the column because the column is centred in the+ window: a caption in the flow moves the heading, the cards and the action by half of+ its own height, which is exactly how the assistants step came to sit 9px above the+ two before it. Bottom-aligned in the cell, what it holds costs the pair nothing, and+ the space it spends is space the screen was already leaving empty.+ Capped, because that room is not the same on every screen: the provider step is the+ tallest and leaves only the band gap. `--ob-aside-max` is the measured floor of the+ screen's own empty band, and what does not fit scrolls rather than covering a card. */+.onboarding-screens > .onboarding-action-aside {+ grid-area: 1 / 1;+ align-self: end;+ z-index: 2;+ margin-bottom: 12px;+ max-height: var(--ob-aside-max, calc(var(--ob-band-gap) - 12px));+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 16px;+}+/* The assistants step leaves more room than the band gap — 76 clear at the narrowest+ desktop tier, 60 on a phone — and it is the step that carries the OpenCode permission+ block, the tallest thing the slot ever holds. 48 is what every tier can give it+ without reaching the cards; the block scrolls inside that. */+/* Align the captions without moving the shared heading, card, or action anchors. */+@media (min-width: 760px) {+ .onboarding-shell {+ --ob-caption-drop: calc(var(--ob-story-band) - var(--ob-summary-h) / 2 - var(--ob-card-h) * 38 / 300);+ --ob-caption-nudge: 36px;+ }+ [data-setup-screen-root="intro"] .onboarding-story-caption {+ top: calc(var(--ob-card-h) * 338 / 300 + (var(--ob-stage-h) - var(--ob-diagram-h)) / 2 + var(--ob-caption-drop) + var(--ob-caption-nudge));+ }+ /* The hint grows around the caption line inside the room above the action. */+ .onboarding-step[data-setup-screen="assistants"] > .onboarding-screens > .onboarding-action-aside:not(:empty) {+ --ob-aside-half: calc(var(--ob-card-h) * 38 / 300 - 8px);+ margin-bottom: calc(var(--ob-band-gap) + var(--ob-summary-h) / 2 - var(--ob-aside-half));+ min-height: calc(var(--ob-aside-half) * 2);+ max-height: calc(var(--ob-aside-half) * 2);+ justify-content: center;+ }+}+@media (max-height: 800px) and (min-width: 760px) {+ .onboarding-shell { --ob-caption-nudge: 37.5px; }+}+@media (min-width: 1600px) and (min-height: 950px) {+ .onboarding-shell { --ob-caption-nudge: 19.5px; }+}+@media (max-width: 759px) {+ .onboarding-step[data-setup-screen="assistants"] { --ob-aside-max: 48px; }+}.onboarding-setup-hint { width: 100%; text-align: center; }+/* Sentence centred on the action's axis, rescan beside it: equal flanking columns put+ the middle one in the middle of the slot whatever the link costs, and the link starts+ where the sentence ends. Both columns can give all their width back, so a narrow+ window wraps the sentence instead of pushing the link off the screen. */+.onboarding-setup-hint-line { display: grid; grid-template-columns: 1fr auto 1fr; align-items: baseline; gap: 6px; }+.onboarding-setup-hint-line > span { grid-column: 2; }+.onboarding-setup-hint-line > :not(span) { grid-column: 3; justify-self: start; }/* Provider tiers are consumed by L2; their bands are the same C3 bands as the shell. */.onboarding-shell {--ob-gateway-h: 72px;--ob-provider-card-h: 76px;--ob-provider-card-pad: 14px;+ --ob-provider-card-gap: 10px;--ob-provider-card-logo: 32px;--ob-provider-card-name: 18px;--ob-provider-card-key: 11px;--ob-wire-h: 48px;- --ob-destination-h: 84px;+ --ob-destination-h: 76px;+ --ob-summary-h: 45px;--ob-gap: 10px;}@media (max-height: 800px) and (min-width: 760px) {@@ -1394,6 +1471,6 @@.onboarding-shell { --ob-gateway-h: 80px; --ob-provider-card-h: 88px; --ob-provider-card-logo: 35px; --ob-provider-card-name: 20px; --ob-provider-card-key: 12px; }}@media (max-width: 759px) {- .onboarding-shell { --ob-provider-card-h: 116px; --ob-provider-card-pad: 10px; --ob-provider-card-logo: 25px; --ob-provider-card-name: 13px; --ob-provider-card-key: 10px; --ob-wire-h: 42px; --ob-gap: 7px; --ob-destination-h: 120px; --ob-content-w: 460px; }+ .onboarding-shell { --ob-provider-card-h: 116px; --ob-provider-card-pad: 10px; --ob-provider-card-gap: 6px; --ob-provider-card-logo: 25px; --ob-provider-card-name: 13px; --ob-provider-card-key: 10px; --ob-wire-h: 42px; --ob-gap: 7px; --ob-destination-h: 120px; --ob-content-w: 460px; }.onboarding-story-caption { display: none; }}diff --git a/ui/src/components/onboarding/providers/AddSourceDialog.test.tsx b/ui/src/components/onboarding/providers/AddSourceDialog.test.tsxindex f6a492d2f..c5c2c74a7 100644--- a/ui/src/components/onboarding/providers/AddSourceDialog.test.tsx+++ b/ui/src/components/onboarding/providers/AddSourceDialog.test.tsx@@ -349,21 +349,19 @@ describe('AddSourceDialog — detected', () => {expect(onAdded).not.toHaveBeenCalled();});- it('marks what is already there and offers no choice about it', async () => {+ it('keeps both detected keys selectable even when one mask matches a Hub source', 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')];+ const [sameMask, 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();+ expect(sameMask.dataset.state).toBe('detected');+ expect(sameMask.disabled).toBe(false);+ await user.click(sameMask);+ expect(onToggleDetected).toHaveBeenCalledWith(expect.objectContaining({ vendor: 'openai' }));+ onToggleDetected.mockClear();await user.click(open);expect(onToggleDetected).toHaveBeenCalledTimes(1);@@ -385,7 +383,6 @@ describe('AddSourceDialog — detected', () => {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);diff --git a/ui/src/components/onboarding/providers/AddSourceDialog.tsx b/ui/src/components/onboarding/providers/AddSourceDialog.tsxindex 7e9bb13f3..db88a9df8 100644--- a/ui/src/components/onboarding/providers/AddSourceDialog.tsx+++ b/ui/src/components/onboarding/providers/AddSourceDialog.tsx@@ -60,7 +60,7 @@ 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';+import { type ProviderSlot } from './providerStage';/*** The subscriptions setup offers.@@ -99,9 +99,8 @@ const subscriptionBrand = (vendor: string): string =>const DetectedRow: React.FC<{slot: ProviderSlot;selected: boolean;- added: boolean;onToggle: () => void;-}> = ({ slot, selected, added, onToggle }) => {+}> = ({ slot, selected, 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@@ -116,10 +115,10 @@ const DetectedRow: React.FC<{type="button"className="setup-add-row"data-provider={slot.vendor}- data-state={added ? 'added' : 'detected'}+ data-state="detected"{...(blocked ? { 'data-blocked': 'true' } : {})}- disabled={added || blocked}- {...(added || blocked ? {} : { 'aria-pressed': selected })}+ disabled={blocked}+ {...(blocked ? {} : { 'aria-pressed': selected })}aria-label={blocked? [slot.label, detail].filter(Boolean).join(' · '): t('onboarding.providers.addDetectedSelectNamed', { name: slot.label })}@@ -132,9 +131,7 @@ const DetectedRow: React.FC<{<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" />}+ {selected && <Check className="setup-add-row-check" strokeWidth={2.2} aria-hidden="true" />}</button>);};@@ -229,20 +226,6 @@ export const AddSourceDialog: React.FC<{// 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;@@ -475,7 +458,6 @@ export const AddSourceDialog: React.FC<{key={slot.vendor}slot={slot}selected={isSelected(slot)}- added={slot.mask !== null && addedCredentials.has(slot.mask)}onToggle={() => onToggleDetected(slot)}/>))}diff --git a/ui/src/components/onboarding/providers/ProviderCard.tsx b/ui/src/components/onboarding/providers/ProviderCard.tsxindex a32ada78c..b8b4d4905 100644--- a/ui/src/components/onboarding/providers/ProviderCard.tsx+++ b/ui/src/components/onboarding/providers/ProviderCard.tsx@@ -39,19 +39,19 @@ export const ProviderCard: FC<{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.+ // subscription has no key to mask, so it names the sign-in instead. A card with+ // nothing behind it states that — 「待添加」 beside the plus — rather than+ // describing what pressing it would offer: the offer is the whole card, and a+ // sentence restating it took the line that says whether this provider is there+ // yet. 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 });+ : t('onboarding.providers.cardNotAdded');// The migration feature's own words for the same group, so the card and the// review it opens from give one answer.@@ -66,7 +66,13 @@ export const ProviderCard: FC<{// 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')}` : '';+ // A connected card says so in words as well as in colour: the check and the mint fill+ // are the only other marks that it is already supplying models, and neither survives+ // being read aloud or looked at quickly. An unverified key keeps its own word instead,+ // because "saved" and "imported" are not the same claim.+ const note = slot.pending+ ? ` · ${t('settings.models.sourceDetail.status.saved')}`+ : connected ? ` · ${t('onboarding.providers.cardImported')}` : '';const keyLine = [`${written}${note}`, reason].filter(Boolean).join(' · ');const label = connected@@ -108,6 +114,12 @@ export const ProviderCard: FC<{{(connected || selected) && (<Check className="setup-provider-check" strokeWidth={2.2} aria-hidden="true" />)}+ {/* An empty slot is the one card here that is an offer, and it says so the way+ the third card does: the plus. The accessible name already carries what+ pressing it opens, so the mark is decoration. */}+ {slot.kind === 'empty' && (+ <Plus className="setup-provider-add-mark" strokeWidth={2} aria-hidden="true" />+ )}</button>);};diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsxindex c0be4f0b0..6b859f629 100644--- a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx+++ b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx@@ -27,7 +27,9 @@ import {type RegionRead,} from '@/components/settings/models/regionRead';import { providerBrandLabel } from '@/components/settings/providers/providerIdentity';+import { isMigrationDismissed, writeMigrationDismissed } from '@/lib/modelHubMigrationDismiss';import type {+ AgentBackend,AgentSupply,MigrationItem,RuntimeDependency,@@ -296,7 +298,6 @@ const gatewayCard = () => {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(); });@@ -453,7 +454,7 @@ describe('ProvidersScreen — the stage', () => {await settled();await waitFor(() => expect(cardFor('anthropic').dataset.state).toBe('connected'));- expect(within(cardFor('anthropic')).getByText('Subscription · [email protected]')).toBeTruthy();+ expect(within(cardFor('anthropic')).getByText('Subscription · [email protected] · In Model Hub')).toBeTruthy();expect(within(cardFor('anthropic')).queryByText(/Add a .* API Key/)).toBeNull();});@@ -463,8 +464,9 @@ describe('ProvidersScreen — the stage', () => {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();+ // No account either: the line is the kind, then the word that says it is already+ // supplying models — no stray separator where the account would have been.+ expect(within(cardFor('openai')).getByText('API key · In Model Hub')).toBeTruthy();});it('says a source was written even when the read that would show it fails', async () => {@@ -644,7 +646,6 @@ describe('ProvidersScreen — the stage', () => {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);@@ -671,48 +672,6 @@ describe('ProvidersScreen — the stage', () => {});});-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@@ -739,11 +698,8 @@ describe('ProvidersScreen — what it found but may not take', () => {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.+ // Nothing to import, so the footer asks for a provider instead of offering a batch.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 () => {@@ -760,8 +716,7 @@ describe('ProvidersScreen — what it found but may not take', () => {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();+ // One number, two readings: the card that is ticked and the footer.expect(lastAction()).toMatchObject({labelKey: 'onboarding.providers.actionImport',labelArgs: { count: 1 },@@ -775,7 +730,7 @@ describe('ProvidersScreen — what it found but may not take', () => {expect(lastAction().labelArgs).toEqual({ count: 1 });});- it('submits the batch it counted, and keeps the blocked card after the rescan', async () => {+ it('MH-MIG-004: 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();@@ -789,15 +744,14 @@ describe('ProvidersScreen — what it found but may not take', () => {// 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();+ // And nothing left to take over: the footer stops offering a batch.+ await waitFor(() => expect(lastAction().labelKey).not.toBe('onboarding.providers.actionImport'));});it('names a credential the server did not name, rather than guessing a brand', async () => {@@ -814,7 +768,6 @@ describe('ProvidersScreen — what it found but may not take', () => {// 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();});});@@ -992,7 +945,7 @@ describe('ProvidersScreen — what an import leaves behind', () => {// 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();+ expect(await screen.findByText('Migrated 2 configuration items')).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'));@@ -1089,8 +1042,89 @@ describe('ProvidersScreen — what an import leaves behind', () => {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 } });+ // Declining the review lets setup continue without changing the native key.+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ expect(modelsApi.applyMigration).not.toHaveBeenCalled();+ });++ it('remembers Not now across reloads and offers newly discovered keys', async () => {+ serve({ scan: [CODEX_KEY] });+ const first = renderScreen();+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionImport'));+ await activate(first.handle);+ await userEvent.setup().click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Not now' }));+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ first.unmount();++ const again = renderScreen();+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ again.unmount();++ server.scan = [CODEX_KEY, OPENCODE_KEY];+ renderScreen();+ await waitFor(() => expect(lastAction()).toMatchObject({ labelKey: 'onboarding.providers.actionImport', labelArgs: { count: 1 } }));+ });++ it('keeps a declined key dismissed when a different newly found key is selected', async () => {+ serve({ scan: [CODEX_KEY] });+ const first = renderScreen();+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionImport'));+ await activate(first.handle);+ await userEvent.setup().click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Not now' }));+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ first.unmount();++ server.scan = [CODEX_KEY, { ...OPENCODE_KEY, selected: false }];+ const second = renderScreen();+ await settled();+ expect(cardFor('openai').getAttribute('aria-pressed')).not.toBe('true');+ await waitFor(() => expect(cardFor('gemini').dataset.state).toBe('detected'));+ await userEvent.setup().click(cardFor('gemini'));+ await waitFor(() => expect(lastAction()).toMatchObject({ labelKey: 'onboarding.providers.actionImport', labelArgs: { count: 1 } }));+ second.unmount();++ server.scan = [CODEX_KEY];+ renderScreen();+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ });++ it('keeps A dismissed when the review unchecks A and migrates only B', async () => {+ serve({ scan: [CODEX_KEY, OPENCODE_KEY] });+ writeMigrationDismissed([CODEX_KEY]);+ const { handle } = renderScreen({ flow: {+ providerSelection: { scan: { items: [CODEX_KEY, OPENCODE_KEY] }, selectedBackends: ['codex', 'opencode'] },+ } });+ await settled();+ await activate(handle);+ const dialog = await screen.findByRole('dialog');+ const [a, b] = within(dialog).getAllByRole('checkbox');+ expect(a.getAttribute('aria-checked')).toBe('true');+ expect(b.getAttribute('aria-checked')).toBe('true');+ await userEvent.setup().click(a);+ expect(a.getAttribute('aria-checked')).toBe('false');+ expect(b.getAttribute('aria-checked')).toBe('true');+ await userEvent.setup().click(within(dialog).getByRole('button', { name: /Start migration/ }));+ await waitFor(() => expect(applied).toEqual([[OPENCODE_KEY.id]]));+ expect(isMigrationDismissed([CODEX_KEY])).toBe(true);+ cleanup();++ renderScreen();+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));+ expect(isMigrationDismissed([CODEX_KEY])).toBe(true);+ });++ it('clears only the identities in a linked group when its card is explicitly selected', async () => {+ const linkedA = { ...CODEX_KEY, required_backends: ['codex', 'opencode'] as AgentBackend[] };+ const linkedB = { ...OPENCODE_KEY, required_backends: ['codex', 'opencode'] as AgentBackend[] };+ serve({ scan: [linkedA, linkedB] });+ writeMigrationDismissed([linkedA, linkedB]);+ renderScreen();+ await settled();+ expect(cardFor('openai').getAttribute('aria-pressed')).toBe('false');+ await userEvent.setup().click(cardFor('openai'));+ await waitFor(() => expect(lastAction()).toMatchObject({ labelKey: 'onboarding.providers.actionImport', labelArgs: { count: 2 } }));+ expect(isMigrationDismissed([linkedA])).toBe(false);+ expect(isMigrationDismissed([linkedB])).toBe(false);});it('refuses a take-over the host cannot install an engine for, and still writes a key', async () => {@@ -1164,7 +1198,7 @@ describe('ProvidersScreen — what an import leaves behind', () => {await show({ runtimeRead: unreadRegion<RuntimeDependency>() });await act(async () => { gate.resolve(); });- expect(await screen.findByText('Migrated 1 API key into Model Hub')).toBeTruthy();+ expect(await screen.findByText('Migrated 1 configuration item')).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.diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.tsxindex 79e88b991..4087264f6 100644--- a/ui/src/components/onboarding/providers/ProvidersScreen.tsx+++ b/ui/src/components/onboarding/providers/ProvidersScreen.tsx@@ -19,6 +19,7 @@ import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';+import { clearMigrationDismissed, isMigrationDismissed, writeMigrationDismissed } from '@/lib/modelHubMigrationDismiss';import { Button } from '@/components/ui/button';import {createAgentCollectionReadAuthority,@@ -27,6 +28,7 @@ import {} from '@/components/settings/models/collectionReadAuthority';import { resumeGatewayAdoption, type GatewayAdoptionFailure } from '@/components/settings/models/gatewayAdoption';import { MigrationDialog } from '@/components/settings/models/MigrationDialog';+import { requiredBackends } from '@/components/settings/models/migrationGrouping';import { isImportableKey } from '@/components/settings/models/migrationScan';import { modelsApi, type SourceCreated } from '@/components/settings/models/modelsApi';import { foldRegionRead } from '@/components/settings/models/regionRead';@@ -36,7 +38,6 @@ import {} from '@/components/settings/models/runtimeLifecycle';import type { AgentBackend, AgentSupply, RuntimeDependency, Source } from '@/components/settings/models/types';-import { ImportKeysNotice } from '../ImportKeysNotice';import { useOnboardingMotion } from '../motion';import {setupCanAttemptInstall,@@ -53,9 +54,9 @@ import {addedThroughMoreCount,adoptionBackend,defaultSelection,+ offeredImportKeys,gatewayEvidenceSettled,gatewayIntent,- offeredImportKeys,pendingImportRows,providerAction,providerSetupAction,@@ -77,11 +78,6 @@ import {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. */@@ -147,15 +143,11 @@ const observationOf = (runtime: RuntimeDependency | null): string => (runtime ==runtime.manifest.resolution,].join(':'));-/** 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(', ');- }-};+/** Enumeration joined with the separator the active language punctuates lists with+ * (`, ` in English, `、` in Chinese), which `Intl.ListFormat`'s unit style drops+ * entirely for zh. */+const formatNames = (names: readonly string[], separator: string): string =>+ names.join(separator);/*** C4 names one owner for every setup supply read, so the shell may hand this screen@@ -180,7 +172,7 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScreonNavigate,agentReads: sharedAgentReads,}, ref) {- const { t, i18n } = useTranslation();+ const { t } = useTranslation();const motion = useOnboardingMotion();const attachMotion = motion.ref;@@ -214,7 +206,6 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScreconst [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);@@ -228,11 +219,12 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScre() => unlistedDetected({ sources, scan: selection.scan }),[sources, selection.scan],);+ // Against the Hub's own inventory: a key it is already supplying is not a batch+ // this screen should ask for, and the action continues instead of opening a review+ // of work that is done.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]);-+ const importDeclined = selection.selectedBackends.length === 0+ && isMigrationDismissed(offeredImportKeys(selection));// ── Supply ──────────────────────────────────────────────────────────────// Whether the server's own row defaults have been honoured yet. A scan is nulled@@ -327,12 +319,20 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScre// 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 offer = offeredImportKeys({ scan: scanned, selectedBackends: [] });+ const priorDismissed = isMigrationDismissed(offeredImportKeys(previous.providerSelection));+ const dismissed = isMigrationDismissed(offer);+ const defaults = defaultSelection(scanned).filter((backend) =>+ !offer.some((item) => requiredBackends(scanned.items, [backend]).has(item.backend)+ && isMigrationDismissed([item])));const selectedBackends = first && previous.providerSelection.scan === null- ? defaultSelection(scanned)- : reconcileSelection(- { scan: scanned, selectedBackends: previous.providerSelection.selectedBackends },- previous.providerSelection.scan,- );+ ? defaults+ : priorDismissed && !dismissed && previous.providerSelection.selectedBackends.length === 0+ ? defaults+ : reconcileSelection(+ { scan: scanned, selectedBackends: previous.providerSelection.selectedBackends },+ previous.providerSelection.scan,+ );return { ...previous, providerSelection: { scan: scanned, selectedBackends } };});seededSelectionRef.current = true;@@ -515,7 +515,7 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScre// ── 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+ // cards, the footer 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@@ -575,7 +575,7 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScrependingCount: pending.length,importFailed,supply: sourceRead === 'read'- ? { kind: 'read', hasSource }+ ? { kind: 'read', hasSource: hasSource || importDeclined }: { kind: sourceRead },gatewayBusy,// The same admission the dialogs are opened and submitted against, so the footer@@ -632,24 +632,6 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScre},}), [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) => {@@ -679,6 +661,8 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScre}, [setFlowState, sourceReads]);const changeSelection = React.useCallback((selectedBackends: AgentBackend[]) => {+ const newlySelected = selectedBackends.filter((backend) => !selection.selectedBackends.includes(backend));+ clearMigrationDismissed(offeredImportKeys(selection).filter((item) => newlySelected.includes(item.backend)));// Editing the selection retires the verdict the server gave about the batch it// no longer describes.setImportFailed(false);@@ -686,18 +670,16 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScre...previous,providerSelection: { ...previous.providerSelection, selectedBackends },}));- }, [setFlowState]);+ }, [selection, setFlowState]);const toggleSlot = React.useCallback((slot: ProviderSlot) => {- setImportFailed(false);- setFlowState((previous) => ({- ...previous,- providerSelection: {- ...previous.providerSelection,- selectedBackends: toggleSlotSelection(previous.providerSelection, slot),- },- }));- }, [setFlowState]);+ changeSelection(toggleSlotSelection(selection, slot));+ }, [changeSelection, selection]);++ const declineImport = React.useCallback(() => {+ writeMigrationDismissed(offeredImportKeys(selection));+ changeSelection([]);+ }, [selection, changeSelection]);// ── Sentence ────────────────────────────────────────────────────────────@@ -706,17 +688,22 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScresources,selected: selection.selectedBackends,failed: supplyFailed,+ reading: sourceRead === 'reading',});- const summaryText = summary.kind === 'none'+ const summaryText = summary.kind === 'pending'+ ? ''+ : 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) },- );+ : [+ t(+ summary.kind === 'added'+ ? 'onboarding.providers.summaryAdded'+ : 'onboarding.providers.summarySelected',+ { count: summary.count, names: formatNames(summary.names, t('onboarding.providers.summaryNameSeparator')) },+ ),+ ].join(' · ');// ── The way on when nothing is connected ────────────────────────────────@@ -744,7 +731,7 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScresetActionAside(setupRoot.current?.closest('.onboarding-step')?.querySelector<HTMLElement>('[data-setup-action-aside]') ?? null);}, [onActionChange]);- const onwardNode = sourceRead === 'read' && !hasSource ? (+ const onwardNode = sourceRead === 'read' && !hasSource && !importDeclined ? (<div className="onboarding-setup-hint"><p className="text-center text-xs text-muted">{t('onboarding.providers.continueHint')}{' '}@@ -799,7 +786,6 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScredirection="inbound"stage={stage}endpointSelector=".setup-provider-card"- pulse={pulse.inbound}/><GatewayCard@@ -812,7 +798,6 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScredirection="outbound"stage={stage}endpointSelector=".setup-destination"- pulse={pulse.outbound}/><DestinationRow />@@ -830,18 +815,6 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScre</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>@@ -903,6 +876,7 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScresetSupplyToken((token) => token + 1);}}onClose={() => setImportOpen(false)}+ onDecline={declineImport}/>)}diff --git a/ui/src/components/onboarding/providers/SupplyWires.tsx b/ui/src/components/onboarding/providers/SupplyWires.tsxindex 5326a9c53..8c982c136 100644--- a/ui/src/components/onboarding/providers/SupplyWires.tsx+++ b/ui/src/components/onboarding/providers/SupplyWires.tsx@@ -7,29 +7,42 @@// 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.+// The authored shape is the reference's own: a short drop off the card, a rounded+// corner onto the band's midline, the run that gathers toward the gateway, a second+// corner, and the drop in. Those breakpoints are y=7, 19 and 31 of a 38-unit 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. Everything the+// wire is *made of* — stroke, port, pulse — is the story's, by class: one screen's+// circuit and this one are the same object seen twice, and there is one place to+// change what that object looks like.import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';-import type { CSSProperties, FC } from 'react';+import type { 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;+/** The reference's y breakpoints as shares of its 38-unit band. */+const LEAVE = 7 / 38;+const RUN = 19 / 38;+const ENTER = 31 / 38;+/** The reference's corner, in px: the band scales vertically, the corner does not. */+const CORNER = 12;+/** The story draws its ports at r=3 in a 350-unit box; this band is the reference's+ * own 38, and 2.5 is the dot it draws there. */+const PORT_R = 2.5;-type Geometry = { width: number; height: number; paths: string[] };+type Geometry = { width: number; height: number; paths: string[]; ports: number[] };-/** 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. */+const round = (value: number) => Math.round(value * 100) / 100;++/** One drop-corner-run-corner-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 run = round(height * RUN);+ const enter = round(height * ENTER);+ // A corner cannot be wider than half the run it turns, or the two would cross.+ const corner = Math.min(CORNER, Math.abs(tx - sx) / 2) * Math.sign(tx - sx);+ return `M ${round(sx)} 0 V ${leave} Q ${round(sx)} ${run} ${round(sx + corner)} ${run}`+ + ` H ${round(tx - corner)} Q ${round(tx)} ${run} ${round(tx)} ${enter} V ${round(height)}`;}const centreIn = (element: Element, originX: number): number => {@@ -38,13 +51,11 @@ const centreIn = (element: Element, originX: number): number => {};/**- * @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 direction `inbound` gathers several sources into one gateway; `outbound` fans+ * one gateway out to several destinations. Both land on the gateway's centre — the+ * reference converges rather than spreading, which is what lets the two bands read+ * as one route through the middle card instead of two symmetric fans.* @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@@ -55,8 +66,7 @@ export const SupplyWires: FC<{direction: 'inbound' | 'outbound';stage: HTMLElement | null;endpointSelector: string;- pulse: boolean;-}> = ({ direction, stage, endpointSelector, pulse }) => {+}> = ({ direction, stage, endpointSelector }) => {const bandRef = useRef<HTMLDivElement | null>(null);const [geometry, setGeometry] = useState<Geometry | null>(null);@@ -72,14 +82,10 @@ export const SupplyWires: FC<{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);- });+ const ports = endpoints.map((endpoint) => round(centreIn(endpoint, box.left)));+ const paths = ports.map((endpointX) => (direction === 'inbound'+ ? wirePath(endpointX, gatewayX, box.height)+ : wirePath(gatewayX, endpointX, box.height)));setGeometry((previous) =>previous@@ -88,7 +94,7 @@ export const SupplyWires: FC<{&& previous.paths.length === paths.length&& previous.paths.every((path, index) => path === paths[index])? previous- : { width: box.width, height: box.height, paths });+ : { width: box.width, height: box.height, paths, ports });}, [direction, endpointSelector, stage]);useLayoutEffect(measure, [measure]);@@ -106,18 +112,28 @@ export const SupplyWires: FC<{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}>+ <svg viewBox={`0 0 ${geometry.width} ${geometry.height}`} width={geometry.width} height={geometry.height} fill="none">{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 key={`wire-${index}`}>+ <path className="onboarding-wire" d={path} fill="none" />+ {/* `pathLength` is what makes the pulse a pulse: the dash is a fixed+ share of 100, so it is one segment crossing one wire whatever that+ wire measures. Without it the dash is user units and a long wire+ wears the pattern several times over — a row of chunks rather than a+ thing in motion. All six run undelayed off one clock: the whole fan+ arriving at once is what reads as convergence.+ One stroke, no halo. The reference draws this band's pulse as a+ single 2px line; a soft wider stroke under it spreads the segment+ across a band only 48px tall, and three spreading segments stop+ reading as three things arriving together. */}+ <path className="onboarding-pulse-core" d={path} fill="none" pathLength={100} /></g>))}+ {/* The far end of every wire, on the edge it leaves from. */}+ {geometry.ports.map((x, index) => (+ <circle key={`port-${index}`} className="onboarding-port" cx={x}+ cy={direction === 'inbound' ? 0 : geometry.height} r={PORT_R} />+ ))}</svg>)}</div>diff --git a/ui/src/components/onboarding/providers/providerStage.test.ts b/ui/src/components/onboarding/providers/providerStage.test.tsindex 2f30b85d2..a8edf88d2 100644--- a/ui/src/components/onboarding/providers/providerStage.test.ts+++ b/ui/src/components/onboarding/providers/providerStage.test.ts@@ -356,6 +356,30 @@ describe('pendingImportRows', () => {expect(rows.map((item) => item.id)).toEqual(['mig_1', 'mig_2']);});+ it('MH-MIG-006: keeps a key whose display mask collides with a Hub source', () => {+ const selection = {+ scan: scanOf(row({ id: 'mig_1', backend: 'codex', vendor: 'openai', masked_credential: 'sk-…0001' })),+ selectedBackends: ['codex' as const],+ };++ expect(pendingImportRows(selection).map((item) => item.id)).toEqual(['mig_1']);+ expect(pendingImportRows(selection).map((item) => item.id)).toEqual(['mig_1']);+ });++ it('still submits a group the Hub only partly holds, whole', () => {+ // The server migrates a backend whole and refuses a batch that omits a row, so one+ // key the Hub does not have keeps the group — and its companion goes with it.+ const rows = pendingImportRows({+ scan: scanOf(+ row({ id: 'mig_1', backend: 'codex', vendor: 'openai', masked_credential: 'sk-…0001' }),+ row({ id: 'mig_2', backend: 'codex', vendor: 'openai', masked_credential: 'sk-…0002' }),+ ),+ 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@@ -844,6 +868,17 @@ describe('providerSummary', () => {expect(providerSummary({ scan: null, sources: [], selected: [], failed: false })).toEqual({ kind: 'none' });});+ it('withholds the verdict while the source read is still out', () => {+ expect(providerSummary({ scan: null, sources: [], selected: [], failed: false, reading: true }))+ .toEqual({ kind: 'pending' });+ });++ it('answers from a landed read even while another one is out', () => {+ expect(providerSummary({+ scan: null, sources: [source({ id: 'src_1', vendor: 'openai' })], selected: [], failed: false, reading: true,+ })).toMatchObject({ kind: 'added', count: 1 });+ });+it('counts every added provider, not just the two on the stage', () => {const sources = [source({ id: 'src_1', vendor: 'openai' }),diff --git a/ui/src/components/onboarding/providers/providerStage.ts b/ui/src/components/onboarding/providers/providerStage.tsindex 0fe47dbd8..a80f65e91 100644--- a/ui/src/components/onboarding/providers/providerStage.ts+++ b/ui/src/components/onboarding/providers/providerStage.ts@@ -162,8 +162,8 @@ export type ProviderSlot = {* 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+ * One helper rather than the call spelled out five times, so the cards, the+ * primary action's batch, the seeded consent and reconciliation cannot drift into* answering the same question two ways.*/const setupGroups = (items: MigrationItem[]): MigrationGroup[] =>@@ -322,7 +322,7 @@ export function providerSlots(input: {* 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+ * two. Letting the stage's brand set answer that question is how a row the scan* 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.*/@@ -354,18 +354,21 @@ export const slotSelected = (* 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[] {+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))+ .filter((group) => groupSelectable(group)+ && selection.selectedBackends.includes(group.backend)).map((group) => group.backend),);return appliableItems(items, consented);}/**- * The keys the capsule offers to review.+ * The keys the setup migration offer can 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@@ -374,9 +377,8 @@ export function pendingImportRows(selection: MigrationSelection): MigrationItem[* 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.+ * This identity set also owns dismissal across rescans; selection remains scoped+ * to complete backend consent groups.*/export function offeredImportKeys(selection: MigrationSelection): MigrationItem[] {return takeableImportRows(selection.scan?.items ?? [], isImportableKey, isImportableKey);@@ -389,7 +391,7 @@ export function offeredImportKeys(selection: MigrationSelection): MigrationItem[* 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+ * chosen while the migration offer announces 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.*/@@ -471,6 +473,8 @@ export function reconcileSelection(}export type ProviderSummary =+ /** The source read has not landed, so the stage has nothing to say yet. */+ | { kind: 'pending' }| { kind: 'none' }| { kind: 'added'; count: number; names: string[] }| { kind: 'selected'; count: number; names: string[] }@@ -491,6 +495,8 @@ export function providerSummary(input: {sources: readonly Source[];selected: readonly AgentBackend[];failed: boolean;+ /** Whether the source read is still out. An empty list is not yet an answer. */+ reading?: boolean;}): ProviderSummary {if (input.failed) return { kind: 'error' };const added = new Map<string, string>();@@ -503,7 +509,10 @@ export function providerSummary(input: {.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' };+ // Nothing found — but an unfinished read has not found nothing, it has not looked.+ // Saying 「no provider selected」 here states a verdict about a question still open,+ // which is what made the sentence flicker through a denial on the way in.+ return input.reading ? { kind: 'pending' } : { kind: 'none' };}/**diff --git a/ui/src/components/onboarding/providers/tsconfig.tests.json b/ui/src/components/onboarding/providers/tsconfig.tests.jsonindex 0c8350d7c..e5177643a 100644--- a/ui/src/components/onboarding/providers/tsconfig.tests.json+++ b/ui/src/components/onboarding/providers/tsconfig.tests.json@@ -8,7 +8,6 @@"include": ["./**/*.ts","./**/*.tsx",- "../ImportKeysNotice.test.tsx","../setupAction.types.test.ts","../setupConfig.test.ts","../SetupFlowShell.test.tsx",@@ -17,10 +16,6 @@"../setupTargets.ts","../entryGate.test.ts","../entryGate.ts",- "../setupRoute.ts",- "../setupRoute.test.ts",- "../DefaultRouteDialog.tsx",- "../DefaultRouteDialog.test.tsx","../../../i18n/i18next.d.ts"],"exclude": []diff --git a/ui/src/components/onboarding/setupFlow.test.ts b/ui/src/components/onboarding/setupFlow.test.tsindex 8a3250a50..0dc0482d6 100644--- a/ui/src/components/onboarding/setupFlow.test.ts+++ b/ui/src/components/onboarding/setupFlow.test.ts@@ -47,23 +47,17 @@ describe('one Hub setup journey', () => {});describe('shell-owned flow state', () => {- it('starts with nothing selected, imported, added or ordered, and no dirty draft', () => {+ it('starts with nothing selected, imported or added', () => {expect(INITIAL_SETUP_FLOW_STATE).toEqual({providerSelection: { scan: null, selectedBackends: [] },importedCount: 0,addedThroughMore: [],- routeOrder: [],- routeOrderDirty: false,});});it('carries screen updates through navigation and composes a late functional update with newer state', async () => {let finishImport: (() => void) | undefined;const pendingImport = new Promise<void>((resolve) => { finishImport = resolve; });- const draft = [- { source_id: '来源-一', model_id: '模型-首选' },- { source_id: '来源-一', model_id: '模型-备用' },- ];const selection: SetupFlowState['providerSelection'] = {scan: { items: [{ id: 'key-a', backend: 'opencode', kind: 'opencode_provider', masked_detail: 'fixture…0001', proposed_action: 'import', selected: true },@@ -87,13 +81,12 @@ describe('shell-owned flow state', () => {setFlowState((previous) => ({ ...previous, addedThroughMore: ['新增来源'] }));onNavigate('assistants');} }, 'Add fixture source'));- const AssistantScreen = ({ active, flowState, setFlowState, onNavigate }: SetupScreenProps) =>+ const AssistantScreen = ({ active, flowState, onNavigate }: SetupScreenProps) =>createElement('section', { hidden: !active, inert: !active, 'data-testid': 'assistants' },createElement('output', null, JSON.stringify(flowState)),createElement('button', { onClick: () => {- setFlowState((previous) => ({ ...previous, routeOrder: draft, routeOrderDirty: true }));onNavigate('providers');- } }, 'Edit fixture route'));+ } }, 'Back to providers'));const Shell = () => {const [current, setCurrent] = useState<SetupScreenId>('providers');const [flowState, setFlowState] = useState(INITIAL_SETUP_FLOW_STATE);@@ -110,13 +103,13 @@ describe('shell-owned flow state', () => {fireEvent.click(screen.getByRole('button', { name: 'Start fixture import' }));expect(read('assistants').providerSelection).toEqual(selection);- fireEvent.click(screen.getByRole('button', { name: 'Edit fixture route' }));- expect(read('providers')).toMatchObject({ providerSelection: selection, routeOrder: draft, routeOrderDirty: true });+ fireEvent.click(screen.getByRole('button', { name: 'Back to providers' }));+ expect(read('providers')).toMatchObject({ providerSelection: selection });fireEvent.click(screen.getByRole('button', { name: 'Add fixture source' }));await act(async () => { finishImport!(); await pendingImport; });expect(read('assistants')).toEqual({providerSelection: { scan: null, selectedBackends: [] }, importedCount: 2,- addedThroughMore: ['新增来源'], routeOrder: draft, routeOrderDirty: true,+ addedThroughMore: ['新增来源'],});expect((screen.getByTestId('providers') as HTMLElement).hidden).toBe(true);expect(screen.getByTestId('providers').hasAttribute('inert')).toBe(true);@@ -167,8 +160,8 @@ function RuntimeConsumer({ active, capability, runtimeRead, flowState, setFlowStcreateElement('output', { 'aria-label': 'capability' }, capability),createElement('output', { 'aria-label': 'runtime read' }, runtimeRead.kind),createElement('button', { onClick: () => setFlowState((previous) => ({- ...previous, routeOrder: [{ source_id: 'src_fixture1', model_id: '模型' }], routeOrderDirty: true,- })) }, 'Edit draft'),+ ...previous, addedThroughMore: ['src_fixture1'],+ })) }, 'Add source'),createElement('button', { onClick: onRetrySetup }, 'Recheck runtime'));}function RuntimeHarness({ capture, retry, install, complete, mode }: {@@ -221,7 +214,7 @@ it('consumes unsupported admission without leaving providers, losing drafts or cact(() => settle({ capability: 'enabled', gatewayEnabled: true, runtimeRead: loadingRegion() }));fireEvent.click(primary()); // Support is first learned after provider bootstrap.expect(output('current screen')).toBe('providers');- fireEvent.click(screen.getByRole('button', { name: 'Edit draft' }));+ fireEvent.click(screen.getByRole('button', { name: 'Add source' }));const draft = output('draft');act(() => settle({ capability: 'enabled', gatewayEnabled: true, runtimeRead: readyRegion(runtime('unsupported')) }));expect(output('current screen')).toBe('providers');@@ -303,7 +296,7 @@ it.each(['deployment', 'saved-intent'] as const)('holds disabled %s without skip// A disabled result arriving later holds the current screen, never redirects to Direct.act(() => settle({ capability: 'enabled', gatewayEnabled: true, runtimeRead: loadingRegion() }));fireEvent.click(primary());- fireEvent.click(screen.getByRole('button', { name: 'Edit draft' }));+ fireEvent.click(screen.getByRole('button', { name: 'Add source' }));const draft = output('draft');act(() => settle({ ...config, runtimeRead: readyRegion(runtime('resolved', 'ok')) }));expect(output('current screen')).toBe('providers');diff --git a/ui/src/components/onboarding/setupFlow.ts b/ui/src/components/onboarding/setupFlow.tsindex c61bd9be0..c0c648911 100644--- a/ui/src/components/onboarding/setupFlow.ts+++ b/ui/src/components/onboarding/setupFlow.ts@@ -1,11 +1,8 @@/*** C2 — the setup flow's interface contract.*- * Proposed for `master` before the three-screen lanes fork, so a lane reads one shared- * declaration instead of transcribing a shape out of a plan document. Everything here is- * cross-lane by construction: the shell (L1) renders it, the providers screen (L2) and the- * assistants screen (L3) implement against it. A deviation needs orchestrator sign-off- * BEFORE the edit, not a reconciling commit afterwards.+ * The shell, providers screen and assistants screen share this declaration. The shell owns+ * navigation and provider selection; each assistant route remains owned by Model Hub.** The binding prose that goes with these types — geometry and DOM hooks (C3), the entry* gate (C4), the stable dialog frame (C5) and the field-by-field data mapping (C6) — lives@@ -15,7 +12,7 @@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 type { AgentBackend, MigrationScan, RuntimeDependency } from '../settings/models/types';import { foldRegionRead, type RegionRead } from '../settings/models/regionRead';import { runtimeCanAttemptInstall, runtimeIsRunning } from '../settings/models/runtimeLifecycle';@@ -27,9 +24,10 @@ export type SetupScreenId = (typeof SETUP_SCREENS)[number];/*** Which transition is playing, or `false` when none is. Named for the screen being* ENTERED, because the snapshot is taken from the screen being left: `providers` shrinks- * the story cards into the destination row, `assistants` lifts that row into full cards.+ * the story cards into the destination row, `assistants` lifts that row into full cards,+ * and `intro` grows the row back into the story it came from.*/-export type SetupHandoffTarget = Exclude<SetupScreenId, 'intro'>;+export type SetupHandoffTarget = SetupScreenId;/** The leading glyph the shell draws inside the primary action. */export type SetupActionIcon = 'none' | 'arrow-right' | 'spinner';@@ -123,9 +121,9 @@ export type SetupProviderSelection = {/*** State the SHELL owns, because it has to outlive any single screen: leaving screen 2 for- * screen 3 and coming back must find the same selection, the same cumulative import count- * and the same route order (handoff §5 "状态保留"). Anything the server already owns —- * installed CLIs, enabled backends, persisted sources — is read, never mirrored here.+ * screen 3 and coming back must find the same selection and cumulative import count.+ * Anything the server already owns — installed CLIs, enabled backends, persisted+ * sources and model routes — is read, never mirrored here.*/export type SetupFlowState = {/** Ephemeral scan/consent draft. Replace on a fresh scan and reconcile whole groups;@@ -136,26 +134,12 @@ export type SetupFlowState = {importedCount: number;/** Source ids added through the "Add more" card, which is what its badge counts. */addedThroughMore: string[];- /** Model-ranked working draft: each row identifies BOTH source and upstream model.- * This is not a putAgentSources payload. C6/D4/D9 specify explicit Agent/menu-model- * targets and projection through each target's reviewed exact-hop membership. The- * shared mounted route owner retains target baselines and pending write receipts;- * this list alone cannot reconstruct them or justify a source-priority write.- * Hydrate only while clean; a dirty draft survives navigation and is cleared only- * after every intended write is read back. Empty means no hydrated draft, not no- * server route. C4 never gates entry on this client draft. */- routeOrder: RouteHop[];- /** Whether `routeOrder` holds an edit the server has not confirmed. Decides if a re-entry- * may hydrate; all intended writes must be confirmed before clearing it. */- routeOrderDirty: boolean;};export const INITIAL_SETUP_FLOW_STATE: SetupFlowState = {providerSelection: { scan: null, selectedBackends: [] },importedCount: 0,addedThroughMore: [],- routeOrder: [],- routeOrderDirty: false,};/**diff --git a/ui/src/components/onboarding/setupHandoff.test.ts b/ui/src/components/onboarding/setupHandoff.test.tsindex fdb3ae514..32f208f4e 100644--- a/ui/src/components/onboarding/setupHandoff.test.ts+++ b/ui/src/components/onboarding/setupHandoff.test.ts@@ -1,6 +1,6 @@// @vitest-environment jsdomimport { afterEach, expect, it, vi } from 'vitest';-import { captureSetupCards, measureSetupScreen, playSetupHandoff, setupHandoffAllowed } from './setupHandoff';+import { captureSetupCards, playSetupHandoff, setupHandoffAllowed } from './setupHandoff';afterEach(() => { document.body.innerHTML = ''; vi.useRealTimers(); vi.unstubAllGlobals(); delete (document as Partial<Document>).hidden; delete (HTMLElement.prototype as Partial<HTMLElement>).animate; });const screen = (selector: string) => {@@ -10,12 +10,6 @@ const screen = (selector: string) => {for (const child of [node, ...node.querySelectorAll<HTMLElement>('*')]) child.getBoundingClientRect = () => new DOMRect(20, 30, 100, 60);return node;};-it('temporarily measures a hidden inert root and restores its inline presentation', () => {- const node = screen('onboarding-assistant'); node.hidden = true; node.inert = true; node.style.color = 'red';- const restore = measureSetupScreen(node);- expect(node.hidden).toBe(false); expect(node.inert).toBe(true); expect(node.style.visibility).toBe('hidden');- restore(); expect(node.hidden).toBe(true); expect(node.style.color).toBe('red'); expect(node.style.position).toBe('');-});it('snapshots C3 hooks without duplicating IDs in the live tree', () => {const source = screen('onboarding-collaboration-card');const snapshot = captureSetupCards(source, 'intro');@@ -28,15 +22,14 @@ it('cancels cleanly and finishes only once after resize/visibility', () => {const cancel = vi.fn();HTMLElement.prototype.animate = vi.fn(() => ({ cancel }) as unknown as Animation);const source = screen('onboarding-collaboration-card');- const target = screen('onboarding-assistant'); target.hidden = true;+ const target = screen('onboarding-assistant');const finish = vi.fn();- const stop = playSetupHandoff(document.body, source, target, 'intro', 'assistants', finish);- expect(target.hidden).toBe(true);+ const stop = playSetupHandoff(document.body, captureSetupCards(source, 'intro'), target, 'assistants', finish);const layer = document.querySelector<HTMLElement>('.onboarding-handoff-layer')!;expect(layer.getAttribute('aria-hidden')).toBe('true'); expect(layer.inert).toBe(true);window.dispatchEvent(new Event('resize')); vi.runAllTimers();expect(finish).toHaveBeenCalledOnce(); expect(document.querySelector('.onboarding-handoff-layer')).toBeNull();- stop(); expect(source.style.visibility).toBe('');+ stop();});it('bails out for explicit pause, hidden documents, and reduced motion', () => {vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));diff --git a/ui/src/components/onboarding/setupHandoff.ts b/ui/src/components/onboarding/setupHandoff.tsindex aff55ca05..ca2b8144b 100644--- a/ui/src/components/onboarding/setupHandoff.ts+++ b/ui/src/components/onboarding/setupHandoff.ts@@ -1,11 +1,16 @@import type { SetupScreenId } from './setupFlow';type Piece = { node: HTMLElement; bounds: DOMRect };+/** A piece the departing card carries but the arriving one has no place for, and how+ * long it is given to leave. The prototype dissolves them rather than cutting them+ * with the screen, which is what keeps the shrinking card readable mid-flight. */+type FadingPiece = Piece & { duration: number; lift: number };type CardSnapshot = {bounds: DOMRect; surface: string; border: string; radius: string;- /** Whether the source card wore the mint halo; the flight fades it through the token. */- glow: boolean;- icon: Piece; name: Piece;+ /** The halo the source card wore, faded out over the flight exactly as the+ * reference does — the arriving card carries none. */+ shadow: string;+ icon: Piece; name: Piece; fading: FadingPiece[];};export type SetupSnapshot = { cards: CardSnapshot[]; retiring?: Piece };const timing: KeyframeAnimationOptions = { duration: 860, easing: 'cubic-bezier(.32,0,.16,1)', fill: 'both' };@@ -14,6 +19,20 @@ const hooks = (screen: SetupScreenId) => screen === 'providers'? { card: '.setup-destination', icon: '.setup-destination-logo', name: '.setup-destination-name' }: { card: screen === 'intro' ? '.onboarding-collaboration-card' : '.onboarding-assistant', icon: '.onboarding-card-logo', name: '.onboarding-card-name' };+/**+ * What a departing card holds beyond its identity: the story's role, caption and+ * written work. The identity flies to the next screen; these have nowhere to land,+ * so they leave on their own timing — the role first, because it sits on the line+ * the identity is still moving along.+ */+const FADING: Partial<Record<SetupScreenId, { selector: string; duration: number; lift: number }[]>> = {+ intro: [+ { selector: '.onboarding-card-role', duration: 130, lift: 0 },+ { selector: '.onboarding-story-status', duration: 190, lift: 12 },+ { selector: '.onboarding-skeleton', duration: 190, lift: 12 },+ ],+};+function capturePiece(element: HTMLElement): Piece {const node = element.cloneNode(true) as HTMLElement;// A snapshot is presentation only. Duplicate IDs must never enter the live tree.@@ -30,8 +49,12 @@ export function captureSetupCards(root: HTMLElement, screen: SetupScreenId): Setconst name = card.querySelector<HTMLElement>(selectors.name);if (!icon || !name) return [];const style = getComputedStyle(card);+ const fading = (FADING[screen] ?? []).flatMap(({ selector, duration, lift }) => {+ const element = card.querySelector<HTMLElement>(selector);+ return element ? [{ ...capturePiece(element), duration, lift }] : [];+ });return [{ bounds: card.getBoundingClientRect(), surface: style.backgroundColor, border: style.borderColor,- radius: style.borderRadius, glow: style.boxShadow !== 'none', icon: capturePiece(icon), name: capturePiece(name) }];+ radius: style.borderRadius, shadow: style.boxShadow, icon: capturePiece(icon), name: capturePiece(name), fading }];});const stage = screen === 'providers' ? root.querySelector<HTMLElement>('.setup-provider-stage') : null;const retiring = stage ? capturePiece(stage) : undefined;@@ -48,26 +71,20 @@ export function setupHandoffAllowed(paused = false): boolean {&& typeof HTMLElement.prototype.animate === 'function';}-/** Measure the incoming mounted screen without activating its effects or changing flow. */-export function measureSetupScreen(root: HTMLElement): () => void {- const hidden = root.hidden;- const style = root.getAttribute('style');- root.hidden = false;- root.inert = true;- Object.assign(root.style, { position: 'absolute', inset: '0', visibility: 'hidden', pointerEvents: 'none' });- return () => {- root.hidden = hidden;- if (style === null) root.removeAttribute('style'); else root.setAttribute('style', style);- };-}--/** The returned cleanup cancels without navigating. Visibility/resize finish instantly. */+/**+ * Fly one screen's identities onto the next screen's, which is already on screen.+ *+ * The incoming screen is live for the whole flight — its wires measure, its reads+ * run and its heading is the real one — so the cards land into a diagram that was+ * drawn before they arrived rather than into a blank that fills in afterwards. Only+ * the landing cards are held back, by the stylesheet, so the moving shells own them.+ *+ * The returned cleanup cancels without navigating. Visibility/resize finish instantly.+ */export function playSetupHandoff(- host: HTMLElement, outgoing: HTMLElement, incoming: HTMLElement,- from: SetupScreenId, to: SetupScreenId, onComplete: () => void,+ host: HTMLElement, snapshot: SetupSnapshot, incoming: HTMLElement,+ to: SetupScreenId, onComplete: () => void,): () => void {- const snapshot = captureSetupCards(outgoing, from);- const restoreIncoming = measureSetupScreen(incoming);const targets = Array.from(incoming.querySelectorAll<HTMLElement>(hooks(to).card));const origin = host.getBoundingClientRect();const layer = document.createElement('div');@@ -87,16 +104,6 @@ export function playSetupHandoff(layer.append(snapshot.retiring.node);animate(snapshot.retiring.node, [{ opacity: 1 }, { opacity: 0, transform: 'translateY(-36px)' }], { ...timing, duration: 300 });}- // The next provider stage enters behind the moving assistant identities.- const providerStage = to === 'providers' ? incoming.querySelector<HTMLElement>('.setup-provider-stage') : null;- if (providerStage) {- const arriving = capturePiece(providerStage);- arriving.node.querySelector('.setup-destinations')?.remove();- position(arriving);- arriving.node.style.visibility = 'visible';- layer.append(arriving.node);- animate(arriving.node, [{ opacity: 0, transform: 'translateY(-24px)' }, { opacity: 1, transform: 'translateY(0)' }]);- }snapshot.cards.forEach((source, index) => {const target = targets[index];if (!target) return;@@ -106,15 +113,25 @@ export function playSetupHandoff(const card = document.createElement('div');card.className = 'onboarding-handoff-card';Object.assign(card.style, { left: `${source.bounds.x - origin.x}px`, top: `${source.bounds.y - origin.y}px`,- width: `${bounds.width}px`, height: `${bounds.height}px` });+ width: `${source.bounds.width}px`, height: `${source.bounds.height}px` });const surface = document.createElement('div');surface.className = 'onboarding-handoff-surface';+ // Scale only ever shrinks, as the reference does: the shell is built at whichever+ // box is bigger and the other end is the scaled one. A shell scaled past its own+ // size would magnify its 1px border and its radius with it, which is the bulging+ // corner the reference never shows.+ const growing = bounds.width * bounds.height > source.bounds.width * source.bounds.height;+ if (growing) Object.assign(surface.style, { right: 'auto', bottom: 'auto', width: `${bounds.width}px`, height: `${bounds.height}px` });+ const scaled = growing+ ? `scale(${source.bounds.width / bounds.width},${source.bounds.height / bounds.height})`+ : `scale(${bounds.width / source.bounds.width},${bounds.height / source.bounds.height})`;card.append(surface);animate(card, [{ transform: 'translate(0,0)' }, { transform: `translate(${bounds.x - source.bounds.x}px,${bounds.y - source.bounds.y}px)` }]);- if (source.glow) surface.dataset.glow = 'true';animate(surface, [- { transform: `scale(${source.bounds.width / bounds.width},${source.bounds.height / bounds.height})`, background: source.surface, borderColor: source.border, borderRadius: source.radius },- { transform: 'scale(1,1)', background: style.backgroundColor, borderColor: style.borderColor, borderRadius: style.borderRadius },+ { transform: growing ? scaled : 'scale(1,1)', background: source.surface, borderColor: source.border, borderRadius: source.radius,+ boxShadow: source.shadow === 'none' ? 'none' : 'var(--ob-active-shadow)' },+ { transform: growing ? 'scale(1,1)' : scaled,+ background: style.backgroundColor, borderColor: style.borderColor, borderRadius: style.borderRadius, boxShadow: 'none' },]);for (const [piece, selector] of [[source.icon, hooks(to).icon], [source.name, hooks(to).name]] as const) {const child = target.querySelector<HTMLElement>(selector);@@ -128,24 +145,22 @@ export function playSetupHandoff(color: getComputedStyle(child).color,}]);}+ for (const piece of source.fading) {+ Object.assign(piece.node.style, { position: 'absolute', left: `${piece.bounds.x - source.bounds.x}px`, top: `${piece.bounds.y - source.bounds.y}px`,+ width: `${piece.bounds.width}px`, height: `${piece.bounds.height}px`, margin: '0', padding: '0' });+ card.append(piece.node);+ animate(piece.node, [{ opacity: 1, transform: 'translateY(0)' }, { opacity: 0, transform: `translateY(${piece.lift}px)` }],+ { duration: piece.duration, easing: 'ease-out', fill: 'both' });+ }layer.append(card);});- restoreIncoming();host.append(layer);- // Start the halo fade one frame in, so the transition runs against the mounted layer.- const fade = window.requestAnimationFrame(() => {- for (const node of layer.querySelectorAll<HTMLElement>('[data-glow]')) node.removeAttribute('data-glow');- });- const previousVisibility = outgoing.style.visibility;- outgoing.style.visibility = 'hidden';let settled = false;const media = typeof window.matchMedia === 'function' ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;const cleanup = () => {window.clearTimeout(timer);- window.cancelAnimationFrame(fade);animations.forEach((animation) => animation.cancel());layer.remove();- outgoing.style.visibility = previousVisibility;window.removeEventListener('resize', finish);document.removeEventListener('visibilitychange', visibility);media?.removeEventListener('change', finish);diff --git a/ui/src/components/onboarding/setupRoute.test.ts b/ui/src/components/onboarding/setupRoute.test.tsdeleted file mode 100644index 509117af6..000000000--- a/ui/src/components/onboarding/setupRoute.test.ts+++ /dev/null@@ -1,498 +0,0 @@-import { describe, expect, it, vi } from 'vitest';-import type { VibeAgentBrief, VibeAgentFull } from '../../context/ApiContext';-import type {- AgentChain,- AgentSupply,- BackendModel,- BackendModelsPut,- ModelCandidate,- ModelCandidateSupplier,- NativeProtocol,- RouteHop,-} from '../settings/models/types';-import {- classifyRetry,- hydrateSetupRoutes,- projectTargetHops,- retrySetupRoutes,- saveSetupRoutes,- selectSetupRouteTarget,- targetChanged,- targetKey,- unionRouteOrder,- type SetupRouteTargetSnapshot,-} from './setupRoute';--const hop = (source_id: string, model_id: string): RouteHop => ({ source_id, model_id });-const A = hop('src_a', 'opus-5');-const B = hop('src_a', 'sonnet-4');-const C = hop('src_b', 'gpt-5');-const D = hop('src_c', 'codex-mini');--const chainOf = (- backend: AgentChain['backend'],- modelId: string,- hops: RouteHop[],- origin: AgentChain['route_origin'] = 'manual',-): AgentChain => ({- contract_version: 10,- backend,- model_id: modelId,- manual_override: origin === 'manual' ? { hops } : null,- route_origin: origin,- current: hops[0] ?? null,- chain: hops.map((row) => ({- source_id: row.source_id,- model_id: row.model_id,- channel: 'hub',- health: 'healthy',- runnable: true,- reason: null,- retry_at: null,- })),- supply_state: 'ok',-});--const target = (- backend: AgentChain['backend'],- modelId: string,- hops: RouteHop[],- names: string[],- origin: AgentChain['route_origin'] = 'manual',-): SetupRouteTargetSnapshot => {- const chain = chainOf(backend, modelId, hops, origin);- return { backend, modelId, agentNames: names, chain, membership: hops };-};--const brief = (name: string, backend: VibeAgentBrief['backend'], model: string): VibeAgentBrief => ({- id: `${backend}-${name}`,- name,- display_name: name,- description: null,- backend,- model,- reasoning_effort: null,- enabled: true,- archived: false,- archived_at: null,- source: 'file',- updated_at: '',-});--const full = (row: VibeAgentBrief): VibeAgentFull => ({- ...row,- system_prompt: null,- created_at: '',- metadata: { builtin_default: true },-});--const supply = (backend: AgentSupply['backend'], names: Array<{ name: string; model: string }>): AgentSupply => ({- backend,- cli_present: true,- mode: 'hub',- menu_kind: 'fixed',- named_agents: names.map((row) => ({- name: row.name,- effective_model_id: row.model,- supply_status: 'ok',- })),-});--describe('setup route projection', () => {- it('keeps two models on the same source as distinct rows', () => {- const claude = target('claude', 'opus-5', [A, B], ['claude']);- expect(unionRouteOrder([claude])).toEqual([A, B]);- expect(projectTargetHops([B, A], claude.membership)).toEqual([B, A]);- });-- it('does not treat a displayed union as a write when existing orders diverge', () => {- const claude = target('claude', 'opus-5', [A, B], ['claude']);- const codex = target('codex', 'gpt-5', [B, A], ['codex']);- const union = unionRouteOrder([claude, codex]);- expect(union).toEqual([A, B]);- expect(targetChanged(union, claude)).toBe(false);- expect(targetChanged(union, codex)).toBe(true);- });-- it('projects disjoint native memberships instead of sharing every row', () => {- const claude = target('claude', 'opus-5', [A, B], ['claude']);- const codex = target('codex', 'gpt-5', [C, D], ['codex']);- const union = unionRouteOrder([claude, codex]);- expect(union).toEqual([A, B, C, D]);- expect(projectTargetHops(union, claude.membership)).toEqual([A, B]);- expect(projectTargetHops(union, codex.membership)).toEqual([C, D]);- expect(targetChanged(union, claude)).toBe(false);- expect(targetChanged(union, codex)).toBe(false);- });-- it('selects the focused Agent/backend and does not inherit another card\'s target', () => {- const claude = target('claude', 'opus-5', [A, B], ['claude']);- const codex = target('codex', 'gpt-5', [C], ['codex']);- expect(selectSetupRouteTarget([claude, codex])).toBe(claude);- expect(selectSetupRouteTarget([claude, codex], { backend: 'codex', agentName: 'codex' })).toBe(codex);- expect(selectSetupRouteTarget([claude, codex], { backend: 'codex' })).toBe(codex);- expect(selectSetupRouteTarget([claude, codex], { backend: 'opencode', agentName: 'opencode' })).toBeNull();- });-});--describe('hydrateSetupRoutes', () => {- it('uses each designated Agent\'s exact saved model, not selected_model_id', async () => {- const claude = brief('claude', 'claude', 'opus-5');- const custom = brief('mine', 'claude', 'other-model');- const reads = {- listVibeAgents: vi.fn(async () => ({ ok: true, agents: [claude, custom], default_agent_name: 'mine' })),- getVibeAgent: vi.fn(async (name: string) => ({- ok: true,- agent: full(name === 'claude' ? claude : custom),- })),- getAgentChain: vi.fn(async (backend: AgentChain['backend'], model: string) => chainOf(backend, model, [A, B])),- };- const hydration = await hydrateSetupRoutes(reads, [- { ...supply('claude', [{ name: 'claude', model: 'opus-5' }]), selected_model_id: 'ignored-default' },- ]);- expect(reads.getAgentChain).toHaveBeenCalledWith('claude', 'opus-5');- expect(reads.getAgentChain).not.toHaveBeenCalledWith('claude', 'ignored-default');- expect(hydration.targets).toHaveLength(1);- expect(hydration.targets[0]?.modelId).toBe('opus-5');- expect(hydration.union).toEqual([A, B]);- });-});--describe('saveSetupRoutes', () => {- const writes = (- chains: Record<string, AgentChain>,- options: { failOn?: string } = {},- ) => {- const store = { ...chains };- const keyOf = (backend: string, model: string) => `${backend}:${model}`;- return {- store,- api: {- getVibeAgent: vi.fn(async (name: string) => ({- ok: true,- agent: full(brief(name, name === 'codex' ? 'codex' : 'claude', store[keyOf(name === 'codex' ? 'codex' : 'claude', name === 'codex' ? 'gpt-5' : 'opus-5')]?.model_id ?? 'opus-5')),- })),- listAgents: vi.fn(async () => [supply('claude', [{ name: 'claude', model: 'opus-5' }]), supply('codex', [{ name: 'codex', model: 'gpt-5' }])]),- getAgentChain: vi.fn(async (backend: AgentChain['backend'], model: string) => {- const current = store[keyOf(backend, model)];- if (!current) throw new Error(`missing ${backend} ${model}`);- return current;- }),- previewAgentChain: vi.fn(async (backend: AgentChain['backend'], model: string, body: { manual_override: { hops: RouteHop[] } | null }) =>- chainOf(backend, model, body.manual_override?.hops ?? [], 'manual')),- putAgentChain: vi.fn(async (backend: AgentChain['backend'], model: string, body: { hops: RouteHop[] }) => {- const key = keyOf(backend, model);- if (options.failOn === key) throw new Error(`failed ${key}`);- const next = chainOf(backend, model, body.hops, 'manual');- store[key] = next;- return { chain: next };- }),- getAgentModelCandidates: vi.fn(async () => ({ builtin: [], providers: [], in_list: [] })),- putAgentModels: vi.fn(async () => supply('claude', [{ name: 'claude', model: 'opus-5' }])),- },- };- };-- it('opening without an edit writes nothing, even when displayed union differs', async () => {- const claude = target('claude', 'opus-5', [A, B], ['claude']);- const codex = target('codex', 'gpt-5', [B, A], ['codex']);- const { api } = writes({- 'claude:opus-5': claude.chain,- 'codex:gpt-5': codex.chain,- });- const results = await saveSetupRoutes([A, B], [claude, codex], api, { dirty: false });- expect(api.putAgentChain).not.toHaveBeenCalled();- expect(results.every((row) => row.kind === 'skipped')).toBe(true);- });-- it('persists an explicit first hop on an empty chain', async () => {- const claude = target('claude', 'opus-5', [], ['claude'], 'automatic');- const { api, store } = writes({ 'claude:opus-5': claude.chain });- api.getVibeAgent = vi.fn(async () => ({ ok: true, agent: full(brief('claude', 'claude', 'opus-5')) }));- const live = { ...claude, membership: [A] };- const results = await saveSetupRoutes([A], [live], api, { dirty: true });- expect(api.putAgentChain).toHaveBeenCalledWith('claude', 'opus-5', { hops: [A] });- expect(results).toEqual([expect.objectContaining({ kind: 'confirmed' })]);- expect(store['claude:opus-5']?.manual_override).toEqual({ hops: [A] });- });-- it('persists a newly admitted backup without rewriting unrelated membership', async () => {- const claude = target('claude', 'opus-5', [A], ['claude']);- const { api, store } = writes({ 'claude:opus-5': claude.chain });- api.getVibeAgent = vi.fn(async () => ({ ok: true, agent: full(brief('claude', 'claude', 'opus-5')) }));- const live = { ...claude, membership: [A, B] };- const results = await saveSetupRoutes([A, B], [live], api, { dirty: true });- expect(api.putAgentChain).toHaveBeenCalledWith('claude', 'opus-5', { hops: [A, B] });- expect(results).toEqual([expect.objectContaining({ kind: 'confirmed' })]);- expect(store['claude:opus-5']?.manual_override?.hops).toEqual([A, B]);- });-- it('reordering an automatic chain persists a manual override and reads it back', async () => {- const claude = target('claude', 'opus-5', [A, B], ['claude'], 'automatic');- const { api, store } = writes({ 'claude:opus-5': claude.chain });- api.getVibeAgent = vi.fn(async () => ({ ok: true, agent: full(brief('claude', 'claude', 'opus-5')) }));- const results = await saveSetupRoutes([B, A], [claude], api, { dirty: true });- expect(api.previewAgentChain).toHaveBeenCalledWith('claude', 'opus-5', { manual_override: { hops: [B, A] } });- expect(api.putAgentChain).toHaveBeenCalledWith('claude', 'opus-5', { hops: [B, A] });- expect(results).toEqual([expect.objectContaining({ kind: 'confirmed' })]);- expect(store['claude:opus-5']?.manual_override).toEqual({ hops: [B, A] });- expect(store['claude:opus-5']?.route_origin).toBe('manual');- });-- it('keeps the first write and retries only the outstanding target after a later failure', async () => {- const claude = target('claude', 'opus-5', [A, B], ['claude']);- const codex = target('codex', 'gpt-5', [A, B], ['codex']);- const { api, store } = writes({- 'claude:opus-5': claude.chain,- 'codex:gpt-5': codex.chain,- }, { failOn: 'codex:gpt-5' });- api.getVibeAgent = vi.fn(async (name: string) => ({- ok: true,- agent: full(brief(name, name === 'codex' ? 'codex' : 'claude', name === 'codex' ? 'gpt-5' : 'opus-5')),- }));- const shared = [B, A];- const first = await saveSetupRoutes(shared, [claude, codex], api, { dirty: true });- expect(first[0]).toEqual(expect.objectContaining({ kind: 'confirmed' }));- expect(first[1]).toEqual(expect.objectContaining({ kind: 'failed' }));- expect(store['claude:opus-5']?.manual_override?.hops).toEqual([B, A]);- expect(store['codex:gpt-5']?.manual_override?.hops).toEqual([A, B]);-- const retried = writes(store);- retried.api.getVibeAgent = api.getVibeAgent;- retried.api.listAgents = api.listAgents;- const second = await retrySetupRoutes(shared, [claude, codex], first, retried.api);- expect(retried.api.putAgentChain).toHaveBeenCalledTimes(1);- expect(retried.api.putAgentChain).toHaveBeenCalledWith('codex', 'gpt-5', { hops: [B, A] });- expect(second[0]?.kind).toBe('confirmed');- expect(second[1]?.kind).toBe('confirmed');- });-- // A retry is separated from the hydration it was built on by however long the- // person spent looking at the failure, so the identity behind the target is the- // most likely thing to have moved — and the write it is about to repeat is the- // one thing that cannot be taken back afterwards.- describe('a target whose identity moved while the failure was on screen', () => {- const outstanding = (chain: AgentChain) => {- const claude = target('claude', 'opus-5', [A, B], ['claude']);- const fixture = writes({ 'claude:opus-5': chain });- return { claude, ...fixture };- };- const failedBefore = [{ key: targetKey('claude', 'opus-5'), kind: 'failed' as const, error: 'boom' }];-- it('writes nothing when the backend has left hub', async () => {- const { claude, api } = outstanding(target('claude', 'opus-5', [A, B], ['claude']).chain);- api.getVibeAgent = vi.fn(async () => ({ ok: true, agent: full(brief('claude', 'claude', 'opus-5')) }));- api.listAgents = vi.fn(async () => [- { ...supply('claude', [{ name: 'claude', model: 'opus-5' }]), mode: 'direct' as const },- ]);- const results = await retrySetupRoutes([B, A], [claude], failedBefore, api);- expect(results).toEqual([expect.objectContaining({ kind: 'reconcile' })]);- expect(api.previewAgentChain).not.toHaveBeenCalled();- expect(api.putAgentChain).not.toHaveBeenCalled();- expect(api.putAgentModels).not.toHaveBeenCalled();- });-- it('writes nothing when the Agent now names another model', async () => {- const { claude, api } = outstanding(target('claude', 'opus-5', [A, B], ['claude']).chain);- api.getVibeAgent = vi.fn(async () => ({ ok: true, agent: full(brief('claude', 'claude', 'sonnet-4')) }));- const results = await retrySetupRoutes([B, A], [claude], failedBefore, api);- expect(results).toEqual([expect.objectContaining({ kind: 'reconcile' })]);- expect(api.previewAgentChain).not.toHaveBeenCalled();- expect(api.putAgentChain).not.toHaveBeenCalled();- expect(api.putAgentModels).not.toHaveBeenCalled();- });-- it('reports a failed identity read as failed, and still writes nothing', async () => {- const { claude, api } = outstanding(target('claude', 'opus-5', [A, B], ['claude']).chain);- api.listAgents = vi.fn(async () => { throw new Error('agents unreachable'); });- const results = await retrySetupRoutes([B, A], [claude], failedBefore, api);- expect(results).toEqual([expect.objectContaining({ kind: 'failed', error: 'agents unreachable' })]);- expect(api.putAgentChain).not.toHaveBeenCalled();- });- });-- it('classifies a confirmed desired override as skip on retry', () => {- const claude = target('claude', 'opus-5', [A, B], ['claude']);- const desired = [B, A];- const current = chainOf('claude', 'opus-5', desired, 'manual');- expect(classifyRetry(claude, current, desired)).toBe('skip');- expect(classifyRetry(claude, claude.chain, desired)).toBe('retry');- });-- // A machine that has just installed OpenCode answers with an empty catalog and an- // Agent that already names the model it was installed with. The backend validates a- // route override against that catalog, so the preview is refused for a model nobody- // has had the chance to add — which is every first route this step tries to save.- describe('an open-menu catalog that does not yet name the Agent\'s model', () => {- // What the server offers for an id: its protocol, and the suppliers it is- // offered with. Both are the server's answer — for OpenCode the protocol is- // derived per model, so an Anthropic-family model states `anthropic` and- // nothing in the browser may decide otherwise.- const candidate = (- id: string,- native_protocol?: NativeProtocol,- suppliers: ModelCandidateSupplier[] = [],- ): ModelCandidate => ({- id,- display_name: id.toUpperCase(),- reasoning_efforts: [],- suppliers,- origin: 'provider',- ...(native_protocol ? { native_protocol } : {}),- });-- const opencodeWrites = (- modelId: string,- catalog: BackendModel[],- candidates: ModelCandidate[],- ) => {- const calls: string[] = [];- const store: Record<string, AgentChain> = {- [`opencode:${modelId}`]: chainOf('opencode', modelId, [], 'automatic'),- };- let listed = catalog;- const api = {- getVibeAgent: vi.fn(async (name: string) => ({ ok: true, agent: full(brief(name, 'opencode', modelId)) })),- listAgents: vi.fn(async () => [{- ...supply('opencode', [{ name: 'opencode', model: modelId }]),- menu_kind: 'open' as const,- catalog_models: listed,- }]),- getAgentModelCandidates: vi.fn(async () => {- calls.push('candidates');- return { builtin: [], providers: candidates, in_list: [] };- }),- getAgentChain: vi.fn(async (backend: AgentChain['backend'], model: string) => {- const current = store[`${backend}:${model}`];- if (!current) throw new Error(`missing ${backend} ${model}`);- return current;- }),- // The backend's own check, as the route override validator states it: a model- // the catalog does not name cannot carry hops.- previewAgentChain: vi.fn(async (backend: AgentChain['backend'], model: string, body: { manual_override: { hops: RouteHop[] } | null }) => {- calls.push('preview');- if (!listed.some((row) => row.id === model)) throw new Error(`unknown model ${model}`);- return chainOf(backend, model, body.manual_override?.hops ?? [], 'manual');- }),- putAgentChain: vi.fn(async (backend: AgentChain['backend'], model: string, body: { hops: RouteHop[] }) => {- const next = chainOf(backend, model, body.hops, 'manual');- store[`${backend}:${model}`] = next;- return { chain: next };- }),- putAgentModels: vi.fn(async (_backend: AgentChain['backend'], body: BackendModelsPut) => {- calls.push('models');- listed = body.models;- return supply('opencode', [{ name: 'opencode', model: 'glm-4.6' }]);- }),- };- return { api, calls, store };- };- // The first route this machine ever saves: nothing is chained yet, and the person- // has just put one source under the model their Agent already names.- const live = (modelId: string) => ({- ...target('opencode', modelId, [], ['opencode'], 'automatic'),- membership: [A],- });-- it('reconciles the saved model into the catalog before the preview, and the save lands', async () => {- const { api, calls, store } = opencodeWrites('glm-4.6', [], [candidate('glm-4.6', 'openai_responses')]);- const results = await saveSetupRoutes([A], [live('glm-4.6')], api, { dirty: true });- expect(calls).toEqual(['candidates', 'models', 'preview']);- expect(api.putAgentModels).toHaveBeenCalledWith('opencode', {- baseline: [],- models: [expect.objectContaining({- id: 'glm-4.6', display_name: 'GLM-4.6', origin: 'provider',- native_protocol: 'openai_responses', locked: false, routeable: true,- })],- // An offered id nothing supplies yet still states its projection: empty- // is the agreement, and the guard it arms is what refuses this write if- // something starts supplying the id before it commits.- expected_suppliers: { 'glm-4.6': [] },- });- expect(results).toEqual([expect.objectContaining({ kind: 'confirmed' })]);- expect(store['opencode:glm-4.6']?.manual_override).toEqual({ hops: [A] });- });-- // The reason the row is the server's candidate rather than one built here. An- // Anthropic-family model driven through OpenCode speaks the Anthropic protocol;- // a row built locally would default to Responses and the config would be quietly- // wrong for every later turn, which is worse than the refusal it replaced.- it('adopts an Anthropic-family model with the protocol the server states', async () => {- const id = 'claude-sonnet-4-5';- const { api, store } = opencodeWrites(id, [], [candidate(id, 'anthropic')]);- const results = await saveSetupRoutes([A], [live(id)], api, { dirty: true });- expect(api.putAgentModels).toHaveBeenCalledWith('opencode', {- baseline: [],- models: [expect.objectContaining({ id, native_protocol: 'anthropic' })],- expected_suppliers: { [id]: [] },- });- expect(results).toEqual([expect.objectContaining({ kind: 'confirmed' })]);- expect(store[`opencode:${id}`]?.manual_override).toEqual({ hops: [A] });- });-- // The other half of the same agreement. The server matches an addition- // against inventory at commit time, and only an addition that states which- // projection it was made against can be refused when that inventory moved;- // one that states none is filed as a hand-written row, which promised- // nothing, and commits a catalog entry nobody agreed to. The projection is- // the candidate's own — its supplier names a different model id than the one- // being added, so a rebuild from anything but the candidate cannot produce it.- it('states the suppliers the candidate was offered with, not a projection rebuilt here', async () => {- const supplier: ModelCandidateSupplier = {- source_id: 'src_a', source_name: 'Relay', model_id: 'glm-4.6-air',- };- const { api, store } = opencodeWrites('glm-4.6', [], [candidate('glm-4.6', 'openai_responses', [supplier])]);- const results = await saveSetupRoutes([A], [live('glm-4.6')], api, { dirty: true });- expect(api.putAgentModels).toHaveBeenCalledWith('opencode', expect.objectContaining({- expected_suppliers: { 'glm-4.6': [{ source_id: 'src_a', model_id: 'glm-4.6-air' }] },- }));- expect(results).toEqual([expect.objectContaining({ kind: 'confirmed' })]);- expect(store['opencode:glm-4.6']?.manual_override).toEqual({ hops: [A] });- });-- // Nobody has an authoritative answer for this id, so nobody invents one: the- // save refuses exactly as it did before, and the person is sent to the catalog.- it.each([- ['no candidate names the model', [] as ModelCandidate[]],- ['the candidate states no protocol', [candidate('claude-sonnet-4-5')]],- ])('writes no catalog when %s', async (_label, candidates) => {- const id = 'claude-sonnet-4-5';- const { api, calls } = opencodeWrites(id, [], candidates);- const results = await saveSetupRoutes([A], [live(id)], api, { dirty: true });- expect(api.putAgentModels).not.toHaveBeenCalled();- expect(calls).toEqual(['candidates', 'preview']);- expect(results).toEqual([expect.objectContaining({ kind: 'failed', error: `unknown model ${id}` })]);- });-- it('reads no candidates and writes no catalog when it already names the model', async () => {- const held: BackendModel = {- id: 'glm-4.6', display_name: 'GLM 4.6', origin: 'manual', models_dev_id: null,- context_window: null, max_output_tokens: null, input_modalities: [], output_modalities: [],- supports_tools: null, supports_reasoning: null, reasoning_efforts: [],- native_protocol: 'openai_responses', locked: false, routeable: true,- };- const { api, calls } = opencodeWrites('glm-4.6', [held], [candidate('glm-4.6', 'openai_responses')]);- const results = await saveSetupRoutes([A], [live('glm-4.6')], api, { dirty: true });- expect(api.getAgentModelCandidates).not.toHaveBeenCalled();- expect(api.putAgentModels).not.toHaveBeenCalled();- expect(calls).toEqual(['preview']);- expect(results).toEqual([expect.objectContaining({ kind: 'confirmed' })]);- });-- // Why the adoption sits where it does. Another Settings surface moved this- // target's chain after hydration, so the save reconciles — and reconciling- // has to mean nothing was persisted. The catalog addition is a write like- // the chain write, so the decision that refuses both has to happen before- // either; deciding afterwards and undoing it would answer an ordering rule- // with a rollback.- it('writes nothing at all, catalog included, when the chain moved after hydration', async () => {- const { api, calls, store } = opencodeWrites('glm-4.6', [], [candidate('glm-4.6', 'openai_responses')]);- store['opencode:glm-4.6'] = chainOf('opencode', 'glm-4.6', [C], 'manual');- const results = await saveSetupRoutes([A], [live('glm-4.6')], api, { dirty: true });- expect(results).toEqual([expect.objectContaining({ kind: 'reconcile' })]);- expect(api.putAgentModels).not.toHaveBeenCalled();- expect(api.putAgentChain).not.toHaveBeenCalled();- expect(calls).toEqual([]);- });- });-});diff --git a/ui/src/components/onboarding/setupRoute.ts b/ui/src/components/onboarding/setupRoute.tsdeleted file mode 100644index 9672f5327..000000000--- a/ui/src/components/onboarding/setupRoute.ts+++ /dev/null@@ -1,494 +0,0 @@-import type { VibeAgentBrief, VibeAgentFull } from '../../context/ApiContext';-import type { AssistantId } from './collaborationTimeline';-import { ASSISTANT_ORDER } from './collaborationTimeline';-import { readSetupTargets } from './setupTargets';-import { routeChainMatchesAttempt, sameManualOverride, sameRouteDraft } from '../settings/models/routeChainDraft';-import { catalogModels, chosenCandidate, draftRowFor, offeredCandidates } from '../settings/models/backendCatalog';-import type {- AgentBackend,- AgentChain,- AgentSupply,- BackendModelCandidates,- BackendModelsPut,- RouteHop,-} from '../settings/models/types';--export const hopIdentity = (hop: RouteHop): string => `${hop.source_id}\0${hop.model_id}`;--export const targetKey = (backend: AgentBackend, modelId: string): string =>- `${backend}\0${modelId}`;--export type SetupRouteTargetSnapshot = {- backend: AgentBackend;- modelId: string;- agentNames: string[];- chain: AgentChain;- membership: RouteHop[];-};--export type SetupRouteHydration = {- defaultAgentName: string | null;- targets: SetupRouteTargetSnapshot[];- union: RouteHop[];-};--/** The assistant card that opened the route editor. */-export type SetupRouteFocus = {- backend: AgentBackend;- agentName?: string;-};--/**- * Pick the snapshot the focused card may edit.- *- * A hosted card always supplies identity and never inherits another backend's- * target. Standalone tests that omit focus keep the first hydrated snapshot.- */-export const selectSetupRouteTarget = (- targets: readonly SetupRouteTargetSnapshot[],- focus?: SetupRouteFocus | null,-): SetupRouteTargetSnapshot | null => {- if (!targets.length) return null;- if (!focus) return targets[0] ?? null;- if (focus.agentName) {- const named = targets.find((target) => (- target.backend === focus.backend && target.agentNames.includes(focus.agentName!)- ));- if (named) return named;- }- return targets.find((target) => target.backend === focus.backend) ?? null;-};--export type SetupRouteReadApi = {- listVibeAgents: (params?: { cache?: boolean }) => Promise<{- ok: boolean;- agents: VibeAgentBrief[];- default_agent_name: string | null;- }>;- getVibeAgent: (- name: string,- params?: { cache?: boolean },- ) => Promise<{ ok: boolean; agent?: VibeAgentFull | null }>;- getAgentChain: (backend: AgentBackend, model: string) => Promise<AgentChain>;-};--export type SetupRouteWriteApi = {- getVibeAgent: SetupRouteReadApi['getVibeAgent'];- listAgents: () => Promise<AgentSupply[]>;- getAgentChain: SetupRouteReadApi['getAgentChain'];- previewAgentChain: (- backend: AgentBackend,- model: string,- body: { manual_override: { hops: RouteHop[] } | null },- ) => Promise<AgentChain>;- putAgentChain: (- backend: AgentBackend,- model: string,- body: { hops: RouteHop[] },- ) => Promise<{ chain: AgentChain }>;- getAgentModelCandidates: (backend: AgentBackend) => Promise<BackendModelCandidates>;- putAgentModels: (backend: AgentBackend, body: BackendModelsPut) => Promise<AgentSupply>;-};--export type TargetSaveResult =- | { key: string; kind: 'skipped' }- | { key: string; kind: 'confirmed'; chain: AgentChain }- | { key: string; kind: 'failed'; error: string }- | { key: string; kind: 'reconcile'; chain: AgentChain };--/** Manual hops win when present; otherwise the automatic chain order. */-export const chainMembership = (chain: AgentChain): RouteHop[] => {- if (chain.manual_override?.hops.length) {- return chain.manual_override.hops.map((hop) => ({ source_id: hop.source_id, model_id: hop.model_id }));- }- return chain.chain.map((link) => ({ source_id: link.source_id, model_id: link.model_id }));-};--export const projectTargetHops = (shared: RouteHop[], membership: RouteHop[]): RouteHop[] => {- const allowed = new Set(membership.map(hopIdentity));- return shared.filter((hop) => allowed.has(hopIdentity(hop)));-};--export const targetChanged = (shared: RouteHop[], target: SetupRouteTargetSnapshot): boolean =>- !sameRouteDraft(projectTargetHops(shared, target.membership), target.membership);--export const withMembershipHop = (membership: RouteHop[], hop: RouteHop): RouteHop[] => {- if (membership.some((row) => hopIdentity(row) === hopIdentity(hop))) return membership;- return [...membership, hop];-};--export const appendSharedHop = (order: RouteHop[], hop: RouteHop): RouteHop[] => {- if (order.some((row) => hopIdentity(row) === hopIdentity(hop))) return order;- return [...order, hop];-};--export const moveRouteHop = (order: RouteHop[], index: number, direction: -1 | 1): RouteHop[] => {- const next = index + direction;- if (index < 0 || next < 0 || next >= order.length) return order;- const copy = [...order];- const current = copy[index];- const swap = copy[next];- if (!current || !swap) return order;- copy[index] = swap;- copy[next] = current;- return copy;-};--const backendRank = (backend: AgentBackend): number => {- const index = ASSISTANT_ORDER.indexOf(backend as AssistantId);- return index === -1 ? ASSISTANT_ORDER.length : index;-};--const byName = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);--export const orderSetupTargets = (- targets: readonly SetupRouteTargetSnapshot[],- defaultAgentName?: string | null,-): SetupRouteTargetSnapshot[] => {- const inDefault = defaultAgentName- ? targets.filter((target) => target.agentNames.includes(defaultAgentName))- : [];- const rest = defaultAgentName- ? targets.filter((target) => !target.agentNames.includes(defaultAgentName))- : [...targets];- const byStable = (left: SetupRouteTargetSnapshot, right: SetupRouteTargetSnapshot) =>- backendRank(left.backend) - backendRank(right.backend)- || byName(left.agentNames[0] ?? '', right.agentNames[0] ?? '')- || byName(left.modelId, right.modelId);- return [...inDefault].sort(byStable).concat([...rest].sort(byStable));-};--export const unionRouteOrder = (- targets: readonly SetupRouteTargetSnapshot[],- defaultAgentName?: string | null,-): RouteHop[] => {- const seen = new Set<string>();- const union: RouteHop[] = [];- for (const target of orderSetupTargets(targets, defaultAgentName)) {- for (const hop of target.membership) {- const key = hopIdentity(hop);- if (seen.has(key)) continue;- seen.add(key);- union.push(hop);- }- }- return union;-};--/** The Agent's exact saved model. Never selected_model_id or the first catalog row. */-export const menuModelFor = (agent: Pick<VibeAgentFull, 'model'>, _supply?: AgentSupply): string | null => {- const saved = agent.model?.trim();- return saved ? saved : null;-};--const discloseNames = (- backend: AgentBackend,- modelId: string,- designated: string[],- supplies: readonly AgentSupply[],-): string[] => {- const names = new Set(designated);- for (const supply of supplies) {- if (supply.backend !== backend) continue;- for (const named of supply.named_agents ?? []) {- if (named.effective_model_id === modelId) names.add(named.name);- }- }- return [...names].sort(byName);-};--export async function hydrateSetupRoutes(- reads: SetupRouteReadApi,- supplies: readonly AgentSupply[],-): Promise<SetupRouteHydration> {- const listing = await reads.listVibeAgents({ cache: false });- const briefs = listing.ok ? listing.agents : [];- const designated = await readSetupTargets(briefs, reads);- const supplyByBackend = new Map(supplies.map((row) => [row.backend, row]));- const grouped = new Map<string, { backend: AgentBackend; modelId: string; names: string[] }>();-- for (const agent of designated) {- const backend = agent.backend as AgentBackend;- const modelId = menuModelFor(agent, supplyByBackend.get(backend));- if (!modelId) continue;- const key = targetKey(backend, modelId);- const existing = grouped.get(key);- if (existing) existing.names.push(agent.name);- else grouped.set(key, { backend, modelId, names: [agent.name] });- }-- const targets: SetupRouteTargetSnapshot[] = [];- for (const group of grouped.values()) {- try {- const chain = await reads.getAgentChain(group.backend, group.modelId);- targets.push({- backend: group.backend,- modelId: group.modelId,- agentNames: discloseNames(group.backend, group.modelId, group.names, supplies),- chain,- membership: chainMembership(chain),- });- } catch {- // Keep configure reachable; a failed chain is not a save target.- }- }-- const ordered = orderSetupTargets(targets, listing.default_agent_name);- return {- defaultAgentName: listing.default_agent_name,- targets: ordered,- union: unionRouteOrder(ordered, listing.default_agent_name),- };-}--export const classifyRetry = (- target: SetupRouteTargetSnapshot,- current: AgentChain,- desired: RouteHop[],-): 'skip' | 'retry' | 'reconcile' => {- if (routeChainMatchesAttempt(current, {- backend: target.backend,- modelId: target.modelId,- submitted: desired,- manual_override: { hops: desired },- })) return 'skip';- const original = chainMembership(target.chain);- const sameMembership = sameRouteDraft(chainMembership(current), original);- const sameOverride = sameManualOverride(current.manual_override, target.chain.manual_override);- return sameMembership && sameOverride ? 'retry' : 'reconcile';-};--const errorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));--const precheckTarget = async (- target: SetupRouteTargetSnapshot,- api: SetupRouteWriteApi,-): Promise<{ kind: 'ok'; supply: AgentSupply } | 'reconcile' | { kind: 'failed'; error: string }> => {- try {- const supplies = await api.listAgents();- const supply = supplies.find((row) => row.backend === target.backend);- if (supply?.mode !== 'hub') return 'reconcile';- for (const name of target.agentNames) {- const result = await api.getVibeAgent(name, { cache: false });- if (result.ok && result.agent && result.agent.backend === target.backend && result.agent.model === target.modelId) {- return { kind: 'ok', supply };- }- }- return 'reconcile';- } catch (error) {- return { kind: 'failed', error: errorMessage(error) };- }-};--/**- * Make the backend know the model this target is for, before anything asks it to- * route one.- *- * A route is previewed and saved against a model the backend's catalog names. An- * open-menu backend's catalog is the user's own, so a machine that just installed- * OpenCode has an empty one — while the Agent it was installed with already carries- * the model this target was hydrated from. Without this, the first preview of that- * model is refused for a model nobody could have added yet, and setup's route step- * can never succeed on a new install.- *- * Only the open-menu path, and only a model the catalog does not already hold: a- * fixed-menu backend ships its own catalog, and a server that predates backend- * catalogs states none at all, so both are left exactly as they were.- *- * What is added is a candidate the server offered, so it is added the way the- * picker adds one — the whole agreement, through the functions that own it,- * rather than the fields this path happens to need. `draftRowFor` owns which row- * an id gets, and `chosenCandidate` pairs a pick with the projection it was- * picked against so the two cannot drift apart. Composing either half here is- * what produced the defects this comment is now the record of: a protocol- * defaulted to Responses under an Anthropic-family model, and an addition that- * promised nothing about its suppliers.- *- * So the protocol is the one the server derived — the generic default is- * Responses, and an Anthropic-family model adopted without asking would be- * written down as a Responses model and speak the wrong protocol on every later- * turn, a silently wrong config in place of a loud refusal. And the suppliers- * are the projection that candidate was offered with, which is what lets the- * server refuse this write when inventory has moved since the read; without it- * the addition is filed as a hand-written row, which promises nothing, and a- * catalog entry nobody agreed to commits while the route preview still fails.- *- * When no offered candidate names this id, or the one that does states no- * protocol, nothing is written and the preview refuses exactly as it did before:- * the person is sent to the catalog to say what this model is, rather than being- * given an answer nobody gave.- */-const adoptTargetModel = async (- target: SetupRouteTargetSnapshot,- api: SetupRouteWriteApi,- supply: AgentSupply,-): Promise<void> => {- if (supply.menu_kind !== 'open') return;- const catalog = catalogModels(supply);- if (!catalog || catalog.some((model) => model.id === target.modelId)) return;- const offered = offeredCandidates(await api.getAgentModelCandidates(target.backend));- const candidate = offered.get(target.modelId);- if (!candidate?.native_protocol) return;- const chosen = chosenCandidate(candidate);- const adopted = draftRowFor(chosen.candidate, [], catalog);- await api.putAgentModels(target.backend, {- baseline: catalog,- models: [...catalog, adopted],- expected_suppliers: { [adopted.id]: chosen.expected_suppliers },- });-};--/**- * The write, and nothing that decides whether it may happen.- *- * `supply` is required rather than re-read here because the contract wants the- * Agent, the mode and the chain checked against the baseline before EVERY write,- * and a parameter this function cannot invent is what makes 「its caller checked」- * true by construction instead of by each caller remembering to.- */-const writeTarget = async (- target: SetupRouteTargetSnapshot,- desired: RouteHop[],- api: SetupRouteWriteApi,- supply: AgentSupply,-): Promise<TargetSaveResult> => {- const key = targetKey(target.backend, target.modelId);- try {- // Everything that decides whether this save may write at all comes first,- // because a decision made after a write is not a decision. The contract- // re-reads the chain against the baseline before each write, and a target- // another Settings surface has moved since hydration is sent to- // reconciliation — which has to mean nothing was persisted, not that what- // was persisted gets taken back. The catalog addition below is a write like- // any other, so it sits on this side of the check with the chain write.- const pre = await api.getAgentChain(target.backend, target.modelId);- if (routeChainMatchesAttempt(pre, {- backend: target.backend,- modelId: target.modelId,- submitted: desired,- manual_override: { hops: desired },- })) {- return { key, kind: 'confirmed', chain: pre };- }- const check = classifyRetry(target, pre, desired);- if (check === 'reconcile') return { key, kind: 'reconcile', chain: pre };- // Still ahead of the preview, which is what needs it: the backend validates- // an override against its catalog, so the model has to be in there before- // anything asks to route it.- await adoptTargetModel(target, api, supply);- await api.previewAgentChain(target.backend, target.modelId, { manual_override: { hops: desired } });- await api.putAgentChain(target.backend, target.modelId, { hops: desired });- const readback = await api.getAgentChain(target.backend, target.modelId);- if (routeChainMatchesAttempt(readback, {- backend: target.backend,- modelId: target.modelId,- submitted: desired,- manual_override: { hops: desired },- })) {- return { key, kind: 'confirmed', chain: readback };- }- return { key, kind: 'reconcile', chain: readback };- } catch (error) {- return { key, kind: 'failed', error: errorMessage(error) };- }-};--export async function saveSetupRoutes(- shared: RouteHop[],- targets: readonly SetupRouteTargetSnapshot[],- api: SetupRouteWriteApi,- options: { dirty: boolean } = { dirty: true },-): Promise<TargetSaveResult[]> {- if (!options.dirty) {- return targets.map((target) => ({ key: targetKey(target.backend, target.modelId), kind: 'skipped' as const }));- }- const results: TargetSaveResult[] = [];- for (const target of targets) {- const key = targetKey(target.backend, target.modelId);- const desired = projectTargetHops(shared, target.membership);- const baselineHops = chainMembership(target.chain);- if (- desired.length === 0- || (sameRouteDraft(desired, baselineHops) && sameRouteDraft(target.membership, baselineHops))- ) {- results.push({ key, kind: 'skipped' });- continue;- }- const precheck = await precheckTarget(target, api);- if (precheck === 'reconcile') {- const chain = await api.getAgentChain(target.backend, target.modelId).catch(() => target.chain);- results.push({ key, kind: 'reconcile', chain });- continue;- }- if (precheck.kind === 'failed') {- results.push({ key, kind: 'failed', error: precheck.error });- continue;- }- results.push(await writeTarget(target, desired, api, precheck.supply));- }- return results;-}--export async function retrySetupRoutes(- shared: RouteHop[],- targets: readonly SetupRouteTargetSnapshot[],- previous: readonly TargetSaveResult[],- api: SetupRouteWriteApi,-): Promise<TargetSaveResult[]> {- const results: TargetSaveResult[] = [];- for (const target of targets) {- const key = targetKey(target.backend, target.modelId);- const prior = previous.find((row) => row.key === key);- if (!prior || prior.kind === 'skipped') {- results.push(prior ?? { key, kind: 'skipped' });- continue;- }- const desired = projectTargetHops(shared, target.membership);- if (desired.length === 0) {- results.push({ key, kind: 'skipped' });- continue;- }- let current: AgentChain;- try {- current = await api.getAgentChain(target.backend, target.modelId);- } catch (error) {- results.push({ key, kind: 'failed', error: errorMessage(error) });- continue;- }- const classification = classifyRetry(target, current, desired);- if (classification === 'skip') {- results.push({ key, kind: 'confirmed', chain: current });- continue;- }- if (classification === 'reconcile') {- results.push({ key, kind: 'reconcile', chain: current });- continue;- }- // The chain above is only one of the three things the contract re-reads- // before a write. A retry needs the other two more than the first attempt- // did, not less: it is separated from the hydration it was built on by- // however long the person spent looking at the failure, so the backend may- // have left hub and the Agent may now name a different model — and writing- // a route for a target that no longer exists is what asking afterwards- // cannot undo. Same question, same owner, so the two paths cannot answer it- // differently.- const precheck = await precheckTarget(target, api);- if (precheck === 'reconcile') {- results.push({ key, kind: 'reconcile', chain: current });- continue;- }- if (precheck.kind === 'failed') {- results.push({ key, kind: 'failed', error: precheck.error });- continue;- }- results.push(await writeTarget(target, desired, api, precheck.supply));- }- return results;-}--export const saveNeedsRetry = (results: readonly TargetSaveResult[]): boolean =>- results.some((row) => row.kind === 'failed' || row.kind === 'reconcile');--export const hopsFor = (targets: readonly SetupRouteTargetSnapshot[], hop: RouteHop): string[] =>- targets.filter((target) => target.membership.some((row) => hopIdentity(row) === hopIdentity(hop)))- .flatMap((target) => target.agentNames);diff --git a/ui/src/components/onboarding/setupTargets.ts b/ui/src/components/onboarding/setupTargets.tsindex a631c0b1c..d2d7c2624 100644--- a/ui/src/components/onboarding/setupTargets.ts+++ b/ui/src/components/onboarding/setupTargets.ts@@ -15,8 +15,8 @@ import { ASSISTANT_ORDER, type AssistantId } from './collaborationTimeline';* named `claude` must not take the card. The producer is* `is_builtin_default_agent`: metadata `builtin_default` or `lock_delete`.* Only an uncached full Agent read has those fields. A missing or failed read- * is not a designated target; it is an explicit existing-name choice later,- * not an inferred one now.+ * is not a designated target in the permissive reader; the route editor asks+ * for strict reads so an incomplete target list cannot be saved as complete.*/const DEFAULT_AGENT_NAME = 'default';@@ -72,6 +72,7 @@ const sameCurrentIdentity = (brief: VibeAgentBrief, full: VibeAgentFull): booleaexport async function readSetupTargets(briefs: readonly VibeAgentBrief[],reader: SetupTargetReader,+ options: { requireReadable?: boolean } = {},): Promise<VibeAgentFull[]> {const seen = new Set<string>();const relevant = briefs.filter((agent) => {@@ -84,11 +85,15 @@ export async function readSetupTargets(const records = await Promise.all(relevant.map(async (brief) => {try {const result = await reader.getVibeAgent(brief.name, { cache: false });- if (!result.ok || result.agent == null) return null;+ if (!result.ok || result.agent == null) {+ if (options.requireReadable) throw new Error('setup_target_read_failed');+ return null;+ }if (!sameCurrentIdentity(brief, result.agent)) return null;if (!result.agent.enabled || result.agent.archived) return null;return result.agent;- } catch {+ } catch (error) {+ if (options.requireReadable) throw error;return null;}}));diff --git a/ui/src/components/settings/BackendLifecycleChip.tsx b/ui/src/components/settings/BackendLifecycleChip.tsxindex 4470be0cd..f425c6530 100644--- a/ui/src/components/settings/BackendLifecycleChip.tsx+++ b/ui/src/components/settings/BackendLifecycleChip.tsx@@ -34,6 +34,9 @@ interface BackendLifecycleChipProps {cliStatus: CliStatus;/** Setup describes executable availability separately from connection readiness. */readyLabel?: string;+ /** Setup reads an off switch as a step the person has not taken yet, not as a+ backend that was turned off, so it names that state itself. */+ disabledLabel?: string;onChanged?: (info?: BackendChipChange) => void | Promise<void>;onOperationChange?: (pending: boolean) => void;/** The setup card draws the action its lifecycle offers — update or install —@@ -114,6 +117,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({onChanged,onOperationChange,readyLabel,+ disabledLabel,onVisual,refreshKey,externallyBusy = false,@@ -237,7 +241,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({const chipLabel = (() => {switch (visual) {case 'disabled':- return t('backendLifecycle.statusDisabled');+ return disabledLabel || t('backendLifecycle.statusDisabled');case 'ready':return readyLabel || t('backendLifecycle.statusReady');case 'updating':diff --git a/ui/src/components/settings/models/MigrationDialog.test.tsx b/ui/src/components/settings/models/MigrationDialog.test.tsxindex 32b250c3d..0df903e9c 100644--- a/ui/src/components/settings/models/MigrationDialog.test.tsx+++ b/ui/src/components/settings/models/MigrationDialog.test.tsx@@ -426,8 +426,8 @@ describe('MigrationDialog — persisted authentication', () => {{reason: 'transport',path: '/home/用户/.bashrc',- en: /cannot send.*saved authentication in the same way.*original files are unchanged.*permissions will not fix/,- zh: /无法按此接口原有的方式发送认证.*原配置文件未改动.*修改文件权限不能解决/,+ en: /can't use this authentication method yet.*file is unchanged.*standard API key/,+ zh: /暂不支持这里的认证方式.*原文件未改动.*标准 API Key 重新添加/,},] as const;@@ -798,7 +798,7 @@ describe('MigrationDialog — the Settings surface the setup scope must not distconst 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();+ expect(within(dialog).queryByText(/Only API keys can be migrated here/)).toBeNull();});it('still takes a key standing beside a subscription, because its scope is everything', async () => {@@ -879,8 +879,8 @@ describe('MigrationDialog — the setup scope', () => {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).getByText(/After migration, these assistants connect through Model Hub/)).toBeTruthy();+ expect(within(dialog).getByText(/Only API keys can be migrated here/)).toBeTruthy();expect(within(dialog).getByRole('button', { name: 'Not now' })).toBeTruthy();expect(scan).not.toHaveBeenCalled();});diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsxindex 6295f8930..0dd8d2bdd 100644--- a/ui/src/components/settings/models/MigrationDialog.tsx+++ b/ui/src/components/settings/models/MigrationDialog.tsx@@ -228,6 +228,7 @@ type SetupPhase = { kind: 'select' } | { kind: 'applying'; count: number } | { kexport const MigrationDialog: React.FC<{open: boolean;onClose: () => void;+ onDecline?: () => void;/** Fired after a successful apply so callers can refresh sources/agents. */onApplied?: (applied: number) => void;/** Scopes the entry point, then includes every native row and required@@ -261,6 +262,7 @@ export const MigrationDialog: React.FC<{}> = ({open,onClose,+ onDecline,onApplied,eligible,takeable,@@ -404,9 +406,13 @@ export const MigrationDialog: React.FC<{};const reporting = scope === 'setup' && phase.kind !== 'select';+ const decline = () => {+ onDecline?.();+ onClose();+ };return (- <Dialog open={open} onOpenChange={(v) => !v && !applying && onClose()}>+ <Dialog open={open} onOpenChange={(v) => !v && !applying && (phase.kind === 'select' ? decline() : onClose())}><DialogContent className="max-w-[640px] gap-5"><DialogHeader><DialogTitle className="flex items-center gap-3 text-[18px] font-bold">@@ -481,7 +487,7 @@ export const MigrationDialog: React.FC<{{!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}>+ <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={decline} 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}>diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsxindex 69a696177..40e5ac7a5 100644--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx@@ -1008,7 +1008,7 @@ describe("RouteChainDialog", () => {agentRead.resolve(observation([agent]));expect(- await screen.findByText("The current model surface could not be read"),+ await screen.findByText("The route could not be read right now"),).toBeTruthy();expect(readChain).toHaveBeenCalledTimes(2);expect(readSources).toHaveBeenCalledTimes(1);diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsxindex 9a3d21f0a..5504106df 100644--- a/ui/src/components/steps/AgentDetection.tsx+++ b/ui/src/components/steps/AgentDetection.tsx@@ -27,7 +27,6 @@ import { BackendConnectionDialog } from '../onboarding/BackendConnectionDialog';import type { BackendConnectionState } from '@/context/ApiContext';import { setConfigField } from '@/lib/configMutations';import { OpencodePermissionSetup } from '../settings/shared/OpencodePermissionSetup';-import { ImportKeysNotice } from '../onboarding/ImportKeysNotice';import { modelHubEnabledFromConfig } from '../settings/models/featureFlags';import type { SetupAction, SetupFlowState, SetupScreenHandle, SetupScreenId } from '../onboarding/setupFlow';import type { BackendId as RuntimeBackendId } from '../settings/shared/useBackendRuntime';@@ -36,10 +35,13 @@ import { Button } from '../ui/button';import { DEFAULT_AGENT_STATE, getBackendUiMeta } from '@/lib/agentBackends';import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';import { MODEL_HUB_SETTINGS_PATH } from '../settings/models/modelHubRoutes';-import { DefaultRouteDialog } from '../onboarding/DefaultRouteDialog';+import { RouteChainDialog, type RouteChainSelection } from '../settings/models/RouteChainDialog';import type { CollectionReadAuthority } from '../settings/models/collectionReadAuthority';-import type { AgentSupply } from '../settings/models/types';-import type { SetupRouteFocus } from '../onboarding/setupRoute';+import type { AgentChain, AgentSupply, Source } from '../settings/models/types';+import type { AssistantRouteView } from '../onboarding/AssistantRow';+import { isBuiltinAgent } from '../onboarding/setupTargets';+import { readyRegion } from '../settings/models/regionRead';+import { modelsApi } from '../settings/models/modelsApi';interface AgentDetectionProps {active?: boolean;@@ -49,7 +51,6 @@ interface AgentDetectionProps {onNext: (data: any) => void | Promise<void>;onBack?: (data?: { agents: Record<string, AgentState> }) => void;isPage?: boolean;- completionRecovery?: React.ReactNode;onSave?: (data: { agents: Record<string, AgentState> }) => Promise<void> | void;flowState?: SetupFlowState;setFlowState?: React.Dispatch<React.SetStateAction<SetupFlowState>>;@@ -115,7 +116,7 @@ const normalizeAgents = (source: any): Record<string, AgentState> => {// description, status pill, enable switch) and an action row (configure// provider / set up Allow / install). Detection runs automatically on mount —// the user enables what they have and installs anything missing.-export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onBack, isPage = false, onSave, completionRecovery, active = true, ref, onActionChange, flowState, setFlowState, onNavigate, agentReads }) => {+export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onBack, isPage = false, onSave, active = true, ref, onActionChange, onNavigate, agentReads }) => {const { t } = useTranslation();const api = useApi();const { showToast } = useToast();@@ -136,14 +137,118 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onconst [expandedOutputs, setExpandedOutputs] = useState<Record<string, boolean>>({});// Which backend's "Configure provider" modal is open (wizard mode only).const [providerModal, setProviderModal] = useState<{ backend: RuntimeBackendId; method: 'oauth' | 'api_key' } | null>(null);- const [routeOpen, setRouteOpen] = useState(false);- const [routeFocus, setRouteFocus] = useState<SetupRouteFocus | null>(null);- const canEditSetupRoute = Boolean(flowState && setFlowState && onNavigate && agentReads);- const openSetupRoute = (backend: RuntimeBackendId) => {- setRouteFocus({ backend, agentName: backend });- setRouteOpen(true);+ const [routeSelection, setRouteSelection] = useState<RouteChainSelection | null>(null);+ const [routeReconciliation, setRouteReconciliation] = useState({ pending: false, failed: false });+ const committedRouteRefresh = useRef(false);+ const canEditSetupRoute = Boolean(onNavigate && agentReads);+ const [routeRead, setRouteRead] = useState<{+ done: boolean;+ failed: boolean;+ confirmed: { epoch: number; token: number } | null;+ failure: { epoch: number; token: number } | null;+ chains: Partial<Record<RuntimeBackendId, AgentChain | null>>;+ models: Partial<Record<RuntimeBackendId, string | null>>;+ backendReads: Partial<Record<RuntimeBackendId, 'ready' | 'failed'>>;+ sources: Source[];+ supplies: AgentSupply[];+ }>({ done: false, failed: false, confirmed: null, failure: null, chains: {}, models: {}, backendReads: {}, sources: [], supplies: [] });+ const routeReadToken = useRef(0);+ const sharedRouteReady = () => active && activeRef.current && routeRead.done && !routeRead.failed+ && routeRead.confirmed?.epoch === activation.current+ && routeRead.confirmed?.token === routeReadToken.current;+ const routeTargetReady = (backend: RuntimeBackendId) => sharedRouteReady() && routeRead.backendReads[backend] === 'ready';+ const routeFailureCurrent = (backend: RuntimeBackendId) => active && activeRef.current && (+ (routeRead.failed && routeRead.failure?.epoch === activation.current+ && routeRead.failure?.token === routeReadToken.current)+ || (sharedRouteReady() && routeRead.backendReads[backend] === 'failed'));+ const readCardRoutes = useCallback(async (target?: RuntimeBackendId) => {+ if (!agentReads) return false;+ const token = ++routeReadToken.current;+ const epoch = activation.current;+ setRouteRead((current) => ({ ...current, done: false, failed: false, confirmed: null, failure: null }));+ try {+ const [supplyRead, listed, vibeAgents] = await Promise.all([+ agentReads.read(),+ modelsApi.listSources(),+ api.listVibeAgents({ cache: false, includeDisabled: true }),+ ]);+ if (supplyRead.kind !== 'current' || !vibeAgents.ok) throw new Error('Route inventory unreadable');+ const supplies = supplyRead.value;+ if (token !== routeReadToken.current || epoch !== activation.current) return false;+ setRouteRead({ done: true, failed: false, confirmed: { epoch, token }, failure: null,+ chains: {}, models: {}, backendReads: {}, sources: listed, supplies });+ const backendPromises = ASSISTANT_ORDER.map(async (backend) => {+ try {+ const candidates = vibeAgents.agents.filter((row) => !row.archived && row.backend === backend)+ .sort((left, right) => {+ const rank = (name: string) => name === backend ? 0 : name === 'default' ? 1 : 2;+ return rank(left.name) - rank(right.name)+ || (left.name < right.name ? -1 : left.name > right.name ? 1 : 0);+ });+ let selected = null;+ for (const candidate of candidates) {+ const detail = await api.getVibeAgent(candidate.name, { cache: false });+ if (!detail.ok || !detail.agent) throw new Error('Agent detail unreadable');+ const current = detail.agent;+ if (current.name === candidate.name && current.backend === backend+ && !current.archived && isBuiltinAgent(current)) {+ selected = current;+ break;+ }+ }+ const model = selected?.model ?? null;+ const supply = supplies.find((row) => row.backend === backend);+ let chain: AgentChain | null = null;+ if (supply?.mode === 'hub' && model) {+ const backendChains = await modelsApi.getAgentChains(backend);+ chain = backendChains.find((row) => row.model_id === model) ?? null;+ }+ if (token !== routeReadToken.current || epoch !== activation.current) return false;+ setRouteRead((current) => ({ ...current,+ models: { ...current.models, [backend]: model },+ chains: { ...current.chains, [backend]: chain },+ backendReads: { ...current.backendReads, [backend]: 'ready' },+ }));+ return true;+ } catch {+ if (token !== routeReadToken.current || epoch !== activation.current) return false;+ setRouteRead((current) => ({ ...current,+ backendReads: { ...current.backendReads, [backend]: 'failed' },+ }));+ return false;+ }+ });+ return target ? backendPromises[ASSISTANT_ORDER.indexOf(target)]+ : Promise.all(backendPromises).then(() => true);+ } catch {+ if (token !== routeReadToken.current || epoch !== activation.current) return false;+ setRouteRead((current) => ({ ...current, done: true, failed: true, confirmed: null, failure: { epoch, token } }));+ return false;+ }+ }, [agentReads, api]);+ useEffect(() => {+ if (!active || !modelHubEnabled || !canEditSetupRoute) return;+ void readCardRoutes();+ }, [active, modelHubEnabled, canEditSetupRoute, readCardRoutes]);+ const modelLabel = (hop: { source_id: string; model_id: string }): string => {+ const source = routeRead.sources.find((row) => row.id === hop.source_id);+ const model = source?.models?.find((row) => row.id === hop.model_id);+ return model?.display_name?.trim() || hop.model_id;+ };+ const routeViewFor = (backend: RuntimeBackendId): AssistantRouteView => {+ if (!canEditSetupRoute || !modelHubEnabled) return { kind: 'unavailable' };+ if (!routeTargetReady(backend)) return { kind: routeFailureCurrent(backend) ? 'failed' : 'pending' };+ if (!routeRead.models[backend]) return { kind: 'no-agent-model' };+ const chain = routeRead.chains[backend];+ const mine = chain?.chain[0] ?? null;+ return {+ kind: 'route',+ model: mine ? modelLabel(mine) : null,+ backups: Math.max(0, (chain?.chain.length ?? 0) - 1),+ };};const [connections, setConnections] = useState<Partial<Record<RuntimeBackendId, BackendConnectionState>>>({});+ const [connectionConfirmed, setConnectionConfirmed] = useState<Partial<Record<RuntimeBackendId, { epoch: number; token: number }>>>({});const [connectionPending, setConnectionPending] = useState<Partial<Record<RuntimeBackendId, boolean>>>({});const [connectionErrors, setConnectionErrors] = useState<Partial<Record<RuntimeBackendId, string>>>({});const [pendingWrites, setPendingWrites] = useState<Partial<Record<RuntimeBackendId, boolean>>>({});@@ -157,6 +262,20 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on// What the latest settled write still owes this screen, held until someone who can// answer for it reports it — see EnableReceipt.const enableReceipt = useRef<Partial<Record<RuntimeBackendId, EnableReceipt>>>({});+ const confirmedConnectionMode = (backend: RuntimeBackendId) => {+ const confirmed = connectionConfirmed[backend];+ if (!active || !activeRef.current || connections[backend]?.ok !== true || connectionPending[backend]+ || confirmed?.epoch !== activation.current || confirmed.token !== connectionTokens.current[backend]) return undefined;+ return connections[backend]?.supply_mode ?? (!modelHubEnabled ? 'direct' : undefined);+ };+ const confirmedSupplyMode = (backend: RuntimeBackendId) => sharedRouteReady()+ ? routeRead.supplies.find((row) => row.backend === backend)?.mode+ : undefined;+ const installMode = (backend: RuntimeBackendId) => {+ const connection = confirmedConnectionMode(backend);+ const supply = confirmedSupplyMode(backend);+ return connection && supply && connection !== supply ? undefined : connection;+ };// One provider modal/reconciliation at a time; Configure and navigation stay// disabled until persisted fields and the subsequent detection reach agents.const [syncing, setSyncing] = useState(false);@@ -198,6 +317,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onif (!owns()) return;if (!result.ok) throw new Error(result.message || t('onboarding.connection.readFailed'));setConnections((current) => ({ ...current, [name]: result }));+ setConnectionConfirmed((current) => ({ ...current, [name]: { epoch, token } }));setAgents((current) => ({ ...current, [name]: { ...current[name], enabled: result.enabled } }));// Spending the verdict takes all three: this read still owns the screen, the// caller is an operation that actually answers for it, and the verdict in hand@@ -205,7 +325,10 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on// meanwhile is still owed to whoever reads next.const retire = acknowledge && owed && enableReceipt.current[name] === owed;if (retire) delete enableReceipt.current[name];- setConnectionErrors((current) => ({ ...current, [name]: retire ? '' : owed?.message || '' }));+ setConnectionErrors((current) => ({+ ...current,+ [name]: retire ? '' : owed?.message || '',+ }));} catch (error) {if (!owns()) return;setConnections((current) => ({ ...current, [name]: undefined }));@@ -217,10 +340,9 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onif (connectionTokens.current[name] === token) setConnectionPending((current) => ({ ...current, [name]: false }));}}, [api, t]);- const onRoutesSaved = async (saved: SetupRouteFocus) => {- await agentReads?.refresh();- await refreshConnection(saved.backend);- };+ const refreshRouteOwnership = (name: RuntimeBackendId) => Promise.all([+ readCardRoutes(name), refreshConnection(name),+ ]).then(([routeReady]) => routeReady);// Being read again is one event with one owner, however it arrives: the shell// activates this screen, or the route surface it sits on comes back. In the shell both// happen in the same commit, so two effects would mean two refreshes — and neither of@@ -377,6 +499,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on// failed, and it does not bury what the write had to say.try {await agentReads?.refresh();+ if (modelHubEnabled && canEditSetupRoute) await readCardRoutes();} catch (error) {if (enableIntent.current[backend] !== intent) return;setConnectionErrors((current) => ({ ...current, [backend]: current[backend] || String(error) }));@@ -438,8 +561,11 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on}};- const installAgent = async (name: string) => {+ const installAgent = async (name: string, promisedEnable = false) => {if (pendingInstalls.current.has(name) || (isPage && isAnyInstalling)) return;+ const backend = name as RuntimeBackendId;+ const installEnableIntent = enableIntent.current[backend];+ const hubAtClick = promisedEnable && installMode(backend) === 'hub';pendingInstalls.current.add(name);setInstallingAgents((prev) => ({ ...prev, [name]: true }));@@ -463,6 +589,16 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on}));}await detect(name, installedPath || agents[name]?.cli_path || name);+ if (!isPage && hubAtClick && !agents[name]?.enabled+ && enableIntent.current[backend] === installEnableIntent) {+ try {+ const current = await api.getBackendConnection(backend);+ if (current.ok && current.supply_mode === 'hub' && !current.enabled+ && enableIntent.current[backend] === installEnableIntent) toggle(name, true);+ } catch {+ // The connection refresh below reports an unreadable post-install state.+ }+ }await agentReads?.refresh();}} catch (e) {@@ -503,25 +639,21 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onconst actionBusy = syncing || entering || isAnyInstalling || Object.values(pendingWrites).some(Boolean) || Object.values(refreshingAgents).some(Boolean);- // The recovery node is fresh JSX on every shell render, so the publication depends on- // whether one exists, never on its identity — an identity dependency would republish- // against itself forever.- const recoveryOpen = Boolean(completionRecovery);- useImperativeHandle(ref, () => ({ activate: () => { if (canContinue && !actionBusy && !recoveryOpen) void handlePrimaryAction(); } }));+ useImperativeHandle(ref, () => ({ activate: () => { if (canContinue && !actionBusy) void handlePrimaryAction(); } }));// A layout effect, so the shell's action label lands in the same commit as the state// it describes: a passive publish would leave one render where the screen already// shows a settled state while the shared button still carries the previous label.useLayoutEffect(() => {if (active) onActionChange?.({ labelKey: entering ? 'onboarding.connection.connecting' : 'onboarding.connection.enter',- disabled: !canContinue || actionBusy || recoveryOpen, busy: actionBusy, icon: entering ? 'spinner' : 'arrow-right' });- }, [active, onActionChange, entering, canContinue, actionBusy, recoveryOpen]);-- // What sits under the shared pair in the shell: the readiness caption, the OpenCode- // permission callout and the completion recovery. All three are ancillary to the- // action and all three grow — a permission error carries a full diagnostic, a- // recovery is a form. Kept inside the screen they push the anchor the two steps- // share; lifted out of flow they cover the very buttons they explain. So the shell- // reserves a slot after the pair and the active screen portals them into it.+ disabled: !canContinue || actionBusy, busy: actionBusy, icon: entering ? 'spinner' : 'arrow-right' });+ }, [active, onActionChange, entering, canContinue, actionBusy]);++ // What sits under the shared pair in the shell: the readiness caption and the+ // OpenCode permission callout. Both are ancillary to the action and both grow — a+ // permission error carries a full diagnostic. Kept inside the screen they push the+ // anchor the two steps share; lifted out of flow they cover the very buttons they+ // explain. So the shell reserves a slot after the pair and the active screen portals+ // them into it.const setupRoot = useRef<HTMLDivElement>(null);const [actionAside, setActionAside] = useState<HTMLElement | null>(null);useEffect(() => {@@ -529,19 +661,34 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on? setupRoot.current?.closest('.onboarding-step')?.querySelector<HTMLElement>('[data-setup-action-aside]') ?? null: null);}, [onActionChange]);- const hintInner = (<>- <p className="text-center text-xs text-muted">- {t(readyBackends.some((name) => connections[name]?.ready) ? 'onboarding.connection.entryReady' : canContinue ? 'onboarding.connection.entryStopped' : 'onboarding.connection.entryHint')}{' '}- {/* The whole-screen rescan, kept as part of the sentence that explains why a- card might not say what was expected rather than a control competing with- the action above it. */}+ // Only while the action is held. Once it lights up, the cards already say which+ // assistants are connected and the button says the rest; a caption repeating it is a+ // line of type under a settled screen. Held, it is the only place that says WHY the+ // button is grey — and the rescan goes with it, because the reason to rescan is a+ // CLI installed outside this window that the screen has not noticed yet.+ /* The whole-screen rescan: what answers 「I installed it in another window」. In the+ sentence rather than beside the action, so it reads as part of the explanation+ instead of a second control competing with the button. */+ const rescan = (<Button type="button" variant="link" size="xs" className="h-auto p-0 align-baseline text-xs"onClick={() => void detectAll()} disabled={isAnyInstalling || Object.values(detectingAgents).some(Boolean)}><RefreshCw size={12} />{t('agentDetection.rescan')}</Button>+ );+ const hintSentence = canContinue ? null : (+ /* The sentence is what the eye lines up with the action below it, so the+ sentence is what gets centred. The rescan rides in the flanking column+ beside it — inside one centred line it pulled the sentence off the+ action's axis by half its own width. */+ <p className="onboarding-setup-hint-line text-xs text-muted">+ <span>{t('onboarding.connection.entryHint')}</span>+ {rescan}</p>+ );+ const hintInner = (hintSentence || entryError) ? (<>+ {hintSentence}{entryError && <div role="alert" className="connection-error">{entryError} <Button variant="link" size="sm" disabled={entering} onClick={() => void handlePrimaryAction()}>{t('common.retry')}</Button></div>}- </>);+ </>) : null;// Hosted in one place so the order under the pair is the same every time, and so the// standalone host keeps the arrangement it already had.const permissionNode = <OpencodePermissionSetup cliReady={opencodeAgent?.status === 'ok'}@@ -554,19 +701,20 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on// nobody is reading, so what it carries has to answer to the same activity itself.const asideNode = onActionChange? (active && routeSurfaceActive && actionAside ? createPortal(<>- <div className="onboarding-setup-hint">{hintInner}</div>+ {hintInner && <div className="onboarding-setup-hint">{hintInner}</div>}{permissionNode}- {completionRecovery}</>, actionAside) : null): (<div className="onboarding-setup-footer"><Button type="button" variant="brand" className="group onboarding-action-w onboarding-primary-action" onClick={() => void handlePrimaryAction()}- disabled={!canContinue || syncing || entering || Boolean(completionRecovery)}>+ disabled={!canContinue || syncing || entering}>{t(entering ? 'onboarding.connection.connecting' : 'onboarding.connection.enter')}<ArrowRight size={16} className="motion-safe:transition-transform motion-safe:duration-180 motion-safe:group-hover:translate-x-1" /></Button>- {hintInner}- {onBack && <Button type="button" variant="ghost" className="onboarding-action-w onboarding-back-action" disabled={syncing || entering || Boolean(completionRecovery)} onClick={() => onBack({ agents })}><ArrowLeft size={14} />{t('common.back')}</Button>}+ {/* The standalone host has no shell slot and no screen after it, so it keeps the+ rescan reachable even once the action has lit up. */}+ {hintInner ?? <p className="text-center text-xs text-muted">{rescan}</p>}+ {onBack && <Button type="button" variant="ghost" className="onboarding-action-w onboarding-back-action" disabled={syncing || entering} onClick={() => onBack({ agents })}><ArrowLeft size={14} />{t('common.back')}</Button>}</div>);// Page mode keeps the existing settings shell — render the inner content only@@ -780,22 +928,38 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onconst result = installResults[name];const error = detectionErrors[name] ? { message: detectionErrors[name] }: result && !result.ok && result.message ? result : undefined;- const hubRoute = connections[name]?.supply_mode === 'hub'- || Boolean(canEditSetupRoute && modelHubEnabled && agent.status === 'ok');+ const connectionMode = confirmedConnectionMode(name);+ const supplyMode = confirmedSupplyMode(name);+ const ownershipConflict = !!connectionMode && !!supplyMode && connectionMode !== supplyMode;+ const mode = agent.status === 'missing' ? installMode(name)+ : ownershipConflict ? undefined+ : connectionMode ?? supplyMode;+ const hubRoute = mode === 'hub';+ const openRoute = () => {+ if (mode !== 'hub' || !routeTargetReady(name)) return;+ const supply = routeRead.supplies.find((row) => row.backend === name);+ const modelId = routeRead.models[name];+ if (supply?.mode === 'hub' && modelId) {+ setRouteSelection({ agent: supply, modelId,+ read: routeRead.chains[name] ? readyRegion(routeRead.chains[name]) : undefined });+ }+ };return <AssistantRow key={name} backend={name} status={agent.status || 'unknown'}installing={!!installingAgents[name]} detecting={!!detectingAgents[name]} error={error}- onInstall={() => void installAgent(name)} onDetect={() => void detect(name, agent.cli_path)}+ onInstall={() => void installAgent(name, mode === 'hub')} onDetect={() => void detect(name, agent.cli_path)}onConfigure={() => {+ if (!mode) return;if (hubRoute) {- if (canEditSetupRoute) { openSetupRoute(name); return; }+ if (canEditSetupRoute) { openRoute(); return; }navigate(MODEL_HUB_SETTINGS_PATH);return;}setProviderModal({ backend: name, method: 'oauth' });}}onAddKey={() => {+ if (!mode) return;if (hubRoute) {- if (canEditSetupRoute) { openSetupRoute(name); return; }+ if (canEditSetupRoute) { openRoute(); return; }navigate(MODEL_HUB_SETTINGS_PATH);return;}@@ -803,13 +967,21 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on}}connection={hubRoute? 'hub'- : !connectionErrors[name] && connections[name]?.ready+ : mode === 'direct' && !connectionErrors[name] && connections[name]?.ready? (connections[name]?.auth === 'subscription' ? 'subscription' : 'api_key'): undefined}+ hubManaged={hubRoute}+ enabled={agent.enabled}+ route={routeViewFor(name)}connectionPending={connectionPending[name]}connectionError={connectionErrors[name] || connections[name]?.message}onRefreshConnection={() => void refreshConnection(name, { acknowledge: true })}- configuringDisabled={syncing || pendingWrites[name] || !!refreshingAgents[name] || !!connectionPending[name]+ routeError={canEditSetupRoute && modelHubEnabled && routeFailureCurrent(name)+ ? t('settings.models.routeDialog.fail.reconcileRead')+ : ownershipConflict ? t('onboarding.setup.ownershipChanged') : undefined}+ onRetryRoute={() => void (ownershipConflict ? refreshRouteOwnership(name) : readCardRoutes(name))}+ configuringDisabled={!mode || syncing || pendingWrites[name] || !!refreshingAgents[name] || !!connectionPending[name]+ || (hubRoute && canEditSetupRoute && (!routeTargetReady(name) || supplyMode !== 'hub'))|| (hubRoute? agent.status !== 'ok': !agent.enabled || agent.status !== 'ok')}@@ -817,7 +989,8 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onlabel={t('onboarding.setup.enableNamed', { name: getBackendUiMeta(name).label })}onClick={() => toggle(name, !agent.enabled)} />}lifecycle={<BackendLifecycleChip name={name} enabled={agent.enabled} cliStatus={active ? agent.status || 'unknown' : 'unknown'}- readyLabel={t('onboarding.setup.installed')}+ readyLabel={t('onboarding.setup.enabled')}+ disabledLabel={t('onboarding.setup.notEnabled')}refreshKey={chipRefresh[name]}externallyBusy={!!refreshingAgents[name]}onVisual={(visual) => setVisuals((current) => (current[name] === visual ? current : { ...current, [name]: visual }))}@@ -847,32 +1020,37 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on</div></div>{!onActionChange && permissionNode}- {/* Wizard-only: the offer to take over API keys already on this machine.- Settings → Backends reaches the same migration through- BackendSupplyModeCard, with its broader scope intact. Self-hides when- there is nothing importable or the gateway isn't reachable — which is- why the slot around it is rendered either way: the stage keeps the- capsule's height while the read is still out, when it turns out there- is nothing to offer, and after the offer is refused, so none of the- three can move the action below it. */}- <div className="onboarding-import-slot">- {visited && modelHubEnabled === true && <ImportKeysNotice />}- </div></div>{providerDialog}- {canEditSetupRoute && flowState && setFlowState && onNavigate && agentReads && (- <DefaultRouteDialog- open={routeOpen}- onClose={() => { setRouteOpen(false); setRouteFocus(null); }}- flowState={flowState}- setFlowState={setFlowState}- onNavigate={onNavigate}- agentReads={agentReads}- focus={routeFocus}- onSaved={onRoutesSaved}+ {canEditSetupRoute && agentReads && (+ <RouteChainDialog selection={routeSelection} sources={routeRead.sources}+ onClose={() => {+ const backend = routeSelection?.agent.backend;+ setRouteSelection(null);+ if (backend && !committedRouteRefresh.current) void refreshRouteOwnership(backend);+ committedRouteRefresh.current = false;+ }}+ onCommitted={() => {+ committedRouteRefresh.current = true;+ setRouteReconciliation({ pending: true, failed: false });+ if (routeSelection) void refreshRouteOwnership(routeSelection.agent.backend)+ .then((ok) => setRouteReconciliation({ pending: false, failed: !ok }));+ }}+ commitReconciliation={{ ...routeReconciliation, retry: () => {+ setRouteReconciliation({ pending: true, failed: false });+ if (routeSelection) void refreshRouteOwnership(routeSelection.agent.backend)+ .then((ok) => setRouteReconciliation({ pending: false, failed: !ok }));+ } }}+ readAgents={async () => {+ const value = await agentReads.readValue();+ return { value, install: () => setRouteRead((current) => ({ ...current, supplies: value })) };+ }}+ readSources={async () => {+ const value = await modelsApi.listSources();+ return { value, install: () => setRouteRead((current) => ({ ...current, sources: value })) };+ }}/>)}- {!onActionChange && completionRecovery}{asideNode}</div>);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex cf2d3f5a6..e0fbaf873 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -555,7 +555,7 @@"oauthRemoved": "Credentials removed.","oauthRemoveFailed": "Could not remove credentials: {{detail}}","oauthRemovePartial": "Credentials cleared from Avibe, but the backend CLI logout reported a problem: {{detail}}. The CLI's own files may still be present.",- "nativeAuthHubOwned": "Authentication is managed by Model Hub.",+ "nativeAuthHubOwned": "Authentication is managed by Model Hub","openModelHub": "Open Model Hub","oauthFlowLockedToast": "OAuth login is in progress — finish or cancel it before switching auth mode.","testConnectionTitle": "Test connection",@@ -1394,19 +1394,19 @@"cancel": "Cancel","save": "Save","saving": "Saving route chain…",- "refreshing": "Route chain saved. Refreshing the model surface…",+ "refreshing": "Route chain saved. Refreshing…","fail": {"read": "The route chain could not be read","save": "The route chain was not saved","unconfirmed": "The save outcome is not confirmed",- "reconcileRead": "The current model surface could not be read"+ "reconcileRead": "The route could not be read right now"},"retry": "Retry","empty": "This model follows default routing, but no eligible provider can route it.","impact": {"title": "The route chain was saved","detail": "These are the items this save actually removed or interrupted.",- "refreshFail": "The route chain was saved, but the model surface could not be refreshed.",+ "refreshFail": "The route chain was saved, but the display could not be refreshed.","done": "Done"},"hint": "This model has a saved, fixed route. Default routing changes do not overwrite it."@@ -1640,7 +1640,7 @@"helper": "Credentials supplied by a command cannot be imported. Save them in a supported static configuration or add the source manually in Model Hub.","token": "This login token or authentication format cannot be imported. Add a source in Model Hub or sign in again for that source.","headers": "Custom credential headers cannot be imported. Use a supported authentication method or add the source manually in Model Hub.",- "transport": "Model Hub cannot send this endpoint's saved authentication in the same way. The original files are unchanged. Use an authentication method supported by both the provider and Model Hub; changing file permissions will not fix this.",+ "transport": "Model Hub can't use this authentication method yet, so it was skipped and the file is unchanged. You can add the provider again with a standard API key.","fallback": "This credential cannot be imported. Use the existing Add flow in Model Hub to add this source manually."},"applying": "Migrating…",@@ -1884,18 +1884,6 @@"refreshed": "Updated","unresolved": "Still not working","failed": "Couldn't do that, please retry"- },- "importNotice": {- "found_one": "Found {{count}} API key to import into Model Hub",- "found_other": "Found {{count}} API keys to import into Model Hub",- "review": "Review and migrate",- "help": "What is Model Hub?",- "helpBody": "Model Hub manages the credentials you select and supplies them to your AI assistants.",- "dismiss": "Dismiss import notice",- "imported_one": "Migrated {{count}} API key into Model Hub",- "imported_other": "Migrated {{count}} API keys into Model Hub",- "importedRemaining_one": "Migrated {{imported}} · {{count}} API key still available",- "importedRemaining_other": "Migrated {{imported}} · {{count}} API keys still available"}}},@@ -4732,7 +4720,7 @@"onboarding": {"welcome": {"getStarted": "Get started",- "title": "Different strengths. One team.",+ "title": "Different capabilities. One team.","subtitle": "Bring Claude Code, Codex, and OpenCode together","detecting": "Checking…","detectionFailed": "Could not check your assistants. Try again."@@ -4740,7 +4728,7 @@"details": "View details","story": {"label": "Assistants working together",- "description": "Claude Code plans the work, Codex builds it, OpenCode tests it, and Claude Code summarizes the result.",+ "description": "Claude Code plans the work, Codex builds it, OpenCode tests it, and Claude Code summarizes the result","caption": "Plan · Build · Test · Deliver","returnCaption": "Tests passed · back to the PM","claude": {@@ -4777,7 +4765,6 @@"title": "Choose your AI assistants","subtitle": "Enable an assistant, confirm its default model, and start working","install": "Install",- "installed": "Installed","notInstalled": "Not installed","installFailed": "Installation failed","enabled": "Enabled",@@ -4787,7 +4774,7 @@"subscriptionConnected": "Subscription connected","api_keyConnected": "API Key connected","claudeGuide": "Sign in with Claude or enter an API key",- "codexGuide": "Sign in with ChatGPT or use OPENAI_API_KEY",+ "codexGuide": "Sign in with ChatGPT or use an OpenAI API key","opencodeGuide": "Choose either way to connect","installFirstNamed": "Install {{name}} first","subscriptionConnectedHint": "Subscription saved. Enter the workspace to use it.",@@ -4796,18 +4783,17 @@"configureRoute": "Configure model route","defaultModel": "Default model","defaultModelNamed": "Model route for {{name}}, review and reorder",- "noteEnabled": "Enabled. Ready to work once its model route is ready."- },- "route": {- "title": "Default model route",- "description": "Set a shared model order for the assistants shown below. Each tries its own model subset in that order; other routes stay unchanged.",- "preferred": "Preferred",- "backup": "Backup {{index}}",- "singleNote": "This route has one model. Add a source, then select a backup model.",- "addSource": "Add model source",- "done": "Done",- "moveUpNamed": "Move {{name}} up",- "moveDownNamed": "Move {{name}} down"+ "noteEnabled": "Uses a Model Hub route",+ "notEnabled": "Not enabled",+ "installAndEnable": "Install and enable",+ "installedNotEnabled": "Installed, not enabled",+ "noteNotEnabled": "Enable to use your models",+ "noteNotInstalled": "Install {{name}} to use your models",+ "defaultModelWithBackups_one": "Default model · 1 backup",+ "defaultModelWithBackups_other": "Default model · {{count}} backups",+ "noteNoModels": "No usable model yet",+ "ownershipChanged": "Connection changed. Refresh to continue",+ "noteModelUnset": "No model set yet; you can set one later in Model Hub"},"connection": {"method": "Connection method",@@ -4821,14 +4807,14 @@"codexAccount": "Sign in with your ChatGPT account","claudeHint": "Approve access in your browser, then paste the authorization code here","deviceHint": "Get a device code, sign in and authorize in your browser. The connection completes automatically.",- "codeHint": "Paste the full code, including everything after #.",- "keyHint": "Use the API Key supplied by your provider.",- "tokenHint": "For relay services that require a Bearer Token.",+ "codeHint": "Paste the full code, including everything after #",+ "keyHint": "Use the API Key supplied by your provider",+ "tokenHint": "For relay services that require a Bearer Token","baseUrl": "Base URL (optional)","providerDefault": "Use provider default URL","claudeUrlHint": "Leave empty for Anthropic. The URL does not change the credential type.",- "urlHint": "Leave empty to use the provider’s default URL.",- "invalidUrl": "Enter a valid http:// or https:// URL.",+ "urlHint": "Leave empty to use the provider’s default URL",+ "invalidUrl": "Enter a valid http:// or https:// URL","saveConnect": "Save and connect","finishConnect": "Complete connection","connecting": "Connecting…",@@ -4859,39 +4845,35 @@"codexKeyIntro": "Connect OpenAI or a compatible provider to Codex","pickKey": "Choose an API Key provider","pickSubscription": "Choose a subscription provider to connect",- "catalogHint": "Providers come from your installed OpenCode runtime.",+ "catalogHint": "Providers come from your installed OpenCode runtime","noProviders": "No matching providers. Try an API Key or refresh the catalog.","changeProvider": "Change","enter": "Enter workspace","entryHint": "Connect any one subscription or API Key to enter the workspace",- "entryReady": "Connected. You can start working.",- "entryStopped": "Connection saved. Enter workspace to start the service.","entryFailed": "A ready assistant could not be confirmed. Refresh and try again.","addSubscription": "Add subscription / sign in","addKey": "Add API Key","moreProviders": "More providers","refresh": "Refresh connection",- "enableFirst": "Enable this assistant to connect it.",+ "enableFirst": "Enable this assistant to connect it","checkSettings": "Review settings","manualCode": "Authorization code","manualCodePlaceholder": "Paste the code from your browser",- "manualCodeHint": "Complete authorization in your browser, then paste the code here.",+ "manualCodeHint": "Complete authorization in your browser, then paste the code here","copyDevice": "1 Copy the device code","openDevice": "2 Open the sign-in page and enter the code","openChatGPT": "Open ChatGPT sign-in","openProvider": "Open authorization page",- "codexCompleteIntro": "Sign in through your browser. Codex will connect automatically",+ "codexCompleteIntro": "Sign in through your browser. Codex will connect automatically.","providerIntro": "Connect {{name}} to OpenCode","providerKeyIntro": "Save an API Key for {{name}} in OpenCode","providerConfigured": "Connected","providerCredentialHint": "This credential is only used for {{name}} in OpenCode","providerDescription": "Provider · For OpenCode",- "modelUnavailable": "No available Agent has a usable model route. Check your connections and try again.",+ "modelUnavailable": "No assistant can reach a model yet. Check your connections and try again.","credentialType": "Credential type","apiKeyLabel": "API Key",- "authTokenLabel": "Auth Token",- "platformRepair": "Repair saved messaging configuration",- "platformRepairHint": "Your saved {{platform}} configuration is incomplete. Repair its required credentials before entering the workspace."+ "authTokenLabel": "Auth Token"},"brand": {"name": "Avibe",@@ -4902,41 +4884,42 @@"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.",+ "gatewayTagline": "Connect once, share with every assistant","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}}",+ "cardImported": "In Model Hub",+ "cardNotAdded": "Not added yet","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",+ "summaryNameSeparator": ", ","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",+ "actionImport_one": "Migrate {{count}} key and continue",+ "actionImport_other": "Migrate {{count}} keys 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…",- "continueHint": "You can connect a provider later.",+ "continueHint": "You can connect a provider later","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.",+ "addDescriptionMore": "Review detected configurations and confirm migration without retyping","addMethodsLabel": "Add method","addMethodDetected": "Detected","addMethodSubscription": "Subscription",@@ -4944,7 +4927,6 @@"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",@@ -4964,12 +4946,10 @@},"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.",+ "description": "After migration, these assistants connect through Model Hub. The matching keys are removed from their original config files; other settings stay as they are.","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.",+ "scopeNote": "Only API keys can be migrated here. Handle subscription sign-ins and anything else 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…",@@ -4986,7 +4966,7 @@},"flow": {"backToIntro": "Back to introduction",- "backToProviders": "Back to models",+ "backToProviders": "Back to providers","gatewayRequired": "Setup requires Model Hub to be enabled. Your saved configuration is unchanged. Restore it through your existing configuration controls, then retry.","completionUnconfirmed": "Setup completion could not be confirmed. Try again."}diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 53178ad67..6c5cc98bf 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -555,7 +555,7 @@"oauthRemoved": "已移除凭据。","oauthRemoveFailed": "移除凭据失败:{{detail}}","oauthRemovePartial": "已清除 Avibe 内的凭据,但 CLI logout 返回错误:{{detail}}。CLI 自己的凭据文件可能仍在磁盘上。",- "nativeAuthHubOwned": "认证由模型网关管理。",+ "nativeAuthHubOwned": "认证由模型网关管理","openModelHub": "打开模型网关","oauthFlowLockedToast": "OAuth 登录进行中——请先完成或取消,再切换验证方式。","testConnectionTitle": "测试连通性",@@ -1394,19 +1394,19 @@"cancel": "取消","save": "保存","saving": "正在保存路由…",- "refreshing": "路由已保存,正在刷新模型页面…",+ "refreshing": "路由已保存,正在刷新…","fail": {"read": "路由暂时不可用","save": "路由没有保存","unconfirmed": "保存结果还没确认",- "reconcileRead": "当前模型页面暂时不可用"+ "reconcileRead": "暂时无法读取路由"},"retry": "重试","empty": "此模型跟随默认路由,但目前没有符合条件的供应商。","impact": {"title": "路由已保存","detail": "以下是这次保存实际移除或中断的项目。",- "refreshFail": "路由已保存,但模型页面暂时无法刷新。",+ "refreshFail": "路由已保存,但暂时无法刷新显示。","done": "完成"},"hint": "此模型已保存固定路由,默认路由的调整不会覆盖它。"@@ -1640,7 +1640,7 @@"helper": "无法导入由命令提供的凭据。请将凭据保存为受支持的静态配置,或在模型网关中手动添加供应商。","token": "此登录令牌或认证格式暂不支持导入。请在模型网关中添加供应商,或为该供应商重新登录。","headers": "暂不支持导入自定义认证请求头。请使用受支持的认证方式,或在模型网关中手动添加供应商。",- "transport": "模型网关目前无法按此接口原有的方式发送认证,原配置文件未改动。请使用供应商和模型网关都支持的认证方式;修改文件权限不能解决此问题。",+ "transport": "模型网关暂不支持这里的认证方式,已跳过,原文件未改动。可以改用供应商的标准 API Key 重新添加。","fallback": "暂时无法导入此认证,请使用模型网关现有的添加流程手动添加供应商。"},"applying": "迁移中…",@@ -1884,18 +1884,6 @@"refreshed": "已更新","unresolved": "仍然不可用","failed": "没能处理,请重试"- },- "importNotice": {- "found_one": "发现 {{count}} 个可导入模型网关的 API Key",- "found_other": "发现 {{count}} 个可导入模型网关的 API Key",- "review": "查看并迁移",- "help": "什么是模型网关?",- "helpBody": "模型网关管理你选择的认证信息,并为 AI 助手提供统一的模型入口。",- "dismiss": "关闭导入提示",- "imported_one": "已迁移 {{count}} 个 API Key 到模型网关",- "imported_other": "已迁移 {{count}} 个 API Key 到模型网关",- "importedRemaining_one": "已迁移 {{imported}} 个 · 还有 {{count}} 个可迁移",- "importedRemaining_other": "已迁移 {{imported}} 个 · 还有 {{count}} 个可迁移"}}},@@ -4735,12 +4723,12 @@"title": "各有所长,接力完成","subtitle": "让 Claude Code、Codex、OpenCode 一起工作","detecting": "检测中…",- "detectionFailed": "未能检测助手,请重试。"+ "detectionFailed": "未能检测助手,请重试"},"details": "查看详情","story": {"label": "助手接力协作",- "description": "Claude Code 规划任务,Codex 编写代码,OpenCode 执行测试,最后由 Claude Code 汇总交付。",+ "description": "Claude Code 规划任务,Codex 编写代码,OpenCode 执行测试,最后由 Claude Code 汇总交付","caption": "规划 · 开发 · 测试 · 交付","returnCaption": "测试通过,回传 PM","claude": {@@ -4765,7 +4753,7 @@},"access": {"label": "随时随地安排工作",- "description": "6个工作入口,随时随地安排工作",+ "description": "6 个工作入口,随时随地安排工作","avibe": "Avibe App","slack": "Slack","discord": "Discord",@@ -4777,17 +4765,16 @@"title": "选择你的 AI 助手","subtitle": "启用助手,确认默认模型,即可开始工作","install": "安装",- "installed": "已安装","notInstalled": "未安装","installFailed": "安装失败",- "enabled": "启用",+ "enabled": "已启用","enableNamed": "启用 {{name}}","subscription": "订阅","api_key": "API Key","subscriptionConnected": "订阅已连接","api_keyConnected": "API Key 已连接","claudeGuide": "通过 Claude 登录或填入 API Key",- "codexGuide": "通过 ChatGPT 登录或 OPENAI_API_KEY",+ "codexGuide": "通过 ChatGPT 登录,或使用 OpenAI API Key","opencodeGuide": "选择一种方式连接即可","installFirstNamed": "先安装 {{name}}","subscriptionConnectedHint": "订阅已保存,进入工作台即可使用",@@ -4796,24 +4783,23 @@"configureRoute": "配置模型路由","defaultModel": "默认模型","defaultModelNamed": "{{name}} 的模型路由,查看并调整顺序",- "noteEnabled": "已启用,模型路由就绪后即可使用"- },- "route": {- "title": "默认模型路由",- "description": "为下列助手调整共享模型顺序。各助手按自己的模型列表依次尝试;其他路由保持不变。",- "preferred": "首选",- "backup": "备用 {{index}}",- "singleNote": "此路由只有一个模型。可添加来源,再选择备用模型。",- "addSource": "添加模型来源",- "done": "完成",- "moveUpNamed": "上移 {{name}}",- "moveDownNamed": "下移 {{name}}"+ "noteEnabled": "使用模型网关路由",+ "notEnabled": "未启用",+ "installAndEnable": "安装并启用",+ "installedNotEnabled": "已安装,未启用",+ "noteNotEnabled": "启用后即可使用已添加的模型",+ "noteNotInstalled": "安装 {{name}},使用已添加的模型",+ "defaultModelWithBackups_one": "默认模型 · 另有 {{count}} 个备选",+ "defaultModelWithBackups_other": "默认模型 · 另有 {{count}} 个备选",+ "noteNoModels": "还没有可用的模型",+ "ownershipChanged": "连接状态已变化,请刷新后继续",+ "noteModelUnset": "尚未设置模型,可稍后在模型网关中设置"},"connection": {"method": "连接方式","subscription": "订阅","claudeLogin": "Claude 账号登录",- "claudeCredentials": "Claude Code 凭据",+ "claudeCredentials": "API 凭据","claudeSignIn": "使用 Claude 登录","codexSignIn": "使用 ChatGPT 登录","openaiKey": "OpenAI API Key",@@ -4822,12 +4808,12 @@"claudeHint": "打开授权页面并批准访问,再将返回的授权码粘贴到这里","deviceHint": "获取设备码,在浏览器中登录并授权,完成后自动连接","codeHint": "请完整粘贴,包含 # 后的内容",- "keyHint": "使用服务商提供的 API Key",+ "keyHint": "使用供应商提供的 API Key","tokenHint": "适用于要求 Bearer Token 的中转服务","baseUrl": "Base URL(可选)",- "providerDefault": "使用服务商默认地址",+ "providerDefault": "使用供应商默认地址","claudeUrlHint": "留空使用 Anthropic 默认地址;地址不改变凭据类型",- "urlHint": "留空使用服务商默认地址",+ "urlHint": "留空使用供应商默认地址","invalidUrl": "请输入有效的 http:// 或 https:// 地址","saveConnect": "保存并连接","finishConnect": "完成连接",@@ -4845,37 +4831,35 @@"applyFailed": "凭据已保存,但运行时应用失败,请重试保存","applyPending": "运行时尚未确认生效,请刷新连接状态","unconfirmed": "无法确认当前生效的连接,请重试",- "uncertain": "凭据可能保存在系统钥匙串,暂时无法确认其生效状态。可以在此登录或保存密钥",+ "uncertain": "凭据可能保存在系统钥匙串,暂时无法确认其生效状态。可以在此登录或保存密钥。","partial": "已保存,但有警告,请检查连接状态","dialogTitle": "连接 {{name}}",- "claudeDialogIntro": "Claude Code 可以使用 Anthropic 订阅,也可以使用 API Key,在下方选择一种。",- "codexDialogIntro": "Codex 可以使用 ChatGPT 订阅,也可以使用 OpenAI API Key,在下方选择一种。",- "opencodeDialogIntro": "OpenCode 支持多家服务商,先选择一家,再登录或保存它的 API Key。",+ "claudeDialogIntro": "Claude Code 可以使用 Anthropic 订阅,也可以使用 API Key,在下方选择一种",+ "codexDialogIntro": "Codex 可以使用 ChatGPT 订阅,也可以使用 OpenAI API Key,在下方选择一种",+ "opencodeDialogIntro": "OpenCode 支持多家供应商,先选择一家,再登录或保存它的 API Key","removeConfirm": "移除此已保存凭据?","claudeIntro": "使用 Anthropic 账号授权 Claude Code","claudeCompleteIntro": "在浏览器中批准访问,然后粘贴返回的授权码",- "claudeKeyIntro": "为 Claude Code 连接 Anthropic 或兼容服务商",+ "claudeKeyIntro": "为 Claude Code 连接 Anthropic 或兼容供应商","codexIntro": "使用 OpenAI 账号授权 Codex",- "codexKeyIntro": "为 Codex 连接 OpenAI 或兼容服务商",- "pickKey": "选择 API Key 服务商",- "pickSubscription": "选择要连接的订阅服务商",- "catalogHint": "服务商来自当前安装的 OpenCode",- "noProviders": "没有匹配的服务商,请尝试 API Key 或刷新列表",+ "codexKeyIntro": "为 Codex 连接 OpenAI 或兼容供应商",+ "pickKey": "选择 API Key 供应商",+ "pickSubscription": "选择要连接的订阅供应商",+ "catalogHint": "供应商来自当前安装的 OpenCode",+ "noProviders": "没有匹配的供应商,请尝试 API Key 或刷新列表","changeProvider": "更换","enter": "进入工作台","entryHint": "添加任意一个订阅或 API Key,即可进入工作台",- "entryReady": "已连接,可以开始工作",- "entryStopped": "连接已保存,进入工作台即可启动服务","entryFailed": "无法确认可用助手,请刷新后重试","addSubscription": "添加订阅 / 登录","addKey": "添加 API Key",- "moreProviders": "更多服务商",+ "moreProviders": "更多供应商","refresh": "刷新连接","enableFirst": "请先启用此助手以连接","checkSettings": "检查设置","manualCode": "授权码","manualCodePlaceholder": "粘贴浏览器显示的授权码",- "manualCodeHint": "在浏览器中完成授权后,将授权码粘贴到这里。",+ "manualCodeHint": "在浏览器中完成授权后,将授权码粘贴到这里","copyDevice": "1 复制设备码","openDevice": "2 打开授权页并输入设备码","openChatGPT": "打开 ChatGPT 授权页",@@ -4884,59 +4868,58 @@"providerIntro": "将 {{name}} 连接到 OpenCode","providerKeyIntro": "在 OpenCode 中保存 {{name}} 的 API Key","providerConfigured": "已连接",- "providerCredentialHint": "此凭据只用于 OpenCode 中的 {{name}} 服务商",- "providerDescription": "服务商 · 用于 OpenCode",- "modelUnavailable": "没有可用 Agent 的模型路由。请检查连接后重试。",+ "providerCredentialHint": "此凭据只用于 OpenCode 中的 {{name}} 供应商",+ "providerDescription": "供应商 · 用于 OpenCode",+ "modelUnavailable": "还没有助手能用上模型,请检查连接后重试","credentialType": "凭据类型","apiKeyLabel": "API Key",- "authTokenLabel": "Auth Token",- "platformRepair": "修复已保存的消息配置",- "platformRepairHint": "已保存的 {{platform}} 配置不完整。请修复必填凭据后进入工作区。"+ "authTokenLabel": "Auth Token"},"brand": {"name": "Avibe","tagline": "Agent OS"},"providers": {- "title": "添加模型提供商",+ "title": "添加模型供应商","subtitle": "添加订阅或 API Key,由模型网关统一路由",- "stageLabel": "提供商接入模型网关,再统一路由到助手",+ "stageLabel": "供应商接入模型网关,再统一路由到助手","gatewayName": "模型网关",- "gatewayTagline": "模型一次接入,网关统一路由",+ "gatewayTagline": "一次接入,所有助手共用","gatewayInstalling": "正在安装模型网关…","gatewayStarting": "正在启动模型网关…","gatewayNotReady": "模型网关未就绪,请重试","cardKeyDetected": "检测到 API Key {{mask}}","cardKeyAdded": "API Key {{mask}}",+ "cardImported": "已接入网关",+ "cardNotAdded": "待添加","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}} 项并继续",+ "summaryNameSeparator": "、",+ "summaryNone": "未选择供应商",+ "summarySelected_one": "已选 {{count}} 个供应商:{{names}}",+ "summarySelected_other": "已选 {{count}} 个供应商:{{names}}",+ "summaryAdded_one": "已添加 {{count}} 个供应商:{{names}}",+ "summaryAdded_other": "已添加 {{count}} 个供应商:{{names}}",+ "summaryError": "连接未完成,请检查配置后重试",+ "actionImport_one": "迁移 {{count}} 个 Key 并继续",+ "actionImport_other": "迁移 {{count}} 个 Key 并继续","actionRetryImport_one": "查看 {{count}} 项迁移状态","actionRetryImport_other": "查看 {{count}} 项迁移状态","actionContinue": "继续,选择 AI 助手","actionAdd": "添加订阅或 API Key","actionConnecting": "正在连接…","actionChecking": "正在检查连接…",- "continueHint": "也可以稍后再连接提供商。",+ "continueHint": "也可以稍后再连接供应商","addTitle": "添加订阅或 API Key",- "addTitleMore": "添加更多模型提供商",- "addDescription": "添加一个来源即可开始,由模型网关统一路由。",- "addDescriptionMore": "查看检测到的配置,确认后迁移,无需重新填写。",+ "addTitleMore": "添加更多模型供应商",+ "addDescription": "添加一个来源即可开始,由模型网关统一路由",+ "addDescriptionMore": "查看检测到的配置,确认后迁移,无需重新填写","addMethodsLabel": "添加方式","addMethodDetected": "已检测到","addMethodSubscription": "订阅",@@ -4944,11 +4927,10 @@"addDetectedNote": "查看全部关联配置并确认后开始迁移。其他无关设置会保留。","addDetectedGroup": "其余已检测到的配置","addDetectedSelectNamed": "选择 {{name}} 的已有配置",- "addDetectedAdded": "已添加","addSignInNamed": "通过 {{name}} 登录",- "addSubscriptionNote": "前往服务商完成授权,无需在 Avibe 输入账号密码。",+ "addSubscriptionNote": "前往供应商完成授权,无需在 Avibe 输入账号密码","addKeyLabelNamed": "{{name}} API Key",- "addMoreProviders": "更多服务商",+ "addMoreProviders": "更多供应商","addFooterAddKey": "添加","addFooterAdd_one": "查看选中的 {{count}} 项","addFooterAdd_other": "查看选中的 {{count}} 项",@@ -4957,20 +4939,18 @@"addProgressSaving": "正在保存配置…","addProgressChecking": "正在检查模型连接…","addProgressWaitingAuth": "等待授权完成…",- "addErrorPreserved": "连接未完成,输入已保留,请重试。",+ "addErrorPreserved": "连接未完成,输入已保留,请重试","addErrorDetectedPreserved": "操作未确认完成,选择已保留。请先检查当前状态,再继续恢复。","gatewayUnsupported": "此设备无法安装模型网关。请重新检查可用性,或在受支持的环境中设置 Avibe。","gatewayEnvironmentHelp": "查看安装指南"},"import": {"title": "迁移到模型网关",- "description": "迁移后,CLI的认证信息将完全交由模型网关管理",- "review": "查看并迁移",- "helpBody": "模型网关统一管理认证和模型连接。迁移会清理已替代的原生认证,并将关联助手切换到模型网关;其他无关设置会保留。",+ "description": "迁移后,这些助手改用模型网关连接模型,原配置文件里对应的 Key 会被移除,其他设置不变。","action_one": "查看选中的 {{count}} 项","action_other": "查看选中的 {{count}} 项",- "scopeNote": "此入口仅处理完整的 API Key 组。涉及订阅登录或阻塞项的关联组不可在此接管,请前往设置检查。",- "outOfScope": "此凭据可以迁移,但不能在此入口迁移,请前往设置检查。",+ "scopeNote": "这里只迁移 API Key。订阅登录和无法迁移的配置,请到设置中处理。",+ "outOfScope": "此凭据可以迁移,但不能在此入口迁移,请前往设置检查","progress_one": "正在迁移 {{count}} 项配置…","progress_other": "正在迁移 {{count}} 项配置…","progressDetail": "正在迁移认证并更新关联助手的连接",@@ -4986,7 +4966,7 @@},"flow": {"backToIntro": "返回介绍",- "backToProviders": "返回模型",+ "backToProviders": "返回供应商","gatewayRequired": "设置流程需要启用模型网关。已有配置未改变,请通过现有配置管理恢复后重试。","completionUnconfirmed": "无法确认设置已完成,请重试"}diff --git a/ui/src/lib/modelHubMigrationDismiss.ts b/ui/src/lib/modelHubMigrationDismiss.tsindex 652b2afb2..ad8e76c09 100644--- a/ui/src/lib/modelHubMigrationDismiss.ts+++ b/ui/src/lib/modelHubMigrationDismiss.ts@@ -1,36 +1,41 @@-// Remembers which Model Hub migration configs the user dismissed, so the banner-// stays non-nagging. Stores the dismissed set of per-config identities (stable-// scan id + proposed action — the backend derives ids as content hashes,-// `migration.py` sha256[:16]). The banner stays hidden while the current-// importable set is a SUBSET of what was dismissed — so importing or removing one-// config from a dismissed batch does NOT re-nag — and resurfaces only when a-// genuinely new id/action appears. Mirrors the localStorage conventions used-// elsewhere (module-level key, best-effort try/catch, pure helpers).import type { MigrationItem } from '@/components/settings/models/types';const STORAGE_KEY = 'vibe-remote:model-hub-migration-dismissed';-const identity = (item: MigrationItem): string => `${item.id}:${item.proposed_action}`;-/** Record the current importable set as dismissed. */+const readDismissed = (): Set<string> => {+ try {+ return new Set<string>(JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]'));+ } catch {+ return new Set();+ }+};+export function writeMigrationDismissed(items: MigrationItem[]): void {+ if (items.length === 0) return;+ try {+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify([...new Set([...readDismissed(), ...items.map(identity)])].sort()));+ } catch {+ // Setup remains usable when storage is unavailable.+ }+}++export function clearMigrationDismissed(items: MigrationItem[]): void {+ if (items.length === 0) return;try {- const ids = [...new Set(items.map(identity))].sort();- window.localStorage.setItem(STORAGE_KEY, JSON.stringify(ids));+ const dismissed = readDismissed();+ for (const item of items) dismissed.delete(identity(item));+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify([...dismissed].sort()));} catch {- // Best-effort persistence only (private mode / SSR / blocked storage).+ // Explicit selection still applies to the current setup visit.}}-/** True when every current importable config was already dismissed (subset of the- * dismissed set) — i.e. nothing genuinely new to surface. */export function isMigrationDismissed(items: MigrationItem[]): boolean {if (items.length === 0) return false;try {- const raw = window.localStorage.getItem(STORAGE_KEY);- if (!raw) return false;- const dismissed = new Set<string>(JSON.parse(raw));- return items.every((i) => dismissed.has(identity(i)));+ const dismissed = readDismissed();+ return items.every((item) => dismissed.has(identity(item)));} catch {return false;}diff --git a/vibe/api.py b/vibe/api.pyindex 778bf8f55..9e57b46ae 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1069,11 +1069,6 @@ def _platforms_requiring_runtime_credential_validation(previous_enabled = set(base_config.platforms.enabled) if base_config is not None else set()platforms = enabled - previous_enabled if "platforms" in payload or "platform" in payload else set()- # Finishing setup promotes the saved config to a runnable runtime config, so- # every enabled adapter must be bootable at that boundary.- if payload.get("setup_completed") is True:- platforms.update(enabled)-# If a save edits credential fields for an already-enabled platform, reject# partial clears or mismatched edits before they are persisted.for platform in enabled: