Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(setup): finish the assistants route editor and C4 entry (#2116)

Maxa4ee4d1f0aea
diff --git a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts b/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts
index 711d26c2e..26ea715d7 100644
--- a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts
+++ b/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts
@@ -4,13 +4,21 @@ import { ORIGIN, serveProduct } from './support';
// Exercise the actual App/AuthGuard/Settings overlay/Wizard boundary. All
// 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.
for (const width of [1200, 390]) {
- test(`Hub takeover returns to the same setup step and permits completion at ${width}px`, async ({ page }, info) => {
+ test(`Hub owns assistant authentication and its take-over completes inside setup at ${width}px`, async ({ page }, info) => {
await page.setViewportSize({ width, height: 844 });
const denied = await serveProduct(page);
const nativeRequests: string[] = [];
const writes: string[] = [];
const applied: string[][] = [];
+ const configWrites: unknown[] = [];
const observedReady: boolean[] = [];
const pageErrors: string[] = [];
page.on('pageerror', (error) => pageErrors.push(error.message));
@@ -39,10 +47,17 @@ for (const width of [1200, 390]) {
agent: { default_cwd: '/fixture/work' },
model_hub: { enabled: true, runtime_default_applied: true },
});
+ // The gate joins the route to the named Agent it would enter on, so a taken-over
+ // credential is only half the answer: the backend also has to say which model this
+ // name resolves to. That row is what the server writes when the take-over lands,
+ // and without it this machine has a source it cannot run a turn with.
const supply = () => ({
backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed',
sources: { order: migrated ? [source.id] : [], eligibility: [] },
- routes: {}, builtin_models: [], catalog_models: [], named_agents: [], menu: null,
+ routes: {}, builtin_models: [], catalog_models: [], menu: null,
+ named_agents: migrated
+ ? [{ name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'ok', route_reason: null }]
+ : [],
model_supply: [], supply_status: migrated ? 'ok' : 'unavailable',
});
const items = () => migrated ? [] : [{
@@ -64,6 +79,7 @@ for (const width of [1200, 390]) {
if (path === '/api/config') {
if (request.method() === 'POST') {
const body = request.postDataJSON();
+ configWrites.push(body);
if (body.setup_completed === true) completed = true;
}
return answer(config());
@@ -123,15 +139,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);
- await claude.getByRole('button', { name: 'Open Model Hub', exact: true }).click();
- await expect(page).toHaveURL(/\/settings\/models$/);
- await page.getByRole('button', { name: 'Migrate configuration', exact: true }).click();
+
+ // 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 expect(migration).toBeVisible();
await migration.getByRole('button', { name: 'Start migration', exact: true }).click();
@@ -139,13 +164,18 @@ for (const width of [1200, 390]) {
await expect(migration).toHaveCount(0);
await page.screenshot({ path: info.outputPath(`hub-migrated-${width}.png`) });
- // Actual browser history closes both the desktop sheet and mobile surface.
- await page.goBack();
- await expect(page).toHaveURL(/\/setup$/);
+ // The step was never unmounted, so the same node is still the one being read.
await expect(page.locator('.onboarding-assistants')).toBeVisible();
expect(await wizard!.evaluate((node) => node.isConnected)).toBe(true);
+
+ // 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();
await expect(enter).toBeEnabled();
- await expect(page.getByRole('button', { name: 'Review and migrate', exact: true })).toHaveCount(0);
+ 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();
@@ -154,9 +184,16 @@ for (const width of [1200, 390]) {
expect(pageErrors).toEqual([]);
expect(nativeRequests).toEqual([]);
expect(writes.filter((write) => !write.endsWith('/api/models/migration/scan'))).toEqual([
+ 'POST /api/config',
'POST /api/models/migration/apply',
'POST /api/config',
]);
+ // The two config writes are not the same write. The first is the provider screen's
+ // bootstrap seed — an empty patch whose only effect is a config file the controller
+ // can load — and the second is the completion itself. Reading their payloads is what
+ // keeps this an exact account rather than a count: the take-over writes the Hub's
+ // sources and nothing else, and no screen slipped a preference in along the way.
+ expect(configWrites).toEqual([{}, { setup_completed: true }]);
// Initial/return flow must never need a running backend. App-shell reads
// after completion are not part of this test's connection contract.
expect(denied.filter((request) => /\/backend\/.*\/auth/.test(request))).toEqual([]);
diff --git a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts
new file mode 100644
index 000000000..86e10e585
--- /dev/null
+++ b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts
@@ -0,0 +1,84 @@
+import { expect, test } from '@playwright/test';
+import { ORIGIN, serveProduct } from './support';
+import { readFileSync } from 'node:fs';
+const en=JSON.parse(readFileSync(new URL('../../src/i18n/en.json', import.meta.url),'utf8'));
+
+for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] as const) {
+ test(`normal setup route Save entry reload ${width} ${chosen}`, async ({page},info) => {
+ await page.setViewportSize({width,height:844});
+ const denied=await serveProduct(page);
+ let completed=false;
+ let defaultName='claude';
+ const hops=[{source_id:'src_fixture',model_id:'gpt-5'},{source_id:'src_fixture',model_id:'gpt-4.1'}];
+ type Write={setup_completed?:boolean,name?:string,hops?:typeof hops,manual_override?:{hops:typeof hops}};
+ const writes: Array<{path:string,body:Write|null}>=[];
+ const errors:string[]=[]; page.on('pageerror', e=>errors.push(e.message));
+ const 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 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'));
+ await page.route(`${ORIGIN}/api/**`,async route=>{
+ const req=route.request(),path=new URL(req.url()).pathname;
+ const answer=(json:unknown)=>route.fulfill({json});
+ const body:Write|null=req.method()==='GET'?null:req.postDataJSON() as Write;
+ if(req.method()!=='GET') writes.push({path,body});
+ if(path==='/api/config'){if(body?.setup_completed===true)completed=true;return answer(config());}
+ if(path==='/api/session')return answer({remote:false,instance_kind:'personal'});
+ if(path==='/api/version')return answer({current:'1.0.0',latest:'1.0.0',has_update:false,error:null});
+ if(path==='/api/agents/default'){
+ if(typeof body?.name==='string') defaultName=body.name;
+ return answer({ok:true,default_agent_name:defaultName,agent:agent(defaultName)});
+ }
+ if(path==='/api/agents')return answer({ok:true,default_agent_name:defaultName,agents:[agent('claude'),agent('codex')]});
+ if(/^\/api\/agents\/(claude|codex)$/.test(path))return answer({ok:true,agent:agent(path.split('/').at(-1)!),default_agent_name:defaultName});
+ if(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)\/chain/.test(path)){
+ const b=path.split('/')[4];
+ if(req.method()==='PUT'){saved[b]=body?.hops??[];return answer({ok:true,chain:chain(b)});}
+ if(path.endsWith('/preview'))return answer({ok:true,chain:chain(b,body?.manual_override?.hops??[])});
+ return answer({ok:true,chain:chain(b)});
+ }
+ if(/\/api\/backend\/[^/]+\/connection$/.test(path)){
+ const b=path.split('/')[3],ready=!!saved[b]?.length;
+ return answer({ok:true,backend:b,enabled:b!=='opencode',installed:true,supply_mode:'hub',auth:'api_key',application:'applied',ready,entry_eligible:ready});
+ }
+ if(path==='/api/memory/status')return answer({ok:true,enabled:false});
+ if(path==='/api/projects')return answer({ok:true,projects:[]});
+ if(path==='/api/scopes')return answer({ok:true,scopes:[]});
+ if(path==='/api/inbox')return answer({sessions:[],next_cursor:null,unread_by_session:{},unread_total:0,unread_sessions:0});
+ if(path==='/api/events')return route.fulfill({status:204});
+ return route.fallback();
+ });
+ await page.goto('/setup');
+ await page.getByRole('button',{name:'Get started',exact:true}).click();
+ const primary=page.locator('.onboarding-primary-action');
+ await expect(page.locator('[data-setup-screen="providers"]')).toBeVisible();
+ try { await expect(primary).toBeEnabled(); } catch(e) { console.log('DIAGNOSTIC',JSON.stringify({errors,denied,writes,dom:await page.locator('.onboarding-shell').evaluate(e=>e.outerHTML)})); throw e;} await primary.click();
+ const card=page.locator(`[data-setup-screen-root="assistants"] .onboarding-assistant[aria-label="${chosen==='claude'?'Claude Code':'Codex'}"]`);
+ await card.getByRole('button',{name:en.onboarding.setup.configureRoute,exact:true}).click();
+ const add=()=>page.getByRole('button',{name:en.settings.models.routeDialog.addHop,exact:true});
+ await 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 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 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);
+ await expect(page).toHaveURL(`${ORIGIN}/`);
+ await page.reload();await expect(page).toHaveURL(`${ORIGIN}/`);
+ await expect(page.locator('.onboarding-shell')).toHaveCount(0);
+ expect(errors).toEqual([]);
+ expect(writes.filter(w=>w.path==='/api/config').at(-1)?.body?.setup_completed).toBe(true);
+ expect(denied.filter(r=>/PUT|POST.*(?:auth|runtime)/.test(r))).toEqual([]);
+ });
+}
diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.ts
index 41754368e..c4a9c8e15 100644
--- a/ui/e2e/onboarding-fidelity/support.ts
+++ b/ui/e2e/onboarding-fidelity/support.ts
@@ -234,6 +234,13 @@ export async function openSetup(page: Page, lang: string) {
await page.getByRole('button', { name: lang === 'zh' ? '立即开始' : 'Get started' }).click();
// The handoff timer uses the same browser clock as the story in deterministic runs.
await page.clock.runFor(950);
+ // Providers is the first step now. This fixture answers「no sources」and leaves the
+ // Hub unready, so the connection action is disabled and the way on the screen states
+ // is the only control that leaves it — which is how a person gets to the assistants
+ // here, and so how the capture does. Addressed by the hint's own class rather than
+ // its sentence, because these captures run in both languages.
+ await page.locator('.onboarding-setup-hint button').click();
+ await page.clock.runFor(950);
await page.locator('[data-setup-screen="assistants"]').waitFor();
await page.locator('.onboarding-assistants').waitFor();
}
diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsx
index d9c2c0bad..68eceb9b3 100644
--- a/ui/src/components/Wizard.tsx
+++ b/ui/src/components/Wizard.tsx
@@ -1,10 +1,12 @@
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactElement, type Ref } from 'react';
+import { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactElement, type Ref } from 'react';
import { ArrowLeft, ArrowRight, RefreshCw } from 'lucide-react';
import { Button } from './ui/button';
import { AccessTiles } from './onboarding/AccessTiles';
import { RouteSurfaceActiveContext, useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';
import { modelHubEnabledFromConfig } from './settings/models/featureFlags';
-import { loadingRegion, beginRegionRead, failRegionRead } from './settings/models/regionRead';
+import { loadingRegion, readyRegion, beginRegionRead, failRegionRead } from './settings/models/regionRead';
+import { 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 { fetchSetupConfig, type SetupConfigRead, type SetupConfigSnapshot } from './onboarding/setupConfig';
@@ -14,17 +16,23 @@ import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Welcome } from './steps/Welcome';
import { AgentDetection } from './steps/AgentDetection';
+import { ProvidersScreen, type ProvidersScreenProps } from './onboarding/providers/ProvidersScreen';
+import {
+ GatewayBootstrapError,
+ bootstrapGateway,
+ readRuntimeObservation,
+ type GatewayBootstrapDeps,
+} from './onboarding/providers/gatewayBootstrap';
import logoImg from '@/assets/logo.png';
import { LanguageSwitcher } from './LanguageSwitcher';
-import { useApi, type VibeAgentBrief } from '../context/ApiContext';
+import { useApi } from '../context/ApiContext';
import { useStatus } from '../context/StatusContext';
import { setConfigField } from '../lib/configMutations';
-import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
import { SetupPlatformRecovery, type SavedPlatformRecovery } from './onboarding/SetupPlatformRecovery';
import { getEnabledPlatforms, getPlatformCatalog, platformHasRunnableConfig } from '../lib/platforms';
-import { SetupModelRecovery } from './onboarding/SetupModelRecovery';
-import { readOpencodeSetupRoutes } from './onboarding/opencodeSetupRoutes';
import { ASSISTANT_ORDER } from './onboarding/collaborationTimeline';
+import { createAgentCollectionReadAuthority } from './settings/models/collectionReadAuthority';
+import { admitEntry, chooseEntryDefault, readEntryEvidence, type EntryGateDeps, type EntryRefusal } from './onboarding/entryGate';
/**
* The setup's top bar, drawn as the design draws it at every size: the brand lockup —
@@ -66,6 +74,13 @@ export type SetupReadFailure = {
detail?: string;
};
+/** Each C4 refusal keeps the sentence its own situation already had. */
+const REFUSAL_MESSAGE = {
+ entryFailed: 'onboarding.connection.entryFailed',
+ applyPending: 'onboarding.connection.applyPending',
+ modelUnavailable: 'onboarding.connection.modelUnavailable',
+} as const satisfies Record<EntryRefusal, string>;
+
type FlowShellProps = {
sequence: readonly SetupScreenId[];
capability: SetupCapability;
@@ -207,21 +222,38 @@ export function SetupFlowShell({ sequence, capability, gatewayEnabled, onRetrySe
</div>;
}
+/**
+ * The providers screen, plus the one fact about it the shell's props cannot state:
+ * that this journey has ARRIVED here.
+ *
+ * D11 is an entry event, not a condition. Every screen is mounted from the first
+ * render — that is how drafts survive leaving one — so a mount says nothing about
+ * where the person is, and `active` turning true again on the way back from the
+ * assistants must not seed a config or start a controller a second time. So the edge
+ * is reported once, from inside the tree that knows it, and what to do with it stays
+ * with the shell's single runtime owner.
+ */
+const ProvidersEntry = forwardRef<SetupScreenHandle, ProvidersScreenProps & { onEnter: () => void }>(
+ function ProvidersEntry({ onEnter, ...props }, ref) {
+ const { active } = props;
+ useEffect(() => { if (active) onEnter(); }, [active, onEnter]);
+ return <ProvidersScreen ref={ref} {...props} />;
+ },
+);
+
export function Wizard() {
const api = useApi(); const { t } = useTranslation(); const navigate = useNavigate();
const { control } = useStatus();
- const { capabilities } = useInstanceAuthorization();
const [platformRecovery, setPlatformRecovery] = useState<SavedPlatformRecovery | null>(null);
- const [recovery, setRecovery] = useState<VibeAgentBrief | null>(null);
const [data, setData] = useState<Record<string, any> | null>(null);
const [error, setError] = useState<SetupReadFailure | null>(null);
const [loading, setLoading] = useState(true);
const [capability, setCapability] = useState<SetupCapability>('pending');
const [gatewayEnabled, setGatewayEnabled] = useState<boolean | null>(null);
const configGeneration = useRef(0);
- // The shell owns the region and its request generation. L2 integrates a stateless
- // D11 loader here on active provider entry; it returns a validated RuntimeDependency.
- // Until that screen is registered, config reads authorize no runtime read/bootstrap.
+ // The shell owns the region and its request generation; the stateless D11 sequence
+ // below is what fills it, once the journey actually reaches the provider screen.
+ // A config read on its own authorizes no runtime read and no bootstrap.
const [runtimeRead, setRuntimeRead] = useState<SetupScreenProps['runtimeRead']>(() => loadingRegion());
const completing = useRef(false);
/**
@@ -257,7 +289,6 @@ export function Wizard() {
}, [t]);
const load = useCallback(async () => {
const generation = ++configGeneration.current;
- setRuntimeRead((previous) => beginRegionRead(previous));
setLoading(true); setError(null); setCapability('pending'); setGatewayEnabled(null);
const result = await fetchSetupConfig();
// A newer read — another Retry, or a completion boundary — already owns the state.
@@ -266,6 +297,98 @@ export function Wizard() {
setLoading(false);
}, [applyRead]);
useEffect(() => { void load(); return () => { configGeneration.current += 1; }; }, [load]);
+ // ── The runtime region's one owner ────────────────────────────────────────
+ //
+ // `load` deliberately does not touch the region. It re-runs for reasons that have
+ // nothing to do with the machine — a language change re-resolves the copy a failed
+ // read is reported in — and marking a ready region as refreshing there would strand
+ // it: nothing would re-observe the runtime, because nothing asked anything to.
+ // Reporting a read in flight belongs to whoever is actually reading, which is here.
+ //
+ // One ticket covers both reasons the runtime is read: arriving at the provider
+ // screen, and an explicit retry. They are the same request — "observe the machine
+ // now" — and keeping them as one number is also what keeps them countable: an
+ // effect that re-runs for a config read landing, a capability arriving or a
+ // re-render cannot turn one request into several, because only a new ticket is a
+ // new request. Ticket 0 is "the journey has not been here yet".
+ const [entryTicket, setEntryTicket] = useState(0);
+ const enterProviders = useCallback(() => setEntryTicket((previous) => previous + 1), []);
+ const attemptedTicket = useRef(-1);
+ // Whether the sequence has already established what it establishes. Afterwards a
+ // refresh is the observation alone: the config exists and the controller is up, so
+ // re-seeding or re-starting would act on state that is already proven.
+ //
+ // Establishing once is not observing once. Coming back to the provider screen must
+ // show the machine as it is now — something may have changed it while the journey
+ // was on the assistants — so every arrival reads the runtime again, and only the
+ // writes are what happen a single time.
+ const bootstrapped = useRef(false);
+ const runtimeGeneration = useRef(0);
+ const bootstrapDeps = useMemo<GatewayBootstrapDeps>(() => ({
+ // Wrapped rather than passed by reference: the sequence is a dependency injection
+ // seam, and a test that spies on a module after this tree rendered must still be
+ // the thing that runs.
+ fetch: (input, init) => apiFetch(input, init),
+ getBackendConnection: (backend) => api.getBackendConnection(backend),
+ control: (action) => control(action),
+ getRuntimeStatus: () => modelsApi.getRuntimeStatus(),
+ }), [api, control]);
+ // C4 names one owner for every setup supply read, and this is it: the provider
+ // screen's adoption reads and the completion gate's corroboration share a single
+ // generation, so a read one of them superseded cannot come back as evidence for
+ // the other.
+ const [setupAgentReads] = useState(createAgentCollectionReadAuthority);
+ const entryDeps = useMemo<EntryGateDeps>(() => ({
+ listAgents: () => api.listVibeAgents({ cache: false }),
+ getBackendConnection: (backend) => api.getBackendConnection(backend),
+ agentReads: setupAgentReads,
+ getRuntimeStatus: () => modelsApi.getRuntimeStatus(),
+ getVibeAgent: (name, params) => api.getVibeAgent(name, { ...params, cache: false }),
+ detectCli: (binary) => api.detectCli(binary),
+ }), [api, setupAgentReads]);
+ const retrySetup = useCallback(() => {
+ // Order matters only in what it means: re-read the configuration, and let the
+ // runtime owner resume from whatever that read says — which, when it says the
+ // gateway is off, is nothing at all.
+ setEntryTicket((previous) => previous + 1);
+ void load();
+ }, [load]);
+ useEffect(() => {
+ if (entryTicket === 0 || loading) return;
+ // C2's boundary, read from the shell's own config state rather than assumed: a
+ // disabled deployment or a gateway somebody turned off authorizes no attempt.
+ if (!setupNavigationReady(capability, gatewayEnabled)) return;
+ if (attemptedTicket.current === entryTicket) return;
+ attemptedTicket.current = entryTicket;
+ const generation = ++runtimeGeneration.current;
+ setRuntimeRead((previous) => beginRegionRead(previous));
+ void (async () => {
+ try {
+ const runtime = bootstrapped.current
+ ? await readRuntimeObservation(bootstrapDeps)
+ : (await bootstrapGateway(bootstrapDeps, ASSISTANT_ORDER[0])).runtime;
+ if (generation !== runtimeGeneration.current) return;
+ bootstrapped.current = true;
+ setRuntimeRead(readyRegion(runtime));
+ } catch (cause) {
+ if (generation !== runtimeGeneration.current) return;
+ if (cause instanceof GatewayBootstrapError && cause.reason === 'disabled') {
+ // The sequence read a configuration this shell does not have yet, and the
+ // answer a person is owed is the configuration path rather than a retry.
+ // Re-reading is how that arrives: the config owner is the only thing that
+ // may set capability and saved intent, so the alert and the disabled cards
+ // come from the same authoritative read as everything else, and nothing
+ // here invents a flag or turns one back on.
+ void load();
+ return;
+ }
+ // Everything else is the region's own failure, and the provider screen's
+ // gateway card owns what to offer for it. Raising a second flow-level error
+ // beside that card would put two Retrys on screen for one machine.
+ setRuntimeRead((previous) => failRegionRead(previous));
+ }
+ })();
+ }, [loading, capability, gatewayEnabled, entryTicket, bootstrapDeps, load]);
/**
* Read the prerequisite as it is now, and answer whether setup may still act on it.
*
@@ -312,47 +435,47 @@ export function Wizard() {
setPlatformRecovery({ config: entry.config.raw, descriptor: missing });
return;
}
- const readCandidates = async () => {
- const results = await Promise.allSettled(ASSISTANT_ORDER.map((name) => api.getBackendConnection(name)));
- return results.flatMap((result) => result.status === 'fulfilled' && result.value.ok ? [result.value] : []);
- };
- let connections = await readCandidates();
+ // 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.
+ let evidenceOptions = { config: entry.config.raw };
+ let evidence = await readEntryEvidence(entryDeps, evidenceOptions);
if (!holds()) return;
- if (!connections.some((connection) => connection.entry_eligible)) throw new Error(t('onboarding.connection.entryFailed'));
- if (!connections.some((connection) => connection.ready)) {
- // Only confirmed stopped state allows this explicit start. Pending or
- // unknown IPC never becomes a restart request from the browser.
- if (!connections.some((connection) => connection.entry_eligible && connection.application === 'stopped')) throw new Error(t('onboarding.connection.applyPending'));
+ // A superseded supply read is neither an answer nor a failure — a newer
+ // generation of the shared authority is already reading, and that read is what
+ // will settle this. Nothing is written and nothing is claimed.
+ if (!evidence) return;
+ let admission = admitEntry(evidence);
+ if (admission.kind === 'refused' && admission.startable) {
+ // Connection and Agent reads can outlast the saved-intent read that authorised
+ // this click. A generation lease only notices a newer read in THIS shell; another
+ // browser can turn the gateway off while those waits are open. Recheck the
+ // persisted prerequisite immediately before the start, refuse unread/disabled/
+ // superseded, and use the refreshed config for the post-recovery CLI evidence.
+ const stillAuthorised = await readPrerequisite(lease);
+ if (!stillAuthorised) return;
+ lease = stillAuthorised.lease;
+ evidenceOptions = { config: stillAuthorised.config.raw };
+ // Only a connection the server confirmed `stopped` reaches here, and only
+ // once: the re-read below is what admits, not this call's own answer, so a
+ // machine that recovered on its own is never sent a second start. Startup
+ // itself has no assistant or source prerequisite.
const started = await control('start');
if (!holds()) return;
if (started?.ok === false) throw new Error(started.message || t('onboarding.connection.entryFailed'));
- connections = await readCandidates();
+ const recovered = await readEntryEvidence(entryDeps, evidenceOptions);
if (!holds()) return;
+ if (!recovered) return;
+ evidence = recovered;
+ admission = admitEntry(evidence);
}
- const ready = new Set(connections.filter((connection) => connection.ready).map((connection) => connection.backend));
- if (!ready.size) throw new Error(t('onboarding.connection.entryFailed'));
- const agents = await api.listVibeAgents({ cache: false });
- if (!holds()) return;
- const candidates = agents.agents.filter((agent) => agent.enabled && !agent.archived && ready.has(agent.backend as typeof ASSISTANT_ORDER[number]));
- if (!agents.ok || !candidates.length) throw new Error(t('onboarding.connection.entryFailed'));
- let available = candidates.filter((agent) => agent.backend !== 'opencode');
- const opencode = candidates.filter((agent) => agent.backend === 'opencode');
- if (opencode.length) {
- try {
- const routes = await readOpencodeSetupRoutes(api);
- if (!holds()) return;
- available = [...available, ...opencode.filter((agent) => routes.accepts(agent.model))];
- if (!available.length && routes.mode === 'direct' && capabilities.can_manage_agents) {
- setPlatformRecovery(null);
- setRecovery(opencode.find((agent) => agent.name === agents.default_agent_name) || opencode[0]);
- return;
- }
- } catch (cause) {
- // An unused OpenCode failure cannot block another usable backend.
- if (!available.length) throw cause;
- }
+ if (admission.kind === 'refused') {
+ // No detour. Setup's own contract is that the Hub serves the assistants, so a
+ // machine with no routable assistant is repaired where routes are configured —
+ // the route editor on this screen, or the providers screen behind it — not by a
+ // completion-time form that could only reach a backend the gate cannot admit.
+ throw new Error(t(REFUSAL_MESSAGE[admission.reason]));
}
- if (!available.length) throw new Error(t('onboarding.connection.modelUnavailable'));
// Everything above was awaited — a start, several connection reads, an Agent
// listing — so the prerequisite is read once more before the writes that end
// setup. A recovery's completion callback re-enters here and passes the same
@@ -361,20 +484,42 @@ export function Wizard() {
const settled = await readPrerequisite(lease);
if (!settled) return;
lease = settled.lease;
- // Preserve a usable selected Agent. First setup may have auto-seeded a
- // default for a missing backend; choose a real enabled Agent in that case.
- if (!available.some((agent) => agent.name === agents.default_agent_name)) {
- const selected = await api.setDefaultVibeAgent(available[0].name);
+ const choice = chooseEntryDefault(admission.candidates, evidence);
+ if (choice) {
+ const selected = await api.setDefaultVibeAgent(choice.agent.name);
// The default write is itself a wait, and the answer that authorised it can
// stop being the current one inside that wait. What was written stands; what
// it was written for — finishing setup — does not follow from it.
if (!holds()) return;
if (!selected.ok) throw new Error(t('onboarding.connection.entryFailed'));
+ // Confirmed by a fresh read rather than by the write's own answer: the next
+ // screen runs on whatever the server thinks the default is.
+ const confirmed = await api.listVibeAgents({ cache: false });
+ if (!holds()) return;
+ if (!confirmed.ok || confirmed.default_agent_name !== choice.agent.name) {
+ throw new Error(t('onboarding.connection.entryFailed'));
+ }
}
// Persist completion last: failed start/readiness leaves AuthGuard's
// existing setup gate intact. The locked config API validates existing IM.
- await api.mutateConfig([setConfigField(['setup_completed'], true)]);
+ //
+ // Issued once, and settled by a read. A write that lost its reply on the way
+ // back is indistinguishable here from one that never arrived, so it is neither
+ // believed nor sent again — the config itself is the only thing that can say
+ // which happened, and it is read uncached because a cached answer from before
+ // the write cannot settle anything about it.
+ try {
+ await api.mutateConfig([setConfigField(['setup_completed'], true)]);
+ } catch {
+ // Unknown, not failed. The readback below is what decides.
+ }
if (!holds()) return;
+ const persisted = await fetchSetupConfig();
+ if (persisted.state !== 'read' || !persisted.config.setup_completed) {
+ throw new Error(t('onboarding.flow.completionUnconfirmed'));
+ }
+ // Confirmed persisted, so the journey is over whatever else changed meanwhile:
+ // the lease exists to stop the next write, not to take back a finished setup.
navigate('/', { state: { onboardingCompleted: true } });
} finally { completing.current = false; }
};
@@ -382,12 +527,15 @@ export function Wizard() {
<SetupHeader />
<main className="onboarding-shell-content">
<SetupFlowShell sequence={SETUP_REGISTERED_SCREENS} capability={capability} gatewayEnabled={gatewayEnabled}
- runtimeRead={runtimeRead} loading={loading} error={error} onRetrySetup={() => void load()}
- navigationLocked={Boolean(platformRecovery || recovery)} renderScreen={(id, props, ref) => id === 'intro'
+ runtimeRead={runtimeRead} loading={loading} error={error} onRetrySetup={retrySetup}
+ navigationLocked={Boolean(platformRecovery)} 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}
- completionRecovery={platformRecovery ? <SetupPlatformRecovery key={platformRecovery.descriptor.id} saved={platformRecovery} onRepaired={complete} onCancel={() => setPlatformRecovery(null)} /> : recovery ? <SetupModelRecovery key={recovery.id} agent={recovery} onComplete={complete} onCancel={() => setRecovery(null)} /> : undefined}
+ 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.tsx
index d1c524098..6487f5a81 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, ExternalLink, KeyRound, RefreshCw, SlidersHorizontal } from 'lucide-react';
+import { Check, Download, KeyRound, RefreshCw, SlidersHorizontal } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { BackendIcon } from '../visual';
import { Button } from '../ui/button';
@@ -104,12 +104,10 @@ export function AssistantRow({ backend, status, installing, detecting, error, li
the connected state wearing the same row with a mint check. */}
<div className="onboarding-assistant-actions">
{connection === 'hub' ? (
- /* A hub-supplied credential is managed in Model Gateway, so the row names
- where it lives and clicking it goes there. */
<button type="button" className="onboarding-method-connected" onClick={onConfigure}
disabled={configuringDisabled || installing || detecting || !!connectionPending}>
- {connectionPending ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : <ExternalLink size={16} />}
- {t('settings.backends.openModelHub')}
+ {connectionPending ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : <SlidersHorizontal size={16} />}
+ {t('onboarding.setup.configureRoute')}
</button>
) : connection ? (
/* A button wearing the connected row: it reads as the static receipt the
diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsx
index 4ea391bf8..d18ea2745 100644
--- a/ui/src/components/onboarding/AssistantSetup.test.tsx
+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx
@@ -14,8 +14,13 @@ import type { SetupAction } 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() } }));
vi.mock('../../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 } };
+});
vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));
vi.mock('../settings/models/useModelHubCapability', () => ({ useModelHubCapability: () => false }));
vi.mock('../settings/shared/useOpencodePermission', () => ({ useOpencodePermission: () => ({ permissionAllowed: true, statusLoaded: true }) }));
@@ -43,6 +48,10 @@ beforeEach(() => {
mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [] });
mock.api.detectCli.mockResolvedValue({ found: true, path: '/isolated/bin/assistant' });
mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: false });
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [], default_agent_name: null });
+ mock.api.getVibeAgent.mockResolvedValue({ ok: false, agent: null });
+ mock.models.listSources.mockResolvedValue([]);
+ mock.models.getAgentChain.mockRejectedValue(new Error('chain unread'));
});
afterEach(cleanup);
@@ -127,7 +136,7 @@ describe('assistant installation presentation', () => {
expect(await row('Claude Code').findByRole('button', { name: 'API Key connected' })).toBeTruthy();
expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false);
});
- it('opens Model Hub directly when the backend is already Hub-owned', async () => {
+ it('opens the setup route editor when the backend is already Hub-owned', async () => {
const saved = data(); saved.agents.claude.status = 'ok';
mock.api.getBackendConnection.mockImplementation(async (backend) => ({
ok: true,
@@ -140,12 +149,36 @@ describe('assistant installation presentation', () => {
entry_eligible: false,
supply_mode: 'hub',
}));
- render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
- const action = await row('Claude Code').findByRole('button', { name: en.settings.backends.openModelHub });
+ const agent = {
+ id: 'claude-claude', name: 'claude', display_name: 'claude', description: null, backend: 'claude',
+ 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 },
+ };
+ 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({
+ 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 };
+ 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: [] }),
+ readValue: async () => [],
+ 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 });
+ const enter = screen.getByRole('button', { name: 'Enter workspace' });
+ expect(enter.hasAttribute('disabled')).toBe(true);
fireEvent.click(action);
- await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/settings/models'));
- expect(screen.queryByRole('dialog')).toBeNull();
- expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
+ expect(await screen.findByRole('dialog', { name: en.onboarding.route.title })).toBeTruthy();
+ expect(screen.getByTestId('location').textContent).toBe('/');
+ expect(enter.hasAttribute('disabled')).toBe(true);
});
it('an available update keeps Continue and configuration usable', async () => {
const saved = data(); saved.agents.claude.status = 'ok';
@@ -587,6 +620,40 @@ describe('settled wizard enablement follows persistence and latest intent', () =
expect(row('Claude Code').getAllByRole('alert')).toHaveLength(1);
expect(mock.api.mutateConfig).toHaveBeenCalledOnce();
});
+ // The presence read is the last thing a queued enable does, and the only one that can
+ // reject. A rejection used to settle the serial queue itself rejected, so every later
+ // toggle chained onto a continuation that never ran: the next enable wrote nothing,
+ // and nothing on the card said why. The write and the read after it answer separately.
+ it('a presence read that failed is reported and still leaves the next toggle able to run', async () => {
+ const saved = data(); saved.agents.claude.status = 'ok';
+ let backendEnabled = true;
+ mock.api.mutateConfig.mockImplementation(async () => { backendEnabled = !backendEnabled; return {}; });
+ mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name, name === 'claude' ? backendEnabled : true));
+ let presenceFails = true;
+ const refresh = vi.fn(async () => {
+ if (presenceFails) { presenceFails = false; throw new Error('fixture presence failure'); }
+ return { kind: 'current' as const, value: [] };
+ });
+ const agentReads = { read: async () => ({ kind: 'current' as const, value: [] }), refresh, readValue: async () => [], invalidate: () => undefined };
+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} agentReads={agentReads} />));
+ const checkbox = row('Claude Code').getByRole('switch') as HTMLElement;
+ const enter = screen.getByRole('button', { name: 'Enter workspace' });
+ await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(false));
+
+ fireEvent.click(checkbox);
+ expect((await row('Claude Code').findByRole('alert')).textContent).toContain('fixture presence failure');
+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());
+ expect(enter.hasAttribute('disabled')).toBe(true);
+
+ // Still a queue. The next toggle writes, and the connection read it carries settles
+ // the card — which only happens once the finished write released its pending enable.
+ fireEvent.click(checkbox);
+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(false));
+ expect(cardAlert()).toBeNull();
+ expect(refresh).toHaveBeenCalledTimes(2);
+ expect(checkedOf(checkbox)).toBe(true);
+ });
it('delayed modal config cannot undo a newer authoritative enablement result', async () => {
const checkbox = mountReady(); await row('Claude Code').findByRole('button', { name: 'API Key connected' });
const config = pending<unknown>(); mock.api.getConfig.mockReturnValue(config.promise);
diff --git a/ui/src/components/onboarding/DefaultRouteDialog.test.tsx b/ui/src/components/onboarding/DefaultRouteDialog.test.tsx
new file mode 100644
index 000000000..1c819d076
--- /dev/null
+++ b/ui/src/components/onboarding/DefaultRouteDialog.test.tsx
@@ -0,0 +1,264 @@
+// @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.tsx
new file mode 100644
index 000000000..b3dc04f88
--- /dev/null
+++ b/ui/src/components/onboarding/DefaultRouteDialog.tsx
@@ -0,0 +1,374 @@
+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/SetupFlowShell.test.tsx b/ui/src/components/onboarding/SetupFlowShell.test.tsx
index 05900806c..dd71861cf 100644
--- a/ui/src/components/onboarding/SetupFlowShell.test.tsx
+++ b/ui/src/components/onboarding/SetupFlowShell.test.tsx
@@ -36,10 +36,14 @@ beforeEach(() => {
});
afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
-it('derives the interim and complete journey from a static registry alone', () => {
- expect(SETUP_REGISTERED_SCREENS).toEqual(['intro', 'assistants']);
- expect(setupBackTarget(SETUP_REGISTERED_SCREENS, 'assistants')).toBe('intro');
- expect(registeredSetupSequence({ intro: true, providers: true, assistants: true })).toEqual(SETUP_SCREENS);
+it('derives the journey from a static registry alone, in the contract order', () => {
+ expect(SETUP_REGISTERED_SCREENS).toEqual(SETUP_SCREENS);
+ expect(setupBackTarget(SETUP_REGISTERED_SCREENS, 'assistants')).toBe('providers');
+ expect(setupBackTarget(SETUP_REGISTERED_SCREENS, 'intro')).toBeNull();
+ // Registration is build-time membership, not order: a registry written in any order
+ // still yields the one journey C2 declares, and an unregistered screen leaves no slot.
+ expect(registeredSetupSequence({ assistants: true, providers: true, intro: true })).toEqual(SETUP_SCREENS);
+ expect(registeredSetupSequence({ intro: true, assistants: true })).toEqual(['intro', 'assistants']);
});
it.each(['pending', 'disabled', 'enabled'] as const)('policy %s never removes a registered screen', (capability) => {
const { container } = render(show(capability, false));
diff --git a/ui/src/components/onboarding/SetupModelRecovery.tsx b/ui/src/components/onboarding/SetupModelRecovery.tsx
deleted file mode 100644
index e66d8a325..000000000
--- a/ui/src/components/onboarding/SetupModelRecovery.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { useEffect, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useApi, type VibeAgentBrief, type VibeAgentUpdatePayload } from '@/context/ApiContext';
-import { fetchBackendModels, modelOptionLabel, type BackendModels } from '@/lib/backendModels';
-import { resolveEffortOptions } from '@/lib/effortOptions';
-import { errorMessage } from '@/lib/errorMessage';
-import { Button } from '../ui/button';
-import { Combobox } from '../ui/combobox';
-import { readOpencodeSetupRoutes } from './opencodeSetupRoutes';
-
-/** An explicit model repair, scoped to the named Agent and existing catalog. */
-export function SetupModelRecovery({ agent, onComplete, onCancel }: {
- agent: VibeAgentBrief; onComplete: () => Promise<void>; onCancel: () => void;
-}) {
- const api = useApi(); const { t } = useTranslation();
- const [catalog, setCatalog] = useState<BackendModels>({ models: [] });
- const [model, setModel] = useState('');
- const [loading, setLoading] = useState(true);
- const [saving, setSaving] = useState(false);
- const [error, setError] = useState('');
- const [attempt, setAttempt] = useState(0);
- const busy = useRef(false);
- useEffect(() => {
- let cancelled = false;
- setLoading(true); setError('');
- void Promise.all([readOpencodeSetupRoutes(api), fetchBackendModels(api, 'opencode')]).then(([routes, models]) => {
- if (cancelled) return;
- if (routes.mode !== 'direct') throw new Error(t('onboarding.connection.modelChanged'));
- setCatalog({ ...models, models: models.models.filter(routes.accepts) });
- }).catch((cause) => { if (!cancelled) setError(errorMessage(cause) || t('onboarding.connection.modelUnavailable')); })
- .finally(() => { if (!cancelled) setLoading(false); });
- return () => { cancelled = true; };
- }, [api, attempt, t]);
- const apply = async () => {
- if (busy.current || !catalog.models.includes(model)) return;
- busy.current = true; setSaving(true); setError('');
- try {
- const [routes, fresh] = await Promise.all([readOpencodeSetupRoutes(api), api.getVibeAgent(agent.name, { cache: false })]);
- if (!fresh.ok || !fresh.agent.enabled || fresh.agent.archived || fresh.agent.backend !== 'opencode' || routes.mode !== 'direct' || !routes.accepts(model)) throw new Error(t('onboarding.connection.modelChanged'));
- if (fresh.agent.model !== agent.model && fresh.agent.model !== model) throw new Error(t('onboarding.connection.modelChanged'));
- const patch: VibeAgentUpdatePayload = { model };
- // Only an explicit catalog statement justifies changing existing effort.
- const effort = fresh.agent.reasoning_effort;
- if (effort && catalog.reasoningOptions && Object.prototype.hasOwnProperty.call(catalog.reasoningOptions, model)) {
- const options = resolveEffortOptions('opencode', model, catalog.reasoningOptions);
- if (!options.includes(effort)) patch.reasoning_effort = options.includes('medium') ? 'medium' : options[0] ?? null;
- }
- if (fresh.agent.model !== model) {
- const result = await api.updateVibeAgent(agent.name, patch);
- if (!result.ok) throw new Error(t('onboarding.connection.saveFailed'));
- }
- await onComplete();
- } catch (cause) { setError(errorMessage(cause) || t('onboarding.connection.modelUnavailable')); }
- finally { busy.current = false; setSaving(false); }
- };
- return <section className="onboarding-model-recovery" aria-label={t('onboarding.connection.modelTitle')}>
- <h3>{t('onboarding.connection.modelTitle')}</h3>
- <p>{t('onboarding.connection.modelHint', { agent: agent.display_name || agent.name, model: agent.model || '—' })}</p>
- {error && <p role="alert" className="connection-error">{error}</p>}
- {!loading && !catalog.models.length && <p role="status">{t('onboarding.connection.modelEmpty')}</p>}
- <Combobox options={catalog.models.map((value) => ({ value, label: modelOptionLabel(value, catalog.modelLabels) }))}
- value={model} onValueChange={setModel} disabled={loading || saving} allowCustomValue={false}
- searchPlaceholder={t('onboarding.connection.modelSelect')} emptyText={t('onboarding.connection.modelEmpty')}
- ariaLabel={t('onboarding.connection.modelSelect')} placeholder={t('onboarding.connection.modelSelect')} />
- <div className="flex flex-wrap justify-end gap-2">
- <Button variant="ghost" disabled={saving} onClick={onCancel}>{t('common.cancel')}</Button>
- <Button variant="secondary" disabled={loading || saving} onClick={() => setAttempt((value) => value + 1)}>{t('common.retry')}</Button>
- <Button variant="brand" disabled={loading || saving || !catalog.models.includes(model)} onClick={() => void apply()}>{t('onboarding.connection.modelApply')}</Button>
- </div>
- </section>;
-}
diff --git a/ui/src/components/onboarding/WizardCompletion.test.tsx b/ui/src/components/onboarding/WizardCompletion.test.tsx
index 4af9723f0..4a638adce 100644
--- a/ui/src/components/onboarding/WizardCompletion.test.tsx
+++ b/ui/src/components/onboarding/WizardCompletion.test.tsx
@@ -1,19 +1,31 @@
// @vitest-environment jsdom
-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import { createInstance } from 'i18next';
import { I18nextProvider } from 'react-i18next';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { Wizard } from '../Wizard';
+import { CONTRACT_VERSION, type AgentBackend, type AgentSupply, type NamedAgentSupply, type RuntimeDependency, type Source } from '../settings/models/types';
import en from '../../i18n/en.json';
-const mock = vi.hoisted(() => ({ supply: vi.fn(), control: vi.fn(), toast: vi.fn(), permission: vi.fn(), manageAccess: true, apiFetch: vi.fn(), api: {
+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(),
- getOpencodeProviders: vi.fn(), readOpencodeOptionsForModelPicker: vi.fn(), readModelHubAgentCatalogForModelPicker: vi.fn(), updateVibeAgent: vi.fn(), getVibeAgent: vi.fn(), listVibeAgents: vi.fn(), setDefaultVibeAgent: vi.fn(), mutateConfig: vi.fn(),
-} }));
+ readModelHubAgentCatalogForModelPicker: vi.fn(), listVibeAgents: vi.fn(), getVibeAgent: 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:
+ // the collection authority, the lifecycle helper and the take-over dialog underneath
+ // them are the real ones, which is what makes the journey below the journey rather
+ // than a direct mount of the third screen.
+ models: { listSources: vi.fn(), listAgents: vi.fn(), refreshAgentPresence: vi.fn(), scanMigration: vi.fn(), getRuntimeStatus: 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('@/lib/apiFetch', async (importOriginal) => ({ ...await importOriginal<typeof import('@/lib/apiFetch')>(), apiFetch: mock.apiFetch }));
-vi.mock('../settings/models/modelsApi', () => ({ modelsApi: { getAgentSources: mock.supply } }));
+vi.mock('../settings/models/modelsApi', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../settings/models/modelsApi')>();
+ return { ...actual, modelsApi: { ...actual.modelsApi, ...mock.models } };
+});
vi.mock('../../context/InstanceAuthorizationContext', () => ({ useInstanceAuthorization: () => ({ capabilities: { can_manage_agents: true, can_manage_access_members: mock.manageAccess } }) }));
vi.mock('../../context/StatusContext', () => ({ useStatus: () => ({ control: mock.control }) }));
vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: mock.toast }) }));
@@ -31,11 +43,83 @@ const baseConfig = (overrides: Record<string, unknown> = {}) => ({
version: 'v2', setup_completed: false, runtime: {}, capabilities: { model_hub: { enabled: true } }, model_hub: { enabled: true },
agents: { claude: { enabled: true }, codex: { enabled: true }, opencode: { enabled: true } }, platforms: { primary: 'slack', enabled: [] }, ...overrides,
});
+// The second screen's own prerequisites: one usable Hub source and a running runtime is
+// what makes its primary say "continue" rather than "add a source" or "connect".
+const HUB_SOURCE: Source = {
+ id: 'src_openai', vendor: 'openai', display_name: 'OpenAI', kind: 'api_key', protocol: 'openai_chat',
+ supply_channel: 'hub', billing: 'metered', state: { status: 'active' }, last_discovered_at: null,
+ models: [
+ { id: 'gpt-5', origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null },
+ { id: 'gpt-4.1', origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null },
+ ],
+};
+const RUNTIME_OK: RuntimeDependency = {
+ contract_version: CONTRACT_VERSION,
+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },
+ status: { verified: true, health: 'ok' },
+};
let fresh: () => Promise<Response>;
+let served: Record<string, unknown>;
+/** The listing `setDefaultVibeAgent` mutates, so a later uncached read can confirm it. */
+let listing: { ok: true; default_agent_name: string | null; agents: unknown[] };
/** Serve one config to both the cached projection and the uncached prerequisite GET. */
-function serveConfig(config: Record<string, unknown>) { mock.api.getConfig.mockResolvedValue(config); fresh = async () => jsonResponse(config); }
+function serveConfig(config: Record<string, unknown>) { served = config; mock.api.getConfig.mockResolvedValue(config); fresh = async () => jsonResponse(config); }
/** Change only the uncached GET, so the cached projection keeps answering the old one. */
function serveFreshOnly(next: () => Promise<Response>) { fresh = next; }
+/** A config write that actually lands, because the readback is what ends setup now:
+ * completion is believed only when a later uncached read says so, so a fixture whose
+ * writes never reached storage would refuse every completion for the wrong reason.
+ * A case that replaces `mutateConfig` to model its own server delegates back here. */
+function persistConfig(mutations: { path: string[]; value: unknown }[]) {
+ const next = { ...served };
+ for (const mutation of mutations) if (mutation.path.length === 1) next[mutation.path[0]] = mutation.value;
+ serveConfig(next);
+}
+/** One Agent the Hub can route, in the shape the supply projection reports it. */
+const route = (name: string, overrides: Partial<NamedAgentSupply> = {}): NamedAgentSupply =>
+ ({ name, effective_model_id: 'openai/gpt-5.6-sol', supply_status: 'ok', ...overrides });
+const hubSupply = (backend: AgentBackend, named: NamedAgentSupply[], overrides: Partial<AgentSupply> = {}): AgentSupply =>
+ ({
+ backend, cli_present: true, mode: 'hub', menu_kind: 'fixed', named_agents: named,
+ sources: {
+ order: [HUB_SOURCE.id],
+ eligibility: [{ source_id: HUB_SOURCE.id, eligible: true }],
+ },
+ ...overrides,
+ });
+/** The Agent listing and the Hub's routing table, kept agreeing the way a server that
+ * routes the Agents it knows keeps them. The gate exists for the cases where they do
+ * NOT agree, and those set one of the two projections again afterwards. */
+function serveAgents(defaultName: string | null, agents: Array<{ name: string; backend: AgentBackend } & Record<string, unknown>>) {
+ listing = {
+ ok: true,
+ default_agent_name: defaultName,
+ agents: agents.map((agent) => ({
+ id: `${agent.backend}-${agent.name}`, display_name: agent.name, description: null,
+ model: null, reasoning_effort: null, archived_at: null, updated_at: '',
+ enabled: true, archived: false, source: 'builtin', ...agent,
+ })),
+ };
+ mock.api.listVibeAgents.mockImplementation(async () => listing);
+ mock.api.getVibeAgent.mockImplementation(async (name: string, params?: { cache?: boolean }) => {
+ expect(params?.cache).toBe(false);
+ const agent = listing.agents.find((row) => (row as { name: string }).name === name) as
+ | ({ name: string; backend: string; source?: string; metadata?: Record<string, unknown> } & Record<string, unknown>)
+ | undefined;
+ if (!agent) return { ok: false, agent: null, default_agent_name: listing.default_agent_name };
+ const metadata = agent.metadata ?? (agent.source === 'user' ? {} : { builtin_default: true });
+ return {
+ ok: true,
+ default_agent_name: listing.default_agent_name,
+ agent: { ...agent, system_prompt: null, created_at: '', metadata },
+ };
+ });
+ const byBackend = new Map<AgentBackend, NamedAgentSupply[]>();
+ for (const agent of agents) byBackend.set(agent.backend, [...byBackend.get(agent.backend) ?? [], route(agent.name)]);
+ mock.models.listAgents.mockResolvedValue([...byBackend].map(([backend, named]) => hubSupply(backend, named)));
+}
+/** The baseline candidate: an ordinary shipped Claude Agent on a routed backend. */
+const CLAUDE_AGENT = { id: 'cl-1', name: 'claude-agent', backend: 'claude' as const, enabled: true, archived: false, source: 'builtin' };
let running: boolean;
beforeEach(() => {
vi.resetAllMocks(); running = true; mock.manageAccess = true;
@@ -52,19 +136,39 @@ beforeEach(() => {
mock.api.detectCli.mockResolvedValue({ found: true, path: '/测试/bin/assistant' });
mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: false });
mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, enabled: true, installed: true, auth: backend === 'claude' ? 'api_key' : 'none', application: running ? 'applied' : 'stopped', ready: backend === 'claude' && running, entry_eligible: backend === 'claude', permission_required: backend === 'opencode' }));
- mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'missing-codex', agents: [{ name: 'claude-agent', backend: 'claude', enabled: true }] });
- mock.api.setDefaultVibeAgent.mockResolvedValue({ ok: true });
- mock.api.mutateConfig.mockResolvedValue({ setup_completed: true });
- mock.control.mockImplementation(async () => { running = true; return { ok: true }; });
- // Hub-enabled config routes the OpenCode completion read through the supply
- // projection; Direct mode keeps every case authored before the gate on its path.
- mock.supply.mockResolvedValue({ backend: 'opencode', mode: 'direct', sources: { order: [], eligibility: [] }, routes: {}, builtin_models: [], catalog_models: [], named_agents: [], menu: null, model_supply: [], supply_status: 'unavailable' });
+ serveAgents('missing-codex', [CLAUDE_AGENT]);
+ mock.api.setDefaultVibeAgent.mockImplementation(async (name: string) => {
+ listing = { ...listing, default_agent_name: name };
+ return { ok: true };
+ });
+ mock.api.mutateConfig.mockImplementation(async (mutations) => { persistConfig(mutations); return {}; });
+ // `/api/control` answers `{ok, action, status}`; the bootstrap only accepts a start it
+ // can see acknowledged, so the fixture has to answer in the server's shape.
+ mock.control.mockImplementation(async () => { running = true; return { ok: true, action: 'start' }; });
+ mock.models.listSources.mockResolvedValue([HUB_SOURCE]);
+ mock.models.refreshAgentPresence.mockResolvedValue([]);
+ mock.models.scanMigration.mockResolvedValue({ items: [] });
+ mock.models.getRuntimeStatus.mockResolvedValue(RUNTIME_OK);
});
afterEach(async () => { cleanup(); await i18n.changeLanguage('en'); });
-async function setup() {
- mount(); fireEvent.click(await screen.findByRole('button', { name: 'Get started' }));
+/** The registered journey, not a direct mount of the last screen: the second screen is
+ * in the sequence, so every completion case below reaches the third one through it. */
+async function arriveAtProviders() {
+ mount();
+ fireEvent.click(await screen.findByRole('button', { name: 'Get started' }));
+ await waitFor(() => expect(primaryAction().textContent).toContain(en.onboarding.providers.actionContinue));
+ await waitFor(() => expect(primaryAction().hasAttribute('disabled')).toBe(false));
+}
+/** `stopped` is about the state the completion has to find, not the state the journey
+ * needed: arriving at the second screen legitimately starts the Hub, so a case that
+ * owns the completion's own start has to take the runtime back down after the handoff
+ * and forget the bootstrap's calls. Otherwise it would be asserting on both. */
+async function setup(options: { stopped?: boolean } = {}) {
+ await arriveAtProviders();
+ fireEvent.click(primaryAction());
const enter = await screen.findByRole('button', { name: 'Enter workspace' });
await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(false));
+ if (options.stopped) { running = false; mock.control.mockClear(); }
return enter;
}
describe('explicit any-one-ready completion', () => {
@@ -80,30 +184,27 @@ describe('explicit any-one-ready completion', () => {
expect(mock.permission).not.toHaveBeenCalled(); expect(mock.control).not.toHaveBeenCalled();
});
it('allows stopped entry and confirms start before committing setup', async () => {
- running = false;
- const enter = await setup(); fireEvent.click(enter);
+ const enter = await setup({ stopped: true }); fireEvent.click(enter);
await screen.findByTestId('destination');
expect(mock.control).toHaveBeenCalledExactlyOnceWith('start');
expect(mock.control.mock.invocationCallOrder[0]).toBeLessThan(mock.api.mutateConfig.mock.invocationCallOrder[0]);
});
it('preserves an existing usable default', async () => {
- mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'mine', agents: [{ name: 'mine', backend: 'claude', enabled: true }] });
+ serveAgents('mine', [{ name: 'mine', backend: 'claude' }]);
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') { running = false; mock.control.mockRejectedValue(new Error('Start unavailable')); }
- else mock.api.mutateConfig.mockRejectedValue(new Error("Config 'slack.bot_token' must be provided"));
- fireEvent.click(await setup());
+ if (failure !== 'start') mock.api.mutateConfig.mockRejectedValue(new Error("Config 'slack.bot_token' must be provided"));
+ const enter = await setup({ stopped: failure === 'start' });
+ if (failure === 'start') mock.control.mockRejectedValue(new Error('Start unavailable'));
+ fireEvent.click(enter);
await screen.findByRole('alert');
expect(screen.queryByTestId('destination')).toBeNull();
if (failure === 'start') expect(mock.api.mutateConfig).not.toHaveBeenCalled();
expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();
- mock.control.mockImplementation(async () => { running = true; return { ok: true }; });
- // Hub-enabled config routes the OpenCode completion read through the supply
- // projection; Direct mode keeps every case authored before the gate on its path.
- mock.supply.mockResolvedValue({ backend: 'opencode', mode: 'direct', sources: { order: [], eligibility: [] }, routes: {}, builtin_models: [], catalog_models: [], named_agents: [], menu: null, model_supply: [], supply_status: 'unavailable' });
- mock.api.mutateConfig.mockResolvedValue({ setup_completed: true });
+ mock.control.mockImplementation(async () => { running = true; return { ok: true, action: 'start' }; });
+ mock.api.mutateConfig.mockImplementation(async (mutations) => { persistConfig(mutations); return {}; });
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Enter workspace' })));
await screen.findByTestId('destination');
});
@@ -115,118 +216,306 @@ describe('explicit any-one-ready completion', () => {
});
});
-const opencodeAgent = { id: 'oc-1', name: 'opencode', display_name: 'OpenCode', backend: 'opencode', model: 'openai/gpt-5.6-sol', enabled: true, archived: false, source: 'builtin', reasoning_effort: 'high' };
-function directConnection(provider: string) {
- let agent = { ...opencodeAgent };
- mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, enabled: true, installed: true, auth: 'api_key', application: 'applied', ready: backend === 'opencode', entry_eligible: backend === 'opencode' }));
- mock.api.listVibeAgents.mockImplementation(async () => ({ ok: true, default_agent_name: 'opencode', agents: [agent] }));
- mock.api.getVibeAgent.mockImplementation(async () => ({ ok: true, agent }));
- mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, default_provider: 'openai', providers: [{ id: 'openai', configured: true, active_auth_type: null, models: ['gpt-5.6-sol'] }, { id: provider, configured: true, active_auth_type: 'oauth', models: ['selected-model', 'my-model'] }] });
- mock.api.readOpencodeOptionsForModelPicker.mockResolvedValue({ ok: true, data: { models: { providers: [{ id: provider, models: { 'selected-model': {} } }, { id: 'openai', models: { 'gpt-5.6-sol': {} } }] }, reasoning_options: { [`${provider}/selected-model`]: [] } } });
- mock.api.updateVibeAgent.mockImplementation(async (_name, patch) => { agent = { ...agent, ...patch }; return { ok: true, agent }; });
-}
-// AUTH-SETUP-121: the actual Wizard consumes route eligibility and explicit repair.
-describe('OpenCode model recovery', () => {
- it.each(['anthropic', 'poe'])('requires explicit compatible model selection for %s-only auth', async (provider) => {
- directConnection(provider);
+// AUTH-SETUP-121: the journey is Model Hub's, so the gate a completion has to pass is
+// a route the Hub can actually serve for ONE named Agent. The retracted Direct detour
+// used to live here; a completion-time credential form could only ever have repaired a
+// backend this journey does not adopt, so its cases are replaced by the join itself.
+describe('the correlated entry gate', () => {
+ /** Every assistant installed, enabled, applied and in custody — so that what a case
+ * changes afterwards is the only thing keeping the gate shut. */
+ const allConnected = (overrides: (backend: AgentBackend) => Record<string, unknown> = () => ({})) =>
+ mock.api.getBackendConnection.mockImplementation((backend: AgentBackend) => Promise.resolve({
+ ok: true, backend, enabled: true, installed: true, auth: 'api_key',
+ application: 'applied', ready: true, entry_eligible: true, ...overrides(backend),
+ }));
+ const refusal = async (copy: string) => {
+ expect((await screen.findByRole('alert')).textContent).toContain(copy);
+ expectNoForwardWrite();
+ };
+
+ it('refuses three half-answers that belong to different assistants', async () => {
+ // A detected Claude the Hub cannot route, plus a routed Codex whose configured
+ // 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' }],
+ });
+ 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 }));
+ fireEvent.click(enter);
+ await refusal(en.onboarding.connection.modelUnavailable);
+ });
+
+ it('admits a backend whose connection.installed is false once detectCli and presence agree', async () => {
+ allConnected(() => ({ installed: false }));
fireEvent.click(await setup());
- await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
- expect(mock.api.mutateConfig).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
- const picker = screen.getByRole('combobox', { name: en.onboarding.connection.modelSelect });
- await waitFor(() => expect(picker.hasAttribute('disabled')).toBe(false));
- fireEvent.click(picker);
- fireEvent.click(await screen.findByText(`${provider}/selected-model`, { exact: true }));
- fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.modelApply }));
await screen.findByTestId('destination');
- expect(mock.api.updateVibeAgent).toHaveBeenCalledExactlyOnceWith('opencode', { model: `${provider}/selected-model`, reasoning_effort: null });
- expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();
});
- it('cancel leaves the Agent and completion untouched', async () => {
- directConnection('anthropic'); fireEvent.click(await setup());
- await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
- expect(mock.api.updateVibeAgent).not.toHaveBeenCalled(); expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+
+ it('will not let one Agent\'s route speak for another with the same backend', async () => {
+ allConnected();
+ mock.models.listAgents.mockResolvedValue([hubSupply('claude', [route('someone-else')])]);
+ fireEvent.click(await setup());
+ await refusal(en.onboarding.connection.modelUnavailable);
});
- it('keeps selected input after a failed save and permits retry', async () => {
- directConnection('poe'); mock.api.updateVibeAgent.mockRejectedValueOnce(new Error('Agent save failed'));
+
+ // What the server says about THIS name, in the four shapes that are not a run.
+ it.each([
+ ['a route whose sources are still coming up', route('claude-agent', { supply_status: 'waiting' })],
+ ['a route whose sources broke', route('claude-agent', { supply_status: 'interrupted' })],
+ ['a backend that never routed this name', route('claude-agent', { route_reason: 'route_unconfigured' })],
+ ['a name with no model behind it', route('claude-agent', { effective_model_id: null, supply_status: null })],
+ ])('refuses %s', async (_label, named) => {
+ allConnected();
+ mock.models.listAgents.mockResolvedValue([hubSupply('claude', [named])]);
fireEvent.click(await setup());
- const picker = await screen.findByRole('combobox', { name: en.onboarding.connection.modelSelect });
- await waitFor(() => expect(picker.hasAttribute('disabled')).toBe(false)); fireEvent.click(picker);
- fireEvent.click(await screen.findByText('poe/selected-model', { exact: true }));
- fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.modelApply }));
- expect((await screen.findByRole('alert')).textContent).toContain('Agent save failed');
- expect(picker.textContent).toContain('poe/selected-model'); expect(mock.api.mutateConfig).not.toHaveBeenCalled();
- fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.modelApply })); await screen.findByTestId('destination');
- });
- it('preserves a custom compatible default without opening the catalog', async () => {
- directConnection('anthropic');
- mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'custom', agents: [{ ...opencodeAgent, name: 'custom', source: 'user', model: 'anthropic/my-model' }] });
- fireEvent.click(await setup()); await screen.findByTestId('destination');
- expect(mock.api.readOpencodeOptionsForModelPicker).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled(); expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();
- });
- it.each(['anthropic/removed', 'anthropic/typo', 'anthropic/'] as const)('rejects unregistered Direct model %s without editing Agent or auth', async (model) => {
- directConnection('anthropic');
- mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'custom', agents: [{ ...opencodeAgent, name: 'custom', source: 'user', model }] });
- fireEvent.click(await setup()); await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
- expect(mock.api.updateVibeAgent).not.toHaveBeenCalled(); expect(mock.api.mutateConfig).not.toHaveBeenCalled();
- });
- it.each([[], undefined])('keeps an Agent route unverified with absent model list (%s)', async (models) => {
- directConnection('anthropic');
- mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [{ id: 'anthropic', active_auth_type: 'api', models }] });
- fireEvent.click(await setup()); await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
- expect(screen.queryByTestId('destination')).toBeNull(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
- });
- it.each(['anthropic/family/custom-model', 'family-model'] as const)('preserves registered slash or explicit-default Direct model %s', async (model) => {
- directConnection('anthropic');
- mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, default_provider: 'anthropic', providers: [{ id: 'anthropic', active_auth_type: 'api', models: ['family/custom-model', 'family-model'] }] });
- mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'custom', agents: [{ ...opencodeAgent, name: 'custom', source: 'user', model }] });
+ await refusal(en.onboarding.connection.modelUnavailable);
+ });
+
+ it('admits a degraded route, which is a route that still runs', async () => {
+ allConnected();
+ mock.models.listAgents.mockResolvedValue([hubSupply('claude', [route('claude-agent', { supply_status: 'degraded' })])]);
fireEvent.click(await setup()); await screen.findByTestId('destination');
- expect(mock.api.updateVibeAgent).not.toHaveBeenCalled(); expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();
});
- it('does not infer a default provider for a bare model and retries unreadable catalog without auth mutation', async () => {
- directConnection('anthropic');
- mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'custom', agents: [{ ...opencodeAgent, name: 'custom', source: 'user', model: 'my-model' }] });
- mock.api.getOpencodeProviders.mockRejectedValue(new Error('provider catalog unreadable'));
+
+ it('refuses while the Hub that would serve the route is down', async () => {
+ // Hub MODE is not Hub readiness: the routes are configured and nothing can run.
+ // Judged at completion, not at the providers arrival that needs the engine up.
+ const enter = await setup();
+ mock.models.getRuntimeStatus.mockResolvedValue({ ...RUNTIME_OK, status: { verified: true, health: 'down' } });
+ fireEvent.click(enter);
+ await refusal(en.onboarding.connection.modelUnavailable);
+ });
+
+ it('refuses a backend whose CLI the refreshed presence read cannot see', async () => {
+ const enter = await setup();
+ mock.models.listAgents.mockResolvedValue([hubSupply('claude', [route('claude-agent')], { cli_present: false })]);
+ fireEvent.click(enter);
+ await waitFor(() => expect(mock.models.refreshAgentPresence).toHaveBeenCalled());
+ await refusal(en.onboarding.connection.modelUnavailable);
+ });
+
+ it('detects the persisted CLI path before entry, not the backend name', async () => {
+ serveConfig(baseConfig({
+ agents: {
+ claude: { enabled: true, cli_path: '/opt/custom/claude-bin' },
+ codex: { enabled: true },
+ opencode: { enabled: true },
+ },
+ }));
+ const enter = await setup();
+ mock.api.detectCli.mockClear();
+ fireEvent.click(enter);
+ await screen.findByTestId('destination');
+ expect(mock.api.detectCli).toHaveBeenCalledWith('/opt/custom/claude-bin');
+ expect(mock.api.detectCli.mock.invocationCallOrder[0]).toBeLessThan(mock.api.mutateConfig.mock.invocationCallOrder[0]);
+ });
+
+ it('cannot enter when detectCli does not find the configured binary, even with installed and cli_present', async () => {
+ serveConfig(baseConfig({
+ agents: {
+ claude: { enabled: true, cli_path: '/opt/custom/claude-bin' },
+ codex: { enabled: true },
+ opencode: { enabled: true },
+ },
+ }));
+ const enter = await setup();
+ mock.api.detectCli.mockImplementation(async (binary: string) => ({
+ found: binary !== '/opt/custom/claude-bin',
+ path: binary,
+ }));
+ fireEvent.click(enter);
+ await refusal(en.onboarding.connection.modelUnavailable);
+ });
+
+ it('cannot enter when the shared presence refresh fails', async () => {
+ const enter = await setup();
+ mock.models.refreshAgentPresence.mockRejectedValue(new Error('presence unread'));
+ fireEvent.click(enter);
+ await refusal(en.onboarding.connection.modelUnavailable);
+ });
+ it('stops when a fresh read does not confirm the default the server accepted', async () => {
+ // The next screen runs on whatever the server thinks the default is, so the write's
+ // own `ok` is not what setup believes.
+ mock.api.setDefaultVibeAgent.mockImplementation(async () => ({ ok: true }));
fireEvent.click(await setup());
- expect((await screen.findByRole('alert')).textContent).toContain('provider catalog unreadable');
+ expect((await screen.findByRole('alert')).textContent).toContain(en.onboarding.connection.entryFailed);
+ expect(mock.api.setDefaultVibeAgent).toHaveBeenCalledExactlyOnceWith('claude-agent');
+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();
expect(screen.queryByTestId('destination')).toBeNull();
- mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [{ id: 'anthropic', active_auth_type: 'api', models: ['my-model'] }] });
- fireEvent.click(screen.getByRole('button', { name: en.common.retry }));
- await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
- expect(mock.api.mutateConfig).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
- });
- it('an unreadable OpenCode catalog cannot block an existing usable Claude default', async () => {
- directConnection('anthropic');
- mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, enabled: true, installed: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true }));
- mock.api.getOpencodeProviders.mockRejectedValue(new Error('provider catalog unreadable'));
- mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'mine', agents: [opencodeAgent, { name: 'mine', backend: 'claude', enabled: true }] });
+ });
+
+ // A confirmed `stopped` is the one application state an explicit start may answer.
+ // These are the states that are not a confirmation, so nothing is started for them.
+ it.each(['draining', 'failed', 'unknown'] as const)('refuses an application that is %s without asking for a start', async (application) => {
+ const enter = await setup();
+ allConnected(() => ({ application }));
+ fireEvent.click(enter);
+ await refusal(en.onboarding.connection.modelUnavailable);
+ });
+
+ it('prefers the assistant\'s own Agent once the saved default cannot run', async () => {
+ // `aa-custom` sorts first and is a perfectly usable candidate, so picking `claude`
+ // is the preference stated rather than whatever the list happened to hand over.
+ allConnected();
+ serveAgents('gone', [
+ { name: 'aa-custom', backend: 'claude', source: 'user' },
+ { name: 'claude', backend: 'claude', source: 'file', metadata: { builtin_default: true } },
+ ]);
fireEvent.click(await setup()); await screen.findByTestId('destination');
- expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
+ expect(mock.api.setDefaultVibeAgent).toHaveBeenCalledExactlyOnceWith('claude');
+ expect(mock.api.getVibeAgent.mock.calls.every(([, params]) => params?.cache === false)).toBe(true);
});
- it('allows another ready backend despite OpenCode mismatch', async () => {
- directConnection('anthropic');
- mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, enabled: true, installed: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true }));
- mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'mine', agents: [opencodeAgent, { name: 'mine', backend: 'claude', enabled: true }] });
+
+ it('does not treat a same-named Agent as the assistant when its metadata cannot be read', async () => {
+ // `claude` sorts after `aa-custom`. Inferring builtin from source would pick it;
+ // a failed full read must not, so the first runnable candidate is the one entered.
+ allConnected();
+ serveAgents('gone', [
+ { name: 'aa-custom', backend: 'claude', source: 'user' },
+ { name: 'claude', backend: 'claude', source: 'builtin' },
+ ]);
+ mock.api.getVibeAgent.mockImplementation(async (name: string, params?: { cache?: boolean }) => {
+ expect(params?.cache).toBe(false);
+ if (name === 'claude') return { ok: false, agent: null, default_agent_name: 'gone' };
+ const agent = listing.agents.find((row) => (row as { name: string }).name === name);
+ if (!agent) return { ok: false, agent: null, default_agent_name: 'gone' };
+ return { ok: true, default_agent_name: 'gone', agent: { ...agent, system_prompt: null, created_at: '', metadata: {} } };
+ });
fireEvent.click(await setup()); await screen.findByTestId('destination');
- expect(mock.api.readOpencodeOptionsForModelPicker).not.toHaveBeenCalled(); expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
+ expect(mock.api.setDefaultVibeAgent).toHaveBeenCalledExactlyOnceWith('aa-custom');
});
-});
-it('uses canonical Hub supply instead of treating canonical slash IDs as Direct providers', async () => {
- directConnection('anthropic');
- serveConfig(baseConfig({ capabilities: { model_hub: { enabled: true } } }));
- mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'opencode', agents: [{ ...opencodeAgent, model: 'canonical/model' }] });
- mock.supply.mockResolvedValue({ backend: 'opencode', mode: 'hub', catalog_models: [{ id: 'canonical/model', routeable: true }], model_supply: [{ model_id: 'canonical/model', has_runnable_hop: true }] });
- fireEvent.click(await setup()); await screen.findByTestId('destination');
- expect(mock.api.getOpencodeProviders).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
-});
-it('keeps incomplete setup when catalog retrieval fails and allows cancellation', async () => {
- directConnection('anthropic'); mock.api.readOpencodeOptionsForModelPicker.mockRejectedValue(new Error('Catalog unavailable'));
- fireEvent.click(await setup());
- expect((await screen.findByRole('alert')).textContent).toContain('Catalog unavailable');
- expect(mock.api.mutateConfig).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
- expect(screen.queryByRole('region', { name: en.onboarding.connection.modelTitle })).toBeNull();
+ it('keeps a usable custom default that no card represents', async () => {
+ allConnected();
+ serveAgents('mine', [
+ { name: 'mine', backend: 'claude', source: 'user' },
+ { name: 'claude', backend: 'claude', source: 'file', metadata: { builtin_default: true } },
+ ]);
+ fireEvent.click(await setup()); await screen.findByTestId('destination');
+ expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();
+ });
+
+ it('starts a confirmed-stopped controller even when Hub IPC is down, then completes on a fresh read', async () => {
+ const enter = await setup({ stopped: true });
+ mock.models.refreshAgentPresence.mockImplementation(async () => {
+ if (!running) throw new Error('engine_down: controller socket absent');
+ return [];
+ });
+ mock.models.listAgents.mockImplementation(async () => {
+ if (!running) throw new Error('engine_down: controller socket absent');
+ return [hubSupply('claude', [route('claude-agent')])];
+ });
+ mock.models.getRuntimeStatus.mockImplementation(async () => {
+ if (!running) throw new Error('engine_down: controller socket absent');
+ return RUNTIME_OK;
+ });
+ fireEvent.click(enter);
+ fireEvent.click(enter);
+ await screen.findByTestId('destination');
+ expect(mock.control).toHaveBeenCalledExactlyOnceWith('start');
+ expect(mock.control.mock.invocationCallOrder[0]).toBeLessThan(mock.api.mutateConfig.mock.invocationCallOrder[0]);
+ });
+
+ it('starts a stopped controller with no assistant or entry_eligible prerequisite', async () => {
+ const enter = await setup({ stopped: true });
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [], default_agent_name: null });
+ mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({
+ ok: true, backend, enabled: true, installed: true,
+ ready: running, entry_eligible: false, application: running ? 'applied' : 'stopped',
+ }));
+ mock.models.refreshAgentPresence.mockImplementation(async () => {
+ if (!running) throw new Error('engine_down: controller socket absent');
+ return [];
+ });
+ mock.models.listAgents.mockImplementation(async () => {
+ if (!running) throw new Error('engine_down: controller socket absent');
+ return [hubSupply('claude', [route('claude-agent')])];
+ });
+ mock.models.getRuntimeStatus.mockImplementation(async () => {
+ if (!running) throw new Error('engine_down: controller socket absent');
+ return RUNTIME_OK;
+ });
+ mock.control.mockImplementation(async () => {
+ running = true;
+ serveAgents('missing-codex', [CLAUDE_AGENT]);
+ mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({
+ ok: true, backend, enabled: true, installed: true,
+ ready: backend === 'claude', entry_eligible: backend === 'claude', application: 'applied',
+ }));
+ return { ok: true, action: 'start' };
+ });
+ fireEvent.click(enter);
+ await screen.findByTestId('destination');
+ expect(mock.control).toHaveBeenCalledExactlyOnceWith('start');
+ });
+
+ it('does not complete a recovery that is still unready, and does not start twice', async () => {
+ const enter = await setup({ stopped: true });
+ mock.models.refreshAgentPresence.mockImplementation(async () => {
+ if (!running) throw new Error('engine_down: controller socket absent');
+ return [];
+ });
+ mock.models.listAgents.mockImplementation(async () => {
+ if (!running) throw new Error('engine_down: controller socket absent');
+ return [hubSupply('claude', [route('claude-agent')])];
+ });
+ mock.models.getRuntimeStatus.mockImplementation(async () => {
+ if (!running) throw new Error('engine_down: controller socket absent');
+ return { ...RUNTIME_OK, status: { verified: true, health: 'down' } };
+ });
+ fireEvent.click(enter);
+ expect((await screen.findByRole('alert')).textContent).toContain(en.onboarding.connection.modelUnavailable);
+ expect(mock.control).toHaveBeenCalledExactlyOnceWith('start');
+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ expect(screen.queryByTestId('destination')).toBeNull();
+ });
+
+ it('never starts an unknown application even when Hub IPC is down', async () => {
+ const enter = await setup();
+ mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({
+ ok: true, backend, enabled: true, installed: true, ready: false,
+ entry_eligible: true, application: 'unknown',
+ }));
+ mock.models.refreshAgentPresence.mockRejectedValue(new Error('engine_down: controller socket absent'));
+ mock.models.listAgents.mockRejectedValue(new Error('engine_down: controller socket absent'));
+ mock.models.getRuntimeStatus.mockRejectedValue(new Error('engine_down: controller socket absent'));
+ fireEvent.click(enter);
+ expect((await screen.findByRole('alert')).textContent).toContain(en.onboarding.connection.applyPending);
+ expect(mock.control).not.toHaveBeenCalled();
+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ expect(screen.queryByTestId('destination')).toBeNull();
+ });
+
+ it('writes completion last and enters only on a fresh read that says so', async () => {
+ const enter = await setup();
+ fireEvent.click(enter); await screen.findByTestId('destination');
+ expect(mock.api.setDefaultVibeAgent.mock.invocationCallOrder[0]).toBeLessThan(mock.api.mutateConfig.mock.invocationCallOrder[0]);
+ // The last read of the journey is uncached: a cached answer from before the write
+ // cannot settle anything about it.
+ const last = mock.apiFetch.mock.calls.at(-1)!;
+ expect(String(last[0])).toBe('/api/config');
+ expect((last[1] as RequestInit | undefined)?.cache).toBe('no-store');
+ });
+
+ it('refuses to enter on an accepted write the config does not show', async () => {
+ mock.api.mutateConfig.mockResolvedValue({ setup_completed: true });
+ fireEvent.click(await setup());
+ expect((await screen.findByRole('alert')).textContent).toContain(en.onboarding.flow.completionUnconfirmed);
+ expect(screen.queryByTestId('destination')).toBeNull();
+ expect(mock.api.mutateConfig).toHaveBeenCalledOnce();
+ });
+
+ it('reconciles a completion write whose answer was lost by reading, not by writing again', async () => {
+ // The reply never came back; the write did land. Resubmitting would be a guess,
+ // and the config is the only thing that can say which happened.
+ mock.api.mutateConfig.mockImplementation(async (mutations) => { persistConfig(mutations); throw new Error('socket closed'); });
+ fireEvent.click(await setup()); await screen.findByTestId('destination');
+ expect(mock.api.mutateConfig).toHaveBeenCalledOnce();
+ });
});
/** A saved platform whose required credential is gone: the shape that stops completion
@@ -241,12 +530,16 @@ function incompleteSlack() {
// 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(); running = false;
- fireEvent.click(await setup());
+ const config = 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' } });
+ 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 }));
@@ -287,7 +580,11 @@ describe('saved Discord recovery', () => {
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 } });
+ if (changes[0].path[0] === 'discord') {
+ serveConfig({ ...config, discord: { bot_token: '', has_bot_token: true } });
+ return {};
+ }
+ persistConfig(changes);
return {};
});
fireEvent.click(await setup());
@@ -347,6 +644,8 @@ 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
@@ -429,9 +728,10 @@ describe('fresh prerequisite boundary', () => {
it('an older enabled read settling last cannot revive a newer disabled answer or finish setup', async () => {
const enter = await setup();
let releaseEntry!: (value: Response) => void;
+ const readsBefore = mock.apiFetch.mock.calls.length;
serveFreshOnly(() => new Promise<Response>((resolve) => { releaseEntry = resolve; }));
fireEvent.click(enter);
- await waitFor(() => expect(mock.apiFetch).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(mock.apiFetch.mock.calls.length).toBe(readsBefore + 1));
// A language change re-runs the shell's load, which is how a second config read
// legitimately starts while the completion boundary's first one is still open.
serveFreshOnly(async () => jsonResponse(baseConfig({ model_hub: { enabled: false } })));
@@ -442,20 +742,40 @@ describe('fresh prerequisite boundary', () => {
expectNoForwardWrite();
});
it('rereads the prerequisite after the awaited readiness work and before the final writes', async () => {
- running = false;
- const enter = await setup();
- // The gateway goes off while the start and the Agent listing are in flight.
+ const enter = await setup({ stopped: true });
+ // The gateway goes off while the Agent listing is in flight. A start is a write
+ // against persisted intent, so the listing wait is not permission to start: the
+ // next read of the prerequisite has to refuse first.
mock.api.listVibeAgents.mockImplementation(async () => {
serveFreshOnly(async () => jsonResponse(baseConfig({ model_hub: { enabled: false } })));
return { ok: true, default_agent_name: 'missing-codex', agents: [{ name: 'claude-agent', backend: 'claude', enabled: true }] };
});
fireEvent.click(enter);
await waitFor(() => expect(flowError()).toBe(en.onboarding.flow.gatewayRequired));
- expect(mock.control).toHaveBeenCalledExactlyOnceWith('start');
+ expect(mock.control).not.toHaveBeenCalled();
expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();
expect(mock.api.mutateConfig).not.toHaveBeenCalled();
expect(screen.queryByTestId('destination')).toBeNull();
});
+
+ it('rechecks persisted gateway intent after readiness waits before recovery starts', async () => {
+ const enter = await setup({ stopped: true });
+ const original = mock.api.getBackendConnection.getMockImplementation()!;
+ let withdraw = false;
+ mock.api.getBackendConnection.mockImplementation(async (backend) => {
+ const value = await original(backend);
+ if (!withdraw) {
+ withdraw = true;
+ serveFreshOnly(async () => jsonResponse(baseConfig({ model_hub: { enabled: false } })));
+ }
+ return value;
+ });
+ fireEvent.click(enter);
+ await waitFor(() => expect(flowError()).toBe(en.onboarding.flow.gatewayRequired));
+ expect(mock.control).not.toHaveBeenCalled();
+ expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();
+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ });
// The admission the boundary grants is good until the next answer, not for the rest
// of the operation. Both cases below read an enabled prerequisite, then let a real
// second read — the language change that re-runs the shell's own load — arrive while
@@ -465,8 +785,7 @@ describe('fresh prerequisite boundary', () => {
['the prerequisite became unreadable', async () => { throw new Error('network down'); }, en.onboarding.connection.readFailed],
] as const;
it.each(overtaken)('stops before the start it was authorised to make once %s', async (_label, respond, explanation) => {
- running = false;
- const enter = await setup();
+ const enter = await setup({ stopped: true });
const answer = mock.api.getBackendConnection.getMockImplementation()!;
let release!: () => void;
const held = new Promise<void>((resolve) => { release = resolve; });
@@ -541,17 +860,21 @@ describe('fresh prerequisite boundary', () => {
expect(mock.api.mutateConfig).not.toHaveBeenCalled();
});
it('a recovery completion callback passes the same boundary', async () => {
- directConnection('anthropic');
+ // 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());
- const picker = await screen.findByRole('combobox', { name: en.onboarding.connection.modelSelect });
- await waitFor(() => expect(picker.hasAttribute('disabled')).toBe(false));
- fireEvent.click(picker);
- fireEvent.click(await screen.findByText('anthropic/selected-model', { exact: true }));
- serveFreshOnly(async () => jsonResponse(baseConfig({ model_hub: { enabled: false } })));
- fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.modelApply }));
+ 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.updateVibeAgent).toHaveBeenCalledOnce();
- expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ expect(mock.api.mutateConfig).toHaveBeenCalledOnce();
expect(screen.queryByTestId('destination')).toBeNull();
});
});
@@ -559,23 +882,12 @@ describe('fresh prerequisite boundary', () => {
// 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', () => {
- it('holds both controls without a busy spinner, and gives them back on cancel', async () => {
- directConnection('anthropic');
- fireEvent.click(await setup());
- await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
- expect(backAction().hasAttribute('disabled')).toBe(true);
- expect(primaryAction().hasAttribute('disabled')).toBe(true);
- expect(spinners()).toBe(0);
- expect(primaryAction().textContent).toContain('Enter workspace');
- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
- await waitFor(() => expect(backAction().hasAttribute('disabled')).toBe(false));
- });
- // The same claim for the other recovery the slot carries. 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.
+ // 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(); running = false;
- fireEvent.click(await setup());
+ 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);
@@ -588,15 +900,18 @@ describe('recovery navigation ownership', () => {
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(); running = false;
+ const config = incompleteSlack();
let releaseApply!: (ok: boolean) => void;
- mock.api.mutateConfig.mockImplementation(async (mutations: { path: string[] }[]) => {
- if (mutations[0].path[0] !== 'slack') return {};
+ 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());
+ 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);
@@ -624,36 +939,287 @@ describe('recovery navigation ownership', () => {
expect(await screen.findByTestId('destination')).toBeTruthy();
expect(mock.api.mutateConfig.mock.lastCall![0]).toEqual([{ kind: 'set', path: ['setup_completed'], value: true }]);
});
- it('keeps the journey put while a deferred repair is unsettled, then completes on its own settlement', async () => {
- directConnection('anthropic');
- const save = mock.api.updateVibeAgent.getMockImplementation()!;
- let releaseSave!: () => void;
- mock.api.updateVibeAgent.mockImplementation(async (name: string, patch: unknown) => {
- await new Promise<void>((resolve) => { releaseSave = resolve; });
- return save(name, patch);
- });
- fireEvent.click(await setup());
- const picker = await screen.findByRole('combobox', { name: en.onboarding.connection.modelSelect });
- await waitFor(() => expect(picker.hasAttribute('disabled')).toBe(false));
- fireEvent.click(picker);
- fireEvent.click(await screen.findByText('anthropic/selected-model', { exact: true }));
- fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.modelApply }));
- await waitFor(() => expect(mock.api.updateVibeAgent).toHaveBeenCalledOnce());
- fireEvent.click(backAction());
- expect(document.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen')).toBe('assistants');
- expect(screen.queryByTestId('destination')).toBeNull();
- expect(mock.api.mutateConfig).not.toHaveBeenCalled();
- await act(async () => { releaseSave(); });
- expect(await screen.findByTestId('destination')).toBeTruthy();
- });
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
+ // it from the start would hold the journey before it ever reached the third screen.
mock.api.getBackendConnection.mockImplementation(() => new Promise(() => {}));
- mount();
- fireEvent.click(await screen.findByRole('button', { name: 'Get started' }));
+ fireEvent.click(primaryAction());
await screen.findByRole('button', { name: 'Enter workspace' });
expect(primaryAction().hasAttribute('disabled')).toBe(true);
expect(backAction().hasAttribute('disabled')).toBe(false);
fireEvent.click(backAction());
- await waitFor(() => expect(document.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen')).toBe('intro'));
+ await waitFor(() => expect(document.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen')).toBe('providers'));
+ });
+});
+
+// C2/D11: the journey is three screens, and the middle one is where the controller is
+// made answerable. These cases own that edge — when it happens, how often, and what a
+// failure leaves on screen — from the assembled Wizard rather than from the sequence
+// module, which cannot say anything about when a React tree calls it.
+describe('the registered journey', () => {
+ const screenId = () => document.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen');
+ const seeds = () => mock.apiFetch.mock.calls.filter(([, init]) => (init as RequestInit | undefined)?.method === 'POST');
+ const gateway = () => document.querySelector('.setup-gateway')!;
+
+ it('establishes the controller on arrival at the second screen, never on mount', async () => {
+ mount();
+ const start = await screen.findByRole('button', { name: 'Get started' });
+ // Nothing is seeded or started for somebody who has not asked to go anywhere yet.
+ expect(seeds()).toHaveLength(0);
+ expect(mock.models.getRuntimeStatus).not.toHaveBeenCalled();
+
+ fireEvent.click(start);
+ await waitFor(() => expect(screenId()).toBe('providers'));
+ await waitFor(() => expect(mock.models.getRuntimeStatus).toHaveBeenCalledOnce());
+ expect(seeds()).toHaveLength(1);
+ expect(seeds()[0][1]).toMatchObject({ method: 'POST', body: '{}' });
+ // The readback is the next call and is uncached: the seed cleared no projection,
+ // so a cached read here would describe the world before the write.
+ const seedIndex = mock.apiFetch.mock.calls.indexOf(seeds()[0]);
+ expect((mock.apiFetch.mock.calls[seedIndex + 1]?.[1] as RequestInit | undefined)?.cache).toBe('no-store');
+ expect(mock.api.getBackendConnection).toHaveBeenCalledWith('claude');
+ await waitFor(() => expect(primaryAction().textContent).toContain(en.onboarding.providers.actionContinue));
+ await waitFor(() => expect(primaryAction().hasAttribute('disabled')).toBe(false));
+ });
+
+ it('keeps the second screen on the way back without re-establishing anything', async () => {
+ await arriveAtProviders();
+ fireEvent.click(primaryAction());
+ const enter = await screen.findByRole('button', { name: 'Enter workspace' });
+ await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(false));
+
+ const sourcesBeforeReturn = mock.models.listSources.mock.calls.length;
+ const runtimeBeforeReturn = mock.models.getRuntimeStatus.mock.calls.length;
+ fireEvent.click(backAction());
+ await waitFor(() => expect(screenId()).toBe('providers'));
+ // Establishing once is not observing once: coming back must show the machine as
+ // it is now. What does not repeat is the write that made the controller answerable.
+ await waitFor(() => expect(primaryAction().textContent).toContain(en.onboarding.providers.actionContinue));
+ expect(seeds()).toHaveLength(1);
+ expect(mock.models.getRuntimeStatus.mock.calls.length).toBeGreaterThan(runtimeBeforeReturn);
+ expect(mock.models.listSources.mock.calls.length).toBeGreaterThan(sourcesBeforeReturn);
+ expect(mock.control).not.toHaveBeenCalled();
+ await waitFor(() => expect(primaryAction().hasAttribute('disabled')).toBe(false));
+
+ fireEvent.click(primaryAction());
+ await waitFor(() => expect(screenId()).toBe('assistants'));
+ expect(seeds()).toHaveLength(1);
+ const again = await screen.findByRole('button', { name: 'Enter workspace' });
+ await waitFor(() => expect(again.hasAttribute('disabled')).toBe(false));
+ fireEvent.click(again);
+ expect(await screen.findByTestId('destination')).toBeTruthy();
+ });
+
+ it('makes current source supply usable once its own controller bootstrap succeeds', async () => {
+ // Isolated against a real Wizard: the first supply read can fail while the
+ // controller is still stopped, and after D11 brings IPC up the screen has to
+ // take one current read — not stay on Retry for a world that no longer exists.
+ running = false;
+ const observedRunning: boolean[] = [];
+ mock.models.listSources.mockImplementation(async () => {
+ observedRunning.push(running);
+ if (!running) throw new Error('controller unavailable');
+ return [HUB_SOURCE];
+ });
+ mount();
+ fireEvent.click(await screen.findByRole('button', { name: 'Get started' }));
+ await waitFor(() => expect(mock.models.getRuntimeStatus).toHaveBeenCalled());
+ expect(running).toBe(true);
+ await waitFor(() => expect(primaryAction().textContent).toContain(en.onboarding.providers.actionContinue));
+ expect(observedRunning).toContain(true);
+ expect(primaryAction().hasAttribute('disabled')).toBe(false);
+ });
+
+ it('holds the journey on a failed establishment, and its own Retry gives it back', async () => {
+ mock.models.getRuntimeStatus.mockRejectedValueOnce(new Error('runtime unreadable'));
+ mount();
+ fireEvent.click(await screen.findByRole('button', { name: 'Get started' }));
+ await waitFor(() => expect(gateway().getAttribute('data-state')).toBe('failed'));
+ // The shell's read failed, not an attempt this screen made — so the card names no
+ // step, and the one Retry on screen is the card's rather than the footer's.
+ expect(gateway().hasAttribute('data-failed-step')).toBe(false);
+ expect(flowError()).toBeNull();
+ expect(primaryAction().textContent).toContain(en.onboarding.providers.actionContinue);
+ expect(primaryAction().hasAttribute('disabled')).toBe(true);
+ const retry = gateway().querySelector('.setup-gateway-retry') as HTMLButtonElement;
+ expect(retry.textContent).toContain(en.common.retry);
+ expect(screenId()).toBe('providers');
+ expectNoForwardWrite();
+
+ // An explicit retry is the one thing that may seed again: the first attempt's write
+ // was acknowledged, and only a person asking re-runs the sequence that made it.
+ fireEvent.click(retry);
+ await waitFor(() => expect(gateway().getAttribute('data-state')).toBe('running'));
+ expect(seeds()).toHaveLength(2);
+ await waitFor(() => expect(primaryAction().hasAttribute('disabled')).toBe(false));
+ fireEvent.click(primaryAction());
+ const enter = await screen.findByRole('button', { name: 'Enter workspace' });
+ await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(false));
+ fireEvent.click(enter);
+ 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/entryGate.test.ts b/ui/src/components/onboarding/entryGate.test.ts
new file mode 100644
index 000000000..7901d6896
--- /dev/null
+++ b/ui/src/components/onboarding/entryGate.test.ts
@@ -0,0 +1,177 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { BackendConnectionState, VibeAgentBrief } from '../../context/ApiContext';
+import { CONTRACT_VERSION, type AgentSupply, type RuntimeDependency } from '../settings/models/types';
+import {
+ admitEntry,
+ configuredCliPath,
+ entryCandidates,
+ readEntryEvidence,
+ type EntryEvidence,
+ type EntryGateDeps,
+} from './entryGate';
+import type { AssistantId } from './collaborationTimeline';
+
+const RUNTIME_OK: RuntimeDependency = {
+ contract_version: CONTRACT_VERSION,
+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },
+ status: { verified: true, health: 'ok' },
+};
+
+const CLAUDE: VibeAgentBrief = {
+ id: 'cl-1', name: 'claude-agent', backend: 'claude', display_name: 'claude-agent',
+ description: null, model: null, reasoning_effort: null, enabled: true, archived: false,
+ archived_at: null, source: 'file', updated_at: '',
+};
+
+const claudeSupply = (overrides: Partial<AgentSupply> = {}): AgentSupply => ({
+ backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed',
+ named_agents: [{ name: 'claude-agent', effective_model_id: 'openai/gpt-5.6-sol', supply_status: 'ok' }],
+ ...overrides,
+});
+
+const connection = (
+ backend: AssistantId,
+ overrides: Partial<BackendConnectionState> = {},
+): BackendConnectionState => ({
+ ok: true, backend, enabled: true, installed: true, auth: 'none', ready: false,
+ entry_eligible: false, application: 'stopped', ...overrides,
+});
+
+const evidence = (overrides: Partial<EntryEvidence> = {}): EntryEvidence => ({
+ agentsRead: true,
+ agents: [CLAUDE],
+ defaultAgentName: null,
+ targets: [],
+ connections: [connection('claude', { ready: true, entry_eligible: true, application: 'applied' })],
+ suppliesRead: true,
+ supplies: [claudeSupply()],
+ runtime: RUNTIME_OK,
+ cliFound: { claude: true, codex: false, opencode: false },
+ ...overrides,
+});
+
+const ipcDown = () => Promise.reject(new Error('engine_down: controller socket absent'));
+
+const deps = (overrides: Partial<EntryGateDeps> = {}): EntryGateDeps => ({
+ agentReads: { refresh: vi.fn(async () => ({ kind: 'current' as const, value: [claudeSupply()] })), read: vi.fn(), readValue: vi.fn(), invalidate: vi.fn() },
+ getRuntimeStatus: vi.fn(async () => RUNTIME_OK),
+ getBackendConnection: vi.fn(async (backend) => connection(backend, { application: 'applied', ready: true, entry_eligible: true })),
+ listAgents: vi.fn(async () => ({ ok: true, agents: [CLAUDE], default_agent_name: null })),
+ getVibeAgent: vi.fn(async () => ({ ok: false, agent: null as never, default_agent_name: null })),
+ detectCli: vi.fn(async (binary: string) => ({ found: true, path: binary })),
+ ...overrides,
+});
+
+describe('B2 stopped recovery independent of IPC', () => {
+ it('retains a confirmed stopped controller recovery when IPC supply is unavailable', async () => {
+ const gate = deps({
+ agentReads: { refresh: vi.fn(ipcDown), read: vi.fn(), readValue: vi.fn(), invalidate: vi.fn() },
+ getRuntimeStatus: vi.fn(ipcDown),
+ getBackendConnection: vi.fn(async (backend) => connection(backend, {
+ enabled: true, installed: true, ready: false, entry_eligible: true, application: 'stopped',
+ })),
+ listAgents: vi.fn(async () => ({ ok: true, agents: [], default_agent_name: null })),
+ });
+ const read = await readEntryEvidence(gate);
+ expect(read).not.toBeNull();
+ expect(read!.suppliesRead).toBe(false);
+ expect(read!.runtime).toBeNull();
+ expect(read!.connections).toHaveLength(3);
+ expect(admitEntry(read!)).toMatchObject({ kind: 'refused', startable: true });
+ expect(entryCandidates(read!)).toEqual([]);
+ });
+
+ it('is startable without entry_eligible or any listed assistant', async () => {
+ const gate = deps({
+ agentReads: { refresh: vi.fn(ipcDown), read: vi.fn(), readValue: vi.fn(), invalidate: vi.fn() },
+ getRuntimeStatus: vi.fn(ipcDown),
+ getBackendConnection: vi.fn(async (backend) => connection(backend, {
+ ready: false, entry_eligible: false, application: 'stopped',
+ })),
+ listAgents: vi.fn(async () => ({ ok: true, agents: [], default_agent_name: null })),
+ });
+ const read = await readEntryEvidence(gate);
+ expect(admitEntry(read!)).toMatchObject({ kind: 'refused', startable: true });
+ });
+
+ it.each(['unknown', 'failed', 'draining'] as const)('does not treat %s as start permission', async (application) => {
+ const gate = deps({
+ agentReads: { refresh: vi.fn(ipcDown), read: vi.fn(), readValue: vi.fn(), invalidate: vi.fn() },
+ getRuntimeStatus: vi.fn(ipcDown),
+ getBackendConnection: vi.fn(async (backend) => connection(backend, {
+ ready: false, entry_eligible: true, application,
+ })),
+ });
+ const read = await readEntryEvidence(gate);
+ expect(admitEntry(read!)).toMatchObject({ kind: 'refused', startable: false });
+ });
+
+ it('does not admit unread supply even when connections look applied', () => {
+ expect(admitEntry(evidence({ suppliesRead: false, supplies: [] }))).toMatchObject({
+ kind: 'refused', startable: false,
+ });
+ expect(admitEntry(evidence({ runtime: null }))).toMatchObject({ kind: 'refused', startable: false });
+ });
+
+ it('holds when the shared refresh is stale', async () => {
+ const gate = deps({
+ agentReads: { refresh: vi.fn(async () => ({ kind: 'stale' as const })), read: vi.fn(), readValue: vi.fn(), invalidate: vi.fn() },
+ });
+ expect(await readEntryEvidence(gate)).toBeNull();
+ });
+});
+
+describe('C4 configured-path CLI evidence', () => {
+ it('reads a persisted cli_path and falls back to the backend name', () => {
+ expect(configuredCliPath({ agents: { claude: { cli_path: '/opt/custom/claude' } } }, 'claude')).toBe('/opt/custom/claude');
+ expect(configuredCliPath({ agents: { claude: { cli_path: ' /x ' } } }, 'claude')).toBe('/x');
+ expect(configuredCliPath({ agents: { claude: { enabled: true } } }, 'claude')).toBe('claude');
+ expect(configuredCliPath(undefined, 'codex')).toBe('codex');
+ });
+
+ it('detects the configured path from the already-fresh prerequisite', async () => {
+ const detectCli = vi.fn(async (binary: string) => ({ found: binary === '/opt/custom/claude', path: binary }));
+ const gate = deps({ detectCli });
+ const read = await readEntryEvidence(gate, {
+ config: { agents: { claude: { enabled: true, cli_path: '/opt/custom/claude' }, codex: { enabled: true } } },
+ });
+ expect(detectCli).toHaveBeenCalledWith('/opt/custom/claude');
+ expect(detectCli).toHaveBeenCalledWith('codex');
+ expect(detectCli).toHaveBeenCalledWith('opencode');
+ expect(read!.cliFound).toEqual({ claude: true, codex: false, opencode: false });
+ });
+
+ it('does not admit when detectCli is not found even if installed and cli_present', () => {
+ const read = evidence({
+ connections: [connection('claude', { installed: true, ready: true, entry_eligible: true, application: 'applied' })],
+ cliFound: { claude: false, codex: false, opencode: false },
+ });
+ expect(entryCandidates(read)).toEqual([]);
+ expect(admitEntry(read)).toMatchObject({ kind: 'refused', startable: false });
+ });
+
+ it('does not admit when detectCli throws', async () => {
+ const gate = deps({
+ detectCli: vi.fn(async () => { throw new Error('detector unread'); }),
+ });
+ const read = await readEntryEvidence(gate);
+ expect(read!.cliFound).toEqual({ claude: false, codex: false, opencode: false });
+ expect(admitEntry(read!)).toMatchObject({ kind: 'refused', startable: false });
+ });
+
+ it('does not treat connection.installed as the detector', () => {
+ const read = evidence({
+ connections: [connection('claude', { installed: false, ready: true, entry_eligible: true, application: 'applied' })],
+ cliFound: { claude: true, codex: false, opencode: false },
+ });
+ expect(entryCandidates(read)).toEqual([{ agent: CLAUDE, backend: 'claude', modelId: 'openai/gpt-5.6-sol' }]);
+ });
+
+ it('cannot release entry on a stale refresh even with a found CLI', async () => {
+ const gate = deps({
+ agentReads: { refresh: vi.fn(async () => ({ kind: 'stale' as const })), read: vi.fn(), readValue: vi.fn(), invalidate: vi.fn() },
+ detectCli: vi.fn(async () => ({ found: true, path: '/opt/custom/claude' })),
+ });
+ expect(await readEntryEvidence(gate, { config: { agents: { claude: { cli_path: '/opt/custom/claude' } } } })).toBeNull();
+ });
+});
diff --git a/ui/src/components/onboarding/entryGate.ts b/ui/src/components/onboarding/entryGate.ts
new file mode 100644
index 000000000..f3ebfd8cf
--- /dev/null
+++ b/ui/src/components/onboarding/entryGate.ts
@@ -0,0 +1,268 @@
+import type { BackendConnectionState, VibeAgentBrief, VibeAgentFull } from '../../context/ApiContext';
+import type { CollectionReadAuthority } from '../settings/models/collectionReadAuthority';
+import { runtimeIsRunning } from '../settings/models/runtimeLifecycle';
+import type { AgentSupply, RuntimeDependency, SupplyStatus } from '../settings/models/types';
+import { ASSISTANT_ORDER, type AssistantId } from './collaborationTimeline';
+import { readSetupTargets } from './setupTargets';
+
+/**
+ * C4 — the gate setup's last click has to pass.
+ *
+ * The rule this file exists for: **one assistant must satisfy the whole gate.** Three
+ * independent existential checks can each be met by a different object — an enabled
+ * Codex with no route, a route persisted against an uninstalled Claude, a healthy
+ * source neither of them uses — and setup would finish on a machine whose first
+ * workspace turn cannot run. So every condition below is joined to the same candidate,
+ * by backend AND by Agent name, and every one of them is read from the server.
+ *
+ * Kept stateless and separate from the Wizard for the same reason `gatewayBootstrap`
+ * is: the interesting part is a decision over evidence, and a decision over evidence
+ * can be stated as data and tested without a React tree.
+ */
+
+/** One named Agent that satisfies the gate, with the model the server resolved for it. */
+export type EntryCandidate = {
+ agent: VibeAgentBrief;
+ backend: AssistantId;
+ modelId: string;
+};
+
+export type EntryEvidence = {
+ /** False when the Agent listing itself failed. An empty list and an unread list are
+ * different facts, and only one of them is something the person can act on. */
+ agentsRead: boolean;
+ agents: readonly VibeAgentBrief[];
+ defaultAgentName: string | null;
+ /** Designated builtins from uncached full-Agent metadata; empty when none can be proved. */
+ targets: readonly VibeAgentBrief[];
+ connections: readonly BackendConnectionState[];
+ /** False when the shared collection refresh threw; empty supplies then mean unread, not none. */
+ suppliesRead: boolean;
+ supplies: readonly AgentSupply[];
+ /** Null when the Hub runtime read threw or did not answer. Unread is not "running". */
+ runtime: RuntimeDependency | null;
+ /** Per-backend `detectCli(configured path)` result. Missing keys are not found. */
+ cliFound: Readonly<Record<AssistantId, boolean>>;
+};
+
+/**
+ * Why nothing was admitted, named as the sentence the person is owed.
+ *
+ * Each value is an existing `onboarding.connection.*` key, and each keeps the
+ * situation it already described: nothing eligible at all, a machine that has not
+ * applied its configuration yet, and — now also covering the route join — a machine
+ * that is up but has no assistant that could actually run a turn.
+ */
+export type EntryRefusal = 'entryFailed' | 'applyPending' | 'modelUnavailable';
+
+export type EntryAdmission =
+ | { kind: 'admitted'; candidates: EntryCandidate[] }
+ | { kind: 'refused'; reason: EntryRefusal; startable: boolean };
+
+/** A configured route whose sources are all unusable is not a runnable route. */
+const RUNNABLE_SUPPLY: ReadonlySet<SupplyStatus> = new Set<SupplyStatus>(['ok', 'degraded']);
+
+const usableAgent = (agent: VibeAgentBrief): boolean => agent.enabled && !agent.archived;
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+/**
+ * The configured CLI path the gate must detect, from the already-fresh prerequisite.
+ *
+ * A persisted `agents.<backend>.cli_path` wins. When none is configured, the existing
+ * detect path falls back to the backend name — the same default AgentDetection uses.
+ */
+export function configuredCliPath(config: Record<string, unknown> | undefined, backend: AssistantId): string {
+ const agents = config && isRecord(config.agents) ? config.agents : undefined;
+ const row = agents && isRecord(agents[backend]) ? agents[backend] : undefined;
+ if (row && typeof row.cli_path === 'string' && row.cli_path.trim()) return row.cli_path.trim();
+ return backend;
+}
+
+/**
+ * Whether this candidate's assistant is enabled, applied, in custody, and actually on disk.
+ *
+ * Installed is not `connection.installed`. C4 asks for `detectCli(configured path)`
+ * and a current-generation `refresh()` whose `cli_present` agrees, plus
+ * `getBackendConnection.enabled`. A failed detector, a not-found binary, or a stale
+ * refresh cannot be replaced by the connection's own installed bit.
+ *
+ * `ready` carries permission and credential ownership; `applied` is the only
+ * application state that means the configuration is live. A confirmed `stopped` is
+ * something to recover from, never something to enter on.
+ */
+const backendUsable = (
+ connection: BackendConnectionState | undefined,
+ supply: AgentSupply | undefined,
+ cliFound: boolean,
+): boolean =>
+ connection !== undefined && connection.ok
+ && connection.enabled
+ && connection.ready && connection.application === 'applied'
+ && supply !== undefined && supply.cli_present === true
+ && cliFound;
+
+/**
+ * Whether the server can route THIS named Agent to a model right now.
+ *
+ * Deliberately not `selected_model_id`: that is the backend-level pick belonging to
+ * `selected_by_agent`, so reading it would let one Agent's configuration speak for
+ * another's. The runnable-hop owner is the server resolver, and its per-Agent answer
+ * is the `named_agents` row — an absent row is a backend that never routed this name.
+ */
+const routeRunnable = (supply: AgentSupply | undefined, name: string): string | null => {
+ if (!supply || supply.mode !== 'hub') return null;
+ const row = supply.named_agents?.find((named) => named.name === name);
+ if (!row || row.route_reason === 'route_unconfigured') return null;
+ if (!row.effective_model_id || !row.supply_status || !RUNNABLE_SUPPLY.has(row.supply_status)) return null;
+ return row.effective_model_id;
+};
+
+/** Every Agent that passes the whole gate, in C6's backend order and then by name. */
+export function entryCandidates(evidence: EntryEvidence): EntryCandidate[] {
+ // Mode alone is not runtime readiness: a backend can be in hub mode while the Hub
+ // that would serve it is down, and then no route on this machine is runnable.
+ // An unread runtime is the same: we did not observe it, so we may not admit on it.
+ if (!evidence.runtime || !runtimeIsRunning(evidence.runtime) || !evidence.suppliesRead) return [];
+ const connectionOf = new Map(evidence.connections.map((connection) => [connection.backend, connection]));
+ const supplyOf = new Map(evidence.supplies.map((supply) => [supply.backend, supply]));
+ return ASSISTANT_ORDER.flatMap((backend) => {
+ if (!backendUsable(connectionOf.get(backend), supplyOf.get(backend), evidence.cliFound[backend] === true)) return [];
+ return evidence.agents
+ .filter((agent) => agent.backend === backend && usableAgent(agent))
+ .flatMap((agent) => {
+ const modelId = routeRunnable(supplyOf.get(backend), agent.name);
+ return modelId ? [{ agent, backend, modelId }] : [];
+ })
+ .sort((left, right) => (left.agent.name < right.agent.name ? -1 : left.agent.name > right.agent.name ? 1 : 0));
+ });
+}
+
+/**
+ * Whether a refusal is one an explicit start may still resolve.
+ *
+ * Only a connection the server confirmed `stopped` counts. Pending, draining, failed
+ * and unknown are not confirmations, and a browser may not turn "I could not tell"
+ * into a request to start something. Startup itself has no assistant, source, or
+ * `entry_eligible` prerequisite — those belong to the gate after recovery.
+ */
+const startable = (connections: readonly BackendConnectionState[]): boolean =>
+ !connections.some((connection) => connection.ready)
+ && connections.some((connection) => connection.ok && connection.application === 'stopped');
+
+export function admitEntry(evidence: EntryEvidence): EntryAdmission {
+ const candidates = entryCandidates(evidence);
+ if (candidates.length) return { kind: 'admitted', candidates };
+ const connections = evidence.connections.filter((connection) => connection.ok);
+ const reason: EntryRefusal = !evidence.agentsRead || !connections.some((connection) => connection.entry_eligible)
+ ? 'entryFailed'
+ : !connections.some((connection) => connection.ready)
+ ? 'applyPending'
+ // The machine is up and in custody, so what is missing is the run itself: no
+ // enabled Agent to run, or none the Hub can route to a model.
+ : 'modelUnavailable';
+ return { kind: 'refused', reason, startable: startable(connections) };
+}
+
+/**
+ * The Agent setup should enter on, or `null` when the saved default already serves.
+ *
+ * A default someone chose is preserved whenever it still works, including a custom
+ * Agent no card represents — setup is finishing a machine, not imposing its own
+ * preference on one. Only when the saved name cannot run does setup pick, and then it
+ * prefers the assistant's own Agent so the first workspace turn matches the card the
+ * person was just looking at.
+ */
+export function chooseEntryDefault(
+ candidates: readonly EntryCandidate[],
+ evidence: EntryEvidence,
+): EntryCandidate | null {
+ if (candidates.some((candidate) => candidate.agent.name === evidence.defaultAgentName)) return null;
+ const targets = evidence.targets.map((target) => target.name);
+ return candidates.find((candidate) => targets.includes(candidate.agent.name)) ?? candidates[0] ?? null;
+}
+
+export type EntryGateDeps = {
+ listAgents: () => Promise<{ ok: boolean; agents: VibeAgentBrief[]; default_agent_name: string | null }>;
+ getBackendConnection: (backend: AssistantId) => Promise<BackendConnectionState>;
+ agentReads: CollectionReadAuthority<AgentSupply[]>;
+ getRuntimeStatus: () => Promise<RuntimeDependency>;
+ getVibeAgent: (
+ name: string,
+ params?: { cache?: boolean },
+ ) => Promise<{ ok: boolean; agent: VibeAgentFull; default_agent_name: string | null }>;
+ detectCli: (binary: string) => Promise<{ found?: boolean; path?: string }>;
+};
+
+export type EntryReadOptions = {
+ /** Already-fresh prerequisite body, used only for configured CLI paths. */
+ config?: Record<string, unknown>;
+};
+
+const asSettled = <T>(promise: Promise<T>): Promise<PromiseSettledResult<T>> =>
+ promise.then(
+ (value): PromiseSettledResult<T> => ({ status: 'fulfilled', value }),
+ (reason): PromiseSettledResult<T> => ({ status: 'rejected', reason }),
+ );
+
+const noneFound = (): Record<AssistantId, boolean> =>
+ Object.fromEntries(ASSISTANT_ORDER.map((backend) => [backend, false])) as Record<AssistantId, boolean>;
+
+/**
+ * One round of the fresh reads the gate judges, or `null` when it cannot judge.
+ *
+ * `null` is the superseded supply read: a newer generation of the shared authority is
+ * already in flight, so the list this round would have used is not the current answer
+ * and holding is the only honest thing to do. It is not a failure — nothing is written
+ * and nothing is claimed — and the next click reads again.
+ *
+ * Hub IPC (`refresh`, `getRuntimeStatus`) is settled independently of application-state
+ * evidence. A confirmed `stopped` connection must still reach recovery when those reads
+ * throw `engine_down`. Unread supply or runtime is not an admitted machine: the
+ * correlated gate still has to pass on a later current read.
+ *
+ * A connection that throws is dropped rather than fatal: one unreachable backend is a
+ * backend that cannot be entered on, not a verdict about the other two.
+ */
+export async function readEntryEvidence(
+ deps: EntryGateDeps,
+ options: EntryReadOptions = {},
+): Promise<EntryEvidence | null> {
+ const [supplyOutcome, runtimeOutcome, connectionResults, agentsOutcome, cliResults] = await Promise.all([
+ asSettled(deps.agentReads.refresh()),
+ asSettled(deps.getRuntimeStatus()),
+ Promise.allSettled(ASSISTANT_ORDER.map((backend) => deps.getBackendConnection(backend))),
+ asSettled(deps.listAgents()),
+ Promise.allSettled(ASSISTANT_ORDER.map(async (backend) => {
+ const path = configuredCliPath(options.config, backend);
+ const detected = await deps.detectCli(path);
+ return { backend, found: detected?.found === true };
+ })),
+ ]);
+ if (supplyOutcome.status === 'fulfilled' && supplyOutcome.value.kind === 'stale') return null;
+ const supplies = supplyOutcome.status === 'fulfilled' && supplyOutcome.value.kind === 'current'
+ ? supplyOutcome.value.value
+ : null;
+ const agents = agentsOutcome.status === 'fulfilled'
+ ? agentsOutcome.value
+ : { ok: false, agents: [] as VibeAgentBrief[], default_agent_name: null };
+ const listed = agents.ok ? agents.agents : [];
+ const targets = agents.ok ? await readSetupTargets(listed, deps) : [];
+ const cliFound = noneFound();
+ for (const result of cliResults) {
+ if (result.status === 'fulfilled') cliFound[result.value.backend] = result.value.found;
+ }
+ return {
+ agentsRead: agents.ok,
+ agents: listed,
+ defaultAgentName: agents.default_agent_name,
+ targets,
+ connections: connectionResults.flatMap((result) =>
+ result.status === 'fulfilled' && result.value.ok ? [result.value] : []),
+ suppliesRead: supplies !== null,
+ supplies: supplies ?? [],
+ runtime: runtimeOutcome.status === 'fulfilled' ? runtimeOutcome.value : null,
+ cliFound,
+ };
+}
diff --git a/ui/src/components/onboarding/opencodeSetupRoutes.ts b/ui/src/components/onboarding/opencodeSetupRoutes.ts
deleted file mode 100644
index b0cdbee16..000000000
--- a/ui/src/components/onboarding/opencodeSetupRoutes.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { ApiContextType } from '@/context/ApiContext';
-import { modelsApi } from '../settings/models/modelsApi';
-import { modelHubEnabledFromConfig } from '../settings/models/featureFlags';
-import { catalogModelIds } from '../settings/models/backendCatalog';
-
-/** Routing eligibility is separate from backend credential/application readiness. */
-export async function readOpencodeSetupRoutes(api: ApiContextType) {
- const config = await api.getConfig();
- if (modelHubEnabledFromConfig(config)) {
- // Unlike a best-effort picker read, an unreadable active supply cannot
- // silently become Direct mode during explicit setup completion.
- const supply = await modelsApi.getAgentSources('opencode');
- if (supply.mode === 'hub') {
- const catalog = new Set(catalogModelIds(supply));
- const supplied = new Set(supply.model_supply?.filter((row) => row.has_runnable_hop).map((row) => row.model_id));
- return { mode: 'hub' as const, accepts: (model: string | null) => Boolean(model && catalog.has(model) && supplied.has(model)) };
- }
- }
- const result = await api.getOpencodeProviders();
- if (!result.ok) throw new Error(result.message);
- const connected = new Map(result.providers?.filter((provider) => provider.active_auth_type === 'api' || provider.active_auth_type === 'oauth').map((provider) => [provider.id, new Set(provider.models || [])]));
- return {
- mode: 'direct' as const,
- accepts: (model: string | null) => {
- if (!model) return false;
- const slash = model.indexOf('/');
- const provider = slash >= 0 ? model.slice(0, slash) : result.default_provider;
- const modelId = slash < 0 ? model : model.slice(slash + 1);
- return Boolean(provider && modelId && connected.get(provider)?.has(modelId));
- },
- };
-}
diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx
index 88ac1a66f..c0be4f0b0 100644
--- a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx
+++ b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx
@@ -21,6 +21,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import {
beginRegionRead,
+ loadingRegion,
readyRegion,
unreadRegion,
type RegionRead,
@@ -250,6 +251,9 @@ const Harness: React.FC<ScreenOptions & { handle: React.RefObject<SetupScreenHan
const [flowState, setFlowState] = React.useState<SetupFlowState>({ ...INITIAL_SETUP_FLOW_STATE, ...flow });
return (
<I18nextProvider i18n={i18n}>
+ {/* The shell's half of the anchor, not decoration: what is ancillary to the
+ pair is portaled into this slot, so a host without it sees none of it. */}
+ <div className="onboarding-step">
<ProvidersScreen
ref={handle}
active={active}
@@ -263,6 +267,8 @@ const Harness: React.FC<ScreenOptions & { handle: React.RefObject<SetupScreenHan
onActionChange={(action) => { actions.push(action); }}
onNavigate={(screen) => { navigated.push(screen); }}
/>
+ <div className="onboarding-action-aside" data-setup-action-aside="" />
+ </div>
</I18nextProvider>
);
};
@@ -525,6 +531,35 @@ describe('ProvidersScreen — the stage', () => {
expect(modelsApi.startRuntime).not.toHaveBeenCalled();
});
+ it('re-reads supply for a new observation, and not for the same one re-reported', async () => {
+ // The shell owns the runtime region and hands one down on every render it makes.
+ // What this screen takes its inventory against is the machine that answers it, not
+ // the object that described the machine — a refresh that confirmed nothing changed,
+ // or a parent that rebuilt its props, is the same observation said twice. Reading
+ // again for one of those does not merely waste a request: every answer publishes
+ // selection state, which is another render, which is another carrier.
+ serve();
+ const { show } = renderScreen({ runtimeRead: readyRegion(runtimeOf('ok')) });
+ await settled();
+ expect(modelsApi.scanMigration).toHaveBeenCalledTimes(1);
+
+ await show({ runtimeRead: readyRegion(runtimeOf('ok')) });
+ expect(modelsApi.scanMigration).toHaveBeenCalledTimes(1);
+
+ // A genuinely different machine is the other half, and the half that matters: the
+ // engine that could not answer the first read is why it failed, and the sequence
+ // that fixes one publishes into the shell's region rather than into this screen.
+ await show({
+ runtimeRead: readyRegion(runtimeOf('ok', {
+ status: { verified: true, health: 'ok', installed_version: '2.0.0' },
+ })),
+ });
+ await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalledTimes(2));
+ // A read is all it is. Nothing here authorizes a mutation of the engine.
+ expect(modelsApi.installRuntime).not.toHaveBeenCalled();
+ expect(modelsApi.startRuntime).not.toHaveBeenCalled();
+ });
+
it('keeps the sources that did arrive when the scan beside them fails', async () => {
// Two reads, two questions. A scan that fails says nothing about the sources,
// and throwing away a list that did arrive would report providers that exist as
@@ -840,6 +875,104 @@ describe('ProvidersScreen — the action the shell renders', () => {
// lost behind a navigation.
expect(navigated).toEqual([]);
});
+
+ // The invariant rather than the symptom: the shell draws the action this screen
+ // published, and a press is made against the one drawn. So an action that became
+ // pressable may only stop being pressable because something new arrived — someone
+ // asking for a read again, a write going out, an engine going down. A retraction
+ // nobody caused is a press that reaches nothing: `activate` sees the state the
+ // screen is really in and drops it, and the person is given no reason to press a
+ // second time.
+ //
+ // Judged over the published SEQUENCE, not over a rendered frame, because the frame
+ // a retraction leaves behind is identical to the settled one — the action comes
+ // back to exactly what it was a commit later. Only the order the shell was told
+ // about tells the two apart.
+ it('never takes a pressable action back on its own once a new observation lands', async () => {
+ serve({ sources: [source({ id: 'src_zhipu', vendor: 'zhipu' })] });
+ // Arriving before the runtime read has landed is the ordinary way in: the supply
+ // read answers first, so the action already names the way on while the engine is
+ // still unknown — stated, and not yet pressable.
+ const { show } = renderScreen({ runtimeRead: loadingRegion<RuntimeDependency>() });
+ await settled();
+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));
+ expect(lastAction().disabled).toBe(true);
+
+ // The only new input in this case, and the last one: the engine is observed
+ // serving. It admits the press AND is a new observation for the supply read, which
+ // is exactly why the retraction it used to cause was invisible — the same input
+ // produced both halves.
+ await show({ runtimeRead: readyRegion(runtimeOf('ok')) });
+ await waitFor(() => expect(lastAction().disabled).toBe(false));
+ // The refresh that observation starts has to have been made and settled before the
+ // sequence means anything; otherwise this passes on a read that never happened.
+ await waitFor(() => expect(modelsApi.listSources).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(cards()[0].dataset.state).toBe('connected'));
+
+ const pressable = actions.findIndex((action) => !action.disabled && !action.busy);
+ expect(pressable).toBeGreaterThanOrEqual(0);
+ expect(actions.slice(pressable).every((action) => !action.disabled && !action.busy)).toBe(true);
+ });
+});
+
+describe('ProvidersScreen — the way on when nothing is connected', () => {
+ it('states a way on beside the take-over it found, and only navigates', async () => {
+ serve({ scan: [CLAUDE_KEY] });
+ renderScreen();
+ await settled();
+
+ // The take-over keeps the footer: whoever came here to connect something is
+ // still offered the thing they came for. The way on is beside it, not instead.
+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionImport'));
+ const onward = screen.getByRole('button', { name: 'Continue to assistants' });
+ expect((onward as HTMLButtonElement).disabled).toBe(false);
+
+ await userEvent.setup().click(onward);
+
+ // Navigating is the whole action. Nothing was added, taken over or installed
+ // on the way out, and the review that was on offer is still only on offer.
+ expect(navigated).toEqual(['assistants']);
+ expect(server.sources).toEqual([]);
+ expect(modelsApi.applyMigration).not.toHaveBeenCalled();
+ expect(modelsApi.installRuntime).not.toHaveBeenCalled();
+ expect(modelsApi.startRuntime).not.toHaveBeenCalled();
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
+ it('leaves the single action alone once a source is really there', async () => {
+ serve({ sources: [source({ id: 'src_zhipu', vendor: 'zhipu' })] });
+ renderScreen();
+ await settled();
+
+ await waitFor(() => expect(lastAction().labelKey).toBe('onboarding.providers.actionContinue'));
+ expect(screen.queryByRole('button', { name: 'Continue to assistants' })).toBeNull();
+ });
+
+ it('takes the way on back when the shell hides the screen, and returns it on re-entry', async () => {
+ serve();
+ const { show } = renderScreen();
+ await settled();
+ expect(screen.getByRole('button', { name: 'Continue to assistants' })).toBeTruthy();
+
+ // It leaves the screen root to reach the shell's slot, so nothing else would
+ // take it out of reach of a reader on the step after this one.
+ await show({ active: false });
+ expect(screen.queryByRole('button', { name: 'Continue to assistants' })).toBeNull();
+
+ await show({ active: true });
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Continue to assistants' })).toBeTruthy());
+ expect(navigated).toEqual([]);
+ });
+
+ it('says nothing about a way on while the inventory is unread, which is not an empty one', async () => {
+ serve();
+ vi.mocked(modelsApi.listSources).mockRejectedValue(new Error('offline'));
+ renderScreen();
+ await settled();
+
+ await waitFor(() => expect(lastAction().labelKey).toBe('common.retry'));
+ expect(screen.queryByRole('button', { name: 'Continue to assistants' })).toBeNull();
+ });
});
describe('ProvidersScreen — what an import leaves behind', () => {
diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.tsx
index 634b35bb4..79e88b991 100644
--- a/ui/src/components/onboarding/providers/ProvidersScreen.tsx
+++ b/ui/src/components/onboarding/providers/ProvidersScreen.tsx
@@ -15,22 +15,26 @@
// composition, and therefore is this file's: the engine has to be up whether or not
// there is an assistant to adopt.
import * as React from 'react';
+import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
+import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';
import { Button } from '@/components/ui/button';
import {
createAgentCollectionReadAuthority,
createSourceCollectionReadAuthority,
+ type CollectionReadAuthority,
} from '@/components/settings/models/collectionReadAuthority';
import { resumeGatewayAdoption, type GatewayAdoptionFailure } from '@/components/settings/models/gatewayAdoption';
import { MigrationDialog } from '@/components/settings/models/MigrationDialog';
import { isImportableKey } from '@/components/settings/models/migrationScan';
import { modelsApi, type SourceCreated } from '@/components/settings/models/modelsApi';
+import { foldRegionRead } from '@/components/settings/models/regionRead';
import {
installAndStartStep,
resumeInstallAndStartRuntime,
} from '@/components/settings/models/runtimeLifecycle';
-import type { AgentBackend, RuntimeDependency, Source } from '@/components/settings/models/types';
+import type { AgentBackend, AgentSupply, RuntimeDependency, Source } from '@/components/settings/models/types';
import { ImportKeysNotice } from '../ImportKeysNotice';
import { useOnboardingMotion } from '../motion';
@@ -123,6 +127,26 @@ const gatewayReadAnswered = (against: GatewayEvidence | null, now: GatewayEviden
|| against.capability !== now.capability)
&& gatewayEvidenceSettled(now);
+/**
+ * An observation as a VALUE, rather than as the object that carried it.
+ *
+ * What a supply read is taken against is the machine that will answer it, and these
+ * are the facts that decide whether it can: whether it is up, whether it is the
+ * runtime it claims to be, which build is installed, and whether one may exist on
+ * this host at all. A shell that hands down an equal read it rebuilt — a refresh
+ * that confirmed nothing changed, a parent that re-created its props — has observed
+ * nothing new, so taking the carrier's identity for the observation would restart
+ * the read on every render that produced one.
+ */
+const observationOf = (runtime: RuntimeDependency | null): string => (runtime === null
+ ? 'none'
+ : [
+ runtime.status.health,
+ runtime.status.verified,
+ runtime.status.installed_version ?? '',
+ 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 => {
@@ -133,7 +157,17 @@ const formatNames = (names: readonly string[], locale: string): string => {
}
};
-export const ProvidersScreen = React.forwardRef<SetupScreenHandle, SetupScreenProps>(
+/**
+ * C4 names one owner for every setup supply read, so the shell may hand this screen
+ * the authority it shares with the completion gate. Optional because a screen mounted
+ * on its own is still a screen: it then owns one for its own life, which is what the
+ * shipped behaviour already was.
+ */
+export type ProvidersScreenProps = SetupScreenProps & {
+ agentReads?: CollectionReadAuthority<AgentSupply[]>;
+};
+
+export const ProvidersScreen = React.forwardRef<SetupScreenHandle, ProvidersScreenProps>(
function ProvidersScreen({
active,
capability,
@@ -144,6 +178,7 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, SetupScreenPr
setFlowState,
onActionChange,
onNavigate,
+ agentReads: sharedAgentReads,
}, ref) {
const { t, i18n } = useTranslation();
const motion = useOnboardingMotion();
@@ -160,7 +195,8 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, SetupScreenPr
// One owner per collection, for the whole life of the screen: the add dialog
// settles an unknown write against the same generation this screen reads.
const [sourceReads] = React.useState(createSourceCollectionReadAuthority);
- const [agentReads] = React.useState(createAgentCollectionReadAuthority);
+ const [ownAgentReads] = React.useState(createAgentCollectionReadAuthority);
+ const agentReads = sharedAgentReads ?? ownAgentReads;
const [sources, setSources] = React.useState<Source[]>([]);
// Whether the list above is an answer. It starts as neither empty nor absent but
@@ -204,12 +240,57 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, SetupScreenPr
// also true for the rescan that follows an import, whose consent has just been
// spent on purpose and must not come back ticked.
const seededSelectionRef = React.useRef(false);
+ /**
+ * Which request the answer on screen belongs to, or `null` while none does.
+ *
+ * A read with no answer yet, and a retry someone asked for, both mean the screen
+ * is back to not knowing — that is what `reading` says and both have to say it. A
+ * refresh a NEW OBSERVATION started is neither: the inventory it describes has not
+ * been contradicted, so the answer in hand is still the best thing known about it,
+ * and retracting it would take the action away for exactly as long as that refresh
+ * runs. The same reason the shell holds a stale runtime region through a refresh
+ * rather than falling back to `loading`.
+ *
+ * The window that costs is not a matter of patience. The observation that starts
+ * the refresh is the same one that makes the action pressable — `hubAdmitted` needs
+ * the runtime read this screen is re-reading against — so the two land one commit
+ * apart: Continue turns pressable, and the effect that runs straight after takes it
+ * back. A press that arrives in between reaches `activate` with the screen already
+ * 「checking」 and is dropped, and nothing re-issues it. Holding the answer through
+ * the refresh is what stops that commit from existing, rather than narrowing it.
+ */
+ const answeredRef = React.useRef<number | null>(null);
+ /**
+ * The runtime observation this screen's supply read is taken against.
+ *
+ * A supply read is answered by the controller, and D11 is what makes the controller
+ * answerable. On a machine whose controller was merely stopped, the read taken on
+ * arrival can fail for that reason alone — and nothing would ever come back for it,
+ * because the sequence that fixes it publishes into the shell's runtime region, not
+ * into this screen. The observation is therefore part of what the read is taken
+ * against: one current read per observation. It adds no owner, no timer and no
+ * second bootstrap, and a read that fails AFTER establishment is still the explicit
+ * Retry it always was, because nothing new has been observed since.
+ *
+ * Held as the observation's own value — see `observationOf` — so it changes when a
+ * genuinely new one lands and not when the shell merely re-reports the one already
+ * standing. That is also how coming back to this screen brings current server facts
+ * rather than the ones it left behind.
+ */
+ const observation = observationOf(foldRegionRead(runtimeRead, {
+ loading: () => null,
+ ready: (runtime) => runtime,
+ unread: () => null,
+ degraded: (stale) => stale,
+ }));
React.useEffect(() => {
if (!active || !ready) return;
let cancelled = false;
- // A re-read is a read: while it is in flight the screen is back to not knowing,
- // which is what a retry means and what the action should say.
- setSourceRead('reading');
+ // A read with no answer behind it is a read: while it is in flight the screen is
+ // back to not knowing, which is what a retry means and what the action should
+ // say. A refresh of an answer this screen already holds is not — see
+ // `answeredRef`.
+ if (answeredRef.current !== supplyToken) setSourceRead('reading');
void (async () => {
// Settled independently, because they answer different questions. A scan that
// fails says nothing about the sources, and discarding a source list that did
@@ -222,10 +303,15 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, SetupScreenPr
if (cancelled) return;
// A stale source read is neither an answer nor a failure: a newer generation
// superseded it, and that newer one is what will settle this.
- if (read.status === 'rejected') setSourceRead('unreadable');
- else if (read.value.kind === 'current') {
+ if (read.status === 'rejected') {
+ // Nothing is held now, so the next refresh is a read with no answer behind
+ // it again and says so.
+ answeredRef.current = null;
+ setSourceRead('unreadable');
+ } else if (read.value.kind === 'current') {
setSources(read.value.value);
setSourceRead('read');
+ answeredRef.current = supplyToken;
}
// Either failure is still a failure for the sentence: what the screen cannot
// report is exactly what it and its retry exist to say.
@@ -252,7 +338,7 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, SetupScreenPr
seededSelectionRef.current = true;
})();
return () => { cancelled = true; };
- }, [active, ready, supplyToken, setFlowState, sourceReads]);
+ }, [active, ready, observation, supplyToken, setFlowState, sourceReads]);
// ── Gateway ─────────────────────────────────────────────────────────────
@@ -480,14 +566,16 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, SetupScreenPr
// ── The action the shell renders ────────────────────────────────────────
+ // What the screen knows, not what the list happens to hold: an inventory it
+ // could not read is not an empty one, and 「添加」 offered against it is how a
+ // credential that already exists gets written a second time.
+ const hasSource = sourceRead === 'read' && sources.some(usableSource);
+
const action = providerAction({
pendingCount: pending.length,
importFailed,
- // What the screen knows, not what the list happens to hold: an inventory it
- // could not read is not an empty one, and 「添加」 offered against it is how a
- // credential that already exists gets written a second time.
supply: sourceRead === 'read'
- ? { kind: 'read', hasSource: sources.some(usableSource) }
+ ? { kind: 'read', hasSource }
: { kind: sourceRead },
gatewayBusy,
// The same admission the dialogs are opened and submitted against, so the footer
@@ -630,10 +718,51 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, SetupScreenPr
{ count: summary.count, names: formatNames(summary.names, i18n.language) },
);
+ // ── The way on when nothing is connected ────────────────────────────────
+
+ // Connecting a provider is what this screen is for, and it is still the only
+ // thing the stage and the footer offer. But an inventory that answered「none」is
+ // an answer: whoever meant to connect later — or declined the takeover on offer —
+ // has nothing here to press, and a step whose every control stays put is a dead
+ // end. So the way on is stated where the shell keeps what is ancillary to the
+ // pair, as a sentence rather than a second button competing with the one above.
+ //
+ // It navigates and does nothing else. Adding a source, taking over a credential
+ // and installing the engine each keep the control that already owns them, and
+ // none of them happens on the way to the next screen. The engine's admission is
+ // not asked about either: it gates writes, and this is not one — gating the way
+ // out on it is how the dead end got here.
+ //
+ // The slot is the shell's, reached the same way the connection step reaches it,
+ // and only while this screen is the one being read: a portal leaves the screen
+ // root and with it the `inert` the shell puts on the others, so the sentence has
+ // to answer to that activity itself.
+ const routeSurfaceActive = useRouteSurfaceActive();
+ const setupRoot = React.useRef<HTMLDivElement>(null);
+ const [actionAside, setActionAside] = React.useState<HTMLElement | null>(null);
+ React.useEffect(() => {
+ setActionAside(setupRoot.current?.closest('.onboarding-step')
+ ?.querySelector<HTMLElement>('[data-setup-action-aside]') ?? null);
+ }, [onActionChange]);
+ const onwardNode = sourceRead === 'read' && !hasSource ? (
+ <div className="onboarding-setup-hint">
+ <p className="text-center text-xs text-muted">
+ {t('onboarding.providers.continueHint')}{' '}
+ <Button type="button" variant="link" size="xs" className="h-auto p-0 align-baseline text-xs"
+ onClick={() => onNavigate('assistants')}>
+ {t('onboarding.providers.actionContinue')}
+ </Button>
+ </p>
+ </div>
+ ) : null;
+
return (
- <div className="onboarding-setup">
+ <div className="onboarding-setup" ref={setupRoot}>
<header className="onboarding-heading">
- <h2>{t('onboarding.providers.title')}</h2>
+ {/* `h1` with a programmatic tab stop, like every other screen's heading: the
+ shell moves focus here on activation, and a heading it cannot find or
+ cannot focus leaves a keyboard journey standing on the footer button. */}
+ <h1 tabIndex={-1}>{t('onboarding.providers.title')}</h1>
<p>{t('onboarding.providers.subtitle')}</p>
</header>
@@ -776,6 +905,10 @@ export const ProvidersScreen = React.forwardRef<SetupScreenHandle, SetupScreenPr
onClose={() => setImportOpen(false)}
/>
)}
+
+ {onwardNode && active && routeSurfaceActive && actionAside
+ ? createPortal(onwardNode, actionAside)
+ : null}
</div>
);
},
diff --git a/ui/src/components/onboarding/providers/gatewayBootstrap.test.ts b/ui/src/components/onboarding/providers/gatewayBootstrap.test.ts
index b82fcca45..5f218ef29 100644
--- a/ui/src/components/onboarding/providers/gatewayBootstrap.test.ts
+++ b/ui/src/components/onboarding/providers/gatewayBootstrap.test.ts
@@ -10,7 +10,7 @@ import type { Mock } from 'vitest';
import type { BackendConnectionState } from '@/context/ApiContext';
import type { RuntimeDependency } from '@/components/settings/models/types';
-import { GatewayBootstrapError, bootstrapGateway, readSetupConfig } from './gatewayBootstrap';
+import { GatewayBootstrapError, bootstrapGateway, readRuntimeObservation } from './gatewayBootstrap';
import type { GatewayBootstrapDeps } from './gatewayBootstrap';
const CONFIG = {
@@ -88,38 +88,25 @@ const failure = async (promise: Promise<unknown>): Promise<GatewayBootstrapError
return error as GatewayBootstrapError;
};
-describe('readSetupConfig', () => {
- it('accepts the top-level config object the handlers really return', () => {
- expect(readSetupConfig(CONFIG)).toMatchObject({
- version: 'v2',
- capabilityEnabled: true,
- savedIntentEnabled: true,
- primaryPlatform: 'avibe',
- });
- });
+// The parser both this sequence and the shell's prerequisite read share now lives with
+// its one owner, and is exercised there: `../setupConfig.test.ts`.
- it('rejects the envelope shape nobody sends', () => {
- // `{ok:true, config:{...}}` reads as a success to a careless check and carries
- // none of the fields the caller then indexes into.
- expect(readSetupConfig({ ok: true, config: CONFIG })).toBeNull();
- });
+describe('readRuntimeObservation', () => {
+ it('is the same read the sequence ends on, reusable without seeding or starting', async () => {
+ const d = deps();
- it('rejects a body that carries an error alongside a plausible payload', () => {
- expect(readSetupConfig({ ...CONFIG, error: 'config load failed' })).toBeNull();
- expect(readSetupConfig({ ...CONFIG, ok: false })).toBeNull();
+ await expect(readRuntimeObservation(d)).resolves.toBe(RUNTIME);
+ expect(d.fetch).not.toHaveBeenCalled();
+ expect(d.control).not.toHaveBeenCalled();
});
it.each([
- ['version', { version: 'v1' }],
- ['setup_completed', { setup_completed: 'no' }],
- ['platforms.primary', { platforms: { enabled: [] } }],
- ['platforms.enabled', { platforms: { primary: 'avibe', enabled: 'slack' } }],
- ['runtime', { runtime: null }],
- ['agents', { agents: [] }],
- ['capabilities.model_hub', { capabilities: {} }],
- ['model_hub', { model_hub: {} }],
- ])('treats a malformed %s as unread rather than as a value', (_field, over) => {
- expect(readSetupConfig({ ...CONFIG, ...over })).toBeNull();
+ ['a read that threw', async () => { throw new Error('status unavailable'); }],
+ ['a body without the status it had to carry', async () => ({ manifest: {} } as unknown as RuntimeDependency)],
+ ])('reports %s as unread rather than as a runtime', async (_label, getRuntimeStatus) => {
+ const error = await failure(readRuntimeObservation(deps({ getRuntimeStatus: vi.fn(getRuntimeStatus) })));
+
+ expect(error).toMatchObject({ reason: 'unread', step: 'runtime' });
});
});
diff --git a/ui/src/components/onboarding/providers/gatewayBootstrap.ts b/ui/src/components/onboarding/providers/gatewayBootstrap.ts
index e97852c34..01a42d243 100644
--- a/ui/src/components/onboarding/providers/gatewayBootstrap.ts
+++ b/ui/src/components/onboarding/providers/gatewayBootstrap.ts
@@ -22,6 +22,13 @@
// would race the recovery that is still finishing.
import type { AgentBackend, RuntimeDependency } from '@/components/settings/models/types';
import type { BackendConnectionState } from '@/context/ApiContext';
+import {
+ errorDetail,
+ hasError,
+ parseJson,
+ readSetupConfig,
+ type SetupConfigSnapshot,
+} from '../setupConfig';
/**
* Why bootstrap could not finish, in the terms the caller has to act in.
@@ -55,85 +62,9 @@ export class GatewayBootstrapError extends Error {
}
}
-/**
- * The fields of `/api/config` this flow is allowed to read.
- *
- * Narrow on purpose: validating the whole config would couple setup to every future
- * field, and an absent or malformed one of these is unread state rather than an
- * opt-out — which is a distinction the caller has to be able to make.
- */
-export type SetupConfigSnapshot = {
- version: 'v2';
- setup_completed: boolean;
- capabilityEnabled: boolean;
- savedIntentEnabled: boolean;
- primaryPlatform: string;
- enabledPlatforms: string[];
- /** The validated body, for the shell's existing server-config state. */
- raw: Record<string, unknown>;
-};
-
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
-/** The server's error shape is a string on some handlers and an object on others. */
-function errorDetail(body: unknown): string | undefined {
- if (!isRecord(body)) return undefined;
- const error = body.error;
- if (typeof error === 'string') return error;
- if (isRecord(error) && typeof error.message === 'string') return error.message;
- if (body.ok === false && typeof body.message === 'string') return body.message;
- return undefined;
-}
-
-const hasError = (body: unknown): boolean =>
- isRecord(body) && (body.ok === false || body.error !== undefined);
-
-async function parseJson(response: Response): Promise<unknown> {
- try {
- return await response.json();
- } catch {
- return undefined;
- }
-}
-
-/**
- * Validate a config body, or explain what was missing.
- *
- * Returns `null` rather than throwing so both callers — the POST acknowledgement and
- * the GET readback — can decide for themselves what an invalid body means at their
- * own step.
- */
-export function readSetupConfig(body: unknown): SetupConfigSnapshot | null {
- if (!isRecord(body) || hasError(body)) return null;
- if (body.version !== 'v2') return null;
- if (typeof body.setup_completed !== 'boolean') return null;
-
- const platforms = body.platforms;
- if (!isRecord(platforms)) return null;
- if (typeof platforms.primary !== 'string') return null;
- const enabled = platforms.enabled;
- if (!Array.isArray(enabled) || enabled.some((entry) => typeof entry !== 'string')) return null;
-
- if (!isRecord(body.runtime) || !isRecord(body.agents)) return null;
-
- const capabilities = body.capabilities;
- const capability = isRecord(capabilities) ? capabilities.model_hub : undefined;
- const saved = body.model_hub;
- if (!isRecord(capability) || typeof capability.enabled !== 'boolean') return null;
- if (!isRecord(saved) || typeof saved.enabled !== 'boolean') return null;
-
- return {
- version: 'v2',
- setup_completed: body.setup_completed,
- capabilityEnabled: capability.enabled,
- savedIntentEnabled: saved.enabled,
- primaryPlatform: platforms.primary,
- enabledPlatforms: enabled as string[],
- raw: body,
- };
-}
-
export type GatewayBootstrapDeps = {
/** The CSRF-aware `apiFetch`, injected so the sequence is testable as itself. */
fetch: (input: string, init?: RequestInit) => Promise<Response>;
@@ -219,17 +150,35 @@ export async function bootstrapGateway(
// 6. Observe. Controller startup has already run its own recovery with the
// installer admission the server owns; this reads what came of it.
+ const runtime = await readRuntimeObservation(deps);
+
+ return { config, runtime };
+}
+
+/**
+ * The runtime read the sequence ends on, on its own.
+ *
+ * Once bootstrap has run for a mount, a later refresh has nothing left to establish:
+ * the config exists, the controller is up, and re-seeding or re-starting would act on
+ * state that is already proven. So the caller's refresh path is this step alone, and
+ * it is this step — the same validation, the same classified failure — rather than a
+ * second call policy that could drift from it.
+ */
+export async function readRuntimeObservation(
+ deps: Pick<GatewayBootstrapDeps, 'getRuntimeStatus'>,
+): Promise<RuntimeDependency> {
let runtime: RuntimeDependency;
try {
runtime = await deps.getRuntimeStatus();
} catch {
throw new GatewayBootstrapError('unread', 'runtime');
}
+ // A body without a status is a body that did not answer: every consumer of this
+ // reads `status.health`, and inventing one would report an unknown engine as fine.
if (!isRecord(runtime) || !isRecord((runtime as unknown as Record<string, unknown>).status)) {
throw new GatewayBootstrapError('unread', 'runtime');
}
-
- return { config, runtime };
+ return runtime;
}
/**
diff --git a/ui/src/components/onboarding/providers/tsconfig.tests.json b/ui/src/components/onboarding/providers/tsconfig.tests.json
index 15c1b391f..0c8350d7c 100644
--- a/ui/src/components/onboarding/providers/tsconfig.tests.json
+++ b/ui/src/components/onboarding/providers/tsconfig.tests.json
@@ -10,6 +10,17 @@
"./**/*.tsx",
"../ImportKeysNotice.test.tsx",
"../setupAction.types.test.ts",
+ "../setupConfig.test.ts",
+ "../SetupFlowShell.test.tsx",
+ "../WizardCompletion.test.tsx",
+ "../setupTargets.test.ts",
+ "../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/setupConfig.test.ts b/ui/src/components/onboarding/setupConfig.test.ts
new file mode 100644
index 000000000..e6d802436
--- /dev/null
+++ b/ui/src/components/onboarding/setupConfig.test.ts
@@ -0,0 +1,103 @@
+// The one config read setup is allowed to act on, stated as what it refuses to
+// conclude. Every case here is a body that would pass a careless check and then be
+// indexed into as if it had said something: an envelope, an error carried alongside a
+// plausible payload, a field of the wrong type. The distinction the whole flow rests
+// on is that none of those are `false` — they are unread.
+import { describe, expect, it, vi } from 'vitest';
+
+import { fetchSetupConfig, readSetupConfig } from './setupConfig';
+
+const CONFIG = {
+ version: 'v2',
+ setup_completed: false,
+ platforms: { primary: 'avibe', enabled: [] },
+ runtime: {},
+ agents: {},
+ capabilities: { model_hub: { enabled: true } },
+ model_hub: { enabled: true },
+};
+
+const json = (body: unknown, status = 200): Response =>
+ new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+
+describe('readSetupConfig', () => {
+ it('accepts the top-level config object the handlers really return', () => {
+ expect(readSetupConfig(CONFIG)).toMatchObject({
+ version: 'v2',
+ capabilityEnabled: true,
+ savedIntentEnabled: true,
+ primaryPlatform: 'avibe',
+ enabledPlatforms: [],
+ raw: CONFIG,
+ });
+ });
+
+ it('rejects the envelope shape nobody sends', () => {
+ // `{ok:true, config:{...}}` reads as a success to a careless check and carries
+ // none of the fields the caller then indexes into.
+ expect(readSetupConfig({ ok: true, config: CONFIG })).toBeNull();
+ });
+
+ it('rejects a body that carries an error alongside a plausible payload', () => {
+ expect(readSetupConfig({ ...CONFIG, error: 'config load failed' })).toBeNull();
+ expect(readSetupConfig({ ...CONFIG, ok: false })).toBeNull();
+ });
+
+ it.each([
+ ['version', { version: 'v1' }],
+ ['setup_completed', { setup_completed: 'no' }],
+ ['platforms.primary', { platforms: { enabled: [] } }],
+ ['platforms.enabled', { platforms: { primary: 'avibe', enabled: 'slack' } }],
+ ['runtime', { runtime: null }],
+ ['agents', { agents: [] }],
+ ['capabilities.model_hub', { capabilities: {} }],
+ ['model_hub', { model_hub: {} }],
+ ])('treats a malformed %s as unread rather than as a value', (_field, over) => {
+ expect(readSetupConfig({ ...CONFIG, ...over })).toBeNull();
+ });
+
+ it('reads a disabled gateway as disabled, which is the point of the distinction', () => {
+ expect(readSetupConfig({ ...CONFIG, model_hub: { enabled: false } })).toMatchObject({
+ capabilityEnabled: true,
+ savedIntentEnabled: false,
+ });
+ });
+});
+
+describe('fetchSetupConfig', () => {
+ it('asks for the config as it is right now', async () => {
+ // A cached read is the failure this function exists to prevent: it would let setup
+ // finish against a prerequisite somebody already turned off in Settings.
+ const fetch = vi.fn(async () => json(CONFIG));
+
+ await expect(fetchSetupConfig(fetch)).resolves.toMatchObject({ state: 'read' });
+ expect(fetch).toHaveBeenCalledWith('/api/config', { cache: 'no-store' });
+ });
+
+ it('reports a transport failure as unread', async () => {
+ const read = await fetchSetupConfig(vi.fn(async () => { throw new TypeError('network'); }));
+
+ expect(read).toMatchObject({ state: 'unread' });
+ expect((read as { status?: number }).status).toBeUndefined();
+ });
+
+ it("keeps the server's own words about a failed read", async () => {
+ const read = await fetchSetupConfig(vi.fn(async () => json({ error: 'config load failed' }, 500)));
+
+ expect(read).toMatchObject({ state: 'unread', status: 500, detail: 'config load failed' });
+ });
+
+ it('reports a body that arrived and said nothing without a status to explain it', async () => {
+ // HTTP 200 explains nothing about a 200 whose body is unusable, and quoting it
+ // would point a person at the transport instead of the answer.
+ const read = await fetchSetupConfig(vi.fn(async () => json({ version: 'v1' })));
+
+ expect(read).toEqual({ state: 'unread', detail: undefined });
+ });
+
+ it('treats an unparseable body as unread rather than as an empty config', async () => {
+ const read = await fetchSetupConfig(vi.fn(async () => new Response('{"version":', { status: 200 })));
+
+ expect(read).toMatchObject({ state: 'unread' });
+ });
+});
diff --git a/ui/src/components/onboarding/setupConfig.ts b/ui/src/components/onboarding/setupConfig.ts
index 653d7f0e8..1fcba51a2 100644
--- a/ui/src/components/onboarding/setupConfig.ts
+++ b/ui/src/components/onboarding/setupConfig.ts
@@ -10,10 +10,9 @@
*
* Validation is deliberately narrow and shared: absent or malformed fields are UNREAD
* state, not an opt-out, and that distinction is the whole reason a caller can tell
- * "the gateway is off" from "nobody could tell me". The same shape is already written
- * and published in L2's `providers/gatewayBootstrap.ts`; this is that parser, extracted
- * so both callers hold one policy. L2 deletes its copy and imports this in the
- * integration commit after #2087 lands.
+ * "the gateway is off" from "nobody could tell me". `providers/gatewayBootstrap.ts`
+ * reads the same `/api/config` at its own steps and imports this parser, so the two
+ * callers cannot drift into two policies about what a valid config is.
*
* Stateless on purpose: no React, no cache, no owner. It returns one classified read.
*/
@@ -51,8 +50,9 @@ export type SetupConfigFetch = (input: string, init?: RequestInit) => Promise<Re
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
-/** The server's error shape is a string on some handlers and an object on others. */
-function errorDetail(body: unknown): string | undefined {
+/** The server's error shape is a string on some handlers and an object on others.
+ * Exported because the bootstrap sequence quotes the same producers at its own steps. */
+export function errorDetail(body: unknown): string | undefined {
if (!isRecord(body)) return undefined;
const error = body.error;
if (typeof error === 'string') return error;
@@ -61,10 +61,11 @@ function errorDetail(body: unknown): string | undefined {
return undefined;
}
-const hasError = (body: unknown): boolean =>
+export const hasError = (body: unknown): boolean =>
isRecord(body) && (body.ok === false || body.error !== undefined);
-async function parseJson(response: Response): Promise<unknown> {
+/** A body that is not JSON is a body that said nothing, at every step that reads one. */
+export async function parseJson(response: Response): Promise<unknown> {
try {
return await response.json();
} catch {
diff --git a/ui/src/components/onboarding/setupRoute.test.ts b/ui/src/components/onboarding/setupRoute.test.ts
new file mode 100644
index 000000000..509117af6
--- /dev/null
+++ b/ui/src/components/onboarding/setupRoute.test.ts
@@ -0,0 +1,498 @@
+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.ts
new file mode 100644
index 000000000..9672f5327
--- /dev/null
+++ b/ui/src/components/onboarding/setupRoute.ts
@@ -0,0 +1,494 @@
+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/setupScreenRegistry.ts b/ui/src/components/onboarding/setupScreenRegistry.ts
index 4ebbaba54..c60aa7c83 100644
--- a/ui/src/components/onboarding/setupScreenRegistry.ts
+++ b/ui/src/components/onboarding/setupScreenRegistry.ts
@@ -4,5 +4,8 @@ import { SETUP_SCREENS, type SetupScreenId } from './setupFlow';
export const registeredSetupSequence = (registry: Partial<Record<SetupScreenId, true>>) =>
SETUP_SCREENS.filter((id) => registry[id]);
-// L2 adds providers when its implementation ships. There is no empty interim slot.
-export const SETUP_REGISTERED_SCREENS = registeredSetupSequence({ intro: true, assistants: true });
+export const SETUP_REGISTERED_SCREENS = registeredSetupSequence({
+ intro: true,
+ providers: true,
+ assistants: true,
+});
diff --git a/ui/src/components/onboarding/setupTargets.test.ts b/ui/src/components/onboarding/setupTargets.test.ts
new file mode 100644
index 000000000..b6372fa4d
--- /dev/null
+++ b/ui/src/components/onboarding/setupTargets.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { VibeAgentBrief, VibeAgentFull } from '../../context/ApiContext';
+import { isBuiltinAgent, readSetupTargets, setupTargetFor } from './setupTargets';
+
+const agent = (source: string, metadata: Record<string, unknown>) => ({
+ name: 'claude', backend: 'claude', enabled: true, archived: false, source, metadata,
+} as VibeAgentBrief & { metadata: Record<string, unknown> });
+
+const brief = (overrides: Partial<VibeAgentBrief> & { name: string; backend: VibeAgentBrief['backend'] }): VibeAgentBrief => ({
+ id: `${overrides.backend}-${overrides.name}`,
+ display_name: overrides.name,
+ description: null,
+ model: null,
+ reasoning_effort: null,
+ enabled: true,
+ archived: false,
+ archived_at: null,
+ source: 'file',
+ updated_at: '',
+ ...overrides,
+});
+
+const full = (
+ row: VibeAgentBrief,
+ metadata: Record<string, unknown>,
+ extra: Partial<VibeAgentFull> = {},
+): VibeAgentFull => ({
+ ...row,
+ system_prompt: null,
+ created_at: '',
+ metadata,
+ ...extra,
+});
+
+describe('C6 store metadata identity', () => {
+ it('does not infer a designated builtin from source provenance alone', () => {
+ const row = agent('builtin', {});
+ expect(isBuiltinAgent(row)).toBe(false);
+ expect(setupTargetFor([row], 'claude')).toBeNull();
+ });
+
+ it('recognizes the store builtin_default marker regardless of source provenance', () => {
+ const row = agent('file', { builtin_default: true });
+ expect(setupTargetFor([row], 'claude')).toBe(row);
+ });
+
+ it('recognizes lock_delete as the same store identity', () => {
+ const row = agent('user', { lock_delete: true });
+ expect(isBuiltinAgent(row)).toBe(true);
+ expect(setupTargetFor([row], 'claude')).toBe(row);
+ });
+
+ it('prefers the backend-named designated builtin, then default, then name order', () => {
+ const alpha = agent('file', { builtin_default: true });
+ const named = { ...alpha, name: 'claude' };
+ const fallback = { ...alpha, name: 'default' };
+ const other = { ...alpha, name: 'aa-builtin' };
+ expect(setupTargetFor([other, fallback, named], 'claude')).toBe(named);
+ expect(setupTargetFor([other, fallback], 'claude')).toBe(fallback);
+ expect(setupTargetFor([other], 'claude')).toBe(other);
+ });
+});
+
+describe('uncached full-Agent target reads', () => {
+ it('queries relevant candidates concurrently with cache:false and keeps the current record', async () => {
+ const claude = brief({ name: 'claude', backend: 'claude', model: 'stale-model' });
+ const custom = brief({ name: 'mine', backend: 'claude', source: 'user' });
+ const current = full(claude, { builtin_default: true }, { model: 'openai/gpt-5.6-sol' });
+ const getVibeAgent = vi.fn(async (name: string, params?: { cache?: boolean }) => {
+ expect(params).toEqual({ cache: false });
+ if (name === 'claude') return { ok: true, agent: current };
+ return { ok: true, agent: full(custom, {}) };
+ });
+
+ const targets = await readSetupTargets([claude, custom], { getVibeAgent });
+ expect(getVibeAgent).toHaveBeenCalledTimes(2);
+ expect(getVibeAgent.mock.calls.every(([, params]) => params?.cache === false)).toBe(true);
+ expect(targets).toEqual([current]);
+ expect(targets[0].model).toBe('openai/gpt-5.6-sol');
+ });
+
+ it('does not designate a target when metadata cannot be read', async () => {
+ const row = brief({ name: 'claude', backend: 'claude', source: 'builtin' });
+ const getVibeAgent = vi.fn(async () => ({ ok: false, agent: null }));
+ expect(await readSetupTargets([row], { getVibeAgent })).toEqual([]);
+ expect(getVibeAgent).toHaveBeenCalledWith('claude', { cache: false });
+ });
+
+ it('does not designate a target when the full read throws or disagrees about identity', async () => {
+ const claude = brief({ name: 'claude', backend: 'claude', source: 'builtin' });
+ const renamed = brief({ name: 'codex', backend: 'codex', source: 'builtin' });
+ const getVibeAgent = vi.fn(async (name: string) => {
+ if (name === 'claude') throw new Error('engine_down');
+ return { ok: true, agent: full(renamed, { builtin_default: true }, { name: 'someone-else' }) };
+ });
+ expect(await readSetupTargets([claude, renamed], { getVibeAgent })).toEqual([]);
+ });
+});
diff --git a/ui/src/components/onboarding/setupTargets.ts b/ui/src/components/onboarding/setupTargets.ts
new file mode 100644
index 000000000..a631c0b1c
--- /dev/null
+++ b/ui/src/components/onboarding/setupTargets.ts
@@ -0,0 +1,96 @@
+import type { VibeAgentBrief, VibeAgentFull } from '../../context/ApiContext';
+import { ASSISTANT_ORDER, type AssistantId } from './collaborationTimeline';
+
+/**
+ * Which Agent a setup card speaks for.
+ *
+ * Setup shows one card per assistant, not one card per Agent: the route editor
+ * edits a backend's route, and the entry gate prefers that same Agent when it
+ * has to pick a default. Both need the *same* answer to "which Agent is this
+ * card", so the answer lives here once rather than being re-derived on each
+ * screen.
+ *
+ * D4/D9 defines it as the store's builtin selection. The brief list does not
+ * carry that mark — `source` is provenance, not identity — so a custom Agent
+ * 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.
+ */
+const DEFAULT_AGENT_NAME = 'default';
+
+export type SetupTargetAgent = Pick<VibeAgentBrief, 'name' | 'backend' | 'enabled' | 'archived'> & {
+ metadata?: Record<string, unknown>;
+};
+
+export const isBuiltinAgent = (agent: { metadata?: Record<string, unknown> }): boolean =>
+ Boolean(agent.metadata?.builtin_default || agent.metadata?.lock_delete);
+
+/** Deterministic everywhere: code-unit order, not a locale's collation. */
+const byName = (left: { name: string }, right: { name: string }): number =>
+ left.name < right.name ? -1 : left.name > right.name ? 1 : 0;
+
+export function setupTargetFor<T extends SetupTargetAgent>(
+ agents: readonly T[],
+ backend: AssistantId,
+): T | null {
+ const pool = agents.filter((agent) =>
+ agent.backend === backend && agent.enabled && !agent.archived && isBuiltinAgent(agent));
+ return pool.find((agent) => agent.name === backend)
+ ?? pool.find((agent) => agent.name === DEFAULT_AGENT_NAME)
+ ?? [...pool].sort(byName)[0]
+ ?? null;
+}
+
+/** Every assistant's own Agent, in C6's stable order, skipping the ones that have none. */
+export function setupTargets<T extends SetupTargetAgent>(agents: readonly T[]): T[] {
+ return ASSISTANT_ORDER.flatMap((backend) => {
+ const target = setupTargetFor(agents, backend);
+ return target ? [target] : [];
+ });
+}
+
+export type SetupTargetReader = {
+ getVibeAgent: (
+ name: string,
+ params?: { cache?: boolean },
+ ) => Promise<{ ok: boolean; agent?: VibeAgentFull | null }>;
+};
+
+const sameCurrentIdentity = (brief: VibeAgentBrief, full: VibeAgentFull): boolean =>
+ brief.name === full.name && brief.backend === full.backend;
+
+/**
+ * Designated setup targets from the store's current records, not from briefs.
+ *
+ * Relevant enabled/non-archived backend candidates are queried concurrently
+ * with `{cache:false}`. The object handed back is the full current record so
+ * name, backend and model stay the ones the store just answered. A failed,
+ * unread, identity-mismatched or unmarked record does not become a target.
+ */
+export async function readSetupTargets(
+ briefs: readonly VibeAgentBrief[],
+ reader: SetupTargetReader,
+): Promise<VibeAgentFull[]> {
+ const seen = new Set<string>();
+ const relevant = briefs.filter((agent) => {
+ if (!agent.enabled || agent.archived) return false;
+ if (!ASSISTANT_ORDER.includes(agent.backend as AssistantId)) return false;
+ if (seen.has(agent.name)) return false;
+ seen.add(agent.name);
+ return true;
+ });
+ 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 (!sameCurrentIdentity(brief, result.agent)) return null;
+ if (!result.agent.enabled || result.agent.archived) return null;
+ return result.agent;
+ } catch {
+ return null;
+ }
+ }));
+ return setupTargets(records.filter((record): record is VibeAgentFull => record !== null));
+}
diff --git a/ui/src/components/settings/models/backendCatalog.test.ts b/ui/src/components/settings/models/backendCatalog.test.ts
index 5a204b2fb..296efdb2a 100644
--- a/ui/src/components/settings/models/backendCatalog.test.ts
+++ b/ui/src/components/settings/models/backendCatalog.test.ts
@@ -271,23 +271,28 @@ describe('the bare id chokepoint', () => {
* producer that reaches for the resolver directly is one that is about to write
* a draft field without the write that carries the rule.
*/
-const MODELS_DIR = join(process.cwd(), 'src/components/settings/models');
-const OWNER = 'backendCatalog.ts';
+const SRC_DIR = join(process.cwd(), 'src');
+const OWNER = 'components/settings/models/backendCatalog.ts';
/**
- * Every Model Hub module that ships, by path relative to the tree's root.
+ * Every module that ships, by path relative to the source root.
*
* Recursive, and tests excluded. Recursive because a producer one folder down is
* exactly the one a flat read would miss, and a boundary test that can be
- * escaped by moving a file is a boundary in name only.
+ * escaped by moving a file is a boundary in name only — which is why the walk
+ * starts at the source root rather than at the Model Hub's own folder. A
+ * producer in another folder is the same producer: setup's route step reached
+ * past both chokepoints below from `components/onboarding`, and shipped a
+ * defaulted protocol and an addition that promised nothing about its suppliers
+ * while a Hub-scoped walk stayed green.
*/
const shippedModules = (): { name: string; source: string }[] => {
const walk = (dir: string): string[] => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => (
entry.isDirectory() ? walk(join(dir, entry.name)) : [join(dir, entry.name)]
));
- return walk(MODELS_DIR)
+ return walk(SRC_DIR)
.filter((path) => /\.tsx?$/.test(path) && !/\.test\.tsx?$/.test(path))
- .map((path) => ({ name: relative(MODELS_DIR, path), source: readFileSync(path, 'utf8') }));
+ .map((path) => ({ name: relative(SRC_DIR, path), source: readFileSync(path, 'utf8') }));
};
/** Whoever calls this, outside the module that owns the rule, is who breaks it. */
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index d3a655258..9a3d21f0a 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -29,13 +29,17 @@ 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, SetupScreenHandle } from '../onboarding/setupFlow';
+import type { SetupAction, SetupFlowState, SetupScreenHandle, SetupScreenId } from '../onboarding/setupFlow';
import type { BackendId as RuntimeBackendId } from '../settings/shared/useBackendRuntime';
import { useOpencodePermission } from '../settings/shared/useOpencodePermission';
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 type { CollectionReadAuthority } from '../settings/models/collectionReadAuthority';
+import type { AgentSupply } from '../settings/models/types';
+import type { SetupRouteFocus } from '../onboarding/setupRoute';
interface AgentDetectionProps {
active?: boolean;
@@ -47,6 +51,10 @@ interface AgentDetectionProps {
isPage?: boolean;
completionRecovery?: React.ReactNode;
onSave?: (data: { agents: Record<string, AgentState> }) => Promise<void> | void;
+ flowState?: SetupFlowState;
+ setFlowState?: React.Dispatch<React.SetStateAction<SetupFlowState>>;
+ onNavigate?: (screen: SetupScreenId) => void;
+ agentReads?: CollectionReadAuthority<AgentSupply[]>;
}
type AgentState = {
@@ -107,7 +115,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 }) => {
+export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onBack, isPage = false, onSave, completionRecovery, active = true, ref, onActionChange, flowState, setFlowState, onNavigate, agentReads }) => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
@@ -128,6 +136,13 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
const [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 [connections, setConnections] = useState<Partial<Record<RuntimeBackendId, BackendConnectionState>>>({});
const [connectionPending, setConnectionPending] = useState<Partial<Record<RuntimeBackendId, boolean>>>({});
const [connectionErrors, setConnectionErrors] = useState<Partial<Record<RuntimeBackendId, string>>>({});
@@ -202,6 +217,10 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
if (connectionTokens.current[name] === token) setConnectionPending((current) => ({ ...current, [name]: false }));
}
}, [api, t]);
+ const onRoutesSaved = async (saved: SetupRouteFocus) => {
+ await agentReads?.refresh();
+ await refreshConnection(saved.backend);
+ };
// 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
@@ -350,6 +369,18 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
// This uncached projection reads persisted enabled even after a rejected
// write. Apply failure cannot roll back config that was already committed.
await refreshConnection(backend);
+ // The presence read is a follow-up to the write, not the write itself. It is also
+ // the only thing in here that can reject, and this job is a link in the serial
+ // queue: a rejection settles the queue rejected, so every toggle after it chains
+ // onto a continuation that never runs and the person's next enable silently does
+ // nothing. Its failure is reported where this screen already reports a read that
+ // failed, and it does not bury what the write had to say.
+ try {
+ await agentReads?.refresh();
+ } catch (error) {
+ if (enableIntent.current[backend] !== intent) return;
+ setConnectionErrors((current) => ({ ...current, [backend]: current[backend] || String(error) }));
+ }
});
};
@@ -432,6 +463,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
}));
}
await detect(name, installedPath || agents[name]?.cli_path || name);
+ await agentReads?.refresh();
}
} catch (e) {
setInstallResults((prev) => ({
@@ -748,24 +780,28 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
const 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');
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)}
onConfigure={() => {
- if (connections[name]?.supply_mode === 'hub') {
+ if (hubRoute) {
+ if (canEditSetupRoute) { openSetupRoute(name); return; }
navigate(MODEL_HUB_SETTINGS_PATH);
return;
}
setProviderModal({ backend: name, method: 'oauth' });
}}
onAddKey={() => {
- if (connections[name]?.supply_mode === 'hub') {
+ if (hubRoute) {
+ if (canEditSetupRoute) { openSetupRoute(name); return; }
navigate(MODEL_HUB_SETTINGS_PATH);
return;
}
setProviderModal({ backend: name, method: 'api_key' });
}}
- connection={connections[name]?.supply_mode === 'hub'
+ connection={hubRoute
? 'hub'
: !connectionErrors[name] && connections[name]?.ready
? (connections[name]?.auth === 'subscription' ? 'subscription' : 'api_key')
@@ -773,7 +809,10 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
connectionPending={connectionPending[name]}
connectionError={connectionErrors[name] || connections[name]?.message}
onRefreshConnection={() => void refreshConnection(name, { acknowledge: true })}
- configuringDisabled={syncing || pendingWrites[name] || !!refreshingAgents[name] || !!connectionPending[name] || !agent.enabled || agent.status !== 'ok'}
+ configuringDisabled={syncing || pendingWrites[name] || !!refreshingAgents[name] || !!connectionPending[name]
+ || (hubRoute
+ ? agent.status !== 'ok'
+ : !agent.enabled || agent.status !== 'ok')}
enabledControl={<ToggleSwitch variant="onboarding" enabled={agent.enabled}
label={t('onboarding.setup.enableNamed', { name: getBackendUiMeta(name).label })}
onClick={() => toggle(name, !agent.enabled)} />}
@@ -821,6 +860,18 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
</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}
+ />
+ )}
{!onActionChange && completionRecovery}
{asideNode}
</div>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 638f26828..d62eca17f 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -5280,8 +5280,8 @@
"wechat": "WeChat"
},
"setup": {
- "title": "Connect AI. Get to work",
- "subtitle": "Install an assistant and connect a model to get started",
+ "title": "Choose your AI assistants",
+ "subtitle": "Enable an assistant, confirm its default model, and start working",
"install": "Install",
"installed": "Installed",
"notInstalled": "Not installed",
@@ -5298,7 +5298,22 @@
"installFirstNamed": "Install {{name}} first",
"subscriptionConnectedHint": "Subscription saved. Enter the workspace to use it.",
"api_keyConnectedHint": "API Key saved. Enter the workspace to use it.",
- "forNamed": "For {{name}}"
+ "forNamed": "For {{name}}",
+ "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"
},
"connection": {
"method": "Connection method",
@@ -5377,12 +5392,6 @@
"providerConfigured": "Connected",
"providerCredentialHint": "This credential is only used for {{name}} in OpenCode",
"providerDescription": "Provider · For OpenCode",
- "modelTitle": "Choose a model for this connection",
- "modelHint": "{{agent}} currently uses {{model}}. Select a model from a connected provider to finish setup.",
- "modelSelect": "Model from a connected provider",
- "modelApply": "Apply model and enter",
- "modelEmpty": "No compatible models are available. Check the connection above, then retry the catalog.",
- "modelChanged": "The connection or Agent changed. Refresh the catalog and try again.",
"modelUnavailable": "No available Agent has a usable model route. Check your connections and try again.",
"credentialType": "Credential type",
"apiKeyLabel": "API Key",
@@ -5429,6 +5438,7 @@
"actionAdd": "Add subscription or API Key",
"actionConnecting": "Connecting…",
"actionChecking": "Checking connection…",
+ "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.",
@@ -5483,7 +5493,8 @@
"flow": {
"backToIntro": "Back to introduction",
"backToProviders": "Back to models",
- "gatewayRequired": "Setup requires Model Hub to be enabled. Your saved configuration is unchanged. Restore it through your existing configuration controls, then retry."
+ "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.json
index a4ad06a06..469c5dfc7 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -5280,8 +5280,8 @@
"wechat": "微信"
},
"setup": {
- "title": "连接 AI,开始工作",
- "subtitle": "安装助手,连接模型,即可开始工作",
+ "title": "选择你的 AI 助手",
+ "subtitle": "启用助手,确认默认模型,即可开始工作",
"install": "安装",
"installed": "已安装",
"notInstalled": "未安装",
@@ -5298,7 +5298,22 @@
"installFirstNamed": "先安装 {{name}}",
"subscriptionConnectedHint": "订阅已保存,进入工作台即可使用",
"api_keyConnectedHint": "API Key 已保存,进入工作台即可使用",
- "forNamed": "用于 {{name}}"
+ "forNamed": "用于 {{name}}",
+ "configureRoute": "配置模型路由",
+ "defaultModel": "默认模型",
+ "defaultModelNamed": "{{name}} 的模型路由,查看并调整顺序",
+ "noteEnabled": "已启用,模型路由就绪后即可使用"
+ },
+ "route": {
+ "title": "默认模型路由",
+ "description": "为下列助手调整共享模型顺序。各助手按自己的模型列表依次尝试;其他路由保持不变。",
+ "preferred": "首选",
+ "backup": "备用 {{index}}",
+ "singleNote": "此路由只有一个模型。可添加来源,再选择备用模型。",
+ "addSource": "添加模型来源",
+ "done": "完成",
+ "moveUpNamed": "上移 {{name}}",
+ "moveDownNamed": "下移 {{name}}"
},
"connection": {
"method": "连接方式",
@@ -5377,12 +5392,6 @@
"providerConfigured": "已连接",
"providerCredentialHint": "此凭据只用于 OpenCode 中的 {{name}} 服务商",
"providerDescription": "服务商 · 用于 OpenCode",
- "modelTitle": "为此连接选择模型",
- "modelHint": "{{agent}} 当前使用 {{model}}。请选择已连接提供商的模型以完成设置。",
- "modelSelect": "已连接提供商的模型",
- "modelApply": "应用模型并进入",
- "modelEmpty": "暂无兼容模型。请检查上方连接,再重试获取模型列表。",
- "modelChanged": "连接或 Agent 已发生变化。请刷新模型列表后重试。",
"modelUnavailable": "没有可用 Agent 的模型路由。请检查连接后重试。",
"credentialType": "凭据类型",
"apiKeyLabel": "API Key",
@@ -5429,6 +5438,7 @@
"actionAdd": "添加订阅或 API Key",
"actionConnecting": "正在连接…",
"actionChecking": "正在检查连接…",
+ "continueHint": "也可以稍后再连接提供商。",
"addTitle": "添加订阅或 API Key",
"addTitleMore": "添加更多模型提供商",
"addDescription": "添加一个来源即可开始,由模型网关统一路由。",
@@ -5483,7 +5493,8 @@
"flow": {
"backToIntro": "返回介绍",
"backToProviders": "返回模型",
- "gatewayRequired": "设置流程需要启用模型网关。已有配置未改变,请通过现有配置管理恢复后重试。"
+ "gatewayRequired": "设置流程需要启用模型网关。已有配置未改变,请通过现有配置管理恢复后重试。",
+ "completionUnconfirmed": "无法确认设置已完成,请重试"
}
}
}