Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(ui): three-screen setup shell with stable action anchor and handoff (#2087)
Maxee595436c85d
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex bacedf943..ef6bfb25c 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -348,4 +348,41 @@ scenarios:layer: scenariobackend: opencodetest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_explicit_opencode_model_recovery_preserves_agent_and_completes+ - id: AUTH-SETUP-122+ name: Authorized config envelope carries every setup prerequisite field, and completion persists and reads back+ status: covered+ kind: authorization+ layer: scenario+ backend: web+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_authorized_config_envelope_and_completion_persistence_closed_loop+ # Two complementary halves. The scenario test owns the producer side at the real+ # boundary: remote authentication refusal that persists nothing, every field the+ # setup parser requires, CSRF-gated persistence and per-call readback. The supporting+ # test owns the browser side against controlled responses: unread or disabled+ # evidence producing zero mutation and no completion, and recovery only through an+ # explicit successful read. Neither runs a real browser against the real boundary, so+ # the assembled journey is not covered by this entry; it is AUTH-SETUP-123.+ supporting_tests:+ - ui/src/components/onboarding/WizardCompletion.test.tsx+ - id: AUTH-SETUP-123+ name: Assembled browser-to-real-API setup journey from first screen to persisted completion+ status: partial+ kind: authorization+ layer: scenario+ missing_layer: ui-e2e+ backend: web+ reason: >-+ the rule under test is a browser rule — the setup shell reading the config+ endpoint uncached, carrying that answer as a lease across its awaited work, and+ writing completion only while the lease is still current. Neither half of+ AUTH-SETUP-122 can assemble it: the pytest harness drives the real boundary with+ no browser, and the browser tests drive the real shell against controlled+ responses. A pytest node claiming this journey would assert nothing the two+ halves do not already assert, which is why this entry names the gap instead.+ owning_layer: L4 integrated acceptance (real browser against a live instance)+ partial_evidence:+ covers: the producer side at the real boundary — authentication refusal that persists nothing, every field the setup parser requires, CSRF-gated persistence and per-call readback; the browser side is the supporting test below, against controlled responses+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_authorized_config_envelope_and_completion_persistence_closed_loop+ supporting_tests:+ - ui/src/components/onboarding/WizardCompletion.test.tsxnext_priority: []diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex b3519bc79..edcf7aba4 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -179,6 +179,112 @@ def test_setup_completion_uses_the_same_authorized_config_flow(monkeypatch, tmp_SettingsStore.reset_instance()+def test_authorized_config_envelope_and_completion_persistence_closed_loop(monkeypatch, tmp_path):+ """Scenario: AUTH-SETUP-122 — the authorized `/api/config` envelope, and completion+ persistence that reads back.++ This is the producer half of setup's config prerequisite. Unauthenticated remote+ access is refused and persists nothing; an authorized read returns every field+ `readSetupConfig()` requires — a 200 missing one of them is unread state in the shell,+ so setup could never finish against it; the two narrow completion POSTs persist through+ CSRF; and the next read reports the new state rather than the old projection.++ What the 401 here is: remote authentication refusal. The server keeps no record that a+ prerequisite read happened, and nothing in this test implements or observes the shell's+ fresh-read rule — it would pass unchanged with that rule deleted from `Wizard.tsx`.++ Complementary coverage, not a journey. The browser half — unread or disabled evidence+ producing zero mutation and no completion, and recovery only through an explicit+ successful read — is asserted against controlled responses in the `fresh prerequisite+ boundary` cases of `ui/src/components/onboarding/WizardCompletion.test.tsx`. Neither+ layer exercises a real browser against this real boundary; that assembled journey is+ not covered here and stays with the integrated acceptance owner.+ """+ from config.v2_settings import SettingsStore+ from vibe import internal_client++ config = _save_config(tmp_path, paired=True, instance_kind="personal")+ monkeypatch.setattr(ui_server, "_ensure_remote_access_monitoring", lambda *_args: None)+ monkeypatch.setattr(+ internal_client, "reconcile_platforms",+ AsyncMock(return_value={"status_code": 200, "body": {"ok": True}}),+ )+ # Neither the refusal nor the completion may reach a real runtime action.+ monkeypatch.setattr(remote_access, "reconcile", Mock(side_effect=AssertionError("pairing changed")))+ monkeypatch.setattr(+ ui_server, "_schedule_service_restart_for_config_fallback",+ Mock(side_effect=AssertionError("unexpected restart")),+ )+ base_url = "https://alex.avibe.bot"+ peer = {"REMOTE_ADDR": "203.0.113.44"}+ SettingsStore.reset_instance()+ try:+ anonymous = app.test_client()+ # Authentication, not a prerequisite check: the refusal is about who is asking.+ # The shell classifies this answer as unread, but that classification is the+ # shell's, and this boundary is unaware of it.+ unauthenticated = anonymous.get("/api/config", base_url=base_url, environ_base=peer, follow_redirects=False)+ assert unauthenticated.status_code == 401+ assert unauthenticated.get_json()["error"] == "remote_access_login_required"++ refused = anonymous.post(+ "/api/config",+ json={"setup_completed": True, "slack": {"bot_token": "xoxb-must-not-persist"}},+ base_url=base_url, environ_base=peer, follow_redirects=False,+ )+ assert refused.status_code == 401+ blocked = V2Config.load()+ assert blocked.setup_completed is False+ assert blocked.slack.bot_token != "xoxb-must-not-persist"+ assert blocked.setup_state()["needs_setup"] is True++ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(config, "[email protected]", "owner-1", role="owner", access_source="owner"),+ domain="alex.avibe.bot",+ )+ headers = csrf_headers(client, base_url=base_url)+ read = client.get("/api/config", base_url=base_url, environ_base=peer)+ assert read.status_code == 200+ envelope = read.get_json()+ # The exact shape readSetupConfig() validates before setup may act on it.+ assert envelope["version"] == "v2"+ assert isinstance(envelope["setup_completed"], bool)+ assert isinstance(envelope["platforms"]["primary"], str)+ assert isinstance(envelope["platforms"]["enabled"], list)+ assert all(isinstance(name, str) for name in envelope["platforms"]["enabled"])+ assert isinstance(envelope["runtime"], dict)+ assert isinstance(envelope["agents"], dict)+ assert isinstance(envelope["capabilities"]["model_hub"]["enabled"], bool)+ assert isinstance(envelope["model_hub"]["enabled"], bool)+ assert envelope["setup_state"]["needs_setup"] is True++ # The same narrow POSTs the platform step and completion actually send.+ for payload in (+ {"slack": {"bot_token": "xoxb-fresh-prerequisite", "app_token": "xapp-fresh-prerequisite"}},+ {"setup_completed": True},+ ):+ completed = client.post(+ "/api/config", json=payload,+ headers=headers, base_url=base_url, environ_base=peer,+ )+ assert completed.status_code == 200, completed.get_json()+ assert completed.get_json()["setup_state"]["needs_setup"] is False+ saved = V2Config.load()+ assert saved.setup_completed is True+ assert saved.slack.bot_token == "xoxb-fresh-prerequisite"+ # The envelope is produced per call, so a read taken after the write reports the+ # new state. That is what makes an uncached re-read worth doing in the shell; this+ # boundary neither requires nor notices one.+ reread = client.get("/api/config", base_url=base_url, environ_base=peer)+ assert reread.status_code == 200+ assert reread.get_json()["setup_completed"] is True+ assert reread.get_json()["setup_state"]["needs_setup"] is False+ finally:+ SettingsStore.reset_instance()++def test_limited_show_identity_closed_loop_installs_guest_lease(monkeypatch, tmp_path):"""Scenario: AUTH-SETUP-404"""monkeypatch.setenv("AVIBE_HOME", str(tmp_path))diff --git a/ui/e2e/onboarding-fidelity/connections.spec.ts b/ui/e2e/onboarding-fidelity/connections.spec.tsindex 0f2972572..ea5d51461 100644--- a/ui/e2e/onboarding-fidelity/connections.spec.ts+++ b/ui/e2e/onboarding-fidelity/connections.spec.ts@@ -1100,7 +1100,7 @@ for (const width of [1200, 390]) {test('saved Slack recovery narrow uses the existing form only after explicit repair', async ({ page }, info) => {const denied = await serveProduct(page); await authFixtures(page);let manifests = 0;- await page.route('**/api/config', (route) => route.fulfill({ json: { platforms: { enabled: ['slack'] }, platform_catalog: [{ id: 'slack', config_key: 'slack', credential_fields: ['bot_token'] }], slack: { has_app_token: true, bot_token: '' }, agents: { claude: { enabled: true }, codex: { enabled: true }, opencode: { enabled: true } } } }));+ await page.route('**/api/config', (route) => route.fulfill({ json: { version: 'v2', setup_completed: false, runtime: {}, capabilities: { model_hub: { enabled: true } }, model_hub: { enabled: true }, platforms: { primary: 'slack', enabled: ['slack'] }, platform_catalog: [{ id: 'slack', config_key: 'slack', credential_fields: ['bot_token'] }], slack: { has_app_token: true, bot_token: '' }, agents: { claude: { enabled: true }, codex: { enabled: true }, opencode: { enabled: true } } } }));await page.route('**/api/backend/claude/connection', (route) => route.fulfill({ json: { ok: true, backend: 'claude', ready: true, entry_eligible: true, enabled: true, installed: true, application: 'applied', auth: 'api_key' } }));await page.route('**/api/slack/manifest', (route) => { manifests++; return route.fulfill({ json: { ok: true, manifest: '{}' } }); });await page.setViewportSize({ width: 390, height: 640 });diff --git a/ui/e2e/onboarding-fidelity/geometry.spec.ts b/ui/e2e/onboarding-fidelity/geometry.spec.tsindex 3a21c53e4..553b552a1 100644--- a/ui/e2e/onboarding-fidelity/geometry.spec.ts+++ b/ui/e2e/onboarding-fidelity/geometry.spec.ts@@ -44,18 +44,38 @@ const WIRE_RATIO = 350 / 300;const STAGE_EXTRA = 64;const box = async (page: Page, selector: string, index = 0) => {- const rect = await page.locator(selector).nth(index).boundingBox();+ const rect = await page.locator(selector).filter({ visible: true }).nth(index).boundingBox();if (!rect) throw new Error(`${selector} is not rendered`);return rect;};/** Every match's real rect in one round trip — what "aligned" has to be measured from. */const boxes = (page: Page, selector: string) =>- page.locator(selector).evaluateAll((nodes) => nodes.map((node) => {+ page.locator(selector).filter({ visible: true }).evaluateAll((nodes) => nodes.map((node) => {const rect = node.getBoundingClientRect();return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };}));+/**+ * Nothing may sit between a person and the action pair: the centre of each button has to+ * hit the button itself, or its own label. An ancillary caption, capsule or overlay that+ * drifts over the footer intercepts the click long before any box assertion notices, so+ * the anchor fence checks pointer ownership on every screen it walks. An ancestor under+ * the point is not ownership — a covering element's parent is exactly that.+ */+const hitSelf = async (page: Page, selector: string) => {+ const locator = page.locator(selector);+ // On the narrow tiers the pair sits well below the fold, and a point outside the+ // viewport belongs to no element at all; bring it into view first so what comes back+ // is an answer about the layout rather than about the scroll position.+ await locator.scrollIntoViewIfNeeded();+ return locator.evaluate((node) => {+ const rect = node.getBoundingClientRect();+ const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);+ return !!hit && (node === hit || node.contains(hit));+ });+};+const round = (value: number) => Math.round(value * 100) / 100;const spread = (values: number[]) => Math.max(...values) - Math.min(...values);@@ -199,9 +219,11 @@ test.describe('desktop reference geometry', () => {/*** The reference stacks both steps with one rhythm — heading, 20, stage, 20, action — and- * reserves the stage at the card plus 64 in both. That reservation is the whole reason- * the two steps' buttons land on the same coordinates, so it is measured directly rather- * than inferred from the two steps agreeing.+ * draws the story's diagram as its card plus 64. That diagram box is the design's own+ * number and is measured directly; the stage around it is the reservation both steps+ * spend, which is the diagram wherever the connection's card fits its frame and more+ * where that card's sentence wraps to the two lines it is clamped to. So the design is+ * asserted on the box the design draws, and the stage is asserted to hold it.*/test('the welcome spends its column on the reference rhythm', async ({ page }) => {const denied = await serveProduct(page);@@ -212,19 +234,22 @@ test.describe('desktop reference geometry', () => {const heading = await box(page, '.onboarding-heading');const stage = await box(page, '.onboarding-stage');const action = await box(page, '.onboarding-primary-action');- const access = await box(page, '.onboarding-access');// The heading block carries its tier's own distance to the stage — 15 under an// 800px window — while the stage's distance to the action is 20 in every row.const headingGap = await page.evaluate(() =>- parseFloat(getComputedStyle(document.querySelector('.onboarding-heading')!).marginBottom));+ parseFloat(getComputedStyle(document.querySelector('[data-setup-screen-root]:not([hidden]) .onboarding-heading')!).marginBottom));expect(round(headingGap)).toBe(15);expect(stage.y - (heading.y + heading.height)).toBeCloseTo(headingGap, 0);expect(action.y - (stage.y + stage.height)).toBeCloseTo(20, 0);- expect(stage.height).toBeCloseTo(reference.card + STAGE_EXTRA, 1);-- // The access row is an epilogue under the action, not a block inside the stage: the- // connection step has no counterpart to it, and the stage is what the two steps share.- expect(access.y).toBeGreaterThan(action.y + action.height);+ const diagram = await box(page, '.onboarding-collaboration');+ expect(diagram.height).toBeCloseTo(reference.card + STAGE_EXTRA, 1);+ expect(diagram.y).toBeCloseTo(stage.y, 1);+ expect(stage.height).toBeGreaterThanOrEqual(diagram.height - 0.5);++ // The entry block is collapsed throughout setup (owner handoff, design boards and+ // prototype agree), so the rhythm under the action ends at the reserved back row.+ const back = await page.locator('.onboarding-back-action').evaluate((node) => node.getBoundingClientRect().top);+ expect(back).toBeGreaterThan(action.y + action.height);expect(denied).toEqual([]);});@@ -321,7 +346,7 @@ test.describe('desktop reference geometry', () => {const stage = await box(page, '.onboarding-stage');const action = await box(page, '.onboarding-primary-action');const headingGap = await page.evaluate(() =>- parseFloat(getComputedStyle(document.querySelector('.onboarding-heading')!).marginBottom));+ parseFloat(getComputedStyle(document.querySelector('[data-setup-screen-root]:not([hidden]) .onboarding-heading')!).marginBottom));expect(stage.y - (heading.y + heading.height)).toBeCloseTo(headingGap, 0);expect(action.y - (stage.y + stage.height)).toBeCloseTo(20, 0);// The card, and the whole composition with it, follows the window's tier: the@@ -335,7 +360,6 @@ test.describe('desktop reference geometry', () => {const overflows = () => page.evaluate(() =>(document.querySelector('.onboarding-shell') as HTMLElement).scrollHeight > globalThis.innerHeight);expect(await overflows()).toBe(false);- await expect(page.locator('.onboarding-access')).toBeInViewport();// Shorter than the frame it was drawn at, the card keeps paying and the leftover// scrolls — the spacing and the type are never the budget, at any height.@@ -350,8 +374,6 @@ test.describe('desktop reference geometry', () => {// scrolls the rest.expect(round((await box(page, '.onboarding-collaboration-card')).height)).toBe(232);expect(await overflows()).toBe(true);- await page.locator('.onboarding-access').scrollIntoViewIfNeeded();- await expect(page.locator('.onboarding-access')).toBeInViewport();});/**@@ -372,7 +394,7 @@ test.describe('desktop reference geometry', () => {await serveProduct(page);await openOnboarding(page);const type = () => page.evaluate(() => {- const node = document.querySelector('.onboarding-heading :is(h1, h2)')!;+ const node = document.querySelector('[data-setup-screen-root]:not([hidden]) .onboarding-heading :is(h1, h2)')!;const style = getComputedStyle(node);return {size: parseFloat(style.fontSize),@@ -452,57 +474,6 @@ test.describe('capped fluid width', () => {});}- /**- * "Six access points … using circular logo containers, compact spacing and names- * underneath", drawn as a centred 560 row inside a block the reference grows in two- * steps — 740 on a standard desktop, 830 on a large one. Stretching the six circles- * themselves to the block turns a row of logos into a rule across the bottom of the- * page, so the grid keeps its 560 span and centres inside the block at every width.- */- for (const width of [1920, 1366, 1024, 768]) {- test(`the access row is a centred 560 of six circles at ${width}`, async ({ page }) => {- await page.setViewportSize({ width, height: 900 });- await serveProduct(page);- await openOnboarding(page);-- const access = await box(page, '.onboarding-access');- const welcome = await box(page, '.onboarding-welcome');- expect(access.width).toBeCloseTo(Math.min(740, welcome.width), 1);- expect(access.x + access.width / 2).toBeCloseTo(welcome.x + welcome.width / 2, 0);-- const tiles = await boxes(page, '.onboarding-access-tile');- expect(tiles).toHaveLength(6);- // One row, on the 560/6 pitch the tracks produce rather than a gap someone typed.- expect(spread(tiles.map((tile) => tile.y))).toBeLessThanOrEqual(1);- const grid = Math.min(560, welcome.width);- for (let index = 1; index < tiles.length; index += 1) {- expect(tiles[index].x - tiles[index - 1].x).toBeCloseTo(grid / 6, 1);- }- const icons = await page.locator('.onboarding-access-icon').evaluateAll((nodes) => nodes.map((node) => {- const rect = node.getBoundingClientRect();- return { width: rect.width, height: rect.height, radius: getComputedStyle(node).borderRadius };- }));- for (const icon of icons) expect(icon).toEqual({ width: 52, height: 52, radius: '50%' });- });- }-- test('phones fold the access row into two rows of three and keep full labels', async ({ page }) => {- await page.setViewportSize({ width: 390, height: 844 });- await serveProduct(page);- await openOnboarding(page);- const access = await box(page, '.onboarding-access');- const welcome = await box(page, '.onboarding-welcome');- // Six 52px circles cannot sit on one 350px row, so the fixed span is given up here.- expect(round(access.width)).toBe(round(welcome.width));-- const tiles = page.locator('.onboarding-access-tile');- await expect(tiles).toHaveCount(6);- const rows = await tiles.evaluateAll((nodes) => nodes.map((node) => Math.round(node.getBoundingClientRect().top)));- expect(new Set(rows).size).toBe(2);- const labels = await page.locator('.onboarding-access-label')- .evaluateAll((nodes) => nodes.map((node) => node.scrollWidth <= node.clientWidth + 1));- expect(labels).toEqual([true, true, true, true, true, true]);- });});/**@@ -512,13 +483,90 @@ test.describe('capped fluid width', () => {* the copy, the step and the locale all change under them. A screen-sized tolerance would* make it vacuous, so this is exact box equality.*/+/**+ * The six entry tiles belong to the reached worksurface, not to the setup journey: the+ * owner handoff, the design boards and the prototype collapse the block for every setup+ * screen. What stays true here is the property — the block remains mounted (its motion+ * lifecycle is a mounted component's), hidden and inert, leaking nothing focusable, and+ * the reserved action anchor does not depend on it at all.+ */+test('setup keeps the entry block mounted, hidden and inert, and the anchor independent of it', async ({ page }) => {+ for (const viewport of [{ width: 1200, height: 800 }, { width: 390, height: 844 }]) {+ await page.setViewportSize(viewport);+ const denied = await serveProduct(page);+ await openOnboarding(page);+ const block = page.locator('.onboarding-access');+ await expect(block).toHaveCount(1);+ await expect(block).toBeHidden();+ expect(await block.evaluate((node) => node.hasAttribute('inert') && getComputedStyle(node).display === 'none')).toBe(true);+ expect(await block.locator('.onboarding-access-tile').count()).toBe(6);+ // Mounted but inert: nothing inside the block can take focus.+ expect(await block.evaluate((node) => {+ (node.querySelector('.onboarding-access-tile') as HTMLElement).focus();+ return node.contains(document.activeElement);+ })).toBe(false);+ // Revealing the block changes what is below the anchor, never the anchor itself.+ // The back row reserves its box through visibility on the first screen, so it is+ // measured rather than filtered for visibility.+ const rects = () => page.evaluate(() => {+ const read = (selector: string) => {+ const rect = document.querySelector(selector)!.getBoundingClientRect();+ return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };+ };+ return { primary: read('.onboarding-primary-action'), back: read('.onboarding-back-action') };+ });+ const before = await rects();+ await block.evaluate((node) => { (node as HTMLElement).hidden = false; });+ const after = await rects();+ for (const key of ['x', 'y', 'width', 'height'] as const) {+ expect(round(after.primary[key])).toBeCloseTo(round(before.primary[key]), 1);+ expect(round(after.back[key])).toBeCloseTo(round(before.back[key]), 1);+ }+ expect(denied).toEqual([]);+ }+});++/**+ * The tiers the anchor is held across. One list, because every fence below walks the+ * same journey in a different state and "the same six tiers" has to mean one thing.+ */+const ANCHOR_TIERS = [+ { width: 1920, height: 1080 }, { width: 1366, height: 768 }, { width: 1200, height: 800 },+ { width: 768, height: 1024 }, { width: 390, height: 844 }, { width: 320, height: 568 },+] as const;++/** The pair's real rects, measured whether or not the back row is drawn: it reserves its+ * box through `visibility` on the first screen, so filtering for visibility would drop+ * exactly the measurement that proves the reservation. */+const pair = (page: Page) => page.evaluate(() => {+ const read = (selector: string) => {+ const rect = document.querySelector(selector)!.getBoundingClientRect();+ return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };+ };+ return { primary: read('.onboarding-primary-action'), back: read('.onboarding-back-action') };+});++/** The height of the stage the pair currently sits under — every screen keeps one. */+const stageHeight = (page: Page) => page.evaluate(() => {+ const stage = [...document.querySelectorAll('.onboarding-stage')].find((node) => node.getBoundingClientRect().height);+ return stage ? stage.getBoundingClientRect().height : 0;+});++type Pair = Awaited<ReturnType<typeof pair>>;++const expectSamePair = async (page: Page, before: Pair) => {+ await toTop(page);+ const after = await pair(page);+ for (const key of ['x', 'y', 'width', 'height'] as const) {+ expect(round(after.primary[key])).toBeCloseTo(round(before.primary[key]), 1);+ expect(round(after.back[key])).toBeCloseTo(round(before.back[key]), 1);+ }+};+test.describe('shared action anchor', () => {- for (const viewport of [- { width: 1920, height: 1080 }, { width: 1366, height: 768 }, { width: 1200, height: 800 },- { width: 768, height: 1024 }, { width: 390, height: 844 }, { width: 320, height: 568 },- ]) {+ for (const viewport of ANCHOR_TIERS) {for (const lang of ['en', 'zh'] as const) {- test(`${size(viewport)} ${lang} keeps one action anchor across both steps`, async ({ page }) => {+ test(`${size(viewport)} ${lang} keeps one action pair across every registered screen`, async ({ page }) => {await page.setViewportSize(viewport);const denied = await serveProduct(page);await openOnboarding(page, { lang });@@ -530,25 +578,330 @@ test.describe('shared action anchor', () => {const action = await box(page, '.onboarding-primary-action');await expect(page.getByText('Avibe', { exact: true })).toBeVisible();- await openSetup(page, lang);- await toTop(page);- const nextHeading = await box(page, '.onboarding-heading');- const nextTitle = await box(page, '.onboarding-heading h2');- const nextSubtitle = await box(page, '.onboarding-heading p');- const nextStage = await box(page, '.onboarding-stage');- const nextAction = await box(page, '.onboarding-primary-action');-- // The heading block is reserved, so a title that wraps in one step or one language- // and not in the other cannot move the stage below it.- expect(round(nextHeading.height)).toBeCloseTo(round(heading.height), 1);- expect(nextTitle.y).toBeCloseTo(title.y, 0);- expect(nextSubtitle.y).toBeCloseTo(subtitle.y, 0);- expect(round(nextStage.height)).toBeCloseTo(round(stage.height), 1);- for (const key of ['x', 'y', 'width', 'height'] as const) {- expect(round(nextAction[key])).toBeCloseTo(round(action[key]), 1);+ const backBox = await page.locator('.onboarding-back-action').evaluate((node) => {+ const rect = node.getBoundingClientRect(); return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };+ });+ const sequence = (await page.locator('[data-setup-sequence]').getAttribute('data-setup-sequence'))!.split(' ');+ for (const id of sequence.slice(1)) {+ await page.locator('.onboarding-primary-action').click();+ await page.clock.runFor(950);+ await expect(page.locator('[data-setup-sequence]')).toHaveAttribute('data-setup-screen', id);+ await toTop(page);+ const nextHeading = await box(page, '.onboarding-heading');+ const nextTitle = await box(page, '.onboarding-heading h1');+ const nextSubtitle = await box(page, '.onboarding-heading p');+ const nextStage = await box(page, '.onboarding-stage');+ expect(round(nextHeading.height)).toBeCloseTo(round(heading.height), 1);+ expect(nextTitle.y).toBeCloseTo(title.y, 0);+ expect(nextSubtitle.y).toBeCloseTo(subtitle.y, 0);+ expect(round(nextStage.height)).toBeCloseTo(round(stage.height), 1);+ for (const [selector, original] of [['.onboarding-primary-action', action], ['.onboarding-back-action', backBox]] as const) {+ const next = await box(page, selector);+ for (const key of ['x', 'y', 'width', 'height'] as const) expect(round(next[key])).toBeCloseTo(round(original[key]), 1);+ }+ // The pair is not only where it was, it is what a tap actually reaches.+ expect(await hitSelf(page, '.onboarding-primary-action')).toBe(true);+ expect(await hitSelf(page, '.onboarding-back-action')).toBe(true);+ await expect(page.locator('[data-setup-screen-root]:not([hidden]) h1')).toBeFocused();+ await expect(page.locator('[data-setup-screen-root][hidden]:not([inert])')).toHaveCount(0);}+ // The last screen contributes a caption, and a caption is ancillary: it is drawn+ // below the pair it explains. That placement is what lets it grow without moving+ // the anchor, and what keeps it off the button it is describing.+ const caption = await box(page, '.onboarding-setup-hint');+ const backRect = await box(page, '.onboarding-back-action');+ expect(caption.y).toBeGreaterThanOrEqual(backRect.y + backRect.height - 1);await page.locator('.onboarding-primary-action').scrollIntoViewIfNeeded();await expect(page.locator('.onboarding-primary-action')).toBeInViewport();+ // And the last word on reachability is a real click, which Playwright refuses to+ // deliver when something else would receive it. The caption's own controls have+ // to stay live too: it is an aside, not a decoration.+ await page.locator('.onboarding-setup-hint').getByRole('button').first().click();+ await page.locator('.onboarding-back-action').click();+ await expect(page.locator('[data-setup-sequence]')).toHaveAttribute('data-setup-screen', sequence[0]);+ expect(denied).toEqual([]);+ });+ }+ }+});++/**+ * The anchor fence above walks a journey where nothing goes wrong, and everything the+ * shell's post-action slot exists for appears only when something does: a detection that+ * failed, a permission write that was refused, a completion that found a saved platform+ * it cannot use. All three carry a server's own sentence, so all three GROW — and each of+ * them used to be drawn inside the screen, above the footer, which is the one place in+ * this layout where content can drag the anchor. So the same tiers are walked again with+ * those states actually produced rather than mocked into place.+ */+const LONG_DETAIL = `probe exited 1: ${'the cli-detect subprocess reported an unreadable execution environment; '.repeat(3)}see the service log for the full trace`;+const LONG_PERMISSION = `opencode.json could not be written: ${'the configuration directory is owned by another user and the write was refused; '.repeat(2)}resolve the ownership and try again`;++/** The toast container, which is `fixed` and therefore a different surface with its own+ * placement. It is dismissed before any pointer question is asked, so the answer is+ * about the setup layout rather than about a transient global overlay. */+const clearToasts = async (page: Page) => {+ await page.clock.runFor(3100);+ await expect(page.locator('div.fixed.right-4.z-50 > div')).toHaveCount(0);+};++/** The path probe, with a switch on it. A 500 carrying the server's sentence is the shape+ * this endpoint really fails with, and the same sentence for all three binaries is what+ * the toast layer coalesces — one overlay to spend, not three. */+async function switchableDetect(page: Page) {+ let failing = true;+ await page.route('**/api/cli/detect**', (route) => {+ if (failing) return route.fulfill({ status: 500, json: { error: LONG_DETAIL } });+ const binary = new URL(route.request().url()).searchParams.get('binary') ?? '';+ return route.fulfill({ json: { found: true, path: `/fixture/bin/${binary.split('/').pop()}` } });+ });+ return { recover: () => { failing = false; } };+}++/** OpenCode's permission write, held open so the callout's loading, refusal and success+ * are three observable moments rather than one settled render. */+async function deferredPermission(page: Page) {+ const waiting: (() => void)[] = [];+ let failing = true;+ await page.route('**/api/opencode/permission-status', (route) =>+ route.fulfill({ json: { ok: true, permission_allowed: false, config_path: '/fixture/opencode.json' } }));+ await page.route('**/api/opencode/setup-permission', async (route) => {+ await new Promise<void>((resolve) => { waiting.push(resolve); });+ return route.fulfill({ json: failing+ ? { ok: false, message: LONG_PERMISSION, config_path: '/fixture/opencode.json' }+ : { ok: true, message: 'Allowed', config_path: '/fixture/opencode.json' } });+ });+ return {+ settle: async () => { await expect.poll(() => waiting.length).toBeGreaterThan(0); waiting.shift()!(); },+ succeed: () => { failing = false; },+ };+}++test.describe('post-action aside', () => {+ for (const viewport of ANCHOR_TIERS) {+ for (const lang of ['en', 'zh'] as const) {+ test(`${size(viewport)} ${lang} explains a failed detection below the pair and retries from it`, async ({ page }) => {+ await page.setViewportSize(viewport);+ const denied = await serveProduct(page);+ const detect = await switchableDetect(page);+ await openOnboarding(page, { lang });+ await toTop(page);+ const before = await pair(page);++ await page.locator('.onboarding-primary-action').click();+ const alert = page.locator('.onboarding-action-aside [role="alert"]');+ await expect(alert).toContainText(lang === 'zh' ? '未能检测助手' : 'Could not check your assistants');+ // In the shell's slot after the footer, not in the screen above it.+ await expect(page.locator('[data-setup-screen-root="intro"] [role="alert"]')).toHaveCount(0);+ // The same sentence also reaches the global toast layer. Spend it now so every+ // question below is about the slot rather than about a transient overlay.+ await clearToasts(page);+ await expectSamePair(page, before);++ // Expanding the diagnostic is the growth the old placement could not absorb.+ const aside = page.locator('.onboarding-action-aside');+ const closed = (await box(page, '.onboarding-action-aside')).height;+ await aside.getByText(lang === 'zh' ? '查看详情' : 'View details').click();+ await expect(aside.locator('details')).toContainText(LONG_DETAIL);+ expect((await box(page, '.onboarding-action-aside')).height).toBeGreaterThan(closed);+ await expectSamePair(page, before);+ // Grown, and still not over the button it explains.+ expect((await box(page, '.onboarding-action-aside')).y)+ .toBeGreaterThanOrEqual(before.primary.y + before.primary.height - 1);+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= globalThis.innerWidth)).toBe(true);++ expect(await hitSelf(page, '.onboarding-primary-action')).toBe(true);++ // The last word on reachability is a real click, which Playwright refuses to+ // deliver when anything else would receive it. The primary now says Retry.+ detect.recover();+ await expect(page.locator('.onboarding-primary-action')).toContainText(lang === 'zh' ? '重试' : 'Retry');+ await page.locator('.onboarding-primary-action').click();+ await page.clock.runFor(950);+ const sequence = (await page.locator('[data-setup-sequence]').getAttribute('data-setup-sequence'))!.split(' ');+ await expect(page.locator('[data-setup-sequence]')).toHaveAttribute('data-setup-screen', sequence[1]);+ await expect(page.locator('.onboarding-action-aside [role="alert"]')).toHaveCount(0);+ expect(denied).toEqual([]);+ });++ test(`${size(viewport)} ${lang} holds a refused permission write and the import offer under the pair`, async ({ page }) => {+ await page.setViewportSize(viewport);+ const denied = await serveProduct(page);+ await serveModelHub(page);+ const permission = await deferredPermission(page);+ await openOnboarding(page, { lang });+ // The fence starts one screen earlier than the state it is about. The reservation+ // claims the pair is in the same place on the introduction as on a connection step+ // carrying the offer and the refused permission write at once, so the introduction's+ // pair is what every box below is compared against — not the first setup render.+ await toTop(page);+ const before = await pair(page);+ await openSetup(page, lang);++ // Co-presence: the capsule keeps its reserved slot in the stage, the permission+ // callout is in the slot after the pair. Two asides, one anchor.+ const notice = page.locator('.onboarding-import-notice');+ const callout = page.locator('.onboarding-action-aside').getByText(+ lang === 'zh' ? '不设置时 OpenCode' : 'Without this, OpenCode');+ await expect(notice).toBeVisible();+ await expect(callout).toBeVisible();+ await expectSamePair(page, before);+ expect((await box(page, '.onboarding-import-notice')).y).toBeLessThan(before.primary.y);++ // A write that has not answered yet: the callout says so and nothing moves.+ const setup = page.locator('.onboarding-action-aside').getByRole('button', {+ name: lang === 'zh' ? '在 opencode.json 写入 allow' : 'Allow tool calls in opencode.json' });+ await setup.scrollIntoViewIfNeeded();+ await setup.click();+ await expect(setup).toBeDisabled();+ await expectSamePair(page, before);++ await permission.settle();+ await expect(page.locator('.onboarding-action-aside').getByText(LONG_PERMISSION)).toBeVisible();+ await expectSamePair(page, before);+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= globalThis.innerWidth)).toBe(true);+ await clearToasts(page);+ expect(await hitSelf(page, '.onboarding-primary-action')).toBe(true);+ expect(await hitSelf(page, '.onboarding-back-action')).toBe(true);++ // Granted, the callout is not a cleared message but an absent one.+ permission.succeed();+ await setup.click();+ await permission.settle();+ await expect(page.locator('.onboarding-action-aside').getByText(LONG_PERMISSION)).toHaveCount(0);+ await expect(callout).toHaveCount(0);+ await expectSamePair(page, before);+ await clearToasts(page);++ // Refusing the offer is the stage's event, not the slot's: the capsule lives in+ // the stage and the callout in the aside, so dismissing one may not disturb the+ // other or the pair's own box. Nor may it move the pair at all — the capsule's+ // place in the stage is reserved whether or not the capsule is in it, and the+ // stage is floored at the taller of the two steps' cards, so a card that wraps+ // past `--ob-card-h` no longer spends the offer's band on its way down.+ const stageBefore = await stageHeight(page);+ const slotBefore = await box(page, '.onboarding-import-slot');+ await page.getByRole('button', { name: lang === 'zh' ? '关闭导入提示' : 'Dismiss import notice' }).click();+ await expect(notice).toHaveCount(0);+ await expectSamePair(page, before);+ // The slot is what makes that true: refusing empties it, it does not remove it.+ const slotAfter = await box(page, '.onboarding-import-slot');+ expect(round(slotAfter.height)).toBe(round(slotBefore.height));+ expect(round(slotAfter.y)).toBe(round(slotBefore.y));+ expect(await stageHeight(page)).toBeCloseTo(stageBefore, 1);+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= globalThis.innerWidth)).toBe(true);+ expect(await hitSelf(page, '.onboarding-primary-action')).toBe(true);+ expect(await hitSelf(page, '.onboarding-back-action')).toBe(true);++ // A portal escapes `inert`, so leaving the screen has to empty the slot rather+ // than leave reachable content behind a hidden screen.+ await page.locator('.onboarding-back-action').click();+ await page.clock.runFor(950);+ await expect(page.locator('[data-setup-sequence]')).toHaveAttribute('data-setup-screen', 'intro');+ expect(await page.locator('.onboarding-action-aside').evaluate((node) => ({+ children: node.childElementCount,+ focusable: node.querySelectorAll('a[href], button, input, select, textarea, [tabindex]').length,+ }))).toEqual({ children: 0, focusable: 0 });+ // Back is the other half of the cross-screen claim: the introduction the pair+ // returns to is the one it started on, after the step it came from had spent an+ // offer, a refusal and a permission write.+ await expectSamePair(page, before);++ // And re-entering is not a third position. The offer stays refused, so this is+ // the step at its shortest — the reading the reservation exists for. The clock+ // here is frozen and only a test moves it, so the handoff is nudged until the+ // screen has arrived rather than once, which races the click's own commit.+ await page.getByRole('button', { name: lang === 'zh' ? '立即开始' : 'Get started' }).click();+ await expect.poll(async () => {+ await page.clock.runFor(950);+ return page.locator('[data-setup-sequence]').getAttribute('data-setup-screen');+ }).toBe('assistants');+ await page.locator('.onboarding-assistants').waitFor();+ await expect(notice).toHaveCount(0);+ await expectSamePair(page, before);+ const slotAgain = await box(page, '.onboarding-import-slot');+ expect(round(slotAgain.height)).toBe(round(slotBefore.height));+ expect(round(slotAgain.y)).toBe(round(slotBefore.y));+ expect(await stageHeight(page)).toBeCloseTo(stageBefore, 1);+ expect(await hitSelf(page, '.onboarding-primary-action')).toBe(true);+ expect(await hitSelf(page, '.onboarding-back-action')).toBe(true);+ expect(denied).toEqual([]);+ });+ }+ }+});++/**+ * The completion recovery is the largest thing the slot ever carries — a whole form,+ * opened by the action it sits under, on the tiers with the least room for it. While it+ * owns the journey the pair is held, which is a state the pair has to survive without+ * moving, and cancelling has to give both the journey and the slot back.+ */+test.describe('completion recovery in the slot', () => {+ for (const viewport of [{ width: 390, height: 640 }, { width: 320, height: 568 }]) {+ for (const lang of ['en', 'zh'] as const) {+ test(`${size(viewport)} ${lang} opens the repair under the held pair and gives it back on cancel`, async ({ page }, info) => {+ await page.setViewportSize(viewport);+ const denied = await serveProduct(page);+ let manifests = 0;+ // A saved platform whose required credential is gone: the shape that makes+ // completion stop and hand the slot a form instead of entering the workspace.+ await page.route('**/api/config', (route) => route.fulfill({ json: {+ version: 'v2', setup_completed: false, runtime: {},+ capabilities: { model_hub: { enabled: true } }, model_hub: { enabled: true },+ platforms: { primary: 'slack', enabled: ['slack'] },+ platform_catalog: [{ id: 'slack', config_key: 'slack', credential_fields: ['bot_token'] }],+ slack: { has_app_token: true, bot_token: '' },+ agents: { claude: { enabled: true }, codex: { enabled: true }, opencode: { enabled: true } },+ } }));+ await page.route('**/api/backend/claude/connection', (route) => route.fulfill({ json: {+ ok: true, backend: 'claude', ready: true, entry_eligible: true,+ enabled: true, installed: true, application: 'applied', auth: 'api_key' } }));+ await page.route('**/api/slack/manifest', (route) => { manifests++; return route.fulfill({ json: { ok: true, manifest: '{}' } }); });+ await openOnboarding(page, { lang });+ await openSetup(page, lang);+ await toTop(page);+ const before = await pair(page);++ await page.locator('.onboarding-primary-action').click();+ const recovery = page.getByRole('region', { name: lang === 'zh' ? '修复已保存的消息配置' : 'Repair saved messaging configuration' });+ await expect(recovery).toBeVisible();+ expect(await recovery.evaluate((node) => !!node.closest('[data-setup-action-aside]'))).toBe(true);+ await expectSamePair(page, before);+ // Held, not busy: the journey is refused while the form owns it, and refusing is+ // not the same as pretending something is running.+ await expect(page.locator('.onboarding-primary-action')).toBeDisabled();+ await expect(page.locator('.onboarding-back-action')).toBeDisabled();+ // The spinner carries Tailwind's `motion-safe:` variant, so the token in the DOM+ // is the whole `motion-safe:animate-spin`; a bare `.animate-spin` finds nothing+ // here whatever the footer renders.+ expect(await page.locator('.onboarding-primary-action [class~="motion-safe:animate-spin"]').count()).toBe(0);+ expect(manifests).toBe(0);++ // Expanding it into the real form is the growth these two tiers have least room+ // for, and its own controls still have to be reachable rather than merely present.+ await recovery.getByRole('button', { name: lang === 'zh' ? '修复已保存的消息配置' : 'Repair saved messaging configuration' }).click();+ await expect.poll(() => manifests).toBe(1);+ // Exact: the Slack step headers inside the form spell "Slack 应用" / "Slack app".+ const apply = recovery.getByRole('button', { name: lang === 'zh' ? '应用' : 'Apply', exact: true });+ await apply.scrollIntoViewIfNeeded();+ await expect(apply).toBeInViewport();+ expect(await recovery.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(1);+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= globalThis.innerWidth)).toBe(true);+ await expectSamePair(page, before);+ await settleEffects(page);+ await recovery.screenshot({ path: info.outputPath(`recovery-slot-${size(viewport)}-${lang}.png`) });++ // Cancel is a real click, and it gives back both the slot and the journey.+ const cancel = recovery.getByRole('button', { name: lang === 'zh' ? '取消' : 'Cancel' });+ await cancel.scrollIntoViewIfNeeded();+ await cancel.click();+ await expect(recovery).toHaveCount(0);+ await expectSamePair(page, before);+ await expect(page.locator('.onboarding-primary-action')).toBeEnabled();+ await expect(page.locator('.onboarding-back-action')).toBeEnabled();+ expect(await hitSelf(page, '.onboarding-primary-action')).toBe(true);+ expect(await hitSelf(page, '.onboarding-back-action')).toBe(true);expect(denied).toEqual([]);});}@@ -575,23 +928,36 @@ test.describe('import capsule', () => {await expect(notice).toHaveText(/发现 3 个可导入模型网关的 API Key/);const capsule = await box(page, '.onboarding-import-notice');+ const slot = await box(page, '.onboarding-import-slot');const cards = await box(page, '.onboarding-assistants');+ const stage = await box(page, '.onboarding-stage');const action = await box(page, '.onboarding-primary-action');expect(round(capsule.height)).toBe(44);// Content width, centred under the cards — not a full-width banner.expect(capsule.width).toBeLessThan(cards.width);expect(capsule.x + capsule.width / 2).toBeCloseTo(cards.x + cards.width / 2, 0);expect(capsule.y - (cards.y + cards.height)).toBeCloseTo(20, 0);- expect(action.y - (capsule.y + capsule.height)).toBeCloseTo(20, 0);+ // It sits at the top of its own slot, and the slot is the offer's reserved place in+ // the stage rather than a box drawn around whatever arrived: a reservation that has+ // to hold the other language's wrapped card leaves its slack under the composition,+ // which is where the action's own 20 is measured from.+ expect(capsule.y).toBeCloseTo(slot.y, 0);+ expect(slot.height).toBeGreaterThanOrEqual(capsule.height - 0.5);+ expect(action.y - (stage.y + stage.height)).toBeCloseTo(20, 0);expect(await page.locator('.onboarding-import-notice').evaluate((node) => getComputedStyle(node).boxShadow)).toBe('none');await settleEffects(page);await page.screenshot({ path: info.outputPath('import-capsule-1200x800-dark-zh.png') });- // The layout space is reserved, so refusing the offer moves nothing.+ // The layout space is reserved, so refusing the offer moves nothing: the slot keeps+ // the height the capsule had, and the stage and the action keep theirs.await page.getByRole('button', { name: '关闭导入提示' }).click();await expect(notice).toHaveCount(0);+ const emptySlot = await box(page, '.onboarding-import-slot');const after = await box(page, '.onboarding-primary-action');+ expect(round(emptySlot.height)).toBe(round(slot.height));+ expect(round(emptySlot.y)).toBe(round(slot.y));+ expect(round((await box(page, '.onboarding-stage')).height)).toBe(round(stage.height));expect(round(after.y)).toBe(round(action.y));expect(round(after.x)).toBe(round(action.x));expect(denied).toEqual([]);@@ -726,7 +1092,7 @@ test.describe('narrow identity alignment', () => {// adjacent row/card. Check the actual visible label boxes.const clipped = await page.locator('.onboarding-card-name, .onboarding-card-role, .onboarding-status-text',- ).evaluateAll((nodes) => nodes+ ).filter({ visible: true }).evaluateAll((nodes) => nodes.filter((node) => {const style = getComputedStyle(node);const label = node.getBoundingClientRect();@@ -742,7 +1108,7 @@ test.describe('narrow identity alignment', () => {});}// …and the labels are still the product's own words at a readable size.- const names = await page.locator('.onboarding-card-name').allInnerTexts();+ const names = await page.locator('.onboarding-card-name').filter({ visible: true }).allInnerTexts();expect(names.map((name) => name.replace(/\s+/g, ' ').trim())).toEqual(['Claude Code', 'Codex', 'OpenCode']);const smallest = await page.locator('.onboarding-card-role').evaluateAll((nodes) => Math.min(...nodes.map((node) => parseFloat(getComputedStyle(node).fontSize))));@@ -822,61 +1188,6 @@ test.describe('motion lifecycle', () => {expect(await renderedPhase(page)).not.toEqual(before);});- /**- * The other half of the same lifecycle. A hidden tab is not the only way a story goes- * unwatched: at 390x300 the diagram and the button below it cannot share the screen, so- * reading the button puts the whole composition above the viewport while the document- * stays perfectly visible. Element visibility is what closes that, and `threshold: 0`- * is what keeps a partly scrolled composition alive instead of stuttering at the seam.- */- test('a story scrolled out of sight suspends, and partial visibility does not', async ({ page }, info) => {- const denied = await serveProduct(page);- await page.setViewportSize({ width: 390, height: 300 });- await openOnboarding(page);- await freezeAt(page, PHASES['codex-working']);- const diagram = page.locator('.onboarding-collaboration');- const rect = () => diagram.evaluate((node) => {- const found = node.getBoundingClientRect();- return { top: Math.round(found.top), bottom: Math.round(found.bottom) };- });- // Whichever element actually scrolls here, the page or the shell inside it.- const scrollBy = (delta: number) => page.evaluate((amount) => {- const shell = document.querySelector('.onboarding-shell') as HTMLElement | null;- const scroller = shell && shell.scrollHeight > shell.clientHeight ? shell : document.scrollingElement!;- scroller.scrollTop += amount;- }, delta);-- await page.locator('.onboarding-access').scrollIntoViewIfNeeded();- expect((await rect()).bottom).toBeLessThanOrEqual(0);- expect(await page.evaluate(() => document.hidden)).toBe(false);- await expect(diagram).toHaveAttribute('data-motion', 'paused');-- const before = await renderedPhase(page);- const stopped = await cssEffects(page);- expect(stopped.every((effect) => effect.state === 'paused')).toBe(true);- await page.clock.runFor(3000);- await page.waitForTimeout(250);- expect(await renderedPhase(page)).toEqual(before);- expect(await cssEffects(page)).toEqual(stopped);- // The companion still for the design-frame crop: the CTA, reached by scrolling.- await page.screenshot({ path: info.outputPath('scrolled-cta-390x300.png') });-- // Partly back: any intersecting pixel counts, so the story is live again at the seam.- await scrollBy(-100);- await page.waitForTimeout(150);- const seam = await rect();- expect(seam.top).toBeLessThan(0);- expect(seam.bottom).toBeGreaterThan(0);- await expect(diagram).toHaveAttribute('data-motion', 'running');-- // And it resumed rather than restarted or skipped: the phase is the one it was- // holding, and it moves on from there once the clock runs again.- expect(await renderedPhase(page)).toEqual(before);- await freezeAt(page, PHASES['pm-summary'] - PHASES['codex-working']);- expect(await renderedPhase(page)).not.toEqual(before);- expect(denied).toEqual([]);- });-test('a reduced-motion preference draws the settled story and no pulse', async ({ page }, info) => {await serveProduct(page);await page.emulateMedia({ reducedMotion: 'reduce' });@@ -996,7 +1307,6 @@ test.describe('capture', () => {await openOnboarding(page);await freezeAt(page, PHASES[CAPTURE_PHASE]);expect((await renderedPhase(page)).states).toEqual(CAPTURE_STATES);- await expect(page.locator('.onboarding-access')).toBeInViewport({ ratio: 1 });await settleEffects(page);await page.screenshot({ path: info.outputPath(`welcome-design-frame-1200x756-${CAPTURE_PHASE}.png`) });await openSetup(page, 'en');diff --git a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts b/ui/e2e/onboarding-fidelity/hub-ownership.spec.tsindex 8d1099330..711d26c2e 100644--- a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts+++ b/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts@@ -23,10 +23,16 @@ for (const width of [1200, 390]) {state: { status: 'standby', retry_at: null, detail_key: null },models: [], last_discovered_at: null,};+ // `mode` is the deployment mode and `version` is the schema — AuthGuard reads the+ // first, setup validates the second, and this fixture used to answer the schema in+ // the deployment field and neither of them correctly. No platform is enabled here+ // on purpose; `primary` is which one would be, which the envelope always carries.const config = () => ({- mode: 'v2', setup_completed: completed, setup_state: { needs_setup: !completed },+ version: 'v2', mode: 'self_host',+ setup_completed: completed, setup_state: { needs_setup: !completed },capabilities: { model_hub: { enabled: true } },- platforms: { enabled: [] },+ platforms: { primary: 'slack', enabled: [] },+ runtime: {},agents: Object.fromEntries(['claude', 'codex', 'opencode'].map((backend) => [backend, { enabled: backend === 'claude', cli_path: backend },])),diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.tsindex a2e090092..41754368e 100644--- a/ui/e2e/onboarding-fidelity/support.ts+++ b/ui/e2e/onboarding-fidelity/support.ts@@ -33,8 +33,17 @@ export const VIEWPORTS = [export const size = ({ width, height }: { width: number; height: number }) => `${width}x${height}`;+// A complete v2 envelope. Setup validates the config it acts on rather than reading+// fields out of whatever arrives, so a fixture missing `version`, `setup_completed`,+// `platforms.primary` or `runtime` is an UNREAD prerequisite — which is exactly the+// blocked state these captures are not about.const CONFIG = {- platforms: { enabled: [] },+ version: 'v2',+ setup_completed: false,+ capabilities: { model_hub: { enabled: true } },+ model_hub: { enabled: true },+ platforms: { primary: 'slack', enabled: [] },+ runtime: {},agents: {claude: { enabled: true, cli_path: 'claude' },codex: { enabled: true, cli_path: 'codex' },@@ -63,6 +72,17 @@ export async function serveProduct(page: Page) {denied.push(`${method} ${request.url()}`);return route.abort();});+ await page.route('**/api/csrf-token', (route) => route.fulfill({ json: { csrf_token: 'fixture-token' } }));+ await page.route('**/api/models/migration/scan', (route) => route.fulfill({ json: { scan: { items: [] } } }));+ // A Hub-enabled config makes the settings surfaces read the Hub projection. The+ // answers stay Direct-mode so every case authored before the gate keeps its path.+ await page.route('**/api/models/agents', (route) => route.fulfill({ json: { ok: true, agents: [] } }));+ await page.route('**/api/models/sources', (route) => route.fulfill({ json: { ok: true, sources: [] } }));+ await page.route('**/api/models/agents/*/sources', (route) => {+ const backend = new URL(route.request().url()).pathname.split('/')[4];+ return route.fulfill({ json: { ok: true, agent: { backend, mode: 'direct', sources: { order: [], eligibility: [] }, routes: {}, builtin_models: [], catalog_models: [], named_agents: [], menu: null, model_supply: [], supply_status: 'unavailable' } } });+ });+ await page.route('**/api/models/runtime/status', (route) => route.fulfill({ json: { ok: true, runtime: { contract_version: 10, enabled: true, host_platform: 'linux', manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', assets: [] }, status: { installed_version: 'fixture', verified: true, health: 'ok' } } } }));await page.route('**/status', (route) => route.fulfill({ json: { state: 'running' } }));await page.route('**/api/backend/*/connection', (route) => route.fulfill({ json: { ok: true, backend: new URL(route.request().url()).pathname.split('/').at(-2), installed: true, enabled: true, auth: 'none', application: 'applied', ready: false, entry_eligible: false } }));await page.route('**/api/config', (route) => route.fulfill({ json: CONFIG }));@@ -211,15 +231,11 @@ export async function setDocumentHidden(page: Page, hidden: boolean) {}export async function openSetup(page: Page, lang: string) {- await page.getByRole('button', { name: lang === 'zh' ? '开始使用' : 'Get started' }).click();+ 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);+ await page.locator('[data-setup-screen="assistants"]').waitFor();await page.locator('.onboarding-assistants').waitFor();- // The step switch plays a 450ms entrance that translates and blurs the incoming- // composition. It runs on the document timeline, so a frozen clock does not hold- // it; geometry read mid-entrance would be geometry of a composition still- // arriving. CSS animations, unlike timers, settle on their own.- await page.locator('.onboarding-step').evaluate((node) => Promise.all(- node.getAnimations({ subtree: false }).map((animation) => animation.finished.catch(() => null)),- ));}/**diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsxindex 7931267b8..d9c2c0bad 100644--- a/ui/src/components/Wizard.tsx+++ b/ui/src/components/Wizard.tsx@@ -1,4 +1,15 @@-import { useCallback, useEffect, useRef, useState } from 'react';+import { 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 { 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';+import { SETUP_REGISTERED_SCREENS } from './onboarding/setupScreenRegistry';+import './onboarding/onboarding.css';import { useNavigate } from 'react-router-dom';import { useTranslation } from 'react-i18next';import { Welcome } from './steps/Welcome';@@ -37,35 +48,268 @@ function SetupHeader() {);}+/**+ * A read that failed, kept as two different kinds of string.+ *+ * `message` is the line a person reads, and it only ever comes from a bundle key — the+ * producer resolves it, so a Chinese setup is addressed in Chinese whatever the server+ * happened to say. `detail` is what the server or the transport said: English error+ * text, a backend code, a transport exception. That is diagnostics, not copy, and it is+ * shown as a disclosure beside the sentence rather than as the sentence.+ *+ * Because `message` is language-bound the moment it is produced, the read that produces+ * it re-runs when the language changes — which is also how a second config read can+ * legitimately start while an earlier one is still open.+ */+export type SetupReadFailure = {+ message: string;+ detail?: string;+};++type FlowShellProps = {+ sequence: readonly SetupScreenId[];+ capability: SetupCapability;+ gatewayEnabled: boolean | null;+ onRetrySetup: () => void;+ loading?: boolean;+ error?: SetupReadFailure | null;+ paused?: boolean;+ /**+ * Something the parent is showing inside the active screen owns the flow until it+ * is finished or cancelled, so the shell may not move away from it.+ *+ * Private between this shell and its parent — deliberately NOT part of C2. A screen+ * publishes `busy` to say "work is running, show the spinner"; a recovery is usually+ * idle, waiting for someone to type. Those are different facts and the pair draws+ * them differently: this one holds the controls without claiming anything is running.+ */+ navigationLocked?: boolean;+ runtimeRead: SetupScreenProps['runtimeRead'];+ renderScreen: (id: SetupScreenId, props: SetupScreenProps, ref: Ref<SetupScreenHandle>) => ReactElement<{ ref?: Ref<SetupScreenHandle> }>;+};++function SetupScreenContent({ id, screenProps, renderScreen, ref }: {+ id: SetupScreenId; screenProps: SetupScreenProps; renderScreen: FlowShellProps['renderScreen']; ref: Ref<SetupScreenHandle>;+}) {+ return renderScreen(id, screenProps, ref);+}++/** One mounted screen collection and one action pair. Activation epochs reject late work. */+export function SetupFlowShell({ sequence, capability, gatewayEnabled, onRetrySetup, loading = false, error = null, paused = false, navigationLocked = false, runtimeRead, renderScreen }: FlowShellProps) {+ const { t } = useTranslation();+ const routeActive = useRouteSurfaceActive();+ const [activation, setActivation] = useState({ id: sequence[0], epoch: 0 });+ const [handoff, setHandoff] = useState<SetupScreenProps['handoff']>(false);+ const [action, setAction] = useState<SetupAction | null>(null);+ const [flowState, setFlowState] = useState(INITIAL_SETUP_FLOW_STATE);+ const host = useRef<HTMLDivElement>(null);+ const roots = useRef<Partial<Record<SetupScreenId, HTMLDivElement | null>>>({});+ const handles = useRef<Partial<Record<SetupScreenId, SetupScreenHandle | null>>>({});+ const current = useRef(activation);+ const transition = useRef<(() => void) | null>(null);+ const transitioning = useRef(false);+ const ready = setupNavigationReady(capability, gatewayEnabled);+ const policy = useRef({ ready, sequence, locked: navigationLocked, routeActive });+ useLayoutEffect(() => { current.current = activation; policy.current = { ready, sequence, locked: navigationLocked, routeActive }; });+ useLayoutEffect(() => {+ roots.current[activation.id]?.querySelector<HTMLElement>('h1')?.focus({ preventScroll: true });+ }, [activation]);+ useEffect(() => () => transition.current?.(), []);++ const navigate = useCallback((target: SetupScreenId) => {+ // The guard is here rather than on the Back button, because a screen's own+ // `onNavigate` reaches the same journey without touching that button at all —+ // and an asynchronous continuation that settles after `/setup` was retained+ // behind another surface reaches it without anyone touching anything.+ //+ // Three facts decide whether this journey may move, and this is the one place+ // that answers for all three: the recovery hold, the activation that issued the+ // request, and whether the route surface holding this shell is the one being+ // read. A screen may re-check its own activity, but it cannot be the owner:+ // every screen would have to remember to, and a future one would not.+ if (policy.current.locked || !policy.current.routeActive) return;+ if (transitioning.current || !policy.current.sequence.includes(target) || target === current.current.id) return;+ const previous = current.current;+ const backwards = policy.current.sequence.indexOf(target) < policy.current.sequence.indexOf(previous.id);+ if (!backwards && !policy.current.ready) return;+ const next = { id: target, epoch: previous.epoch + 1 };+ const finish = () => {+ transition.current = null;+ transitioning.current = false;+ current.current = next;+ setAction(null);+ setHandoff(false);+ setActivation(next);+ };+ if (mediaQuery('(max-width: 759px)')) {+ host.current?.closest('.onboarding-shell')?.scrollTo({ top: 0, behavior: 'instant' });+ window.scrollTo({ top: 0, behavior: 'instant' });+ }+ if (backwards || !setupHandoffAllowed(paused) || !host.current || !roots.current[previous.id] || !roots.current[target]) {+ finish(); return;+ }+ transitioning.current = true;+ setHandoff(target === 'intro' ? false : target);+ transition.current = playSetupHandoff(host.current, roots.current[previous.id]!, roots.current[target]!, previous.id, target, finish);+ }, [paused]);+ // A callback belongs to this activation, even if an asynchronous consumer saves it.+ const feeds = useMemo(() => Object.fromEntries(sequence.map((id) => [id, {+ onActionChange: (next: SetupAction) => {+ if (current.current.id === id && current.current.epoch === activation.epoch && !transitioning.current) setAction(next);+ },+ onNavigate: (target: SetupScreenId) => {+ if (current.current.id === id && current.current.epoch === activation.epoch) navigate(target);+ },+ }])) as Record<SetupScreenId, Pick<SetupScreenProps, 'onActionChange' | 'onNavigate'>>, [activation.epoch, navigate, sequence]);+ const back = setupBackTarget(sequence, activation.id);+ const authoritativeBlock = capability === 'disabled' || gatewayEnabled === false;+ const retry = !loading && (authoritativeBlock || !!error);+ return <div className="onboarding-step" data-setup-sequence={sequence.join(' ')} data-setup-screen={activation.id} data-handoff={handoff || undefined}>+ <div className="onboarding-screens" ref={host}>+ {sequence.map((id) => {+ const active = routeActive && id === activation.id;+ return <div key={id} ref={(node) => { roots.current[id] = node; }} data-setup-screen-root={id}+ hidden={id !== activation.id} inert={!active || !!handoff}>+ <RouteSurfaceActiveContext.Provider value={active && !handoff}>+ <SetupScreenContent id={id} screenProps={{ active, handoff, capability, gatewayEnabled, runtimeRead,+ onRetrySetup, flowState, setFlowState, ...feeds[id] }} renderScreen={renderScreen}+ ref={(handle) => { handles.current[id] = handle; }} />+ </RouteSurfaceActiveContext.Provider>+ </div>;+ })}+ </div>+ <div className="onboarding-setup-footer">+ <Button type="button" variant="brand" className="group onboarding-action-w onboarding-primary-action"+ disabled={loading || !!handoff || navigationLocked || (!retry && (!action || action.disabled || action.busy || !ready))}+ onClick={() => { if (transitioning.current || policy.current.locked) return; if (retry) onRetrySetup(); else if (ready && action && !action.disabled && !action.busy) handles.current[current.current.id]?.activate(); }}>+ {t(loading ? 'common.loading' : retry ? 'common.retry' : action?.labelKey ?? 'common.loading', action?.labelArgs)}+ {(loading || action?.busy || action?.icon === 'spinner') ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : action?.icon === 'arrow-right' && <ArrowRight size={16} />}+ </Button>+ <Button type="button" variant="ghost" className="onboarding-action-w onboarding-back-action" style={{ visibility: back ? 'visible' : 'hidden' }}+ disabled={!back || !!handoff || !!action?.busy || navigationLocked} onClick={() => { if (back) navigate(back); }}>+ <ArrowLeft size={14} />{t(back === 'providers' ? 'onboarding.flow.backToProviders' : 'onboarding.flow.backToIntro')}+ </Button>+ </div>+ {/* Where a screen puts what is ancillary to the pair above: below it, in normal flow,+ so a caption that grows can neither move the anchor nor cover it. */}+ <div className="onboarding-action-aside" data-setup-action-aside="" />+ {(authoritativeBlock || (!!error && !loading)) && <div className="onboarding-flow-error" role="alert">+ <p>{authoritativeBlock ? t('onboarding.flow.gatewayRequired') : error?.message ?? t('onboarding.connection.readFailed')}</p>+ {/* Same shape the detection failure already uses one screen over: the sentence+ addresses the reader, the disclosure keeps what the server actually said. */}+ {!authoritativeBlock && error?.detail && <details className="mt-2 max-w-xl break-words">+ <summary>{t('onboarding.details')}</summary>{error.detail}</details>}+ </div>}+ {/* The owner handoff, the design boards and the prototype all collapse the six entry+ tiles for the whole setup journey; the block stays mounted hidden and inert so its+ motion lifecycle survives, and the reserved stage keeps the anchor where it was. */}+ <AccessTiles active={false} />+ </div>;+}+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 [step, setStep] = useState<'welcome' | 'agents'>('welcome');- // The first screen arrives without an entrance of its own — the reference opens- // on it, settled. Only a switch between the two screens plays the transition, so- // the flag flips in the two places that move between them, never on mount.- const [entered, setEntered] = useState(false);const [data, setData] = useState<Record<string, any> | null>(null);- const [error, setError] = useState('');+ 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.+ const [runtimeRead, setRuntimeRead] = useState<SetupScreenProps['runtimeRead']>(() => loadingRegion());const completing = useRef(false);+ /**+ * The single place a config read becomes shell state.+ *+ * Unknown is not an opt-out. An unread answer — transport, HTTP, JSON or shape —+ * leaves the prerequisite pending/null and says so, which is what turns the shared+ * primary into an explicit Retry. It never decays into `false`, which would claim+ * the gateway is off, nor into `true`, which would let setup finish against a+ * prerequisite nobody could confirm.+ */+ const applyRead = useCallback((result: SetupConfigRead): SetupConfigSnapshot | null => {+ if (result.state === 'unread') {+ setCapability('pending'); setGatewayEnabled(null);+ // The sentence is copy, so both bundles own it, and an HTTP status is a number+ // the sentence can carry. What the server or the transport said is not copy — it+ // is written in whatever language that producer speaks — so it travels beside+ // the sentence as a disclosure and never becomes the sentence itself.+ setError({+ message: result.status !== undefined+ ? t('onboarding.connection.readFailedStatus', { status: result.status })+ : t('onboarding.connection.readFailed'),+ detail: result.detail,+ });+ setRuntimeRead((previous) => failRegionRead(previous));+ return null;+ }+ const snapshot = result.config;+ setData(snapshot.raw); setError(null);+ setCapability(setupCapability(modelHubEnabledFromConfig(snapshot.raw)));+ setGatewayEnabled(snapshot.savedIntentEnabled);+ return snapshot;+ }, [t]);const load = useCallback(async () => {- setError('');- try { setData(await api.getConfig()); }- catch (cause) { setError(String(cause)); }- }, [api]);- useEffect(() => { void load(); }, [load]);+ 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.+ if (generation !== configGeneration.current) return;+ applyRead(result);+ setLoading(false);+ }, [applyRead]);+ useEffect(() => { void load(); return () => { configGeneration.current += 1; }; }, [load]);+ /**+ * Read the prerequisite as it is now, and answer whether setup may still act on it.+ *+ * `null` means stop, for the three reasons a caller must treat identically: the read+ * failed, the gateway is persisted off, or a newer read took ownership while this one+ * was in flight — a config Retry racing the completion owner. None of them may write.+ *+ * A successful read hands back the generation it claimed. That is the lease the+ * caller carries through its awaited work: an admission is only good for as long as+ * it is still the current answer. Passing a lease back in asks to renew it, which an+ * owner that has already lost it may not do — re-reading is how a live completion+ * continues, not how an obsolete one comes back to life.+ */+ const readPrerequisite = useCallback(async (held?: number): Promise<{ config: SetupConfigSnapshot; lease: number } | null> => {+ if (held !== undefined && held !== configGeneration.current) return null;+ const generation = ++configGeneration.current;+ const result = await fetchSetupConfig();+ if (generation !== configGeneration.current) return null;+ const snapshot = applyRead(result);+ if (!snapshot) return null;+ if (!setupNavigationReady(setupCapability(modelHubEnabledFromConfig(snapshot.raw)), snapshot.savedIntentEnabled)) return null;+ return { config: snapshot, lease: generation };+ }, [applyRead]);const complete = async () => {if (completing.current) return;completing.current = true;try {- const freshConfig = await api.getConfig();- const enabledPlatforms = getEnabledPlatforms(freshConfig);- const missing = getPlatformCatalog(freshConfig).find((platform) => enabledPlatforms.includes(platform.id) && !platformHasRunnableConfig(freshConfig, platform.id));+ // The prerequisite is persisted state another browser, operator or Settings page+ // can switch off while this flow is open, so completion reads it instead of+ // trusting the initial load. A refusal here writes nothing and leaves the shell+ // showing why, with Retry.+ const entry = await readPrerequisite();+ if (!entry) return;+ // Everything below is awaited, and an answer read before a wait is not an answer+ // that survives it. The lease is what the rest of this operation acts under: each+ // step asks whether the admission it started from is still the current one, and a+ // newer load — a Retry, a language change, this shell unmounting — ends it here.+ // Writes already issued cannot be recalled; the lease is what stops the next one.+ let lease = entry.lease;+ const holds = () => lease === configGeneration.current;+ const enabledPlatforms = getEnabledPlatforms(entry.config.raw);+ const missing = getPlatformCatalog(entry.config.raw).find((platform) => enabledPlatforms.includes(platform.id) && !platformHasRunnableConfig(entry.config.raw, platform.id));if (missing) {- setPlatformRecovery({ config: freshConfig, descriptor: missing });+ setPlatformRecovery({ config: entry.config.raw, descriptor: missing });return;}const readCandidates = async () => {@@ -73,18 +317,22 @@ export function Wizard() {return results.flatMap((result) => result.status === 'fulfilled' && result.value.ok ? [result.value] : []);};let connections = await readCandidates();+ 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'));const started = await control('start');+ if (!holds()) return;if (started?.ok === false) throw new Error(started.message || t('onboarding.connection.entryFailed'));connections = await readCandidates();+ if (!holds()) return;}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');@@ -92,6 +340,7 @@ export function Wizard() {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);@@ -104,32 +353,43 @@ export function Wizard() {}}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+ // boundary. This is not a cross-process transaction; it is the last moment the+ // browser can still see a gateway that was turned off underneath it.+ 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);+ // 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'));}// 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)]);+ if (!holds()) return;navigate('/', { state: { onboardingCompleted: true } });} finally { completing.current = false; }};- if (!data) return <div className="min-h-screen flex flex-col items-center justify-center bg-background text-muted">- {error ? <><p role="alert">{error}</p><button onClick={() => void load()}>{t('common.retry')}</button></> : t('common.loading')}- </div>;return <div className="onboarding-shell"><SetupHeader /><main className="onboarding-shell-content">- {/* One keyed wrapper per step: switching steps swaps the composition and- the incoming one fades, slides and unblurs in, the way the reference's- connection layer arrives over the introduction. Reduced motion takes the- whole shell's animation away, so the swap stays instant for it. */}- <div key={step} className={entered ? 'onboarding-step onboarding-step-enter' : 'onboarding-step'}>- {step === 'welcome' ? <Welcome data={data} onNext={(next) => { setData({ ...data, ...Object(next) }); setStep('agents'); setEntered(true); window.scrollTo({ top: 0, behavior: 'instant' }); }} />- : <AgentDetection data={data} 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} onNext={complete} onBack={(next) => { setData({ ...data, ...next }); setStep('welcome'); setEntered(true); window.scrollTo({ top: 0, behavior: 'instant' }); }} />}- </div>+ <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'+ ? <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]); }} />+ : <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}+ onNext={complete} />}+ /></main></div>;}diff --git a/ui/src/components/onboarding/AccessTiles.tsx b/ui/src/components/onboarding/AccessTiles.tsxindex 05fa2fe1a..fb9811dbd 100644--- a/ui/src/components/onboarding/AccessTiles.tsx+++ b/ui/src/components/onboarding/AccessTiles.tsx@@ -5,9 +5,9 @@ import { useOnboardingMotion } from './motion';const PLATFORMS = ['avibe', 'slack', 'discord', 'telegram', 'lark', 'wechat'] as const;-export function AccessTiles() {+export function AccessTiles({ active = true }: { active?: boolean }) {const { t } = useTranslation();- const { ref, running } = useOnboardingMotion();+ const { ref, running } = useOnboardingMotion(active);const [pointerInside, setPointerInside] = useState(false);const [focusInside, setFocusInside] = useState(false);const [emphasis, setEmphasis] = useState<number | null>(null);@@ -25,7 +25,7 @@ export function AccessTiles() {}, [automatic]);return (- <section ref={ref} className="onboarding-access" aria-label={t('onboarding.access.label')}>+ <section ref={ref} className="onboarding-access" hidden={!active} inert={!active} aria-label={t('onboarding.access.label')}><p>{t('onboarding.access.description')}</p><ul className="onboarding-access-grid" onPointerEnter={() => setPointerInside(true)} onPointerLeave={() => setPointerInside(false)}onFocus={() => setFocusInside(true)} onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) setFocusInside(false); }}>diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsxindex 5fa3524bc..4ea391bf8 100644--- a/ui/src/components/onboarding/AssistantSetup.test.tsx+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+import { StrictMode } from 'react';import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { createInstance } from 'i18next';import { I18nextProvider } from 'react-i18next';@@ -9,9 +10,10 @@ import { AssistantRow } from './AssistantRow';import en from '../../i18n/en.json';import type { BackendConnectionState } from '../../context/ApiContext';import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';+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(),+ 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(),} }));vi.mock('../../context/ApiContext', () => ({ useApi: () => mock.api }));vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));@@ -24,6 +26,13 @@ const LocationProbe = () => <span data-testid="location">{useLocation().pathnameconst wrap = (node: React.ReactNode, active = true) => <MemoryRouter><I18nextProvider i18n={i18n}><RouteSurfaceActiveContext.Provider value={active}>{node}</RouteSurfaceActiveContext.Provider><LocationProbe /></I18nextProvider></MemoryRouter>;const data = () => ({ __onboardingDetected: true, agents: Object.fromEntries(['claude', 'codex', 'opencode'].map((name) => [name, { enabled: true, cli_path: name, status: 'missing' }])) });const row = (name: string) => within(screen.getByLabelText(name));+// The shell's own adapter: every screen stays mounted, Back is a deactivation rather+// than an unmount, and the screen publishes its action instead of drawing one. The+// cases below go through that adapter because the retained-screen bugs only exist there.+const next = vi.fn();+const shown = (saved: ReturnType<typeof data>, active: boolean, onActionChange: (action: SetupAction) => void) =>+ wrap(<AgentDetection data={saved} active={active} onActionChange={onActionChange} onNext={next} />, active);+const configureAction = () => row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ });beforeEach(() => {vi.resetAllMocks();mock.api.getConfig.mockResolvedValue(data());@@ -233,6 +242,91 @@ describe('assistant installation presentation', () => {expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false);expect(row('Codex').getByRole('button', { name: 'Installed' })).toBeTruthy();});+ it('settles an enable write that lands while the screen is away, and reads nothing from hiding', async () => {+ const saved = data(); saved.agents.claude.status = 'ok';+ // The persisted value the uncached projection would report, moved by the write.+ let persisted = false;+ mock.api.getBackendConnection.mockImplementation(async (backend: string) => ({+ ok: true, backend, installed: true, auth: 'api_key', application: 'applied',+ enabled: backend === 'claude' ? persisted : true,+ ready: backend === 'claude' && persisted,+ entry_eligible: backend === 'claude' && persisted,+ }));+ let finishWrite!: (value: unknown) => void;+ const actions: SetupAction[] = [];+ const publish = (action: SetupAction) => { actions.push(action); };+ const view = render(shown(saved, false, publish));+ view.rerender(shown(saved, true, publish));+ const enable = () => row('Claude Code').getByRole('switch');+ await waitFor(() => expect(enable().getAttribute('aria-checked')).toBe('false'));+ await waitFor(() => expect(actions.at(-1)?.disabled).toBe(true));++ mock.api.mutateConfig.mockImplementation(() => new Promise((resolve) => { finishWrite = resolve; }));+ fireEvent.click(enable());+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());++ // Back, while the write the person asked for is still in flight.+ view.rerender(shown(saved, false, publish));+ const readsWhileHidden = mock.api.getBackendConnection.mock.calls.length;+ const publishedWhileHidden = actions.length;+ persisted = true;+ await act(async () => { finishWrite({ ok: true }); });+ // A screen nobody is reading owns no side effects: settling is bookkeeping only.+ expect(mock.api.getBackendConnection.mock.calls.length).toBe(readsWhileHidden);+ expect(actions.length).toBe(publishedWhileHidden);++ // Returning pays what that write owed, instead of latching the row pending behind+ // an intent check that can never pass again.+ view.rerender(shown(saved, true, publish));+ await waitFor(() => expect(actions.at(-1)?.disabled).toBe(false));+ expect(enable().getAttribute('aria-checked')).toBe('true');+ expect(configureAction().hasAttribute('disabled')).toBe(false);+ expect(mock.api.mutateConfig).toHaveBeenCalledOnce();+ });++ it('reports an enable write that failed while the screen was away instead of losing it', async () => {+ const saved = data(); saved.agents.claude.status = 'ok';+ let failWrite!: (reason: Error) => void;+ const publish = vi.fn();+ const view = render(shown(saved, false, publish));+ view.rerender(shown(saved, true, publish));+ await waitFor(() => expect(configureAction().hasAttribute('disabled')).toBe(false));+ mock.api.mutateConfig.mockImplementation(() => new Promise((_resolve, reject) => { failWrite = reject; }));+ fireEvent.click(row('Claude Code').getByRole('switch'));+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());+ view.rerender(shown(saved, false, publish));+ await act(async () => { failWrite(new Error('fixture persist failure')); });+ view.rerender(shown(saved, true, publish));+ // The receipt is what the write actually did, and returning is when there is finally+ // someone to tell. Dropping it would leave a silent failure behind a clean read.+ expect((await row('Claude Code').findByRole('alert')).textContent).toContain('fixture persist failure');+ });++ it('probes the path this screen learned, not the parent snapshot, when it is shown again', async () => {+ const saved = data();+ saved.agents.claude.cli_path = '/stale/claude';+ // Only the retained path resolves, so a probe that fell back to the snapshot is+ // visible twice over: in the call log, and as a backend reported missing again.+ mock.api.detectCli.mockImplementation((binary: string) => Promise.resolve(+ binary === '/retained/claude' ? { found: true, path: '/retained/claude' } : { found: false }));+ mock.api.installAgent.mockResolvedValue({ ok: true, path: '/retained/claude', message: '' });+ const probes = (binary: string) => mock.api.detectCli.mock.calls.filter(([called]) => called === binary).length;+ const publish = vi.fn();+ const view = render(shown(saved, false, publish));+ view.rerender(shown(saved, true, publish));+ // The first showing does adopt the snapshot: Welcome may have detected after this+ // retained screen mounted. That is the one probe the stale path ever gets.+ await waitFor(() => expect(probes('/stale/claude')).toBe(1));+ fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));+ await waitFor(() => expect(row('Claude Code').getByRole('button', { name: 'Installed' })).toBeTruthy());+ const retainedProbes = probes('/retained/claude');++ view.rerender(shown(saved, false, publish));+ view.rerender(shown(saved, true, publish));+ await waitFor(() => expect(probes('/retained/claude')).toBe(retainedProbes + 1));+ expect(probes('/stale/claude')).toBe(1);+ expect(row('Claude Code').getByRole('button', { name: 'Installed' })).toBeTruthy();+ });it('does not enable entry from installed, draining, failed or unknown states', async () => {for (const application of ['draining', 'failed', 'unknown']) {mock.api.getBackendConnection.mockResolvedValue({ ok: true, auth: 'api_key', application, ready: false, entry_eligible: false });@@ -308,6 +402,191 @@ describe('settled wizard enablement follows persistence and latest intent', () =await waitFor(() => expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false));expect(checkedOf(checkbox)).toBe(true); expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2);});+ // XpVM: what a settled write decided is owed to this screen until somebody who can+ // answer for it reports it. A read starting is not that somebody.+ const failedToggle = async (checkbox: HTMLElement) => {+ mock.api.mutateConfig.mockRejectedValue(new Error('fixture persist failure'));+ fireEvent.click(checkbox);+ expect((await row('Claude Code').findByRole('alert')).textContent).toContain('fixture persist failure');+ };+ const cardAlert = () => row('Claude Code').queryByRole('alert')?.textContent ?? null;+ it('a read that started before the write cannot clear the verdict it never saw', async () => {+ const checkbox = mountReady();+ await row('Claude Code').findByRole('button', { name: 'API Key connected' });+ const early = pending<ReturnType<typeof stateFor>>();+ mock.api.getBackendConnection.mockImplementation((name) => name === 'claude' ? early.promise : Promise.resolve(stateFor(name)));+ fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));+ await waitFor(() => expect(mock.api.detectCli).toHaveBeenCalledWith('claude'));+ mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));+ await failedToggle(checkbox);+ await act(async () => early.resolve(stateFor('claude')));+ expect(cardAlert()).toContain('fixture persist failure');+ });+ it('competing refreshes settling in reverse order each still report the write verdict', async () => {+ const checkbox = mountReady();+ await row('Claude Code').findByRole('button', { name: 'API Key connected' });+ const slow = pending<ReturnType<typeof stateFor>>();+ let reads = 0;+ mock.api.getBackendConnection.mockImplementation((name) => {+ if (name !== 'claude') return Promise.resolve(stateFor(name));+ reads += 1;+ return reads === 1 ? slow.promise : Promise.resolve(stateFor(name));+ });+ await failedToggle(checkbox);+ await waitFor(() => expect(reads).toBe(1));+ // A second ordinary refresh overtakes the first and answers for the same write.+ fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));+ await waitFor(() => expect(reads).toBe(2));+ expect(cardAlert()).toContain('fixture persist failure');+ await act(async () => slow.resolve(stateFor('claude')));+ expect(cardAlert()).toContain('fixture persist failure');+ // Reported, not latched: the card is still offering the retry that answers it.+ await waitFor(() => expect(row('Claude Code').getByRole('button', { name: 'Retry' }).hasAttribute('disabled')).toBe(false));+ });+ it('only an acknowledged refresh retires the verdict', async () => {+ const checkbox = mountReady();+ await row('Claude Code').findByRole('button', { name: 'API Key connected' });+ await failedToggle(checkbox);+ const rescan = () => fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));+ const probes = () => mock.api.detectCli.mock.calls.length;+ let seen = probes(); rescan();+ await waitFor(() => expect(probes()).toBeGreaterThan(seen));+ expect(cardAlert()).toContain('fixture persist failure');+ fireEvent.click(row('Claude Code').getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(cardAlert()).toBeNull());+ // Retired for good: an ordinary refresh afterwards does not bring it back.+ seen = probes(); rescan();+ await waitFor(() => expect(probes()).toBeGreaterThan(seen));+ expect(cardAlert()).toBeNull();+ expect(mock.api.mutateConfig).toHaveBeenCalledOnce();+ });+ // Lifecycle is not an answer. A dialog that only opened, a write that failed and+ // said so by reporting nothing pending, a read that failed, an acknowledgement that+ // lost the screen — each of these used to make an unresolved apply failure+ // disappear. They run through the shell adapter, which is the host the wizard uses.+ const owedInShell = async () => {+ const saved = data(); saved.agents.claude.status = 'ok';+ mock.api.getConfig.mockResolvedValue(saved);+ mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));+ const publish = vi.fn();+ const view = render(shown(saved, false, publish));+ view.rerender(shown(saved, true, publish));+ await row('Claude Code').findByRole('button', { name: 'API Key connected' });+ await failedToggle(row('Claude Code').getByRole('switch') as HTMLElement);+ await waitFor(() => expect(configureAction().hasAttribute('disabled')).toBe(false));+ return { view, publish, saved };+ };+ const retryLink = () => row('Claude Code').getByRole('button', { name: 'Retry' });+ it('a provider dialog that only opened and closed answers for nothing', async () => {+ await owedInShell();+ fireEvent.click(row('Claude Code').getByRole('button', { name: /Add subscription/ }));+ const dialog = await screen.findByRole('dialog');+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ // Closing re-reads persisted config and the connection. Neither of them connected+ // anything, so the failure the person still has to deal with is still there.+ await waitFor(() => expect(configureAction().hasAttribute('disabled')).toBe(false));+ expect(cardAlert()).toContain('fixture persist failure');+ expect(retryLink().hasAttribute('disabled')).toBe(false);+ });+ it('a provider write that failed reports nothing pending, which answers for nothing', async () => {+ await owedInShell();+ fireEvent.click(row('Claude Code').getByRole('button', { name: 'Add API Key' }));+ const dialog = await screen.findByRole('dialog');+ const secret = await waitFor(() => dialog.querySelector('input[type="password"]') as HTMLInputElement);+ fireEvent.change(secret, { target: { value: 'sk-ant-fixture' } });+ mock.api.saveClaudeAuth.mockResolvedValue({ ok: false, message: 'fixture provider failure' });+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save and connect' }));+ await waitFor(() => expect(within(dialog).getByRole('alert').textContent).toContain('fixture provider failure'));+ await act(async () => {});+ // The card sits behind an open modal here, so its line is read from the document+ // rather than from the accessibility tree the dialog has taken over.+ expect(screen.getByLabelText('Claude Code').querySelector('.onboarding-assistant-error')?.textContent).toContain('fixture persist failure');+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ await waitFor(() => expect(configureAction().hasAttribute('disabled')).toBe(false));+ expect(cardAlert()).toContain('fixture persist failure');+ });+ it('an acknowledgement that lost the screen cannot clear what it no longer owns', async () => {+ const { view, publish, saved } = await owedInShell();+ const slow = pending<ReturnType<typeof stateFor>>();+ let reads = 0;+ mock.api.getBackendConnection.mockImplementation((name) => {+ if (name !== 'claude') return Promise.resolve(stateFor(name));+ reads += 1;+ return reads === 1 ? slow.promise : Promise.resolve(stateFor(name));+ });+ // Retry is the one caller here that may spend the verdict — until the person+ // leaves the screen under it and comes back to a different activation.+ fireEvent.click(retryLink());+ await waitFor(() => expect(reads).toBe(1));+ view.rerender(shown(saved, false, publish));+ view.rerender(shown(saved, true, publish));+ await waitFor(() => expect(reads).toBeGreaterThan(1));+ await act(async () => slow.resolve(stateFor('claude')));+ expect(cardAlert()).toContain('fixture persist failure');+ // And ordinary recovery still works: a Retry that does own the screen retires it.+ fireEvent.click(retryLink());+ await waitFor(() => expect(cardAlert()).toBeNull());+ expect(mock.api.mutateConfig).toHaveBeenCalledOnce();+ });+ it('an explicit Retry whose read failed keeps the verdict it could not answer', async () => {+ const { view, publish, saved } = await owedInShell();+ let reads = 0;+ mock.api.getBackendConnection.mockImplementation((name) => {+ if (name === 'claude') reads += 1;+ return Promise.reject(new Error('fixture read failure'));+ });+ fireEvent.click(retryLink());+ await waitFor(() => expect(reads).toBe(1));+ await act(async () => {});+ expect(cardAlert()).toContain('fixture persist failure');+ expect(cardAlert()).not.toContain('fixture read failure');+ // Still owed, and a healthy ordinary read on return proves it: had the failed+ // acknowledgement spent it, that read would have had nothing to report.+ mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));+ view.rerender(shown(saved, false, publish));+ view.rerender(shown(saved, true, publish));+ await waitFor(() => expect(configureAction().hasAttribute('disabled')).toBe(false));+ expect(cardAlert()).toContain('fixture persist failure');+ fireEvent.click(retryLink());+ await waitFor(() => expect(cardAlert()).toBeNull());+ });+ it('a read that also failed does not bury what the write reported', async () => {+ const checkbox = mountReady();+ await row('Claude Code').findByRole('button', { name: 'API Key connected' });+ mock.api.getBackendConnection.mockRejectedValue(new Error('fixture read failure'));+ await failedToggle(checkbox);+ expect(cardAlert()).not.toContain('fixture read failure');+ });+ it('a successful read still reports the write that failed under it', async () => {+ const checkbox = mountReady();+ await row('Claude Code').findByRole('button', { name: 'API Key connected' });+ await failedToggle(checkbox);+ // The projection is healthy and says enabled; the apply underneath it was not.+ expect(checkedOf(checkbox)).toBe(true);+ expect(cardAlert()).toContain('fixture persist failure');+ });+ it('a StrictMode replay of the return neither loses nor doubles the verdict', async () => {+ const saved = data(); saved.agents.claude.status = 'ok';+ mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));+ const publish = vi.fn();+ const strict = (active: boolean) => <StrictMode>{wrap(<AgentDetection data={saved} active={active} onActionChange={publish} onNext={vi.fn()} />, active)}</StrictMode>;+ const view = render(strict(false));+ view.rerender(strict(true));+ const checkbox = () => row('Claude Code').getByRole('switch');+ await waitFor(() => expect(checkedOf(checkbox())).toBe(true));+ let failWrite!: (reason: Error) => void;+ mock.api.mutateConfig.mockImplementation(() => new Promise((_resolve, reject) => { failWrite = reject; }));+ fireEvent.click(checkbox());+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());+ view.rerender(strict(false));+ await act(async () => { failWrite(new Error('fixture persist failure')); });+ view.rerender(strict(true));+ await waitFor(() => expect(cardAlert()).toContain('fixture persist failure'));+ expect(row('Claude Code').getAllByRole('alert')).toHaveLength(1);+ expect(mock.api.mutateConfig).toHaveBeenCalledOnce();+ });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/CollaborationStory.tsx b/ui/src/components/onboarding/CollaborationStory.tsxindex 82b9a4409..051399035 100644--- a/ui/src/components/onboarding/CollaborationStory.tsx+++ b/ui/src/components/onboarding/CollaborationStory.tsx@@ -135,9 +135,9 @@ function Circuit({ handoff }: { handoff: { wire: number; progress: number } | nu}/** The design has no playback controls, so the loop starts with the screen and owns itself. */-export function CollaborationStory() {+export function CollaborationStory({ active = true }: { active?: boolean }) {const { t } = useTranslation();- const { ref, reducedMotion, running } = useOnboardingMotion();+ const { ref, reducedMotion, running } = useOnboardingMotion(active);const [elapsed, setElapsed] = useState(0);useEffect(() => {if (!running) return;diff --git a/ui/src/components/onboarding/SetupFlowShell.test.tsx b/ui/src/components/onboarding/SetupFlowShell.test.tsxnew file mode 100644index 000000000..05900806c--- /dev/null+++ b/ui/src/components/onboarding/SetupFlowShell.test.tsx@@ -0,0 +1,100 @@+// @vitest-environment jsdom+import { useEffect, useImperativeHandle, useState, type Ref } from 'react';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { createInstance } from 'i18next';+import { I18nextProvider } from 'react-i18next';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { SetupFlowShell } from '../Wizard';+import { SETUP_SCREENS, setupBackTarget, type SetupScreenHandle, type SetupScreenId, type SetupScreenProps } from './setupFlow';+import { registeredSetupSequence, SETUP_REGISTERED_SCREENS } from './setupScreenRegistry';+import { loadingRegion } from '../settings/models/regionRead';+import en from '../../i18n/en.json';++const i18n = createInstance();+await i18n.init({ lng: 'en', resources: { en: { translation: en } } });+const savedFeeds: SetupScreenProps[] = [];+function Screen({ id, ref, ...props }: SetupScreenProps & { id: SetupScreenId; ref?: Ref<SetupScreenHandle> }) {+ const [value, setValue] = useState('');+ useEffect(() => {+ if (props.active) {+ savedFeeds.push(props);+ props.onActionChange({ labelKey: 'onboarding.welcome.getStarted', disabled: false, busy: false, icon: 'none' });+ }+ }, [props.active, props.onActionChange]);+ useImperativeHandle(ref, () => ({ activate: () => props.onNavigate(id === 'intro' ? 'providers' : 'assistants') }));+ return <><h1 tabIndex={-1}>{id}</h1><input aria-label={`${id} draft`} value={value} onChange={(event) => setValue(event.target.value)} /></>;+}+const show = (capability: SetupScreenProps['capability'] = 'enabled', gatewayEnabled: boolean | null = true,+ extra: { navigationLocked?: boolean; onRetrySetup?: () => void } = {}) =>+ <I18nextProvider i18n={i18n}><SetupFlowShell sequence={SETUP_SCREENS} capability={capability} gatewayEnabled={gatewayEnabled}+ onRetrySetup={extra.onRetrySetup ?? vi.fn()} navigationLocked={extra.navigationLocked} runtimeRead={loadingRegion()}+ renderScreen={(id, props, ref) => <Screen {...props} id={id} ref={ref} />} /></I18nextProvider>;+beforeEach(() => {+ savedFeeds.length = 0;+ vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false, addEventListener() {}, removeEventListener() {} })));+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+});+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.each(['pending', 'disabled', 'enabled'] as const)('policy %s never removes a registered screen', (capability) => {+ const { container } = render(show(capability, false));+ expect([...container.querySelectorAll('[data-setup-screen-root]')].map((node) => node.getAttribute('data-setup-screen-root'))).toEqual(SETUP_SCREENS);+});+// XpVU: a recovery holds the journey by holding the pair. A screen's own `onNavigate`+// reaches the same journey without touching either button, so the hold lives there too.+it('a held journey refuses the screen own navigate, not only the buttons', () => {+ const { container, rerender } = render(show('enabled', true, { navigationLocked: true }));+ const current = () => container.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen');+ expect(screen.getByRole('button', { name: 'Get started' }).hasAttribute('disabled')).toBe(true);+ // Held, not busy: nothing is running, so nothing spins. The spinner carries Tailwind's+ // `motion-safe:` variant, so the token in the DOM is the whole `motion-safe:animate-spin`+ // — feeding a genuinely busy action proves this selector can find one, which is what+ // makes its absence above an answer about the shell rather than about the query.+ const spinners = () => container.querySelectorAll('.onboarding-primary-action [class~="motion-safe:animate-spin"]').length;+ const feed = (busy: boolean) => act(() => savedFeeds[0].onActionChange({ labelKey: 'onboarding.welcome.getStarted', disabled: false, busy, icon: 'none' }));+ expect(spinners()).toBe(0);+ feed(true); expect(spinners()).toBe(1);+ feed(false); expect(spinners()).toBe(0);+ act(() => savedFeeds[0].onNavigate('providers'));+ expect(current()).toBe('intro');+ rerender(show('enabled', true, { navigationLocked: false }));+ act(() => savedFeeds[0].onNavigate('providers'));+ expect(current()).toBe('providers');+});+it('a held journey does not hand the shared primary to the config retry either', () => {+ const onRetrySetup = vi.fn();+ render(show('disabled', false, { navigationLocked: true, onRetrySetup }));+ const primary = screen.getByRole('button', { name: en.common.retry });+ expect(primary.hasAttribute('disabled')).toBe(true);+ fireEvent.click(primary);+ expect(onRetrySetup).not.toHaveBeenCalled();+});+it('keeps drafts and DOM identity, focuses each heading, and rejects old activation callbacks', async () => {+ const { container } = render(show());+ const intro = screen.getByRole('textbox', { name: 'intro draft' });+ fireEvent.change(intro, { target: { value: '保留 / draft' } });+ const obsolete = savedFeeds[0];+ fireEvent.click(screen.getByRole('button', { name: 'Get started' }));+ expect(document.activeElement?.textContent).toBe('providers');+ const root = container.querySelector('[data-setup-screen-root="intro"]')!;+ expect(root.hasAttribute('hidden')).toBe(true);+ expect(root.hasAttribute('inert')).toBe(true);+ act(() => {+ obsolete.onActionChange({ labelKey: 'common.cancel', disabled: false, busy: false, icon: 'none' });+ obsolete.onNavigate('assistants');+ });+ expect(screen.queryByRole('button', { name: 'Cancel' })).toBeNull();+ expect(document.activeElement?.textContent).toBe('providers');+ fireEvent.click(screen.getByRole('button', { name: 'Back to introduction' }));+ expect(screen.getByRole('textbox', { name: 'intro draft' })).toBe(intro);+ expect((intro as HTMLInputElement).value).toBe('保留 / draft');+ act(() => obsolete.onNavigate('assistants'));+ await waitFor(() => expect(document.activeElement?.textContent).toBe('intro'));+ expect(container.querySelectorAll('.onboarding-setup-footer')).toHaveLength(1);+ expect(container.querySelectorAll('.onboarding-primary-action')).toHaveLength(1);+});diff --git a/ui/src/components/onboarding/Welcome.test.tsx b/ui/src/components/onboarding/Welcome.test.tsxindex 78e83a616..d5852fdd0 100644--- a/ui/src/components/onboarding/Welcome.test.tsx+++ b/ui/src/components/onboarding/Welcome.test.tsx@@ -4,6 +4,14 @@ import { createInstance } from 'i18next';import { I18nextProvider } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { Welcome } from '../steps/Welcome';+import { SetupFlowShell } from '../Wizard';+import { loadingRegion } from '../settings/models/regionRead';+import { useRef, useState, type ComponentProps } from 'react';+import { useTranslation } from 'react-i18next';+import { SETUP_SCREENS, type SetupAction, type SetupScreenHandle } from './setupFlow';+import { SETUP_REGISTERED_SCREENS } from './setupScreenRegistry';+import { ASSISTANT_ORDER } from './collaborationTimeline';+import { RouteSurfaceActiveContext } from '@/lib/routeSurfaceActivity';import { CollaborationStory } from './CollaborationStory';import { AccessTiles } from './AccessTiles';import en from '../../i18n/en.json';@@ -16,6 +24,16 @@ const i18n = createInstance();await i18n.init({ lng: 'en', resources: { en: { translation: en }, zh: { translation: zh } }, interpolation: { escapeValue: false } });const wrap = (element: React.ReactNode) => <I18nextProvider i18n={i18n}>{element}</I18nextProvider>;+function Intro(props: Omit<ComponentProps<typeof Welcome>, 'active' | 'onActionChange'> & { active?: boolean }) {+ const { t } = useTranslation();+ const ref = useRef<SetupScreenHandle>(null);+ const [action, setAction] = useState<SetupAction | null>(null);+ return <><Welcome {...props} active={props.active ?? true} ref={ref} onActionChange={setAction} />+ {action && <button disabled={action.disabled} onClick={() => ref.current?.activate()}>{t(action.labelKey)}</button>}+ {/* The setup shell collapses the entry block on every screen; the wrapper mirrors it. */}+ <AccessTiles active={false} /></>;+}+/** The tab going to the background, which jsdom exposes no other way. */const setHidden = (hidden: boolean) => act(() => {Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden });@@ -58,7 +76,7 @@ describe('Welcome', () => {it('checks saved paths before advancing without persisting configuration', async () => {mocks.api.detectCli.mockImplementation(async (binary: string) => ({ found: binary !== 'codex', path: `/test/${binary}` }));const next = vi.fn();- render(wrap(<Welcome data={{ agents: { claude: { cli_path: '/custom/claude' } } }} onNext={next} />));+ render(wrap(<Intro data={{ agents: { claude: { cli_path: '/custom/claude' } } }} onNext={next} />));fireEvent.click(screen.getByRole('button', { name: 'Get started' }));await waitFor(() => expect(next).toHaveBeenCalledOnce());expect(mocks.api.detectCli.mock.calls.map(([binary]) => binary)).toEqual(['/custom/claude', 'codex', 'opencode']);@@ -67,7 +85,7 @@ describe('Welcome', () => {it('retains a failed detection on Welcome and permits retry', async () => {mocks.api.detectCli.mockRejectedValueOnce(new Error('Probe unavailable')).mockResolvedValue({ found: false });const next = vi.fn();- render(wrap(<Welcome onNext={next} />));+ render(wrap(<Intro onNext={next} />));fireEvent.click(screen.getByRole('button', { name: 'Get started' }));await screen.findByRole('alert');expect(next).not.toHaveBeenCalled();@@ -75,11 +93,76 @@ describe('Welcome', () => {fireEvent.click(screen.getByRole('button', { name: 'Retry' }));await waitFor(() => expect(next).toHaveBeenCalledOnce());});- it('renders the approved Chinese copy', async () => {+ // XpVZ/B: in the shell the failure must land in the slot AFTER the shared pair. Left+ // in the screen it sits before the footer, and a long diagnostic there moves the+ // anchor Welcome and the setup screen are supposed to share.+ it('hands a failed detection to the slot below the shared pair instead of the screen', async () => {+ vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false, addEventListener() {}, removeEventListener() {} })));+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+ mocks.api.detectCli.mockRejectedValue(new Error('Probe unavailable'));+ const { container } = render(wrap(<SetupFlowShell sequence={SETUP_SCREENS} capability="enabled" gatewayEnabled+ onRetrySetup={vi.fn()} runtimeRead={loadingRegion()}+ renderScreen={(id, { active, onActionChange }, ref) => (id === 'intro'+ ? <Welcome active={active} onActionChange={onActionChange} ref={ref} onNext={vi.fn()} />+ : <h1 tabIndex={-1}>{id}</h1>)} />));+ fireEvent.click(screen.getByRole('button', { name: 'Get started' }));+ const alert = await screen.findByRole('alert');+ const aside = container.querySelector('[data-setup-action-aside]') as HTMLElement;+ const footer = container.querySelector('.onboarding-setup-footer') as HTMLElement;+ expect(aside.contains(alert)).toBe(true);+ expect(container.querySelector('[data-setup-screen-root="intro"]')!.contains(alert)).toBe(false);+ // Order, not just ownership: only content after the footer is content the anchor+ // cannot feel.+ expect(footer.compareDocumentPosition(aside) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Retry' }).closest('.onboarding-primary-action')).toBeTruthy();+ });+ // e-Dq: detection awaits three CLI probes and only then asks to move. That+ // continuation captured its answer before the await, so it cannot know the setup+ // route stopped being the surface being read — and teaching this screen to re-check+ // would only move the obligation onto the next screen that forgets. Movement has one+ // owner, the shell, which is where a journey sitting behind another retained surface+ // is held still and where it is handed back when the route returns.+ it('refuses a detection that settles after the route went quiet, then moves when it returns', async () => {+ vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false, addEventListener() {}, removeEventListener() {} })));+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+ const probes: ((result: { found: boolean; path: string }) => void)[] = [];+ mocks.api.detectCli.mockImplementation(() => new Promise((resolve) => { probes.push(resolve); }));+ const onward = SETUP_REGISTERED_SCREENS[1];+ const shell = (routeActive: boolean) => wrap(+ <RouteSurfaceActiveContext.Provider value={routeActive}>+ <SetupFlowShell sequence={SETUP_REGISTERED_SCREENS} capability="enabled" gatewayEnabled+ onRetrySetup={vi.fn()} runtimeRead={loadingRegion()}+ renderScreen={(id, { active, onActionChange, onNavigate }, ref) => (id === 'intro'+ ? <Welcome active={active} onActionChange={onActionChange} ref={ref} onNext={() => { onNavigate(onward); }} />+ : <h1 tabIndex={-1}>{id}</h1>)} />+ </RouteSurfaceActiveContext.Provider>);+ const { container, rerender } = render(shell(true));+ const current = () => container.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen');+ const answer = async () => act(async () => { for (const resolve of probes.splice(0)) resolve({ found: true, path: '/test/bin' }); });++ fireEvent.click(screen.getByRole('button', { name: 'Get started' }));+ await waitFor(() => expect(probes).toHaveLength(ASSISTANT_ORDER.length));+ rerender(shell(false));+ await answer();+ expect(current()).toBe('intro');+ expect(document.activeElement?.textContent).not.toBe(onward);+ // Refused, not broken: nothing failed, so there is nothing to report to anybody.+ expect(screen.queryByRole('alert')).toBeNull();++ rerender(shell(true));+ fireEvent.click(screen.getByRole('button', { name: 'Get started' }));+ await waitFor(() => expect(probes).toHaveLength(ASSISTANT_ORDER.length));+ await answer();+ await waitFor(() => expect(current()).toBe(onward));+ });+ it('renders the approved Chinese copy and keeps the entry block mounted, hidden and inert', async () => {await i18n.changeLanguage('zh');- render(wrap(<Welcome onNext={vi.fn()} />));+ const { container } = render(wrap(<Intro onNext={vi.fn()} />));expect(screen.getByRole('heading', { name: '各有所长,接力完成' })).toBeTruthy();- expect(screen.getAllByRole('listitem')).toHaveLength(6);+ const block = container.querySelector('.onboarding-access') as HTMLElement;+ expect(block.querySelectorAll('.onboarding-access-tile')).toHaveLength(6);+ expect(block.hasAttribute('hidden')).toBe(true);+ expect(block.hasAttribute('inert')).toBe(true);});});@@ -153,7 +236,7 @@ describe('collaboration lifecycle and access interaction', () => {});it('shows completed work and stops all timers for reduced motion', () => {vi.useFakeTimers(); mocks.reduced = true;- const { container } = render(wrap(<Welcome onNext={vi.fn()} />));+ const { container } = render(wrap(<Intro onNext={vi.fn()} />));expect(container.querySelectorAll('[data-state="complete"]')).toHaveLength(3);expect(screen.queryByTestId('handoff-pulse')).toBeNull();// Get started is the only button on the screen.@@ -163,6 +246,8 @@ describe('collaboration lifecycle and access interaction', () => {it('pauses idle emphasis throughout pointer and keyboard interaction', () => {vi.useFakeTimers();const { container } = render(wrap(<AccessTiles />));+ // An active consumer still draws the block: hiding it in setup is shell policy.+ expect((container.querySelector('.onboarding-access') as HTMLElement).hasAttribute('hidden')).toBe(false);act(() => vi.advanceTimersByTime(2000));expect(container.querySelectorAll('[data-emphasis="true"]')).toHaveLength(1);fireEvent.pointerEnter(screen.getByRole('list'));diff --git a/ui/src/components/onboarding/WizardCompletion.test.tsx b/ui/src/components/onboarding/WizardCompletion.test.tsxindex 0a1f422c3..4af9723f0 100644--- a/ui/src/components/onboarding/WizardCompletion.test.tsx+++ b/ui/src/components/onboarding/WizardCompletion.test.tsx@@ -7,11 +7,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { Wizard } from '../Wizard';import en from '../../i18n/en.json';-const mock = vi.hoisted(() => ({ supply: vi.fn(), control: vi.fn(), toast: vi.fn(), permission: vi.fn(), manageAccess: true, api: {+const mock = vi.hoisted(() => ({ supply: vi.fn(), 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(),} }));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('../../context/InstanceAuthorizationContext', () => ({ useInstanceAuthorization: () => ({ capabilities: { can_manage_agents: true, can_manage_access_members: mock.manageAccess } }) }));vi.mock('../../context/StatusContext', () => ({ useStatus: () => ({ control: mock.control }) }));@@ -19,9 +20,22 @@ vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: mocvi.mock('../settings/models/useModelHubCapability', () => ({ useModelHubCapability: () => false }));vi.mock('../settings/shared/useOpencodePermission', () => ({ useOpencodePermission: () => ({ permissionAllowed: false, statusLoaded: true, setupPermission: mock.permission }) }));const i18n = createInstance();-await i18n.init({ lng: 'en', resources: { en: { translation: en } } });+await i18n.init({ lng: 'en', fallbackLng: 'en', resources: { en: { translation: en } } });function Destination() { const location = useLocation(); return <div data-testid="destination">{JSON.stringify(location.state)}</div>; }function mount() { return render(<MemoryRouter initialEntries={['/setup']}><I18nextProvider i18n={i18n}><Routes><Route path="/setup" element={<Wizard />} /><Route path="/" element={<Destination />} /></Routes></I18nextProvider></MemoryRouter>); }+// `api.getConfig()` answers from a 30-second cache, and the shell's prerequisite reads+// deliberately do not. Both are driven from here so a case can make them disagree and+// prove which one the flow actually acted on.+const jsonResponse = (body: unknown, init: { ok?: boolean; status?: number } = {}) => ({ ok: init.ok ?? true, status: init.status ?? 200, json: async () => body }) as unknown as Response;+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,+});+let fresh: () => Promise<Response>;+/** 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); }+/** Change only the uncached GET, so the cached projection keeps answering the old one. */+function serveFreshOnly(next: () => Promise<Response>) { fresh = next; }let running: boolean;beforeEach(() => {vi.resetAllMocks(); running = true; mock.manageAccess = true;@@ -30,7 +44,11 @@ beforeEach(() => {Element.prototype.scrollIntoView = vi.fn();vi.spyOn(window, 'scrollTo').mockImplementation(() => {});mock.api.readModelHubAgentCatalogForModelPicker.mockResolvedValue(null);- mock.api.getConfig.mockResolvedValue({ setup_completed: false, agents: { claude: { enabled: true }, codex: { enabled: true }, opencode: { enabled: true } }, platforms: { enabled: [] } });+ mock.apiFetch.mockImplementation(async (input: RequestInfo | URL) => {+ if (String(input) !== '/api/config') throw new Error(`unexpected apiFetch ${String(input)}`);+ return fresh();+ });+ serveConfig(baseConfig());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' }));@@ -38,8 +56,11 @@ beforeEach(() => {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' });});-afterEach(cleanup);+afterEach(async () => { cleanup(); await i18n.changeLanguage('en'); });async function setup() {mount(); fireEvent.click(await screen.findByRole('button', { name: 'Get started' }));const enter = await screen.findByRole('button', { name: 'Enter workspace' });@@ -79,6 +100,9 @@ describe('explicit any-one-ready completion', () => {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 });await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Enter workspace' })));await screen.findByTestId('destination');@@ -190,8 +214,7 @@ describe('OpenCode model recovery', () => {it('uses canonical Hub supply instead of treating canonical slash IDs as Direct providers', async () => {directConnection('anthropic');- const config = await mock.api.getConfig();- mock.api.getConfig.mockResolvedValue({ ...config, capabilities: { model_hub: { enabled: true } } });+ 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');@@ -206,21 +229,24 @@ it('keeps incomplete setup when catalog retrieval fails and allows cancellation'expect(screen.queryByRole('region', { name: en.onboarding.connection.modelTitle })).toBeNull();});+/** A saved platform whose required credential is gone: the shape that stops completion+ * and hands the slot a repair form. Shared with the navigation-ownership cases below. */+function incompleteSlack() {+ const config = baseConfig({ platforms: { primary: 'slack', enabled: ['slack'] }, platform_catalog: [{ id: 'slack', config_key: 'slack', credential_fields: ['bot_token', 'app_token'] }], slack: { bot_token: '', app_token: '', has_bot_token: false, has_app_token: true, proxy_url: '' }, agent: { default_cwd: '/original' } }) as ReturnType<typeof baseConfig> & { slack: Record<string, unknown>; platform_catalog: Record<string, unknown>[] };+ serveConfig(config);+ mock.api.slackManifest.mockResolvedValue({ ok: true, manifest: '{}' });+ return config;+}+// AUTH-SETUP-120: the actual Wizard consumes legacy-IM recovery and narrow mutations.describe('saved messaging recovery', () => {- function incompleteSlack() {- const config = { setup_completed: false, agents: { claude: { enabled: true }, codex: { enabled: true }, opencode: { enabled: true } }, platforms: { enabled: ['slack'] }, platform_catalog: [{ id: 'slack', config_key: 'slack', credential_fields: ['bot_token', 'app_token'] }], slack: { bot_token: '', app_token: '', has_bot_token: false, has_app_token: true, proxy_url: '' }, agent: { default_cwd: '/original' } };- mock.api.getConfig.mockResolvedValue(config);- mock.api.slackManifest.mockResolvedValue({ ok: true, manifest: '{}' });- return config;- }it('mounts only after explicit repair, saves changed credentials only, then rechecks and completes', async () => {const config = incompleteSlack(); running = false;fireEvent.click(await setup());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') mock.api.getConfig.mockResolvedValue({ ...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 {};});fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.platformRepair }));@@ -246,7 +272,7 @@ describe('saved messaging recovery', () => {});it('honors redacted credential markers and the WeChat runnable exception', async () => {const config = incompleteSlack();- mock.api.getConfig.mockResolvedValue({ ...config, platforms: { enabled: ['slack', 'wechat'] }, slack: { has_bot_token: true, has_app_token: true }, wechat: {}, platform_catalog: [...config.platform_catalog, { id: 'wechat', credential_fields: ['bot_token'] }] });+ serveConfig({ ...config, platforms: { primary: 'slack', enabled: ['slack', 'wechat'] }, slack: { has_bot_token: true, has_app_token: true }, wechat: {}, platform_catalog: [...config.platform_catalog, { id: 'wechat', credential_fields: ['bot_token'] }] });fireEvent.click(await setup()); await screen.findByTestId('destination');expect(mock.api.slackManifest).not.toHaveBeenCalled(); expect(mock.api.slackAuthTest).not.toHaveBeenCalled();});@@ -256,12 +282,12 @@ describe('saved messaging recovery', () => {// AUTH-SETUP-120: Discord's existing form emits credential and auxiliary settings.describe('saved Discord recovery', () => {async function repairDiscord() {- const config = { setup_completed: false, agents: { claude: { enabled: true } }, platforms: { enabled: ['discord'] }, platform_catalog: [{ id: 'discord', config_key: 'discord', credential_fields: ['bot_token'] }], discord: { bot_token: '', has_bot_token: false } };- mock.api.getConfig.mockResolvedValue(config);+ const config = baseConfig({ agents: { claude: { enabled: true } }, platforms: { primary: 'discord', enabled: ['discord'] }, platform_catalog: [{ id: 'discord', config_key: 'discord', credential_fields: ['bot_token'] }], discord: { bot_token: '', has_bot_token: false } });+ serveConfig(config);mock.api.discordAuthTest.mockResolvedValue({ ok: true });mock.api.discordGuilds.mockResolvedValue({ ok: true, guilds: [{ id: 'g-one', name: 'Guild One' }, { id: 'g-two', name: 'Guild Two' }] });mock.api.mutateConfig.mockImplementation(async (changes) => {- if (changes[0].path[0] === 'discord') mock.api.getConfig.mockResolvedValue({ ...config, discord: { bot_token: '', has_bot_token: true } });+ if (changes[0].path[0] === 'discord') serveConfig({ ...config, discord: { bot_token: '', has_bot_token: true } });return {};});fireEvent.click(await setup());@@ -309,3 +335,325 @@ describe('saved Discord recovery', () => {expect(screen.queryByTestId('destination')).toBeNull();});});++// e-Da: the block holds two different kinds of string. `flowError` is the sentence a+// person reads, which is always a bundle key; the disclosure below it is whatever the+// server or the transport said. Reading them apart is what makes "the raw detail is not+// the alert" an assertion rather than a coincidence of concatenation.+const flowError = () => document.querySelector('.onboarding-flow-error p')?.textContent ?? null;+const flowErrorDetail = () => {+ const disclosure = document.querySelector('.onboarding-flow-error details');+ if (!disclosure) return null;+ return (disclosure.textContent ?? '').slice((disclosure.querySelector('summary')?.textContent ?? '').length);+};+const primaryAction = () => document.querySelector('.onboarding-primary-action') as HTMLButtonElement;+const backAction = () => document.querySelector('.onboarding-back-action') as HTMLButtonElement;+// The footer's spinner carries Tailwind's `motion-safe:` variant, so the token in the+// DOM is the whole `motion-safe:animate-spin`. A bare `.animate-spin` matches nothing+// here whatever the shell renders, which would make every "not busy" check vacuous.+const spinners = () => primaryAction().querySelectorAll('[class~="motion-safe:animate-spin"]').length;+/** Nothing that ends setup, and nothing that leaves the screen. */+function expectNoForwardWrite() {+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();+ expect(mock.control).not.toHaveBeenCalled();+ expect(screen.queryByTestId('destination')).toBeNull();+}++// XpVZ/XpVc: the prerequisite is persisted state somebody else can change while this+// flow is open, so every case here starts from a config the initial load accepted.+//+// AUTH-SETUP-122, browser half: these cases own the admission rule — what the shell does+// with an answer it could not validate — against controlled responses. The producer half+// (real authentication refusal, the full envelope shape, CSRF-gated persistence, readback)+// is the scenario test the catalog entry names. The two do not compose into the assembled+// browser-to-API journey: that is AUTH-SETUP-123, recorded as partial and owned by+// integrated acceptance, because no harness without a real browser can claim it.+describe('fresh prerequisite boundary', () => {+ it.each([+ ['the saved intent', { model_hub: { enabled: false } }],+ ['the capability', { capabilities: { model_hub: { enabled: false } } }],+ ])('refuses completion when a fresh read says %s is off, while the cached projection still says on', async (_label, off) => {+ const enter = await setup();+ serveFreshOnly(async () => jsonResponse(baseConfig(off)));+ fireEvent.click(enter);+ await waitFor(() => expect(flowError()).toBe(en.onboarding.flow.gatewayRequired));+ // The bypass is the point: `api.getConfig()` would still have answered "enabled".+ expect(await mock.api.getConfig()).toMatchObject({ capabilities: { model_hub: { enabled: true } }, model_hub: { enabled: true } });+ expectNoForwardWrite();+ expect(backAction().hasAttribute('disabled')).toBe(false);+ expect(primaryAction().textContent).toContain(en.common.retry);+ });+ // The fourth column is what the producer said, and every producer that says anything+ // here says it in English whatever language the setup is being read in — so it belongs+ // under the disclosure, never in the sentence. `null` is the honest case where the+ // server offered nothing quotable: then there is no disclosure to open at all.+ it.each([+ ['a body that never says what it had to', async () => jsonResponse({ ...baseConfig(), runtime: undefined }), en.onboarding.connection.readFailed, null],+ ['a body that is not JSON at all', async () => ({ ok: true, status: 200, json: async () => { throw new SyntaxError('Unexpected token <'); } }) as unknown as Response, en.onboarding.connection.readFailed, null],+ ['an HTTP failure that explains itself', async () => jsonResponse({ error: 'config unavailable' }, { ok: false, status: 503 }), en.onboarding.connection.readFailedStatus.replace('{{status}}', '503'), 'config unavailable'],+ ['an HTTP failure that does not', async () => jsonResponse({}, { ok: false, status: 500 }), en.onboarding.connection.readFailedStatus.replace('{{status}}', '500'), null],+ ['a transport that never answered', async () => { throw new Error('network down'); }, en.onboarding.connection.readFailed, 'Error: network down'],+ ])('leaves the prerequisite unknown and offers Retry for %s', async (_label, respond, explanation, detail) => {+ const enter = await setup();+ serveFreshOnly(respond);+ fireEvent.click(enter);+ await waitFor(() => expect(flowError()).toBe(explanation));+ // Unknown is not "off": the gateway copy would be a claim nobody could confirm.+ expect(flowError()).not.toBe(en.onboarding.flow.gatewayRequired);+ // What the producer said is kept, and kept out of the sentence.+ expect(flowErrorDetail()).toBe(detail);+ if (detail) expect(flowError()).not.toContain(detail);+ expectNoForwardWrite();+ expect(backAction().hasAttribute('disabled')).toBe(false);+ expect(primaryAction().textContent).toContain(en.common.retry);+ });+ it('a Retry that reads a healthy config restores ordinary action without completing setup', async () => {+ const enter = await setup();+ serveFreshOnly(async () => { throw new Error('network down'); });+ fireEvent.click(enter);+ await waitFor(() => expect(flowError()).toBe(en.onboarding.connection.readFailed));+ expect(flowErrorDetail()).toBe('Error: network down');+ serveConfig(baseConfig());+ fireEvent.click(screen.getByRole('button', { name: en.common.retry }));+ await waitFor(() => expect(flowError()).toBeNull());+ // Recovering the read is not consent to finish.+ expectNoForwardWrite();+ const enterAgain = await screen.findByRole('button', { name: 'Enter workspace' });+ await waitFor(() => expect(enterAgain.hasAttribute('disabled')).toBe(false));+ fireEvent.click(enterAgain);+ expect(await screen.findByTestId('destination')).toBeTruthy();+ expect(mock.api.mutateConfig).toHaveBeenCalledExactlyOnceWith([{ kind: 'set', path: ['setup_completed'], value: true }]);+ expect(enter).toBe(enterAgain);+ });+ 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;+ serveFreshOnly(() => new Promise<Response>((resolve) => { releaseEntry = resolve; }));+ fireEvent.click(enter);+ await waitFor(() => expect(mock.apiFetch).toHaveBeenCalledTimes(2));+ // 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 } })));+ await act(async () => { await i18n.changeLanguage('zh'); });+ await waitFor(() => expect(flowError()).toBe(en.onboarding.flow.gatewayRequired));+ await act(async () => { releaseEntry(jsonResponse(baseConfig())); });+ expect(flowError()).toBe(en.onboarding.flow.gatewayRequired);+ 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.+ 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.api.setDefaultVibeAgent).not.toHaveBeenCalled();+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ expect(screen.queryByTestId('destination')).toBeNull();+ });+ // 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+ // the completion is parked on an await it had already been authorised to make.+ const overtaken = [+ ['the gateway went off', async () => jsonResponse(baseConfig({ model_hub: { enabled: false } })), en.onboarding.flow.gatewayRequired],+ ['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 answer = mock.api.getBackendConnection.getMockImplementation()!;+ let release!: () => void;+ const held = new Promise<void>((resolve) => { release = resolve; });+ let reads = 0;+ mock.api.getBackendConnection.mockImplementation(async (backend) => { reads++; await held; return answer(backend); });+ fireEvent.click(enter);+ // The readiness reads the completion makes before it may ask for a start.+ await waitFor(() => expect(reads).toBeGreaterThanOrEqual(3));+ serveFreshOnly(respond);+ await act(async () => { await i18n.changeLanguage('zh'); });+ await waitFor(() => expect(flowError()).toBe(explanation));+ await act(async () => { release(); });+ await waitFor(() => expect(primaryAction().textContent).toContain(en.common.retry));+ expectNoForwardWrite();+ // And the stop is a stop, not a dead end: a Retry that reads a healthy config+ // hands the journey back, and the next explicit completion goes through.+ serveConfig(baseConfig());+ fireEvent.click(screen.getByRole('button', { name: en.common.retry }));+ await waitFor(() => expect(flowError()).toBeNull());+ 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();+ expect(mock.control).toHaveBeenCalledExactlyOnceWith('start');+ });+ it.each(overtaken)('stops before finishing setup when %s during the default write', async (_label, respond, explanation) => {+ const enter = await setup();+ let release!: (result: { ok: boolean }) => void;+ mock.api.setDefaultVibeAgent.mockImplementation(() => new Promise((resolve) => { release = resolve; }));+ fireEvent.click(enter);+ await waitFor(() => expect(mock.api.setDefaultVibeAgent).toHaveBeenCalledOnce());+ serveFreshOnly(respond);+ await act(async () => { await i18n.changeLanguage('zh'); });+ await waitFor(() => expect(flowError()).toBe(explanation));+ // The default was already written and stays written; what does not follow from it+ // is the completion it was a step towards.+ await act(async () => { release({ ok: true }); });+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ expect(screen.queryByTestId('destination')).toBeNull();+ expect(primaryAction().textContent).toContain(en.common.retry);+ });+ it('an obsolete completion cannot renew its own admission by reading again', async () => {+ const enter = await setup();+ let release!: (agents: unknown) => void;+ mock.api.listVibeAgents.mockImplementation(() => new Promise((resolve) => { release = resolve; }));+ fireEvent.click(enter);+ await waitFor(() => expect(mock.api.listVibeAgents).toHaveBeenCalledOnce());+ const readsBefore = mock.apiFetch.mock.calls.length;+ // The shell's own load takes the region while the listing is parked. The healthy+ // answer it leaves behind is exactly what a re-read would find, so a completion+ // that resumed here would sail through its final check and finish setup.+ await act(async () => { await i18n.changeLanguage('zh'); });+ await waitFor(() => expect(mock.apiFetch.mock.calls.length).toBeGreaterThan(readsBefore));+ const settled = mock.apiFetch.mock.calls.length;+ await act(async () => { release({ ok: true, default_agent_name: 'missing-codex', agents: [{ name: 'claude-agent', backend: 'claude', enabled: true }] }); });+ expect(mock.apiFetch).toHaveBeenCalledTimes(settled);+ expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ expect(screen.queryByTestId('destination')).toBeNull();+ });+ it('a completion whose setup surface is gone stops instead of writing into nothing', async () => {+ const enter = await setup();+ let release!: (result: { ok: boolean }) => void;+ mock.api.setDefaultVibeAgent.mockImplementation(() => new Promise((resolve) => { release = resolve; }));+ fireEvent.click(enter);+ await waitFor(() => expect(mock.api.setDefaultVibeAgent).toHaveBeenCalledOnce());+ // The other way the admission ends: the person left the setup route, so there is+ // no shell holding the answer this operation was acting under and no journey for+ // it to finish. What was already written stays written; nothing more follows.+ cleanup();+ await act(async () => { release({ ok: true }); });+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ });+ it('a recovery completion callback passes the same boundary', async () => {+ directConnection('anthropic');+ 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 }));+ await waitFor(() => expect(flowError()).toBe(en.onboarding.flow.gatewayRequired));+ expect(mock.api.updateVibeAgent).toHaveBeenCalledOnce();+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ expect(screen.queryByTestId('destination')).toBeNull();+ });+});++// XpVU: a recovery owns the journey while it is open, and says so by holding the+// shared pair — not by pretending work is running.+describe('recovery navigation ownership', () => {+ 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.+ 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());+ await screen.findByRole('region', { name: en.onboarding.connection.platformRepair });+ expect(backAction().hasAttribute('disabled')).toBe(true);+ expect(primaryAction().hasAttribute('disabled')).toBe(true);+ expect(spinners()).toBe(0);+ expect(mock.api.slackManifest).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ await waitFor(() => expect(backAction().hasAttribute('disabled')).toBe(false));+ expect(screen.queryByRole('region', { name: en.onboarding.connection.platformRepair })).toBeNull();+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();+ expect(screen.queryByTestId('destination')).toBeNull();+ });+ it('keeps the journey put while a deferred platform repair is unsettled, survives its failure, and completes on a later success', async () => {+ const config = incompleteSlack(); running = false;+ let releaseApply!: (ok: boolean) => void;+ mock.api.mutateConfig.mockImplementation(async (mutations: { path: string[] }[]) => {+ if (mutations[0].path[0] !== 'slack') 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 screen.findByRole('button', { name: en.onboarding.connection.platformRepair }));+ fireEvent.click(await screen.findByRole('button', { name: new RegExp(en.slackConfig.step2Title) }));+ const input = await screen.findByPlaceholderText(en.slackConfig.botTokenPlaceholder);+ fireEvent.change(input, { target: { value: 'xoxb-deferred' } });+ fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());+ // Unsettled: the write is out and the answer is not in, so the journey neither+ // leaves nor arrives on its own.+ fireEvent.click(backAction());+ expect(document.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen')).toBe('assistants');+ expect(screen.queryByTestId('destination')).toBeNull();++ // A refused write is not a finished recovery: the form stays, with its draft.+ await act(async () => { releaseApply(false); });+ await screen.findByText('Platform apply failed');+ await screen.findByRole('region', { name: en.onboarding.connection.platformRepair });+ expect(screen.queryByTestId('destination')).toBeNull();+ expect((input as HTMLInputElement).value).toBe('xoxb-deferred');+ expect(backAction().hasAttribute('disabled')).toBe(true);++ // And an explicit second attempt, settling for real, is what finishes setup.+ fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2));+ await act(async () => { releaseApply(true); });+ expect(await screen.findByTestId('destination')).toBeTruthy();+ expect(mock.api.mutateConfig.mock.lastCall![0]).toEqual([{ kind: 'set', path: ['setup_completed'], value: true }]);+ });+ 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 () => {+ mock.api.getBackendConnection.mockImplementation(() => new Promise(() => {}));+ mount();+ fireEvent.click(await screen.findByRole('button', { name: 'Get started' }));+ 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'));+ });+});diff --git a/ui/src/components/onboarding/motion.ts b/ui/src/components/onboarding/motion.tsindex 37a6186fa..3e8c3f42b 100644--- a/ui/src/components/onboarding/motion.ts+++ b/ui/src/components/onboarding/motion.ts@@ -1,4 +1,5 @@import { useEffect, useState } from 'react';+import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';import { useReducedMotion } from 'framer-motion';/**@@ -60,9 +61,10 @@ function useElementOnScreen() {* skeleton shimmer and the test ticks) are held at their current frame rather than left* to play on against a stopped clock.*/-export function useOnboardingMotion() {+export function useOnboardingMotion(active = true) {+ const surfaceActive = useRouteSurfaceActive();const reducedMotion = useReducedMotion() === true;const documentVisible = useDocumentVisible();const [ref, onScreen] = useElementOnScreen();- return { ref, reducedMotion, running: !reducedMotion && documentVisible && onScreen };+ return { ref, reducedMotion, running: active && surfaceActive && !reducedMotion && documentVisible && onScreen };}diff --git a/ui/src/components/onboarding/onboarding.css b/ui/src/components/onboarding/onboarding.cssindex 754e679a4..ec77d599b 100644--- a/ui/src/components/onboarding/onboarding.css+++ b/ui/src/components/onboarding/onboarding.css@@ -125,8 +125,33 @@every desktop row — the introduction on the return wire's band under thecards, the connection on a 20 gap and the 44 import capsule — so one numberholds the action still both when the step changes and when the offer is- dismissed. It is also the diagram's own height: the return band IS the 64. */- --ob-stage-h: calc(var(--ob-card-h) + 64px);+ dismissed.+ The connection's card is the one that can outgrow that frame. The reference+ draws it at `--ob-card-h`, but the sentence under an assistant's name takes+ the two lines it is clamped to in English where it takes one in Chinese, and+ the same card has to hold its state row and two method rows. So the floor is+ the tier's worst reading of that card rather than the text currently in it —+ the same thing the heading block above already does for a title that wraps in+ one language and not the other — written as the card's own composition in+ this tier's numbers: its frame, its padding, the identity row, the state row,+ the note at its clamp, and the two method rows. A tier that restates its+ padding or its rows restates this with them. */+ --ob-assistant-wrap: 0px;+ --ob-assistant-h: calc(2px + var(--ob-card-pv) * 2 + var(--ob-id-h) + var(--ob-card-gap) * 2+ + var(--ob-life-h) + var(--ob-note-lh) * 2 + var(--ob-spacer-2)+ + var(--ob-method-h) * 2 + var(--ob-method-gap) + var(--ob-assistant-wrap));+ --ob-import-gap: 20px;+ /* What the capsule's slot holds whether the offer is absent, still loading,+ arrived or dismissed: the reference's own 44-tall line on a desktop. */+ --ob-import-h: 44px;+ /* One reservation, spent by both steps: the taller of the two cards, the gap+ under it, and the capsule's slot. */+ --ob-stage-h: calc(max(var(--ob-card-h), var(--ob-assistant-h)) + var(--ob-import-gap) + var(--ob-import-h));+ /* The diagram keeps the box the reference draws it in — the story's own card+ plus the same band — so a reservation that has to hold a wrapped sentence on+ the other step does not redraw the story. What it takes instead is slack+ under the diagram, which is what the shorter step was already given. */+ --ob-diagram-h: calc(var(--ob-card-h) + var(--ob-import-gap) + var(--ob-import-h));background: var(--background);color: var(--foreground);@@ -409,16 +434,16 @@the action is 20 in every row, and the access block sits 40 under the action. */}/* The block between the heading and the action, in both steps, and the one owner of- every layout reservation this screen makes. Its floor is `--ob-card-h + 64`, which- is what the reference spends on it in both steps at every accepted width — so the- shorter step is padded to exactly the taller one's height instead of both being given- a number to keep in sync by hand. That is what puts "Get started" and "Enter+ every layout reservation this screen makes. Its floor is `--ob-stage-h`: the taller+ of the two steps' cards plus the band the reference draws under it — so the shorter+ step is padded to exactly the taller one's height instead of both being given a+ number to keep in sync by hand. That is what puts "Get started" and "EnterWorkbench" on identical coordinates: same heading above, same stage height, sameaction width below.The same floor is what keeps the action still when the import notice is dismissed:- the notice lives inside this box, so removing it changes the box's content, not its- height. One owner answers both invariants and neither needs an empty placeholder- node to hold a line nothing is drawn on.+ the notice lives inside this box, in a slot that keeps its height either way (see+ `.onboarding-import-slot`), so refusing the offer changes what is drawn in the box,+ not the height of the box or of anything under it.It applies at every width, phones included: the stack band re-derives the same floorfrom the stacked card instead of the side-by-side one (see the 759 band), so theinvariant holds there too. Matching the two costs slack at the bottom of whichever@@ -483,14 +508,16 @@.onboarding-story { position: relative; width: 100%; display: flex; align-items: flex-start; justify-content: center; }/* The diagram is the card plus the return wire's band beneath it: the reference drawsa 296-tall box around a 232-tall card, a 326 around a 262 and a 394 around a 330 —- the card plus 64 at every reading, which is the stage's own floor. The wires inside- take their own height from the card (see `.onboarding-wires`), which is what keeps- the handoffs on the cards' midline at every tier. */+ the card plus 64 at every reading. It keeps that box even where the stage around it+ reserves more for the other step's wrapped card, because the return band is drawn,+ not padding. The wires inside take their own height from the card (see+ `.onboarding-wires`), which is what keeps the handoffs on the cards' midline at+ every tier. */.onboarding-collaboration {position: relative;width: 100%;max-width: var(--ob-content-w);- height: var(--ob-stage-h);+ height: var(--ob-diagram-h);container-type: inline-size;}/* Three 299-wide cards in a 976 box, which is the same fraction as three 367 in 1200 —@@ -1073,15 +1100,30 @@/* ---- Import notice ------------------------------------------------------- */+/* The capsule's own place in the stage, kept whether or not anything is drawn in it:+ the offer arrives after a read that the rest of the step does not wait for, and it+ can be refused. A slot that is always there makes all four states — absent, still+ loading, arrived, dismissed — cost the same height, so none of them can move the+ action under the person's pointer. It is the stage's gap that puts the 20 above it,+ and the stage's own floor holds the same total when the cards below the frame grow,+ which is why this reserves a height and nothing else. The capsule sits at the top of+ it: slack belongs under the composition, not between it and the offer. */+.onboarding-import-slot {+ width: 100%;+ min-height: var(--ob-import-h);+ display: flex;+ align-items: flex-start;+ justify-content: center;+}+/* An offer, not a row of the list above it: a capsule that takes the width of what itsays and sits centred under the cards, flat and one line tall. A full-width bannerread as a fourth row of the list and as the loudest thing on a step whose subject isthe three assistants; a capsule is an aside.The reference gives it 20 above, 44 of its own and 20 below, which is exactly the 64the stage reserves beyond the card — so the offer costs the composition nothing it- was not already spending. Nothing below it moves when it is dismissed: the stage that- holds it is floored (see `.onboarding-stage`), so what changes is this box's content,- not the height of the box it sits in. */+ was not already spending. Its own height stays the reference's line at every tier;+ what the tier restates is the slot that holds it. */.onboarding-import-notice {max-width: 100%;min-height: 44px;@@ -1144,7 +1186,16 @@card answers to the window rather than to a breakpoint, so 1366, 1440 and 1920 arethree readings of one rule rather than three layouts. */@media (max-width: 1023px) {- .onboarding-shell { --ob-gutter: 24px; }+ .onboarding-shell {+ --ob-gutter: 24px;+ /* Three columns in this much window is the narrowest reading the composition has,+ and the connection card answers for it twice: "Claude Code" takes a second line+ in the identity header, and the first method label takes one in its row. Two+ line boxes of the card's own type — 24 for the name, 11 for the row — so the+ step that has to draw them and the step that does not still end at the same+ action. */+ --ob-assistant-wrap: 35px;+ }}/* "Stack the three assistant cards below 760px and allow natural scrolling."@@ -1186,9 +1237,20 @@--ob-h1-min: calc(2 * var(--ob-h1-lh));--ob-p-min: var(--ob-sub-lh);--ob-heading-mb: 27px;- /* The stacked floor, plus the three wrapped guide lines a 320px card can- carry: the floor has to hold the taller of the two steps' natural stacks. */- --ob-stage-h: calc(var(--ob-card-h) * 3 + 145px);+ /* Stacked, the cards are one above another and nothing is narrow enough to+ wrap a name or a method row: the card's own composition answers for the+ tier again. */+ --ob-assistant-wrap: 0px;+ --ob-stack-gap: 16px;+ /* Four things do not fit on one line here, so the capsule folds (see the rule+ below) and its slot reserves the fold: two rows of type for the sentence,+ the row gap, and the two actions on a row of their own — which is what a+ 320px reading of the offer actually draws. */+ --ob-import-h: 126px;+ /* The same reservation as the desktop rows, re-derived from the stack: three+ of the taller card, the two gaps between them, and the capsule's band. */+ --ob-stage-h: calc(max(var(--ob-card-h), var(--ob-assistant-h)) * 3 + var(--ob-stack-gap) * 2+ + var(--ob-import-gap) + var(--ob-import-h));--ob-main-top: 0px;--ob-access-w: 100%;--ob-access-pad: 24px;@@ -1215,13 +1277,13 @@.onboarding-collaboration-cards {grid-template-columns: minmax(0, 1fr);grid-template-rows: repeat(3, minmax(0, 1fr));- gap: 16px;+ gap: var(--ob-stack-gap);height: auto;flex: 1;}.onboarding-wires { display: none; }.onboarding-story-caption { position: static; transform: none; align-self: center; }- .onboarding-assistants-list { grid-template-columns: minmax(0, 1fr); gap: 16px; }+ .onboarding-assistants-list { grid-template-columns: minmax(0, 1fr); gap: var(--ob-stack-gap); }/* Six 52px logos cannot sit on one 350px row, so the row folds into two of three —the reference's own mobile arrangement — and gives up the fixed 560 span with it. */.onboarding-access-grid { width: min(300px, 100%); grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px 12px; }@@ -1283,3 +1345,55 @@.onboarding-model-recovery { width: 100%; padding: 20px; border: 1px solid var(--border); border-radius: 12px; display: flex; flex-direction: column; gap: 16px; background: var(--surface); min-width: 0; }.onboarding-model-recovery h3 { font-size: 16px; font-weight: 600; }.onboarding-model-recovery p { font-size: 13px; color: var(--muted); overflow-wrap: anywhere; }++/* C2/C3: persistent screens share one reservation and one shell-owned action pair. */+.onboarding-step { max-width: var(--ob-content-w); }+.onboarding-screens { position: relative; width: 100%; }+.onboarding-screens [hidden], .onboarding-access[hidden] { display: none !important; }+.onboarding-handoff-layer { position: absolute; inset: 0; pointer-events: none; z-index: 3; }+.onboarding-handoff-layer * { animation-play-state: paused !important; }+.onboarding-handoff-card { position: absolute; pointer-events: none; }+.onboarding-handoff-surface { position: absolute; inset: 0; border: 1px solid; transform-origin: top left;+ /* The halo a working card wears is a token, so the flight borrows it through the same+ name and fades it out on the token's own terms rather than carrying a computed+ shadow string through the animation. */+ transition: box-shadow 360ms ease 480ms; }+.onboarding-handoff-surface[data-glow="true"] { box-shadow: var(--ob-active-shadow); }+.onboarding-step[data-handoff] .onboarding-primary-action:disabled { opacity: 1; }+.onboarding-heading h1:focus { outline: none; }+.onboarding-flow-error { width: 100%; margin-top: 16px; text-align: center; color: var(--destructive-ink); overflow-wrap: anywhere; }+/* The retained assistant caption is ancillary to the common stage: the active screen+ portals it into the shell's slot BELOW the action pair. In normal flow under a+ top-anchored step it can say as much as it needs to without moving the anchor, and it+ cannot intercept a tap meant for the buttons — which is what it did while it was+ lifted out of flow and offset back over the footer. The slot itself costs nothing+ when no screen is contributing one; the caption brings its own gap. */+.onboarding-action-aside { width: 100%; display: flex; flex-direction: column; gap: 16px; }+/* The slot costs nothing while no screen contributes to it, and pays for its own+ distance from the pair the moment one does — so the gap belongs here rather than on+ whichever node happens to be first. */+.onboarding-action-aside:not(:empty) { margin-top: 16px; }+.onboarding-setup-hint { width: 100%; text-align: center; }++/* Provider tiers are consumed by L2; their bands are the same C3 bands as the shell. */+.onboarding-shell {+ --ob-gateway-h: 72px;+ --ob-provider-card-h: 76px;+ --ob-provider-card-pad: 14px;+ --ob-provider-card-logo: 32px;+ --ob-provider-card-name: 18px;+ --ob-provider-card-key: 11px;+ --ob-wire-h: 48px;+ --ob-destination-h: 84px;+ --ob-gap: 10px;+}+@media (max-height: 800px) and (min-width: 760px) {+ .onboarding-shell { --ob-provider-card-h: 62px; --ob-provider-card-pad: 12px; --ob-provider-card-logo: 24px; --ob-wire-h: 32px; --ob-access-circle: 48px; }+}+@media (min-width: 1600px) and (min-height: 950px) {+ .onboarding-shell { --ob-gateway-h: 80px; --ob-provider-card-h: 88px; --ob-provider-card-logo: 35px; --ob-provider-card-name: 20px; --ob-provider-card-key: 12px; }+}+@media (max-width: 759px) {+ .onboarding-shell { --ob-provider-card-h: 116px; --ob-provider-card-pad: 10px; --ob-provider-card-logo: 25px; --ob-provider-card-name: 13px; --ob-provider-card-key: 10px; --ob-wire-h: 42px; --ob-gap: 7px; --ob-destination-h: 120px; --ob-content-w: 460px; }+ .onboarding-story-caption { display: none; }+}diff --git a/ui/src/components/onboarding/setupConfig.ts b/ui/src/components/onboarding/setupConfig.tsnew file mode 100644index 000000000..653d7f0e8--- /dev/null+++ b/ui/src/components/onboarding/setupConfig.ts@@ -0,0 +1,131 @@+/**+ * The config evidence setup is allowed to act on, and the only way it reads it.+ *+ * C2's prerequisite is a persisted fact that another browser, another operator or+ * Settings can change while this flow is open. `api.getConfig()` answers from a 30s+ * cache, so calling it again is not a freshness test — it can hand back the world as+ * it was before the change. Everything that must not be wrong about the prerequisite+ * — the initial read, an explicit Retry and the completion boundary — comes through+ * the uncached GET here instead.+ *+ * 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.+ *+ * Stateless on purpose: no React, no cache, no owner. It returns one classified read.+ */+import { apiFetch } from '@/lib/apiFetch';++/**+ * 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>;+};++/**+ * One read, classified in the terms the caller acts in. `unread` covers every way the+ * answer failed to arrive — transport, HTTP, JSON, shape — because they all leave the+ * prerequisite unknown, and unknown never becomes `false` or `true` by fallback.+ */+export type SetupConfigRead =+ | { state: 'read'; config: SetupConfigSnapshot }+ | { state: 'unread'; status?: number; detail?: string };++export type SetupConfigFetch = (input: string, init?: RequestInit) => Promise<Response>;++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 by refusing it.+ *+ * Returns `null` rather than throwing so each caller decides what an invalid body+ * means at its 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,+ };+}++/**+ * Read the config as it is right now.+ *+ * `cache: 'no-store'` is the point of the function: this is the read whose staleness+ * would let setup complete against a prerequisite somebody already turned off.+ */+export async function fetchSetupConfig(fetch: SetupConfigFetch = apiFetch): Promise<SetupConfigRead> {+ let response: Response;+ try {+ response = await fetch('/api/config', { cache: 'no-store' });+ } catch (cause) {+ return { state: 'unread', detail: String(cause) };+ }+ const body = await parseJson(response);+ if (!response.ok) return { state: 'unread', status: response.status, detail: errorDetail(body) };+ const config = readSetupConfig(body);+ // No status here: the transport succeeded, so `HTTP 200` would explain nothing about+ // a body that arrived and did not say what it had to say.+ if (!config) return { state: 'unread', detail: errorDetail(body) };+ return { state: 'read', config };+}diff --git a/ui/src/components/onboarding/setupHandoff.test.ts b/ui/src/components/onboarding/setupHandoff.test.tsnew file mode 100644index 000000000..fdb3ae514--- /dev/null+++ b/ui/src/components/onboarding/setupHandoff.test.ts@@ -0,0 +1,47 @@+// @vitest-environment jsdom+import { afterEach, expect, it, vi } from 'vitest';+import { captureSetupCards, measureSetupScreen, playSetupHandoff, setupHandoffAllowed } from './setupHandoff';++afterEach(() => { document.body.innerHTML = ''; vi.useRealTimers(); vi.unstubAllGlobals(); delete (document as Partial<Document>).hidden; delete (HTMLElement.prototype as Partial<HTMLElement>).animate; });+const screen = (selector: string) => {+ const node = document.createElement('div');+ node.innerHTML = `<div class="${selector}"><span class="onboarding-card-logo" id="duplicate">icon</span><strong class="onboarding-card-name">Claude Code</strong></div>`;+ document.body.append(node);+ for (const child of [node, ...node.querySelectorAll<HTMLElement>('*')]) child.getBoundingClientRect = () => new DOMRect(20, 30, 100, 60);+ return node;+};+it('temporarily measures a hidden inert root and restores its inline presentation', () => {+ const node = screen('onboarding-assistant'); node.hidden = true; node.inert = true; node.style.color = 'red';+ const restore = measureSetupScreen(node);+ expect(node.hidden).toBe(false); expect(node.inert).toBe(true); expect(node.style.visibility).toBe('hidden');+ restore(); expect(node.hidden).toBe(true); expect(node.style.color).toBe('red'); expect(node.style.position).toBe('');+});+it('snapshots C3 hooks without duplicating IDs in the live tree', () => {+ const source = screen('onboarding-collaboration-card');+ const snapshot = captureSetupCards(source, 'intro');+ expect(snapshot.cards).toHaveLength(1);+ expect(snapshot.cards[0].icon.node.id).toBe('');+});+it('cancels cleanly and finishes only once after resize/visibility', () => {+ vi.useFakeTimers();+ vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false, addEventListener() {}, removeEventListener() {} })));+ const cancel = vi.fn();+ HTMLElement.prototype.animate = vi.fn(() => ({ cancel }) as unknown as Animation);+ const source = screen('onboarding-collaboration-card');+ const target = screen('onboarding-assistant'); target.hidden = true;+ const finish = vi.fn();+ const stop = playSetupHandoff(document.body, source, target, 'intro', 'assistants', finish);+ expect(target.hidden).toBe(true);+ const layer = document.querySelector<HTMLElement>('.onboarding-handoff-layer')!;+ expect(layer.getAttribute('aria-hidden')).toBe('true'); expect(layer.inert).toBe(true);+ window.dispatchEvent(new Event('resize')); vi.runAllTimers();+ expect(finish).toHaveBeenCalledOnce(); expect(document.querySelector('.onboarding-handoff-layer')).toBeNull();+ stop(); expect(source.style.visibility).toBe('');+});+it('bails out for explicit pause, hidden documents, and reduced motion', () => {+ vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));+ expect(setupHandoffAllowed()).toBe(false);+ expect(setupHandoffAllowed(true)).toBe(false);+ Object.defineProperty(document, 'hidden', { configurable: true, value: true });+ expect(setupHandoffAllowed()).toBe(false);+});diff --git a/ui/src/components/onboarding/setupHandoff.ts b/ui/src/components/onboarding/setupHandoff.tsnew file mode 100644index 000000000..aff55ca05--- /dev/null+++ b/ui/src/components/onboarding/setupHandoff.ts@@ -0,0 +1,160 @@+import type { SetupScreenId } from './setupFlow';++type Piece = { node: HTMLElement; bounds: DOMRect };+type CardSnapshot = {+ bounds: DOMRect; surface: string; border: string; radius: string;+ /** Whether the source card wore the mint halo; the flight fades it through the token. */+ glow: boolean;+ icon: Piece; name: Piece;+};+export type SetupSnapshot = { cards: CardSnapshot[]; retiring?: Piece };+const timing: KeyframeAnimationOptions = { duration: 860, easing: 'cubic-bezier(.32,0,.16,1)', fill: 'both' };++const hooks = (screen: SetupScreenId) => screen === 'providers'+ ? { card: '.setup-destination', icon: '.setup-destination-logo', name: '.setup-destination-name' }+ : { card: screen === 'intro' ? '.onboarding-collaboration-card' : '.onboarding-assistant', icon: '.onboarding-card-logo', name: '.onboarding-card-name' };++function capturePiece(element: HTMLElement): Piece {+ const node = element.cloneNode(true) as HTMLElement;+ // A snapshot is presentation only. Duplicate IDs must never enter the live tree.+ for (const child of [node, ...node.querySelectorAll<HTMLElement>('[id]')]) child.removeAttribute('id');+ const style = getComputedStyle(element);+ Object.assign(node.style, { font: style.font, color: style.color, letterSpacing: style.letterSpacing, lineHeight: style.lineHeight });+ return { node, bounds: element.getBoundingClientRect() };+}++export function captureSetupCards(root: HTMLElement, screen: SetupScreenId): SetupSnapshot {+ const selectors = hooks(screen);+ const cards = Array.from(root.querySelectorAll<HTMLElement>(selectors.card)).flatMap((card) => {+ const icon = card.querySelector<HTMLElement>(selectors.icon);+ const name = card.querySelector<HTMLElement>(selectors.name);+ if (!icon || !name) return [];+ const style = getComputedStyle(card);+ return [{ bounds: card.getBoundingClientRect(), surface: style.backgroundColor, border: style.borderColor,+ radius: style.borderRadius, glow: style.boxShadow !== 'none', icon: capturePiece(icon), name: capturePiece(name) }];+ });+ const stage = screen === 'providers' ? root.querySelector<HTMLElement>('.setup-provider-stage') : null;+ const retiring = stage ? capturePiece(stage) : undefined;+ retiring?.node.querySelector('.setup-destinations')?.remove();+ return { cards, retiring };+}++/** Safe media reading: the shell runs in browsers and in jsdom, which ships no matchMedia. */+export const mediaQuery = (query: string): boolean =>+ typeof window.matchMedia === 'function' && window.matchMedia(query).matches;++export function setupHandoffAllowed(paused = false): boolean {+ return !paused && !document.hidden && !mediaQuery('(prefers-reduced-motion: reduce)')+ && typeof HTMLElement.prototype.animate === 'function';+}++/** Measure the incoming mounted screen without activating its effects or changing flow. */+export function measureSetupScreen(root: HTMLElement): () => void {+ const hidden = root.hidden;+ const style = root.getAttribute('style');+ root.hidden = false;+ root.inert = true;+ Object.assign(root.style, { position: 'absolute', inset: '0', visibility: 'hidden', pointerEvents: 'none' });+ return () => {+ root.hidden = hidden;+ if (style === null) root.removeAttribute('style'); else root.setAttribute('style', style);+ };+}++/** The returned cleanup cancels without navigating. Visibility/resize finish instantly. */+export function playSetupHandoff(+ host: HTMLElement, outgoing: HTMLElement, incoming: HTMLElement,+ from: SetupScreenId, to: SetupScreenId, onComplete: () => void,+): () => void {+ const snapshot = captureSetupCards(outgoing, from);+ const restoreIncoming = measureSetupScreen(incoming);+ const targets = Array.from(incoming.querySelectorAll<HTMLElement>(hooks(to).card));+ const origin = host.getBoundingClientRect();+ const layer = document.createElement('div');+ layer.className = 'onboarding-handoff-layer';+ layer.setAttribute('aria-hidden', 'true');+ layer.inert = true;+ const animations: Animation[] = [];+ const animate = (node: HTMLElement, frames: Keyframe[], options = timing) => {+ animations.push(node.animate(frames, options));+ };+ const position = (piece: Piece) => Object.assign(piece.node.style, {+ position: 'absolute', left: `${piece.bounds.x - origin.x}px`, top: `${piece.bounds.y - origin.y}px`,+ width: `${piece.bounds.width}px`, height: `${piece.bounds.height}px`, margin: '0',+ });+ if (snapshot.retiring) {+ position(snapshot.retiring);+ layer.append(snapshot.retiring.node);+ animate(snapshot.retiring.node, [{ opacity: 1 }, { opacity: 0, transform: 'translateY(-36px)' }], { ...timing, duration: 300 });+ }+ // The next provider stage enters behind the moving assistant identities.+ const providerStage = to === 'providers' ? incoming.querySelector<HTMLElement>('.setup-provider-stage') : null;+ if (providerStage) {+ const arriving = capturePiece(providerStage);+ arriving.node.querySelector('.setup-destinations')?.remove();+ position(arriving);+ arriving.node.style.visibility = 'visible';+ layer.append(arriving.node);+ animate(arriving.node, [{ opacity: 0, transform: 'translateY(-24px)' }, { opacity: 1, transform: 'translateY(0)' }]);+ }+ snapshot.cards.forEach((source, index) => {+ const target = targets[index];+ if (!target) return;+ const bounds = target.getBoundingClientRect();+ if (!bounds.width || !bounds.height || !source.bounds.width || !source.bounds.height) return;+ const style = getComputedStyle(target);+ const card = document.createElement('div');+ card.className = 'onboarding-handoff-card';+ Object.assign(card.style, { left: `${source.bounds.x - origin.x}px`, top: `${source.bounds.y - origin.y}px`,+ width: `${bounds.width}px`, height: `${bounds.height}px` });+ const surface = document.createElement('div');+ surface.className = 'onboarding-handoff-surface';+ card.append(surface);+ animate(card, [{ transform: 'translate(0,0)' }, { transform: `translate(${bounds.x - source.bounds.x}px,${bounds.y - source.bounds.y}px)` }]);+ if (source.glow) surface.dataset.glow = 'true';+ animate(surface, [+ { transform: `scale(${source.bounds.width / bounds.width},${source.bounds.height / bounds.height})`, background: source.surface, borderColor: source.border, borderRadius: source.radius },+ { transform: 'scale(1,1)', background: style.backgroundColor, borderColor: style.borderColor, borderRadius: style.borderRadius },+ ]);+ for (const [piece, selector] of [[source.icon, hooks(to).icon], [source.name, hooks(to).name]] as const) {+ const child = target.querySelector<HTMLElement>(selector);+ if (!child || !piece.bounds.width || !piece.bounds.height) continue;+ const end = child.getBoundingClientRect();+ Object.assign(piece.node.style, { position: 'absolute', left: `${piece.bounds.x - source.bounds.x}px`, top: `${piece.bounds.y - source.bounds.y}px`,+ width: `${piece.bounds.width}px`, height: `${piece.bounds.height}px`, margin: '0', transformOrigin: 'top left' });+ card.append(piece.node);+ animate(piece.node, [{ transform: 'translate(0,0) scale(1)' }, {+ transform: `translate(${end.x - bounds.x - (piece.bounds.x - source.bounds.x)}px,${end.y - bounds.y - (piece.bounds.y - source.bounds.y)}px) scale(${end.width / piece.bounds.width},${end.height / piece.bounds.height})`,+ color: getComputedStyle(child).color,+ }]);+ }+ layer.append(card);+ });+ restoreIncoming();+ host.append(layer);+ // Start the halo fade one frame in, so the transition runs against the mounted layer.+ const fade = window.requestAnimationFrame(() => {+ for (const node of layer.querySelectorAll<HTMLElement>('[data-glow]')) node.removeAttribute('data-glow');+ });+ const previousVisibility = outgoing.style.visibility;+ outgoing.style.visibility = 'hidden';+ let settled = false;+ const media = typeof window.matchMedia === 'function' ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;+ const cleanup = () => {+ window.clearTimeout(timer);+ window.cancelAnimationFrame(fade);+ animations.forEach((animation) => animation.cancel());+ layer.remove();+ outgoing.style.visibility = previousVisibility;+ window.removeEventListener('resize', finish);+ document.removeEventListener('visibilitychange', visibility);+ media?.removeEventListener('change', finish);+ };+ const finish = () => { if (settled) return; settled = true; cleanup(); onComplete(); };+ const visibility = () => { if (document.hidden) finish(); };+ const timer = window.setTimeout(finish, 900);+ window.addEventListener('resize', finish, { once: true });+ document.addEventListener('visibilitychange', visibility);+ media?.addEventListener('change', finish, { once: true });+ return () => { settled = true; cleanup(); };+}diff --git a/ui/src/components/onboarding/setupScreenRegistry.ts b/ui/src/components/onboarding/setupScreenRegistry.tsnew file mode 100644index 000000000..4ebbaba54--- /dev/null+++ b/ui/src/components/onboarding/setupScreenRegistry.ts@@ -0,0 +1,8 @@+import { SETUP_SCREENS, type SetupScreenId } from './setupFlow';++/** Build-time registration only. Capability, saved intent and runtime never remove a step. */+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 });diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsxindex 6df4fbc08..d3a655258 100644--- a/ui/src/components/steps/AgentDetection.tsx+++ b/ui/src/components/steps/AgentDetection.tsx@@ -1,4 +1,5 @@-import React, { useCallback, useEffect, useRef, useState } from 'react';+import React, { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';+import { createPortal } from 'react-dom';import {ArrowLeft,ArrowRight,@@ -27,7 +28,8 @@ import type { BackendConnectionState } from '@/context/ApiContext';import { setConfigField } from '@/lib/configMutations';import { OpencodePermissionSetup } from '../settings/shared/OpencodePermissionSetup';import { ImportKeysNotice } from '../onboarding/ImportKeysNotice';-import { useModelHubCapability } from '../settings/models/useModelHubCapability';+import { modelHubEnabledFromConfig } from '../settings/models/featureFlags';+import type { SetupAction, SetupScreenHandle } from '../onboarding/setupFlow';import type { BackendId as RuntimeBackendId } from '../settings/shared/useBackendRuntime';import { useOpencodePermission } from '../settings/shared/useOpencodePermission';import { Button } from '../ui/button';@@ -36,6 +38,9 @@ import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';import { MODEL_HUB_SETTINGS_PATH } from '../settings/models/modelHubRoutes';interface AgentDetectionProps {+ active?: boolean;+ ref?: React.Ref<SetupScreenHandle>;+ onActionChange?: (action: SetupAction) => void;data: any;onNext: (data: any) => void | Promise<void>;onBack?: (data?: { agents: Record<string, AgentState> }) => void;@@ -50,6 +55,29 @@ type AgentState = {status?: 'unknown' | 'ok' | 'missing';};+/**+ * The verdict of the latest settled enable write, and the intent that earned it.+ *+ * A write can finish with nobody reading the screen, and two reads can start at once+ * when the screen comes back. The intent is what makes the verdict answerable: only a+ * read asking the same question may report it, so a stale read can neither spend it+ * nor throw it away.+ */+type EnableReceipt = { intent: number; message: string };++/**+ * Whether this read answers for the outstanding verdict, or only reports it.+ *+ * Only an operation that succeeded at the same thing the verdict is about may spend+ * it: the card's own Retry, a provider connection that went through, an install that+ * worked. A dialog mounting, closing or being cancelled, a write-state notification+ * saying nothing is pending, an install or a read that failed — those are the+ * lifecycle talking, not an answer, and an apply failure the person has not dealt+ * with yet must still be there afterwards. An ordinary activation, detect or chip+ * refresh reports the verdict rather than replacing it with silence.+ */+type ConnectionRefresh = { acknowledge?: boolean };+const DEFAULT_AGENTS = DEFAULT_AGENT_STATE as Record<string, AgentState>;// Backends with a dedicated provider config body (rendered in the wizard@@ -79,15 +107,20 @@ 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 }) => {+export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onBack, isPage = false, onSave, completionRecovery, active = true, ref, onActionChange }) => {const { t } = useTranslation();const api = useApi();const { showToast } = useToast();const navigate = useNavigate();const routeSurfaceActive = useRouteSurfaceActive();- const modelHubEnabled = useModelHubCapability();+ const modelHubEnabled = modelHubEnabledFromConfig(data);+ const [visited, setVisited] = useState(active);+ const activation = useRef(0);+ const activeRef = useRef(active);+ useLayoutEffect(() => { activeRef.current = active; activation.current += 1; }, [active]);+ useEffect(() => { if (active) setVisited(true); }, [active]);const [agents, setAgents] = useState<Record<string, AgentState>>(normalizeAgents(data));- const permission = useOpencodePermission({ autoFetchStatus: true });+ const permission = useOpencodePermission({ autoFetchStatus: active });const [installingAgents, setInstallingAgents] = useState<Record<string, boolean>>({});const [installResults, setInstallResults] = useState<Record<string, { ok: boolean; message: string; output?: string | null }>@@ -106,6 +139,9 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onconst enableQueue = useRef(Promise.resolve());const enableIntent = useRef<Partial<Record<RuntimeBackendId, number>>>({});const pendingEnable = useRef<Partial<Record<RuntimeBackendId, number>>>({});+ // What the latest settled write still owes this screen, held until someone who can+ // answer for it reports it — see EnableReceipt.+ const enableReceipt = useRef<Partial<Record<RuntimeBackendId, EnableReceipt>>>({});// One provider modal/reconciliation at a time; Configure and navigation stay// disabled until persisted fields and the subsequent detection reach agents.const [syncing, setSyncing] = useState(false);@@ -126,57 +162,93 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onconst detectionTokens = useRef<Record<string, number>>({});const isMissing = (agent: AgentState) => agent.status === 'missing';- const refreshConnection = useCallback(async (name: RuntimeBackendId, receiptError = '') => {- if (pendingEnable.current[name] !== undefined) return;+ const refreshConnection = useCallback(async (name: RuntimeBackendId, { acknowledge = false }: ConnectionRefresh = {}) => {+ if (!activeRef.current || pendingEnable.current[name] !== undefined) return;+ const epoch = activation.current;const intent = enableIntent.current[name];const token = (connectionTokens.current[name] || 0) + 1;connectionTokens.current[name] = token;+ // Read the verdict, don't take it. Starting is not accepting: this read may turn+ // out to be stale, and it may be answering a different intent entirely — either+ // way the verdict has to still be there for the read that can report it.+ const receipt = enableReceipt.current[name];+ const owed = receipt && receipt.intent === intent ? receipt : undefined;+ const owns = () => epoch === activation.current && connectionTokens.current[name] === token && enableIntent.current[name] === intent;setConnectionPending((current) => ({ ...current, [name]: true }));- setConnectionErrors((current) => ({ ...current, [name]: receiptError }));+ // Nothing owed means nothing to say about the write, which is not the same as+ // saying it went fine: an ordinary refresh leaves a reported failure standing.+ if (owed) setConnectionErrors((current) => ({ ...current, [name]: owed.message }));try {const result = await api.getBackendConnection(name);- if (connectionTokens.current[name] !== token || enableIntent.current[name] !== intent) return;+ if (!owns()) return;if (!result.ok) throw new Error(result.message || t('onboarding.connection.readFailed'));setConnections((current) => ({ ...current, [name]: result }));setAgents((current) => ({ ...current, [name]: { ...current[name], enabled: result.enabled } }));+ // Spending the verdict takes all three: this read still owns the screen, the+ // caller is an operation that actually answers for it, and the verdict in hand+ // is the one that was there when the read began. A newer write that landed+ // meanwhile is still owed to whoever reads next.+ const retire = acknowledge && owed && enableReceipt.current[name] === owed;+ if (retire) delete enableReceipt.current[name];+ setConnectionErrors((current) => ({ ...current, [name]: retire ? '' : owed?.message || '' }));} catch (error) {- if (connectionTokens.current[name] !== token || enableIntent.current[name] !== intent) return;+ if (!owns()) return;setConnections((current) => ({ ...current, [name]: undefined }));- setConnectionErrors((current) => ({ ...current, [name]: String(error) }));+ // A read that also failed does not get to bury what the write reported, and it+ // answers for nothing: the apply failure is the original evidence, it is the one+ // the person can act on, and it stays owed until something actually settles it.+ setConnectionErrors((current) => ({ ...current, [name]: owed?.message || String(error) }));} finally {if (connectionTokens.current[name] === token) setConnectionPending((current) => ({ ...current, [name]: false }));}}, [api, t]);+ // 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+ // them consumes the write verdict, so whichever one wins still reports it.useEffect(() => {- if (!isPage) for (const name of ASSISTANT_ORDER) void refreshConnection(name);+ const leftSurface = previousRouteSurfaceActive.current && !routeSurfaceActive;+ previousRouteSurfaceActive.current = routeSurfaceActive;+ // Returning also collects what a write settled while there was nobody to tell.+ if (!isPage && active && !leftSurface) for (const name of ASSISTANT_ORDER) {+ void refreshConnection(name);+ }+ // Leaving drops in-flight READS only. A queued enable intent is a write the person+ // already asked for; invalidating it here would strand `pendingEnable` behind a+ // completion whose intent check can never pass again.return () => { for (const name of ASSISTANT_ORDER) {connectionTokens.current[name] = (connectionTokens.current[name] || 0) + 1;- enableIntent.current[name] = (enableIntent.current[name] || 0) + 1;} };- }, [refreshConnection, isPage]);- useEffect(() => {- const returnedToSurface = routeSurfaceActive && !previousRouteSurfaceActive.current;- previousRouteSurfaceActive.current = routeSurfaceActive;- if (!isPage && returnedToSurface) {- for (const name of ASSISTANT_ORDER) void refreshConnection(name);- }- }, [isPage, refreshConnection, routeSurfaceActive]);+ }, [refreshConnection, isPage, active, routeSurfaceActive]);const isAnyInstalling = Object.values(installingAgents).some(Boolean);useEffect(() => {- if (isPage || !data.__onboardingDetected) void detectAll();+ if (!active || (!onActionChange && !isPage && data.__onboardingDetected)) return;+ // The first showing adopts the parent snapshot, because Welcome may have finished+ // detection after this retained screen mounted. After that the screen owns its own+ // paths: the snapshot predates every install, provider write and probe made here, so+ // copying it back on re-entry would probe a binary nobody chose and report a backend+ // missing while the right path is the one persisted. `visited` is still false in the+ // render that activates the screen, which is exactly that first showing.+ const source = visited ? agents : normalizeAgents(data);+ if (!visited) {+ setAgents((previous) => Object.fromEntries(Object.entries(previous).map(([name, agent]) => [name, { ...agent, cli_path: source[name].cli_path }])));+ }+ void Promise.all(Object.entries(source).map(([name, agent]) => detect(name, agent.cli_path)));// eslint-disable-next-line react-hooks/exhaustive-deps- }, []);+ }, [active]);const detect = async (name: string, binary?: string) => {+ if (!activeRef.current) return;+ const epoch = activation.current;const token = (detectionTokens.current[name] || 0) + 1;detectionTokens.current[name] = token;setDetectingAgents((prev) => ({ ...prev, [name]: true }));setDetectionErrors((prev) => ({ ...prev, [name]: '' }));try {const result = await api.detectCli(binary || name);- if (detectionTokens.current[name] !== token) return;+ if (epoch !== activation.current || detectionTokens.current[name] !== token) return;if (result.found) {setInstallResults((prev) => {if (!prev[name] || prev[name].ok) return prev;@@ -195,7 +267,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on},}));} catch (error) {- if (detectionTokens.current[name] !== token) return;+ if (epoch !== activation.current || detectionTokens.current[name] !== token) return;setDetectionErrors((prev) => ({ ...prev, [name]: String(error) }));setAgents((prev) => ({ ...prev, [name]: { ...prev[name], status: 'unknown' } }));} finally {@@ -269,9 +341,15 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on} catch (error) { receiptError = String(error); }if (enableIntent.current[backend] !== intent) return;delete pendingEnable.current[backend];+ // Record the verdict before anyone is asked to read it, whether or not there is+ // anybody to tell. Two reads can start at once when the screen comes back, and+ // the one that loses the race used to take the message with it.+ enableReceipt.current[backend] = { intent, message: receiptError };+ // A screen the person has left may neither read nor publish; the verdict waits.+ if (!activeRef.current) return;// This uncached projection reads persisted enabled even after a rejected// write. Apply failure cannot roll back config that was already committed.- await refreshConnection(backend, receiptError);+ await refreshConnection(backend);});};@@ -337,8 +415,10 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onsetInstallResults((prev) => ({ ...prev, [name]: { ok: false, message: '', output: null } }));setExpandedOutputs((prev) => ({ ...prev, [name]: false }));+ let installed = false;try {const result = await api.installAgent(name);+ installed = result.ok;const installedPath = typeof result.path === 'string' && result.path ? result.path : null;setInstallResults((prev) => ({...prev,@@ -361,7 +441,9 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on} finally {pendingInstalls.current.delete(name);setInstallingAgents((prev) => ({ ...prev, [name]: false }));- if (!isPage) void refreshConnection(name as RuntimeBackendId);+ // An install that failed reports its own failure and answers for nothing else;+ // only one that worked replaces what the enable write had to say.+ if (!isPage) void refreshConnection(name as RuntimeBackendId, { acknowledge: installed });}};@@ -374,18 +456,87 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on&& !installingAgents[name] && !detectingAgents[name] && !connectionPending[name]&& !pendingWrites[name] && !refreshingAgents[name] && !connectionErrors[name] && connections[name]?.entry_eligible);const canContinue = isPage ? Object.values(agents).some((agent) => agent.enabled) : readyBackends.length > 0;+ const primaryPending = useRef(false);const handlePrimaryAction = async () => {- if (entering) return;- if (isPage && onSave) { await onSave({ agents }); return; }+ if (!active || entering || primaryPending.current) return;+ primaryPending.current = true;+ if (isPage && onSave) { try { await onSave({ agents }); } finally { primaryPending.current = false; } return; }setEntering(true); setEntryError('');try {await enableQueue.current;await onNext({ agents, readyBackends });} catch (error) { setEntryError(String(error)); }- finally { setEntering(false); }+ finally { primaryPending.current = false; setEntering(false); }};+ const actionBusy = syncing || entering || isAnyInstalling || Object.values(pendingWrites).some(Boolean) || Object.values(refreshingAgents).some(Boolean);+ // The recovery node is fresh JSX on every shell render, so the publication depends on+ // whether one exists, never on its identity — an identity dependency would republish+ // against itself forever.+ const recoveryOpen = Boolean(completionRecovery);+ useImperativeHandle(ref, () => ({ activate: () => { if (canContinue && !actionBusy && !recoveryOpen) void handlePrimaryAction(); } }));+ // A layout effect, so the shell's action label lands in the same commit as the state+ // it describes: a passive publish would leave one render where the screen already+ // shows a settled state while the shared button still carries the previous label.+ useLayoutEffect(() => {+ if (active) onActionChange?.({ labelKey: entering ? 'onboarding.connection.connecting' : 'onboarding.connection.enter',+ disabled: !canContinue || actionBusy || recoveryOpen, busy: actionBusy, icon: entering ? 'spinner' : 'arrow-right' });+ }, [active, onActionChange, entering, canContinue, actionBusy, recoveryOpen]);++ // What sits under the shared pair in the shell: the readiness caption, the OpenCode+ // permission callout and the completion recovery. All three are ancillary to the+ // action and all three grow — a permission error carries a full diagnostic, a+ // recovery is a form. Kept inside the screen they push the anchor the two steps+ // share; lifted out of flow they cover the very buttons they explain. So the shell+ // reserves a slot after the pair and the active screen portals them into it.+ const setupRoot = useRef<HTMLDivElement>(null);+ const [actionAside, setActionAside] = useState<HTMLElement | null>(null);+ useEffect(() => {+ setActionAside(onActionChange+ ? setupRoot.current?.closest('.onboarding-step')?.querySelector<HTMLElement>('[data-setup-action-aside]') ?? null+ : null);+ }, [onActionChange]);+ const hintInner = (<>+ <p className="text-center text-xs text-muted">+ {t(readyBackends.some((name) => connections[name]?.ready) ? 'onboarding.connection.entryReady' : canContinue ? 'onboarding.connection.entryStopped' : 'onboarding.connection.entryHint')}{' '}+ {/* The whole-screen rescan, kept as part of the sentence that explains why a+ card might not say what was expected rather than a control competing with+ the action above it. */}+ <Button type="button" variant="link" size="xs" className="h-auto p-0 align-baseline text-xs"+ onClick={() => void detectAll()} disabled={isAnyInstalling || Object.values(detectingAgents).some(Boolean)}>+ <RefreshCw size={12} />{t('agentDetection.rescan')}+ </Button>+ </p>+ {entryError && <div role="alert" className="connection-error">{entryError} <Button variant="link" size="sm" disabled={entering} onClick={() => void handlePrimaryAction()}>{t('common.retry')}</Button></div>}+ </>);+ // Hosted in one place so the order under the pair is the same every time, and so the+ // standalone host keeps the arrangement it already had.+ const permissionNode = <OpencodePermissionSetup cliReady={opencodeAgent?.status === 'ok'}+ permissionAllowed={permission.permissionAllowed} state={permission.state} message={permission.message}+ // Granting permission succeeds at permission. It says nothing about whether+ // enabling the backend was persisted, so it reads the connection without+ // spending a verdict that is about something else.+ onSetup={() => void permission.setupPermission().then(() => refreshConnection('opencode'))} className="w-full" />;+ // A portal leaves the screen root, and with it the `inert` the shell puts on a screen+ // nobody is reading, so what it carries has to answer to the same activity itself.+ const asideNode = onActionChange+ ? (active && routeSurfaceActive && actionAside ? createPortal(<>+ <div className="onboarding-setup-hint">{hintInner}</div>+ {permissionNode}+ {completionRecovery}+ </>, actionAside) : null)+ : (+ <div className="onboarding-setup-footer">+ <Button type="button" variant="brand" className="group onboarding-action-w onboarding-primary-action" onClick={() => void handlePrimaryAction()}+ disabled={!canContinue || syncing || entering || Boolean(completionRecovery)}>+ {t(entering ? 'onboarding.connection.connecting' : 'onboarding.connection.enter')}+ <ArrowRight size={16} className="motion-safe:transition-transform motion-safe:duration-180 motion-safe:group-hover:translate-x-1" />+ </Button>+ {hintInner}+ {onBack && <Button type="button" variant="ghost" className="onboarding-action-w onboarding-back-action" disabled={syncing || entering || Boolean(completionRecovery)} onClick={() => onBack({ agents })}><ArrowLeft size={14} />{t('common.back')}</Button>}+ </div>+ );// Page mode keeps the existing settings shell — render the inner content onlyconst Inner = isPage ? (<>@@ -432,7 +583,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on<BackendLifecycleChipname={name}enabled={agent.enabled}- cliStatus={agent.status || 'unknown'}+ cliStatus={active ? agent.status || 'unknown' : 'unknown'}onChanged={async (info) => {// After a successful (re)install the chip hands back the// path the installer landed at — adopt it before@@ -549,14 +700,18 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onconst name = providerModal.backend;setProviderModal(null);void syncBackendFromConfig(name);+ // Closing is how the dialog leaves, not a result. Cancelled without writing+ // anything, it has answered for nothing the enable failure was about.void refreshConnection(name);}}onWriteState={(pending) => {const name = providerModal.backend;setPendingWrites((current) => ({ ...current, [name]: pending }));+ // "Nothing is pending" is the same notification whether a write succeeded,+ // failed or never happened; `onConnected` is the one that means it worked.if (!pending) void refreshConnection(name);}}- onConnected={async () => { await refreshConnection(providerModal.backend); }} />;+ onConnected={async () => { await refreshConnection(providerModal.backend, { acknowledge: true }); }} />;if (isPage) {return (@@ -572,9 +727,9 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on}return (- <div className="onboarding-setup">+ <div className="onboarding-setup" ref={setupRoot}><header className="onboarding-heading">- <h2>{t('onboarding.setup.title')}</h2>+ <h1 tabIndex={-1}>{t('onboarding.setup.title')}</h1><p>{t('onboarding.setup.subtitle')}</p></header>{/* The stage both steps share, so the action below lands on the same@@ -617,12 +772,12 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on: undefined}connectionPending={connectionPending[name]}connectionError={connectionErrors[name] || connections[name]?.message}- onRefreshConnection={() => void refreshConnection(name)}+ onRefreshConnection={() => void refreshConnection(name, { acknowledge: true })}configuringDisabled={syncing || pendingWrites[name] || !!refreshingAgents[name] || !!connectionPending[name] || !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)} />}- lifecycle={<BackendLifecycleChip name={name} enabled={agent.enabled} cliStatus={agent.status || 'unknown'}+ lifecycle={<BackendLifecycleChip name={name} enabled={agent.enabled} cliStatus={active ? agent.status || 'unknown' : 'unknown'}readyLabel={t('onboarding.setup.installed')}refreshKey={chipRefresh[name]}externallyBusy={!!refreshingAgents[name]}@@ -652,36 +807,22 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on})}</div></div>- <OpencodePermissionSetup cliReady={opencodeAgent?.status === 'ok'}- permissionAllowed={permission.permissionAllowed} state={permission.state} message={permission.message}- onSetup={() => void permission.setupPermission().then(() => refreshConnection('opencode'))} className="w-full" />+ {!onActionChange && permissionNode}{/* Wizard-only: the offer to take over API keys already on this machine.Settings → Backends reaches the same migration throughBackendSupplyModeCard, with its broader scope intact. Self-hides when- there is nothing importable or the gateway isn't reachable. */}- {modelHubEnabled === true && <ImportKeysNotice />}+ there is nothing importable or the gateway isn't reachable — which is+ why the slot around it is rendered either way: the stage keeps the+ capsule's height while the read is still out, when it turns out there+ is nothing to offer, and after the offer is refused, so none of the+ three can move the action below it. */}+ <div className="onboarding-import-slot">+ {visited && modelHubEnabled === true && <ImportKeysNotice />}</div>- {providerDialog}- {completionRecovery}- <div className="onboarding-setup-footer">- <Button type="button" variant="brand" className="group onboarding-action-w onboarding-primary-action" onClick={() => void handlePrimaryAction()}- disabled={!canContinue || syncing || entering || Boolean(completionRecovery)}>- {t(entering ? 'onboarding.connection.connecting' : 'onboarding.connection.enter')}- <ArrowRight size={16} className="motion-safe:transition-transform motion-safe:duration-180 motion-safe:group-hover:translate-x-1" />- </Button>- <p className="text-center text-xs text-muted">- {t(readyBackends.some((name) => connections[name]?.ready) ? 'onboarding.connection.entryReady' : canContinue ? 'onboarding.connection.entryStopped' : 'onboarding.connection.entryHint')}{' '}- {/* The whole-screen rescan, kept as part of the sentence that explains why a- card might not say what was expected rather than as a control competing- with the action above it. */}- <Button type="button" variant="link" size="xs" className="h-auto p-0 align-baseline text-xs"- onClick={() => void detectAll()} disabled={isAnyInstalling || Object.values(detectingAgents).some(Boolean)}>- <RefreshCw size={12} />{t('agentDetection.rescan')}- </Button>- </p>- {entryError && <div role="alert" className="connection-error">{entryError} <Button variant="link" size="sm" disabled={entering} onClick={() => void handlePrimaryAction()}>{t('common.retry')}</Button></div>}- {onBack && <Button type="button" variant="ghost" className="onboarding-action-w onboarding-back-action" disabled={syncing || entering || Boolean(completionRecovery)} onClick={() => onBack({ agents })}><ArrowLeft size={14} />{t('common.back')}</Button>}</div>+ {providerDialog}+ {!onActionChange && completionRecovery}+ {asideNode}</div>);};diff --git a/ui/src/components/steps/Welcome.tsx b/ui/src/components/steps/Welcome.tsxindex f17de5785..b52a2b9ee 100644--- a/ui/src/components/steps/Welcome.tsx+++ b/ui/src/components/steps/Welcome.tsx@@ -1,27 +1,36 @@-import { useRef, useState } from 'react';-import { ArrowRight, RefreshCw } from 'lucide-react';+import { useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type Ref } from 'react';+import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';import { useApi } from '../../context/ApiContext';-import { Button } from '../ui/button';import { CollaborationStory } from '../onboarding/CollaborationStory';-import { AccessTiles } from '../onboarding/AccessTiles';import { ASSISTANT_ORDER } from '../onboarding/collaborationTimeline';import { DEFAULT_AGENT_STATE } from '@/lib/agentBackends';+import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';+import type { SetupAction, SetupScreenHandle } from '../onboarding/setupFlow';import '../onboarding/onboarding.css';interface WelcomeProps {+ active: boolean;+ ref?: Ref<SetupScreenHandle>;+ onActionChange: (action: SetupAction) => void;data?: { agents?: Record<string, { cli_path?: string }> };onNext: (data: unknown) => void | Promise<void>;}-export function Welcome({ data, onNext }: WelcomeProps) {+export function Welcome({ data, onNext, active, ref, onActionChange }: WelcomeProps) {const { t } = useTranslation();const api = useApi();+ const routeSurfaceActive = useRouteSurfaceActive();const [pending, setPending] = useState(false);const [error, setError] = useState<string | null>(null);const busy = useRef(false);+ // Same commit as the state it describes; see AgentDetection's publication note.+ useLayoutEffect(() => {+ if (active) onActionChange({ labelKey: pending ? 'onboarding.welcome.detecting' : error ? 'common.retry' : 'onboarding.welcome.getStarted', disabled: pending, busy: pending, icon: pending ? 'spinner' : 'arrow-right' });+ }, [active, error, onActionChange, pending]);+ useImperativeHandle(ref, () => ({ activate: () => { void start(); } }));const start = async () => {- if (busy.current) return;+ if (!active || busy.current) return;busy.current = true;setPending(true);setError(null);@@ -39,30 +48,38 @@ export function Welcome({ data, onNext }: WelcomeProps) {setPending(false);}};+ // The failure explains the action, so it belongs under it — and in the shell that+ // action is the shared pair this screen no longer draws. Left in the screen, a long+ // diagnostic (or an opened `details`) grows the content above the footer and drags+ // the anchor the two steps share, so the shell's slot after the pair takes it.+ const setupRoot = useRef<HTMLDivElement>(null);+ const [actionAside, setActionAside] = useState<HTMLElement | null>(null);+ useEffect(() => {+ setActionAside(setupRoot.current?.closest('.onboarding-step')?.querySelector<HTMLElement>('[data-setup-action-aside]') ?? null);+ }, [onActionChange]);+ const errorNode = error ? (+ <div role="alert" className="text-center text-sm text-destructive-ink">+ <p>{t('onboarding.welcome.detectionFailed')}</p>+ <details className="mt-2 max-w-xl break-words"><summary>{t('onboarding.details')}</summary>{error}</details>+ </div>+ ) : null;return (- <div className="onboarding-welcome">+ <div className="onboarding-welcome" ref={setupRoot}><header className="onboarding-heading">- <h1>{t('onboarding.welcome.title')}</h1>+ <h1 tabIndex={-1}>{t('onboarding.welcome.title')}</h1><p>{t('onboarding.welcome.subtitle')}</p></header>{/* The stage both steps share, so this button and the setup step's land on thesame coordinates — see `.onboarding-stage` in onboarding.css. */}<div className="onboarding-stage">- <CollaborationStory />+ <CollaborationStory active={active} /></div>- <Button type="button" variant="brand" className="group onboarding-action-w onboarding-primary-action" onClick={() => void start()} disabled={pending}>- {t(pending ? 'onboarding.welcome.detecting' : error ? 'common.retry' : 'onboarding.welcome.getStarted')}- {pending ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : <ArrowRight size={16} className="motion-safe:transition-transform motion-safe:duration-180 motion-safe:group-hover:translate-x-1" />}- </Button>- {error && <div role="alert" className="text-center text-sm text-destructive-ink">- <p>{t('onboarding.welcome.detectionFailed')}</p>- <details className="mt-2 max-w-xl break-words"><summary>{t('onboarding.details')}</summary>{error}</details>- </div>}- {/* Below the action, not inside the stage: where a person can reach Avibe from is- an epilogue to the introduction, and the reference draws it under the button- for that reason. Keeping it out of the stage is also what lets the stage be a- shared reservation — the connection step has no counterpart to this block. */}- <AccessTiles />+ {/* A portal leaves the screen root, and with it the `inert` the shell puts on a+ screen nobody is reading, so the alert answers to the same activity itself.+ Without a shell slot — the standalone host — it stays where it always was. */}+ {errorNode && (active && routeSurfaceActive && actionAside+ ? createPortal(<div className="onboarding-setup-hint">{errorNode}</div>, actionAside)+ : errorNode)}</div>);}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex fa161433f..e839b2624 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -5248,8 +5248,8 @@"onboarding": {"welcome": {"getStarted": "Get started",- "title": "Great on their own. Better together",- "subtitle": "Claude Code, Codex, and OpenCode — from planning to delivery",+ "title": "Different strengths. One team.",+ "subtitle": "Bring Claude Code, Codex, and OpenCode together","detecting": "Checking…","detectionFailed": "Could not check your assistants. Try again."},@@ -5281,7 +5281,7 @@},"access": {"label": "Work from anywhere",- "description": "Work on the go with the Avibe app or your favorite chat apps",+ "description": "6 ways to work. Wherever you are.","avibe": "Avibe App","slack": "Slack","discord": "Discord",@@ -5341,6 +5341,7 @@"savedSubscription": "Subscription credentials detected","savedDisabled": "Credentials saved. This assistant is currently disabled.","readFailed": "Unable to read connection state. Try again.",+ "readFailedStatus": "Unable to read connection state (HTTP {{status}}). Try again.","saveFailed": "Unable to save the connection. Try again.","applyFailed": "Credentials saved, but runtime application failed. Retry the save.","applyPending": "Runtime application is not confirmed yet. Refresh the connection state.",@@ -5402,6 +5403,11 @@"brand": {"name": "Avibe","tagline": "Agent OS"+ },+ "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."}}}diff --git a/ui/src/i18n/translationContract.test.ts b/ui/src/i18n/translationContract.test.tsindex 1e0f971ce..8a321ad56 100644--- a/ui/src/i18n/translationContract.test.ts+++ b/ui/src/i18n/translationContract.test.ts@@ -100,6 +100,15 @@ describe('resource type representation and dynamic boundaries', () => {expect(instance.t('common', { returnObjects: true }).save).toEqual((lng === 'en' ? en : zh).common.save);});+ it.each(['en', 'zh'] as const)('carries the config-read status through localized copy in %s', (lng) => {+ const bundle = lng === 'en' ? en : zh;+ const rendered = translator(lng).t('onboarding.connection.readFailedStatus', { status: 500 });+ // Both languages must spend the placeholder: a locale that drops it would show a+ // sentence with no diagnostic, which is what the raw `HTTP 500` fragment replaced.+ expect(rendered).toBe(bundle.onboarding.connection.readFailedStatus.replace('{{status}}', '500'));+ expect(rendered).toContain('500');+ });+it('matches nested-before-literal collision precedence', () => {const instance = createInstance();void instance.init({ lng: 'en', resources: { en: { translation: { collision } } } });diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 1ce666b5c..f6c17b02f 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -5247,7 +5247,7 @@},"onboarding": {"welcome": {- "getStarted": "开始使用",+ "getStarted": "立即开始","title": "各有所长,接力完成","subtitle": "让 Claude Code、Codex、OpenCode 一起工作","detecting": "检测中…",@@ -5281,7 +5281,7 @@},"access": {"label": "随时随地安排工作",- "description": "手机 APP 和常用聊天应用,随时随地安排工作",+ "description": "6个工作入口,随时随地安排工作","avibe": "Avibe App","slack": "Slack","discord": "Discord",@@ -5341,6 +5341,7 @@"savedSubscription": "已检测到订阅凭据","savedDisabled": "凭据已保存。此助手当前未启用。","readFailed": "无法读取连接状态,请重试",+ "readFailedStatus": "无法读取连接状态(HTTP {{status}}),请重试","saveFailed": "无法保存连接,请重试","applyFailed": "凭据已保存,但运行时应用失败,请重试保存","applyPending": "运行时尚未确认生效,请刷新连接状态",@@ -5402,6 +5403,11 @@"brand": {"name": "Avibe","tagline": "Agent OS"+ },+ "flow": {+ "backToIntro": "返回介绍",+ "backToProviders": "返回模型",+ "gatewayRequired": "设置流程需要启用模型网关。已有配置未改变,请通过现有配置管理恢复后重试。"}}}