Skip to content

armgit / avibe

Public Imported from GitHub
0

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

106 KB
Raw Blame
// @vitest-environment jsdom
import { createRef, StrictMode } from 'react';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { createInstance } from 'i18next';
import { I18nextProvider } from 'react-i18next';
import { MemoryRouter, useLocation } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentDetection } from '../steps/AgentDetection';
import { AssistantRow } from './AssistantRow';
import en from '../../i18n/en.json';
import type { BackendConnectionState } from '../../context/ApiContext';
import type { Source } from '../settings/models/types';
import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';
import type { SetupAction, SetupScreenHandle } from './setupFlow';
import { INITIAL_SETUP_FLOW_STATE } from './setupFlow';
import { SETUP_LINEUP } from './collaborationTimeline';

const mock = vi.hoisted(() => ({ api: {
  detectCli: vi.fn(), installAgent: vi.fn(), getConfig: vi.fn(), getBackendRuntime: vi.fn(), getBackendConnection: vi.fn(), mutateConfig: vi.fn(), getClaudeAuth: vi.fn(), getCodexAuth: vi.fn(), getOpencodeProviders: vi.fn(), saveClaudeAuth: vi.fn(),
  listVibeAgents: vi.fn(), getVibeAgent: vi.fn(),
}, showToast: vi.fn(), permission: { permissionAllowed: true, statusLoaded: true, state: 'idle', message: '', setupPermission: vi.fn() } as {
  permissionAllowed: boolean; statusLoaded: boolean; state: string; message: string; setupPermission: ReturnType<typeof vi.fn>;
}, models: { getAgentChain: vi.fn(), getAgentChains: vi.fn(), previewAgentChain: vi.fn(), putAgentChain: vi.fn(), listSources: vi.fn() } }));
vi.mock('../../context/ApiContext', () => ({ useApi: () => mock.api }));
vi.mock('../settings/models/modelsApi', async (importOriginal) => {
  const actual = await importOriginal<typeof import('../settings/models/modelsApi')>();
  return { ...actual, modelsApi: { ...actual.modelsApi, ...mock.models } };
});
vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: mock.showToast }) }));
vi.mock('../settings/models/useModelHubCapability', () => ({ useModelHubCapability: () => false }));
vi.mock('../settings/shared/useOpencodePermission', () => ({ useOpencodePermission: () => mock.permission }));
vi.mock('../settings/providers/BackendProviderConfig', () => ({ BackendProviderConfig: ({ backend }: { backend: string }) => <div>Existing provider: {backend}</div> }));
const i18n = createInstance();
await i18n.init({ lng: 'en', resources: { en: { translation: en } }, interpolation: { escapeValue: false } });
const LocationProbe = () => <span data-testid="location">{useLocation().pathname}</span>;
const 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/ });
const hubAgent = (enabled = true) => ({
  id: 'claude-claude', name: 'claude', display_name: 'claude', description: null,
  backend: 'claude' as const, model: 'opus-5', reasoning_effort: null,
  enabled, archived: false, archived_at: null, source: 'file', updated_at: '',
  system_prompt: null, created_at: '', metadata: { builtin_default: true },
});
const hubChain = (modelId: string) => ({
  contract_version: 23, backend: 'claude', model_id: 'opus-5',
  manual_override: { hops: [{ source_id: 'src_a', model_id: modelId }] },
  route_origin: 'manual', current: { source_id: 'src_a', model_id: modelId },
  chain: [{ source_id: 'src_a', model_id: modelId, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],
  supply_state: 'ok',
});
const hubReads = {
  read: async () => ({ kind: 'current' as const, value: [{ backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const, named_agents: [{ name: 'claude', effective_model_id: 'opus-5', supply_status: 'ok' as const }] }] }),
  refresh: async () => ({ kind: 'current' as const, value: [] }),
  readValue: async () => [{ backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const, named_agents: [{ name: 'claude', effective_model_id: 'opus-5', supply_status: 'ok' as const }] }],
  invalidate: () => undefined,
};
const setupSource: Source = {
  id: 'src_a', vendor: 'anthropic', display_name: 'Fixture source', kind: 'api_key',
  protocol: 'anthropic', supply_channel: 'hub', billing: 'metered',
  state: { status: 'active' }, models: [], last_discovered_at: null,
};
beforeEach(() => {
  vi.resetAllMocks();
  mock.permission = { permissionAllowed: true, statusLoaded: true, state: 'idle', message: '', setupPermission: vi.fn(async () => undefined) };
  mock.api.getConfig.mockResolvedValue(data());
  mock.api.mutateConfig.mockResolvedValue({});
  mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, installed: true, enabled: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true }));
  mock.api.getClaudeAuth.mockResolvedValue({ ok: true, active_auth_mode: 'none' });
  mock.api.getCodexAuth.mockResolvedValue({ ok: true, active_auth_mode: 'none' });
  mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [] });
  mock.api.detectCli.mockResolvedValue({ found: true, status: 'ok' as const, path: '/isolated/bin/assistant' });
  mock.api.getBackendRuntime.mockImplementation(async (_name, cliPath) => ({ ok: true, installed: true, status: 'ok', cli_path: cliPath, resolved_path: cliPath, has_update: false }));
  mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [], default_agent_name: null });
  mock.api.getVibeAgent.mockResolvedValue({ ok: false, agent: null });
  mock.models.listSources.mockResolvedValue([]);
  mock.models.getAgentChain.mockRejectedValue(new Error('chain unread'));
  mock.models.getAgentChains.mockResolvedValue([]);
});
afterEach(cleanup);

describe('assistant installation presentation', () => {
  it('renders Direct Claude capability as external authentication, not an API key', async () => {
    const saved = data();
    for (const agent of Object.values(saved.agents)) agent.status = 'ok';
    mock.api.getConfig.mockResolvedValue(saved);
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, supply_mode: 'direct',
      auth: backend === 'claude' ? 'external' : 'api_key', application: 'applied', ready: true, entry_eligible: true,
    }));
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    await row('Claude Code').findByRole('button', { name: en.onboarding.setup.externalConnected });
    expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.api_keyConnected })).toBeNull();
    expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.subscriptionConnected })).toBeNull();
    expect(row('Claude Code').getByText(en.onboarding.setup.externalConnectedHint)).toBeTruthy();
  });
  it('enables a Hub assistant after a successful install', async () => {
    const saved = data();
    saved.agents.codex.enabled = false;
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: false, enabled: false, auth: 'none',
      application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub',
    }));
    mock.api.installAgent.mockResolvedValue({ ok: true, path: '/isolated/bin/codex', message: '' });
    render(wrap(<AgentDetection data={{ ...saved, capabilities: { model_hub: { enabled: true } } }} onNext={vi.fn()} />));
    fireEvent.click(await row('Codex').findByRole('button', { name: 'Install and enable' }));
    await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledWith(
      expect.arrayContaining([expect.objectContaining({ kind: 'set', path: ['agents', 'codex', 'enabled'], value: true })]),
    ));
  });
  it('does not enable a Direct assistant after the ordinary Install action', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.codex.enabled = false;
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: false, enabled: false, auth: 'none',
      application: 'applied', ready: false, entry_eligible: false, supply_mode: 'direct',
    }));
    const install = pending<{ ok: boolean; path: string; message: string }>();
    mock.api.installAgent.mockReturnValue(install.promise);
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(SETUP_LINEUP.length));
    fireEvent.click(row('Codex').getByRole('button', { name: 'Install' }));
    await act(async () => install.resolve({ ok: true, path: '/isolated/bin/codex', message: '' }));
    expect(row('Codex').getByRole('switch').getAttribute('aria-checked')).toBe('false');
    expect(mock.api.mutateConfig).not.toHaveBeenCalled();
  });
  it.each(['unknown', 'failed'] as const)('does not promise Hub enablement when the mode read is %s', async (outcome) => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.codex.enabled = false;
    mock.api.getBackendConnection.mockImplementation(async (backend) => {
      if (backend === 'codex' && outcome === 'failed') throw new Error('unreadable');
      return { ok: true, backend, installed: false, enabled: false, auth: 'none',
        application: 'applied', ready: false, entry_eligible: false,
        supply_mode: backend === 'codex' ? undefined : 'direct' };
    });
    const install = pending<{ ok: boolean; path: string; message: string }>();
    mock.api.installAgent.mockReturnValue(install.promise);
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(SETUP_LINEUP.length));
    expect(row('Codex').queryByRole('button', { name: 'Install and enable' })).toBeNull();
    fireEvent.click(row('Codex').getByRole('button', { name: 'Install' }));
    await act(async () => install.resolve({ ok: true, path: '/isolated/bin/codex', message: '' }));
    expect(mock.api.mutateConfig).not.toHaveBeenCalled();
  });
  it('does not auto-enable if a Hub install changes to Direct before it finishes', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.codex.enabled = false;
    let mode: 'hub' | 'direct' = 'hub';
    const install = pending<{ ok: boolean; path: string; message: string }>();
    mock.api.installAgent.mockReturnValue(install.promise);
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: false, enabled: false, auth: 'none',
      application: 'applied', ready: false, entry_eligible: false,
      supply_mode: backend === 'codex' ? mode : 'direct',
    }));
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    fireEvent.click(await row('Codex').findByRole('button', { name: 'Install and enable' }));
    mode = 'direct';
    await act(async () => install.resolve({ ok: true, path: '/isolated/bin/codex', message: '' }));
    expect(mock.api.getBackendConnection.mock.calls.filter(([backend]) => backend === 'codex').length).toBeGreaterThanOrEqual(4);
    expect(mock.api.mutateConfig).not.toHaveBeenCalled();
  });
  it('does not enable from a stale Hub read when reentry offered ordinary Install', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.enabled = false;
    mock.api.detectCli.mockResolvedValue({ found: false, status: 'missing' as const, path: '' });
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: false, enabled: false, auth: 'none',
      application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub',
    }));
    const install = pending<{ ok: boolean; path: string; message: string }>();
    mock.api.installAgent.mockReturnValue(install.promise);
    let reenter = false;
    let clickedOrdinaryInstall = false;
    const onActionChange = vi.fn(() => {
      if (!reenter || clickedOrdinaryInstall) return;
      const action = row('Claude Code').getByRole<HTMLButtonElement>('button', { name: 'Install' });
      clickedOrdinaryInstall = true;
      action.click();
    });
    const props = { data: saved, onNext: vi.fn(), onActionChange };
    const view = render(wrap(<AgentDetection {...props} active />));
    await row('Claude Code').findByRole('button', { name: 'Install and enable' });
    view.rerender(wrap(<AgentDetection {...props} active={false} />, false));
    reenter = true;
    await act(async () => view.rerender(wrap(<AgentDetection {...props} active />, true)));
    expect(clickedOrdinaryInstall).toBe(true);
    expect(mock.api.installAgent).toHaveBeenCalledWith('claude');

    await act(async () => install.resolve({ ok: true, path: '/isolated/bin/claude', message: '' }));
    expect(mock.api.mutateConfig).not.toHaveBeenCalled();
  });
  it('does not promise enablement when a missing assistant has conflicting Hub and Direct reads', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.enabled = false;
    mock.api.detectCli.mockResolvedValue({ found: false, status: 'missing' as const, path: '' });
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: false, enabled: false, auth: 'none',
      application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub',
    }));
    const listed = pending<[]>();
    mock.models.listSources.mockReturnValue(listed.promise);
    const install = pending<{ ok: boolean; path: string; message: string }>();
    mock.api.installAgent.mockReturnValue(install.promise);
    const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [
      { backend: 'claude' as const, cli_present: false, mode: 'direct' as const, menu_kind: 'fixed' as const },
    ] }) };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));
    await waitFor(() => expect(mock.models.listSources).toHaveBeenCalled());
    await act(async () => listed.resolve([]));

    expect(row('Claude Code').queryByRole('button', { name: 'Install and enable' })).toBeNull();
    fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));
    await act(async () => install.resolve({ ok: true, path: '/isolated/bin/claude', message: '' }));
    expect(mock.api.mutateConfig).not.toHaveBeenCalled();
  });
  it('keeps fixed row order, independent installs and retry details', async () => {
    let finishClaude!: (value: unknown) => void;
    mock.api.installAgent.mockImplementation((name) => name === 'claude'
      ? new Promise((resolve) => { finishClaude = resolve; })
      : Promise.resolve({ ok: true, path: '/isolated/bin/codex' }));
    render(wrap(<AgentDetection data={data()} onNext={vi.fn()} />));
    // The cards are the whole section: the design keeps each assistant's name at the top
    // of its own card and gives the section no heading of its own. The built-in one
    // stands first, with no switch: it is always on.
    expect(screen.getAllByRole('heading', { level: 3 }).map((node) => node.textContent)).toEqual(['Vibey', 'Claude Code', 'Codex', 'OpenCode']);
    expect(within(row('Vibey').getByRole('heading', { name: 'Vibey' }).closest('.onboarding-card-identity') as HTMLElement)
      .queryByRole('switch')).toBeNull();
    // "Connection state replaces roles with enable switches": the switch belongs to the
    // same identity header as the name, not to a separate strip.
    for (const name of ['Claude Code', 'Codex', 'OpenCode']) {
      const identity = screen.getByRole('heading', { name }).closest('.onboarding-card-identity')!;
      expect(within(identity as HTMLElement).getByRole('switch', { name: `Enable ${name}` })).toBeTruthy();
    }
    fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));
    fireEvent.click(row('Codex').getByRole('button', { name: 'Install' }));
    await waitFor(() => expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());
    await act(async () => finishClaude({ ok: false, message: 'Network unavailable', output: 'Installer exited 1' }));
    expect(row('Claude Code').getByText('Network unavailable')).toBeTruthy();
    expect(row('Claude Code').getByText(en.agentDetection.showOutput)).toBeTruthy();
    expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();
    expect(row('OpenCode').getByText('Not installed')).toBeTruthy();
    mock.api.installAgent.mockResolvedValue({ ok: true, path: '/isolated/bin/claude' });
    fireEvent.click(row('Claude Code').getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());
    expect(mock.api.detectCli).toHaveBeenCalledWith('/isolated/bin/claude', 'claude');
    expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();
  });
  it('does not undo a newer disable when an install finishes', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.enabled = false;
    let enabled = false;
    let finish!: (value: unknown) => void;
    mock.api.installAgent.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
    mock.api.mutateConfig.mockImplementation(async (mutations) => {
      enabled = mutations[0].value;
      return {};
    });
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: false, enabled: backend === 'claude' ? enabled : true,
      auth: 'none', application: 'applied', ready: false, entry_eligible: false,
      supply_mode: 'hub',
    }));
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={hubReads} />));
    fireEvent.click(await row('Claude Code').findByRole('button', { name: en.onboarding.setup.installAndEnable }));
    const toggle = row('Claude Code').getByRole('switch');
    fireEvent.click(toggle);
    fireEvent.click(toggle);
    await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2));
    await act(async () => finish({ ok: true, path: '/isolated/bin/claude' }));
    expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2);
    expect(enabled).toBe(false);
  });
  it('a failed install settlement refreshes connection state without admitting stale readiness', async () => {
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({ ok: true, backend, installed: false, enabled: true, auth: 'none', application: 'applied', ready: false, entry_eligible: false }));
    render(wrap(<AgentDetection data={data()} onNext={vi.fn()} />));
    await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(SETUP_LINEUP.length));
    mock.api.installAgent.mockResolvedValue({ ok: false, path: '/fixture/new-cli', message: 'fixture apply failed' });
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({ ok: true, backend, installed: true, enabled: true, auth: 'api_key', application: 'failed', ready: false, entry_eligible: false }));
    fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));
    // The settlement reads the installed backend's connection once more, and the failed
    // application it reports is what keeps entry closed.
    await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(SETUP_LINEUP.length + 1));
    expect(mock.api.getBackendConnection).toHaveBeenLastCalledWith('claude');
    expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
    expect(mock.api.installAgent).toHaveBeenCalledOnce(); expect(mock.api.mutateConfig).not.toHaveBeenCalled();
  });
  it('keeps existing configure entry and does not claim connection from installation', async () => {
    const saved = data(); saved.agents.claude.status = 'ok';
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    expect(screen.queryByText('Subscription connected')).toBeNull();
    expect(screen.queryByText('API Key connected')).toBeNull();
    // The method rows disable while the initial connection read is in flight, so
    // the click that opens the dialog has to wait for the read to settle.
    await waitFor(() => expect(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }).hasAttribute('disabled')).toBe(false));
    fireEvent.click(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }));
    expect(await screen.findByRole('dialog')).toBeTruthy();
  });
  it('refreshes connection readiness when a retained settings surface returns', async () => {
    const saved = data(); saved.agents.claude.status = 'ok';
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true,
      backend,
      installed: true,
      enabled: true,
      auth: 'none',
      application: 'applied',
      ready: false,
      entry_eligible: false,
    }));
    const view = render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />, false));
    await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(SETUP_LINEUP.length));
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true,
      backend,
      installed: true,
      enabled: true,
      auth: 'api_key',
      application: 'applied',
      ready: true,
      entry_eligible: true,
    }));
    view.rerender(wrap(<AgentDetection data={saved} onNext={vi.fn()} />, true));
    await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(SETUP_LINEUP.length * 2));
    expect(await row('Claude Code').findByRole('button', { name: 'API Key connected' })).toBeTruthy();
    expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false);
  });
  it('opens the setup route editor when the backend is already Hub-owned, and reports its save', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } }; saved.agents.claude.status = 'ok';
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true,
      backend,
      installed: true,
      enabled: true,
      auth: 'none',
      application: 'applied',
      ready: false,
      entry_eligible: false,
      supply_mode: 'hub',
    }));
    const agent = {
      id: 'claude-claude', name: 'claude', display_name: 'claude', description: null, backend: 'claude',
      model: 'opus-5', reasoning_effort: null, enabled: true, archived: false, archived_at: null, source: 'file',
      updated_at: '', system_prompt: null, created_at: '', metadata: { builtin_default: true },
    };
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [agent], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent });
    mock.models.listSources.mockResolvedValue([]);
    const chain = {
      contract_version: 23, backend: 'claude', model_id: 'opus-5',
      manual_override: { hops: [{ source_id: 'src_a', model_id: 'opus-5' }, { source_id: 'src_b', model_id: 'opus-5' }] },
      route_origin: 'manual', current: { source_id: 'src_a', model_id: 'opus-5' },
      chain: [
        { source_id: 'src_a', model_id: 'opus-5', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null },
        { source_id: 'src_b', model_id: 'opus-5', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null },
      ],
      supply_state: 'ok',
    };
    mock.models.getAgentChains.mockResolvedValue([chain]);
    mock.models.getAgentChain.mockResolvedValue(chain);
    const flowState = INITIAL_SETUP_FLOW_STATE;
    const agentReads = {
      read: async () => ({ kind: 'current' as const, value: [{ backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const, named_agents: [{ name: 'claude', effective_model_id: 'opus-5', supply_status: 'ok' as const }] }] }),
      refresh: async () => ({ kind: 'current' as const, value: [] }),
      readValue: async () => [],
      invalidate: () => undefined,
    };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} flowState={flowState} setFlowState={vi.fn()} onNavigate={vi.fn()} agentReads={agentReads} />));
    await waitFor(() => expect(mock.api.getVibeAgent).toHaveBeenCalledWith('claude', { cache: false }));
    await waitFor(() => expect(mock.models.getAgentChains).toHaveBeenCalledWith('claude'));
    expect(await mock.models.getAgentChains.mock.results.at(-1)?.value).toEqual([chain]);
    const action = await row('Claude Code').findByRole('button', { name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code') });
    const enter = screen.getByRole('button', { name: 'Enter workspace' });
    expect(enter.hasAttribute('disabled')).toBe(true);
    fireEvent.click(action);
    expect(await screen.findByRole('dialog')).toBeTruthy();
    expect(screen.getByTestId('location').textContent).toBe('/');
    expect(enter.hasAttribute('disabled')).toBe(true);

    // The dialog closes on commit, so the shared toast is the save's only report.
    const savedChain = { ...chain, manual_override: { hops: [chain.manual_override.hops[1]] }, chain: [chain.chain[1]] };
    mock.models.putAgentChain.mockResolvedValue({ chain: savedChain, removed_hops: [], interrupted: [] });
    fireEvent.click((await screen.findAllByRole('button', { name: 'Remove hop' }))[0]);
    fireEvent.click(screen.getByRole('button', { name: 'Save' }));
    await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
    expect(mock.models.putAgentChain).toHaveBeenCalledOnce();
    expect(mock.showToast).toHaveBeenCalledWith(en.common.saved, 'success');
  });
  it('an available update keeps Continue and configuration usable', async () => {
    const saved = data(); saved.agents.claude.status = 'ok';
    mock.api.getBackendRuntime.mockImplementation(async (_name, path) => ({ installed: true, status: 'ok', cli_path: path, resolved_path: path, has_update: true, current_version: '1', latest_version: '2' }));
    const next = vi.fn();
    render(wrap(<AgentDetection data={saved} onNext={next} />));
    await screen.findByRole('button', { name: en.backendLifecycle.statusUpdateAvailable });
    expect(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }).hasAttribute('disabled')).toBe(false);
    fireEvent.click(screen.getByRole('button', { name: 'Enter workspace' }));
    await waitFor(() => expect(next).toHaveBeenCalled());
    expect(mock.api.installAgent).not.toHaveBeenCalled();
  });
  it('keeps a failed upgrade from the state row on the card with its reason and output', async () => {
    const saved = data(); saved.agents.codex.status = 'ok';
    mock.api.getBackendRuntime.mockImplementation(async (_name, path) => ({ installed: true, status: 'ok', cli_path: path, resolved_path: path, has_update: true, current_version: '1', latest_version: '2' }));
    const failure = {
      ok: false, message: 'Could not upgrade Codex.', code: 'npm_leftover_directory', exit_code: 190,
      hint: 'npm left a temporary folder behind from an earlier interrupted update: /usr/local/lib/node_modules/@openai/.codex-lD3lp9Ti. Delete that folder, then try again.',
      output: 'npm error code ENOTEMPTY\nnpm error dest /usr/local/lib/node_modules/@openai/.codex-lD3lp9Ti',
    };
    mock.api.installAgent.mockResolvedValue(failure);
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    fireEvent.click(await row('Codex').findByRole('button', { name: en.backendLifecycle.upgradeNow }));

    const outcome = await row('Codex').findByRole('alert');
    expect(mock.showToast).toHaveBeenCalledWith(failure.message, 'error');
    expect(within(outcome).getByText(failure.message)).toBeTruthy();
    expect(within(outcome).getByText(failure.hint)).toBeTruthy();
    expect(within(outcome).getByText(en.agentDetection.showOutput)).toBeTruthy();
    expect(within(outcome).getByText('Exit code: 190')).toBeTruthy();
    expect(outcome.querySelector('pre')?.textContent).toBe(failure.output);
    // Once the chip has read the CLI back, trying again is one click away.
    await waitFor(() => expect(row('Codex').getByRole('button', { name: en.backendLifecycle.upgradeNow }).hasAttribute('disabled')).toBe(false));
  });
  it('re-detects a CLI a failed upgrade from the state row removed, keeping the reason', async () => {
    const saved = data(); saved.agents.codex.status = 'ok';
    mock.api.getBackendRuntime.mockImplementation(async (_name, path) => ({ installed: true, status: 'ok', cli_path: path, resolved_path: path, has_update: true, current_version: '1', latest_version: '2' }));
    mock.api.installAgent.mockImplementation(async () => {
      mock.api.detectCli.mockResolvedValue({ found: false, status: 'missing' as const, path: null });
      mock.api.getBackendRuntime.mockImplementation(async (_name, path) => ({ installed: false, status: 'missing', cli_path: path, has_update: false, resolved_path: null }));
      return { ok: false, message: 'Could not upgrade Codex.', output: 'npm error code ENOTEMPTY' };
    });
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    fireEvent.click(await row('Codex').findByRole('button', { name: en.backendLifecycle.upgradeNow }));

    // The row falls back to the install state, marked as failed, with the reason kept.
    expect(await row('Codex').findByRole('button', { name: en.common.retry })).toBeTruthy();
    expect(row('Codex').getByText(en.onboarding.setup.installFailed)).toBeTruthy();
    expect(row('Codex').getByText('Could not upgrade Codex.')).toBeTruthy();
  });
  it('holds the state row until the chip reads an upgrade back, then offers it again if still behind', async () => {
    const path = '/isolated/bin/codex';
    const saved = data(); saved.agents.codex.status = 'ok'; saved.agents.codex.cli_path = path;
    const behind = { installed: true, status: 'ok' as const, cli_path: path, has_update: true, current_version: '1', latest_version: '2', resolved_path: path };
    mock.api.getBackendRuntime.mockResolvedValue(behind);
    mock.api.detectCli.mockResolvedValue({ found: true, status: 'ok' as const, path });
    let readBack!: (runtime: typeof behind) => void;
    mock.api.installAgent.mockImplementation(async () => {
      // A native updater can exit zero without moving the version.
      mock.api.getBackendRuntime.mockReturnValue(new Promise((resolve) => { readBack = resolve; }));
      return { ok: true, path };
    });
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    const detections = mock.api.detectCli.mock.calls.length;
    fireEvent.click(await row('Codex').findByRole('button', { name: en.backendLifecycle.upgradeNow }));

    await waitFor(() => expect(mock.api.detectCli.mock.calls.length).toBeGreaterThan(detections));
    await act(async () => {});
    // The attempt is over but the chip has not read it back: nothing to re-arm on yet.
    expect(row('Codex').queryByRole('button', { name: en.backendLifecycle.upgradeNow })).toBeNull();
    expect(row('Codex').getByRole('button', { name: en.backendLifecycle.upgrading }).hasAttribute('disabled')).toBe(true);

    await act(async () => readBack(behind));
    await waitFor(() => expect(row('Codex').getByRole('button', { name: en.backendLifecycle.upgradeNow }).hasAttribute('disabled')).toBe(false));
  });
  it('retains a detection error separately from missing installation', async () => {
    mock.api.detectCli.mockRejectedValue(new Error('Probe failed'));
    render(wrap(<AgentDetection data={{ ...data(), __onboardingDetected: false }} onNext={vi.fn()} />));
    await waitFor(() => expect(screen.getAllByRole('alert')).toHaveLength(3));
    expect(row('Claude Code').queryByRole('button', { name: 'Install' })).toBeNull();
    expect(row('Claude Code').getByRole('button', { name: 'Retry' })).toBeTruthy();
  });
  it('returns current row state to Welcome without saving it', async () => {
    mock.api.installAgent.mockResolvedValue({ ok: true, path: '/isolated/bin/claude' });
    const back = vi.fn();
    render(wrap(<AgentDetection data={data()} onNext={vi.fn()} onBack={back} />));
    fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));
    await waitFor(() => expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());
    fireEvent.click(row('Codex').getByRole('switch'));
    fireEvent.click(screen.getByRole('button', { name: 'Back' }));
    expect(back).toHaveBeenCalledWith({ agents: expect.objectContaining({
      claude: expect.objectContaining({ status: 'ok', cli_path: '/isolated/bin/assistant' }),
      codex: expect.objectContaining({ enabled: false }),
    }) });
  });
  it('reconciles saved non-ASCII CLI paths before navigation resumes', async () => {
    let finishConfig!: (value: unknown) => void;
    let finishDetection!: (value: unknown) => void;
    mock.api.getConfig.mockImplementation(() => new Promise((resolve) => { finishConfig = resolve; }));
    mock.api.detectCli.mockImplementation(() => new Promise((resolve) => { finishDetection = resolve; }));
    const saved = data(); saved.agents.claude.status = 'ok';
    const back = vi.fn();
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onBack={back} />));
    await waitFor(() => expect(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected/ }).hasAttribute('disabled')).toBe(false));
    fireEvent.click(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected/ }));
    fireEvent.keyDown(await screen.findByRole('dialog'), { key: 'Escape' });
    expect(screen.getByRole('button', { name: 'Back' }).hasAttribute('disabled')).toBe(true);
    await act(async () => finishConfig({ agents: { claude: { enabled: true, cli_path: '/isolated/新的路径/claude' } } }));
    expect(mock.api.detectCli).toHaveBeenCalledWith('/isolated/新的路径/claude', 'claude');
    expect(screen.getByRole('button', { name: 'Back' }).hasAttribute('disabled')).toBe(true);
    await act(async () => finishDetection({ found: true, status: 'ok' as const, path: '/isolated/真实路径/claude' }));
    fireEvent.click(screen.getByRole('button', { name: 'Back' }));
    expect(back).toHaveBeenCalledWith({ agents: expect.objectContaining({ claude: expect.objectContaining({ cli_path: '/isolated/真实路径/claude', status: 'ok' }) }) });
  });
  it('clears only obsolete install failures after a successful external rescan', async () => {
    mock.api.installAgent.mockImplementation((name) => Promise.resolve({ ok: false, message: `Failed ${name}`, output: `Details ${name}` }));
    render(wrap(<AgentDetection data={data()} onNext={vi.fn()} />));
    for (const label of ['Claude Code', 'Codex', 'OpenCode']) {
      fireEvent.click(row(label).getByRole('button', { name: 'Install' }));
    }
    await waitFor(() => expect(screen.getAllByRole('alert')).toHaveLength(3));
    mock.api.detectCli.mockImplementation((name) => name === 'claude'
      ? Promise.resolve({ found: true, status: 'ok' as const, path: '/isolated/external/claude' })
      : name === 'codex' ? Promise.resolve({ found: false, status: 'missing' as const }) : Promise.reject(new Error('Probe unavailable')));
    fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));
    await waitFor(() => expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());
    expect(row('Claude Code').queryByRole('alert')).toBeNull();
    expect(row('Claude Code').queryByText('Details claude')).toBeNull();
    expect(row('Codex').getByText('Failed codex')).toBeTruthy();
    expect(row('Codex').getByText('Details codex')).toBeTruthy();
    expect(row('OpenCode').getByText('Error: Probe unavailable')).toBeTruthy();
    expect(row('OpenCode').queryByRole('button', { name: en.onboarding.setup.enabled })).toBeNull();
    // A rejected probe retains install evidence; a later missing result shows it again.
    mock.api.detectCli.mockResolvedValue({ found: false, status: 'missing' as const });
    fireEvent.click(row('OpenCode').getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(row('OpenCode').getByText('Failed opencode')).toBeTruthy());
    expect(row('OpenCode').getByText('Details opencode')).toBeTruthy();
    expect(row('Codex').getByText('Failed codex')).toBeTruthy();
  });
  it('keeps another backend installation independent of provider reconciliation', async () => {
    let finishConfig!: (value: unknown) => void;
    let finishInstall!: (value: unknown) => void;
    mock.api.getConfig.mockImplementation(() => new Promise((resolve) => { finishConfig = resolve; }));
    mock.api.installAgent.mockImplementation(() => new Promise((resolve) => { finishInstall = resolve; }));
    const saved = data(); saved.agents.claude.status = 'ok';
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    await waitFor(() => expect(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }).hasAttribute('disabled')).toBe(false));
    fireEvent.click(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }));
    fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
    fireEvent.click(row('Codex').getByRole('button', { name: 'Install' }));
    expect(mock.api.installAgent).toHaveBeenCalledWith('codex');
    await act(async () => finishInstall({ ok: true, path: '/isolated/bin/codex' }));
    expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();
    expect(row('Codex').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }).hasAttribute('disabled')).toBe(true);
    expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
    await act(async () => finishConfig(data()));
    expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false);
    expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();
  });
  it('settles an enable write that lands while the screen is away, and reads nothing from hiding', async () => {
    const saved = data(); saved.agents.claude.status = 'ok';
    // 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, status: 'ok' as const, path: '/retained/claude' } : { found: false, status: 'missing' as const }));
    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: en.onboarding.setup.enabled })).toBeTruthy());
    const retainedProbes = probes('/retained/claude');

    view.rerender(shown(saved, false, publish));
    view.rerender(shown(saved, true, publish));
    await waitFor(() => expect(probes('/retained/claude')).toBe(retainedProbes + 1));
    expect(probes('/stale/claude')).toBe(1);
    expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();
  });
  it('does not enable entry from installed, draining, failed or unknown states', async () => {
    for (const application of ['draining', 'failed', 'unknown']) {
      mock.api.getBackendConnection.mockResolvedValue({ ok: true, auth: 'api_key', application, ready: false, entry_eligible: false });
      const saved = data(); saved.agents.claude.status = 'ok';
      const { unmount } = render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
      await act(async () => {});
      expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
      expect(screen.queryByText('API Key connected')).toBeNull();
      unmount();
    }
  });
  it('renders connected controls only from explicit presentation state', () => {
    const configure = vi.fn();
    const connectedRow = (configuringDisabled: boolean) => wrap(<AssistantRow backend="claude" status="ok" installing={false} detecting={false} lifecycle={<span>Installed</span>}
      enabledControl={null} onInstall={vi.fn()} onDetect={vi.fn()} onConfigure={configure} connection="subscription" configuringDisabled={configuringDisabled} />);
    const { rerender } = render(connectedRow(true));
    fireEvent.click(screen.getByRole('button', { name: 'Subscription connected' }));
    expect(configure).not.toHaveBeenCalled();
    rerender(connectedRow(false));
    fireEvent.click(screen.getByRole('button', { name: 'Subscription connected' }));
    expect(configure).toHaveBeenCalledOnce();
  });
  it('does not offer route repair when an installed Hub assistant has no selected model', () => {
    render(wrap(<AssistantRow backend="claude" status="ok" installing={false} detecting={false}
      lifecycle={<span>Enabled</span>} enabledControl={null} enabled hubManaged
      onInstall={vi.fn()} onDetect={vi.fn()} onConfigure={vi.fn()}
      route={{ kind: 'no-agent-model' }} />));
    expect(screen.getByText(en.onboarding.setup.noteModelUnset)).toBeTruthy();
    expect(screen.queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();
  });
  it.each([
    ['no-agent-model', en.onboarding.setup.noteModelUnset],
    ['empty-route', en.onboarding.setup.noteNoModels],
  ] as const)('shows %s on a disabled Hub card without offering an editor', (kind, note) => {
    const configure = vi.fn();
    render(wrap(<AssistantRow backend="claude" status="ok" installing={false} detecting={false}
      lifecycle={<span>Installed</span>} enabledControl={null} hubManaged
      onInstall={vi.fn()} onDetect={vi.fn()} onConfigure={configure}
      route={kind === 'no-agent-model' ? { kind } : { kind: 'route', model: null, backups: 0 }} />));
    expect(screen.getByText(note)).toBeTruthy();
    expect(screen.queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();
    expect(configure).not.toHaveBeenCalled();
  });
});

describe('OpenCode tool-call permission', () => {
  it('is asked for in OpenCode\'s own card, and granting it re-reads the connection', async () => {
    mock.permission = { ...mock.permission, permissionAllowed: false };
    const saved = data(); saved.agents.opencode.status = 'ok';
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    const card = row('OpenCode');
    expect(await card.findByText(en.onboarding.setup.notePermission.replace('{{name}}', 'OpenCode'))).toBeTruthy();
    expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.allowToolCalls })).toBeNull();
    const reads = mock.api.getBackendConnection.mock.calls.length;
    fireEvent.click(card.getByRole('button', { name: en.onboarding.setup.allowToolCalls }));
    expect(mock.permission.setupPermission).toHaveBeenCalledOnce();
    await waitFor(() => expect(mock.api.getBackendConnection.mock.calls.length).toBeGreaterThan(reads));
    expect(mock.api.getBackendConnection).toHaveBeenLastCalledWith('opencode');
  });

  it('reports a refused write in the note\'s place, with the server\'s sentence behind it', () => {
    mock.permission = { ...mock.permission, permissionAllowed: false, state: 'error', message: 'opencode.json is not writable' };
    const saved = data(); saved.agents.opencode.status = 'ok';
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    const refusal = row('OpenCode').getByRole('alert');
    expect(refusal.tagName).toBe('DETAILS');
    expect(within(refusal).getByText(en.onboarding.setup.permissionFailed)).toBeTruthy();
    expect(refusal.textContent).toContain('opencode.json is not writable');
  });

  it('asks nothing of an assistant that is not installed, or once it is allowed', () => {
    mock.permission = { ...mock.permission, permissionAllowed: false };
    render(wrap(<AgentDetection data={data()} onNext={vi.fn()} />));
    expect(row('OpenCode').queryByRole('button', { name: en.onboarding.setup.allowToolCalls })).toBeNull();
    cleanup();
    mock.permission = { ...mock.permission, permissionAllowed: true };
    const saved = data(); saved.agents.opencode.status = 'ok';
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    expect(row('OpenCode').queryByRole('button', { name: en.onboarding.setup.allowToolCalls })).toBeNull();
  });
});

describe('Hub route refresh', () => {
  it.each([false, true])('AUTH-SETUP-126: returns to providers with an empty inventory (direct eligible: %s)', async (directEligible) => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'none',
      application: 'applied', ready: directEligible, entry_eligible: directEligible,
      supply_mode: directEligible ? 'direct' : 'hub',
    }));
    const listed = pending<[]>();
    mock.models.listSources.mockReturnValue(listed.promise);
    const navigate = vi.fn();
    const props = { data: saved, onNext: vi.fn(), onNavigate: navigate, agentReads: hubReads };
    const view = render(wrap(<AgentDetection {...props} />));
    await waitFor(() => expect(mock.models.listSources).toHaveBeenCalled());
    expect(screen.queryByRole('button', { name: 'Add model source' })).toBeNull();
    await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(SETUP_LINEUP.length));
    const pendingEntry = screen.getByRole<HTMLButtonElement>('button', { name: 'Enter workspace' });
    expect(pendingEntry.disabled).toBe(true);
    fireEvent.click(pendingEntry);
    expect(props.onNext).not.toHaveBeenCalled();
    await act(async () => listed.resolve([]));
    const recover = await screen.findByRole<HTMLButtonElement>('button', { name: 'Add model source' });
    expect(screen.getByText(en.onboarding.connection.sourceRequired)).toBeTruthy();
    expect(recover.disabled).toBe(false);
    const enter = screen.getByRole<HTMLButtonElement>('button', { name: 'Enter workspace' });
    expect(enter.disabled).toBe(true);
    fireEvent.click(enter);
    fireEvent.click(recover);
    expect(navigate).toHaveBeenCalledExactlyOnceWith('providers');
    expect(props.onNext).not.toHaveBeenCalled();
    view.rerender(wrap(<AgentDetection {...props} active={false} />));
    expect(screen.queryByRole('button', { name: 'Add model source' })).toBeNull();
  });

  it('AUTH-SETUP-126: failed provider evidence blocks entry and retries the inventory read', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    mock.models.listSources.mockRejectedValue(new Error('fixture unavailable'));
    const onNext = vi.fn();
    render(wrap(<AgentDetection data={saved} onNext={onNext} onNavigate={vi.fn()} agentReads={hubReads} />));
    const message = await screen.findByText(en.onboarding.connection.readFailed);
    const enter = screen.getByRole<HTMLButtonElement>('button', { name: 'Enter workspace' });
    expect(enter.disabled).toBe(true);
    expect(screen.queryByRole('button', { name: 'Add model source' })).toBeNull();
    enter.removeAttribute('disabled');
    fireEvent.click(enter);
    expect(onNext).not.toHaveBeenCalled();

    mock.models.listSources.mockResolvedValue([setupSource]);
    fireEvent.click(within(message.parentElement!).getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(enter.disabled).toBe(false));
    expect(screen.queryByText(en.onboarding.connection.readFailed)).toBeNull();
    fireEvent.click(enter);
    await waitFor(() => expect(onNext).toHaveBeenCalledOnce());
  });

  it.each(['empty', 'native', 'pending', 'failed'] as const)('AUTH-SETUP-126: stale completion retry cannot bypass %s provider evidence', async (inventory) => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    mock.models.listSources.mockResolvedValue([setupSource]);
    const onNext = vi.fn().mockRejectedValue(new Error('fixture completion failed'));
    const handle = createRef<SetupScreenHandle>();
    const props = { ref: handle, data: saved, onNext, onNavigate: vi.fn(), agentReads: hubReads };
    const view = render(wrap(<AgentDetection {...props} active />));
    const enter = screen.getByRole<HTMLButtonElement>('button', { name: 'Enter workspace' });
    await waitFor(() => expect(enter.disabled).toBe(false));
    fireEvent.click(enter);
    const alert = await screen.findByRole('alert');
    expect(alert.textContent).toContain('fixture completion failed');
    expect(onNext).toHaveBeenCalledOnce();

    view.rerender(wrap(<AgentDetection {...props} active={false} />));
    const read = pending<Source[]>();
    mock.models.listSources.mockReturnValue(read.promise);
    view.rerender(wrap(<AgentDetection {...props} active />));
    if (inventory === 'failed') await act(async () => read.reject(new Error('fixture unavailable')));
    else if (inventory !== 'pending') await act(async () => read.resolve(inventory === 'native'
      ? [{ ...setupSource, kind: 'subscription', supply_channel: 'native_cli' }] : []));

    const retry = within(alert).getByRole<HTMLButtonElement>('button', { name: 'Retry' });
    expect(enter.disabled).toBe(true);
    expect(retry.disabled).toBe(true);
    retry.removeAttribute('disabled');
    fireEvent.click(retry);
    await act(async () => handle.current?.activate());
    expect(onNext).toHaveBeenCalledOnce();
    if (inventory === 'empty' || inventory === 'native') {
      expect(screen.getByRole('button', { name: 'Add model source' })).toBeTruthy();
    }
  });

  it.each(['direct', 'hub'] as const)('uses current %s route ownership when the connection read fails', async (mode) => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    mock.api.getBackendConnection.mockRejectedValue(new Error('connection unreadable'));
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });
    mock.models.getAgentChains.mockResolvedValue([hubChain('model-a')]);
    mock.models.getAgentChain.mockResolvedValue(hubChain('model-a'));
    const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [
      { backend: 'claude' as const, cli_present: true, mode, menu_kind: 'fixed' as const },
    ] }) };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));

    if (mode === 'direct') {
      const action = await row('Claude Code').findByRole<HTMLButtonElement>('button', { name: /Add subscription/ });
      await waitFor(() => expect(action.disabled).toBe(false));
      expect(row('Claude Code').queryByRole('button', {
        name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
      })).toBeNull();
      fireEvent.click(action);
      expect(await screen.findByRole('dialog')).toBeTruthy();
      expect(mock.models.getAgentChains).not.toHaveBeenCalled();
    } else {
      const action = await row('Claude Code').findByRole<HTMLButtonElement>('button', {
        name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
      });
      await waitFor(() => expect(action.disabled).toBe(false));
      fireEvent.click(action);
      expect(await screen.findByRole('dialog')).toBeTruthy();
      expect(mock.models.getAgentChains).toHaveBeenCalledWith('claude');
    }
  });

  it.each([
    ['hub', 'direct'],
    ['direct', 'hub'],
  ] as const)('keeps conflicting connection %s and route %s ownership in an unknown state', async (connectionMode, routeMode) => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: connectionMode,
    }));
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });
    mock.models.getAgentChains.mockResolvedValue([hubChain('model-a')]);
    const listed = pending<[]>();
    mock.models.listSources.mockReturnValue(listed.promise);
    let currentSupplyMode: 'hub' | 'direct' = routeMode;
    const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [
      { backend: 'claude' as const, cli_present: true, mode: currentSupplyMode, menu_kind: 'fixed' as const },
    ] }) };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));
    await waitFor(() => expect(mock.models.listSources).toHaveBeenCalled());
    await act(async () => listed.resolve([]));

    expect(row('Claude Code').queryByRole('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
    })).toBeNull();
    const action = row('Claude Code').getByRole<HTMLButtonElement>('button', { name: /Add subscription/ });
    expect(action.disabled).toBe(true);
    action.removeAttribute('disabled');
    fireEvent.click(action);
    expect(screen.queryByRole('dialog')).toBeNull();
    expect(row('Claude Code').getByText(en.onboarding.setup.ownershipChanged)).toBeTruthy();
    const connectionReads = mock.api.getBackendConnection.mock.calls.length;
    currentSupplyMode = connectionMode;
    fireEvent.click(row('Claude Code').getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(mock.api.getBackendConnection.mock.calls.length).toBeGreaterThan(connectionReads));
    if (connectionMode === 'hub') {
      await waitFor(() => expect(row('Claude Code').getByText('model-a')).toBeTruthy());
    } else {
      await waitFor(() => expect(row('Claude Code').getByRole<HTMLButtonElement>('button', { name: 'API Key connected' }).disabled).toBe(false));
    }
    expect(row('Claude Code').queryByText(en.onboarding.setup.ownershipChanged)).toBeNull();
  });

  it('keeps configuration disabled when neither ownership read succeeds', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    mock.api.getBackendConnection.mockRejectedValue(new Error('connection unreadable'));
    const reads = { ...hubReads, read: async () => { throw new Error('route unreadable'); } };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));
    await row('Claude Code').findByText('Error: connection unreadable');
    const action = row('Claude Code').getByRole<HTMLButtonElement>('button', { name: /Add subscription/ });
    expect(action.disabled).toBe(true);
    action.removeAttribute('disabled');
    fireEvent.click(action);
    expect(screen.queryByRole('dialog')).toBeNull();
  });

  it('does not reuse a Direct connection while rereading Hub ownership on reentry', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    let mode: 'direct' | 'hub' = 'direct';
    const nextConnection = pending<BackendConnectionState>();
    const nextSupply = pending<Awaited<ReturnType<typeof hubReads.read>>>();
    mock.api.getBackendConnection.mockImplementation(async (backend) => backend === 'claude' && mode === 'hub'
      ? nextConnection.promise
      : { ok: true, backend, installed: true, enabled: true, auth: 'api_key',
        application: 'applied', ready: true, entry_eligible: true, supply_mode: mode });
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });
    mock.models.getAgentChains.mockResolvedValue([hubChain('model-a')]);
    mock.models.getAgentChain.mockResolvedValue(hubChain('model-a'));
    const reads = { ...hubReads, read: async () => mode === 'hub' ? nextSupply.promise
      : { kind: 'current' as const, value: [
        { backend: 'claude' as const, cli_present: true, mode: 'direct' as const, menu_kind: 'fixed' as const },
      ] } };
    const props = { data: saved, onNext: vi.fn(), onNavigate: vi.fn(), agentReads: reads };
    const view = render(wrap(<AgentDetection {...props} active />));
    await waitFor(() => expect(row('Claude Code').getByRole<HTMLButtonElement>('button', { name: 'API Key connected' }).disabled).toBe(false));
    view.rerender(wrap(<AgentDetection {...props} active={false} />, false));
    mode = 'hub';
    view.rerender(wrap(<AgentDetection {...props} active />, true));
    const staleAction = row('Claude Code').getByRole<HTMLButtonElement>('button', { name: /Add subscription/ });
    expect(staleAction.disabled).toBe(true);
    staleAction.removeAttribute('disabled');
    fireEvent.click(staleAction);
    expect(screen.queryByRole('dialog')).toBeNull();

    await act(async () => {
      nextConnection.resolve({ ok: true, backend: 'claude', installed: true, enabled: true,
        auth: 'none', application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub' });
      nextSupply.resolve(await hubReads.read());
    });
    const currentAction = await row('Claude Code').findByRole<HTMLButtonElement>('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
    });
    await waitFor(() => expect(currentAction.disabled).toBe(false));
    fireEvent.click(currentAction);
    expect(await screen.findByRole('dialog')).toBeTruthy();
  });

  it('keeps a failed route read visible and retries it without claiming the model is unset', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });
    mock.models.getAgentChains.mockRejectedValueOnce(new Error('offline')).mockResolvedValue([hubChain('model-a')]);
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} flowState={INITIAL_SETUP_FLOW_STATE}
      setFlowState={vi.fn()} onNavigate={vi.fn()} agentReads={hubReads} />));

    await waitFor(() => expect(row('Claude Code').getByText(en.settings.models.routeDialog.fail.reconcileRead)).toBeTruthy());
    expect(row('Claude Code').queryByText(en.onboarding.setup.noteModelUnset)).toBeNull();
    expect(row('Claude Code').queryByText(en.onboarding.setup.noteNoModels)).toBeNull();
    expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();
    expect(row('Claude Code').getByRole('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
    })).toHaveProperty('disabled', true);
    const connectionReads = mock.api.getBackendConnection.mock.calls.length;
    fireEvent.click(row('Claude Code').getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(row('Claude Code').getByText('model-a')).toBeTruthy());
    expect(row('Claude Code').queryByText(en.settings.models.routeDialog.fail.reconcileRead)).toBeNull();
    expect(mock.models.getAgentChains).toHaveBeenCalledTimes(2);
    expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(connectionReads);
  });

  it.each(['chain', 'detail'] as const)('isolates a failed %s read to its assistant', async (failure) => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    saved.agents.codex.status = 'ok';
    const codexAgent = { ...hubAgent(), id: 'codex-codex', name: 'codex', backend: 'codex' as const };
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent(), codexAgent], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockImplementation(async (name) => {
      if (failure === 'detail' && name === 'claude') throw new Error('detail unreadable');
      return { ok: true, agent: name === 'codex' ? codexAgent : hubAgent() };
    });
    mock.models.getAgentChains.mockImplementation(async (backend) => {
      if (failure === 'chain' && backend === 'claude') throw new Error('chain unreadable');
      return [{ ...hubChain('model-a'), backend }];
    });
    mock.models.getAgentChain.mockResolvedValue({ ...hubChain('model-a'), backend: 'codex' });
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',
    }));
    const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [
      { backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const },
      { backend: 'codex' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'open' as const },
    ] }) };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));
    await row('Claude Code').findByText(en.settings.models.routeDialog.fail.reconcileRead);
    expect(row('Codex').queryByText(en.settings.models.routeDialog.fail.reconcileRead)).toBeNull();
    const action = row('Codex').getByRole<HTMLButtonElement>('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Codex'),
    });
    expect(action.disabled).toBe(false);
    fireEvent.click(action);
    expect(await screen.findByRole('dialog')).toBeTruthy();
  });

  it('lets a ready assistant edit while another chain read remains pending', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    saved.agents.codex.status = 'ok';
    const codexAgent = { ...hubAgent(), id: 'codex-codex', name: 'codex', backend: 'codex' as const };
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent(), codexAgent], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockImplementation(async (name) => ({ ok: true, agent: name === 'codex' ? codexAgent : hubAgent() }));
    const delayed = pending<ReturnType<typeof hubChain>[]>();
    mock.models.getAgentChains.mockImplementation((backend) => backend === 'claude'
      ? delayed.promise : Promise.resolve([{ ...hubChain('model-a'), backend }]));
    mock.models.getAgentChain.mockResolvedValue({ ...hubChain('model-a'), backend: 'codex' });
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',
    }));
    const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [
      { backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const },
      { backend: 'codex' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'open' as const },
    ] }) };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));
    const action = await row('Codex').findByRole<HTMLButtonElement>('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Codex'),
    });
    await waitFor(() => expect(action.disabled).toBe(false));
    expect(row('Claude Code').getByRole('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
    })).toHaveProperty('disabled', true);
    fireEvent.click(action);
    expect(await screen.findByRole('dialog')).toBeTruthy();
    await act(async () => delayed.resolve([hubChain('model-a')]));
  });

  it('does not use an Agent archived after the brief read as a route target', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    saved.agents.codex.status = 'ok';
    const codexAgent = { ...hubAgent(), id: 'codex-codex', name: 'codex', backend: 'codex' as const };
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent(), codexAgent], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockImplementation(async (name) => ({ ok: true,
      agent: name === 'claude' ? { ...hubAgent(), archived: true } : codexAgent }));
    mock.models.getAgentChains.mockImplementation(async (backend) => [{ ...hubChain('model-a'), backend }]);
    mock.models.getAgentChain.mockResolvedValue({ ...hubChain('model-a'), backend: 'codex' });
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',
    }));
    const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [
      { backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const },
      { backend: 'codex' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'open' as const },
    ] }) };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));
    await row('Claude Code').findByText(en.onboarding.setup.noteModelUnset);
    expect(row('Claude Code').queryByText('model-a')).toBeNull();
    expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();
    expect(mock.models.getAgentChains).not.toHaveBeenCalledWith('claude');
    const codexAction = row('Codex').getByRole<HTMLButtonElement>('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Codex'),
    });
    expect(codexAction.disabled).toBe(false);
    fireEvent.click(codexAction);
    expect(await screen.findByRole('dialog')).toBeTruthy();
  });

  it('stops after a confirmed backend-named target, ignoring unreadable custom Agents', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    const custom = { ...hubAgent(), id: 'custom', name: 'custom' };
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [custom, hubAgent()], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockImplementation(async (name) => {
      if (name === 'custom') throw new Error('unreadable custom Agent');
      return { ok: true, agent: hubAgent() };
    });
    mock.models.getAgentChains.mockResolvedValue([hubChain('model-a')]);
    mock.models.getAgentChain.mockResolvedValue(hubChain('model-a'));
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',
    }));
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={hubReads} />));
    const action = await row('Claude Code').findByRole<HTMLButtonElement>('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
    });
    await waitFor(() => expect(action.disabled).toBe(false));
    expect(mock.api.getVibeAgent.mock.calls.filter(([name]) => name === 'custom')).toHaveLength(0);
    fireEvent.click(action);
    expect(await screen.findByRole('dialog')).toBeTruthy();
  });

  it('keeps an unreadable higher-priority target unknown instead of falling back', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    const fallback = { ...hubAgent(), id: 'fallback', name: 'default' };
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [fallback, hubAgent()], default_agent_name: 'default' });
    mock.api.getVibeAgent.mockImplementation(async (name) => {
      if (name === 'claude') throw new Error('unreadable designated Agent');
      return { ok: true, agent: fallback };
    });
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',
    }));
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={hubReads} />));
    await row('Claude Code').findByText(en.settings.models.routeDialog.fail.reconcileRead);
    expect(mock.api.getVibeAgent.mock.calls.filter(([name]) => name === 'default')).toHaveLength(0);
    expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();
    expect(mock.models.getAgentChains).not.toHaveBeenCalledWith('claude');
  });

  it('uses the next current builtin after an archived detail, in stable name order', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    const named = { ...hubAgent(), name: 'zeta', model: 'zeta-model' };
    const earlier = { ...hubAgent(), name: 'alpha', model: 'alpha-model' };
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [named, earlier, hubAgent()], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockImplementation(async (name) => ({ ok: true,
      agent: name === 'claude' ? { ...hubAgent(), archived: true } : name === 'alpha' ? earlier : named }));
    mock.models.getAgentChains.mockResolvedValue([{ ...hubChain('model-a'), model_id: 'alpha-model' }]);
    mock.models.getAgentChain.mockResolvedValue({ ...hubChain('model-a'), model_id: 'alpha-model' });
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',
    }));
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={hubReads} />));
    const action = await row('Claude Code').findByRole<HTMLButtonElement>('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
    });
    await waitFor(() => expect(action.disabled).toBe(false));
    expect(mock.api.getVibeAgent.mock.calls.filter(([name]) => ['claude', 'alpha', 'zeta'].includes(name))
      .map(([name]) => name)).toEqual(['claude', 'alpha']);
    fireEvent.click(action);
    expect(within(await screen.findByRole('dialog')).getByText('alpha-model · Route chain')).toBeTruthy();
  });

  it('does not borrow a menu label from another backend for an upstream hop', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });
    mock.models.getAgentChains.mockResolvedValue([hubChain('shared-id')]);
    mock.models.listSources.mockResolvedValue([{ id: 'src_a', state: { status: 'active' }, models: [] }]);
    const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [
      { backend: 'claude' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const },
      { backend: 'codex' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'fixed' as const,
        catalog_models: [{ id: 'shared-id', display_name: 'Wrong menu label' }] },
    ] }) };
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',
    }));
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));
    await row('Claude Code').findByText('shared-id');
    expect(row('Claude Code').queryByText('Wrong menu label')).toBeNull();
  });

  it('distinguishes a confirmed missing Agent model from a configured model with an empty chain', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    let selectedModel: string | null = null;
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockImplementation(async () => ({ ok: true, agent: { ...hubAgent(), model: selectedModel } }));
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',
    }));
    mock.models.getAgentChains.mockResolvedValue([]);
    const props = { data: saved, onNext: vi.fn(), onNavigate: vi.fn(), agentReads: hubReads };
    const view = render(wrap(<AgentDetection {...props} active />));
    await row('Claude Code').findByText(en.onboarding.setup.noteModelUnset);
    expect(row('Claude Code').queryByText(en.onboarding.setup.noteNoModels)).toBeNull();
    expect(mock.models.getAgentChains).not.toHaveBeenCalled();

    view.rerender(wrap(<AgentDetection {...props} active={false} />, false));
    selectedModel = 'opus-5';
    view.rerender(wrap(<AgentDetection {...props} active />, true));
    await row('Claude Code').findByText(en.onboarding.setup.noteNoModels);
    expect(row('Claude Code').queryByText(en.onboarding.setup.noteModelUnset)).toBeNull();
    expect(mock.models.getAgentChains).toHaveBeenCalledWith('claude');
    const action = row('Claude Code').getByRole<HTMLButtonElement>('button', { name: en.onboarding.setup.configureRoute });
    expect(action.disabled).toBe(false);
    fireEvent.click(action);
    expect(await screen.findByRole('dialog')).toBeTruthy();
  });

  it('refreshes connection and route ownership when a route dialog closes after Hub becomes Direct', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    let mode: 'hub' | 'direct' = 'hub';
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });
    mock.models.getAgentChains.mockResolvedValue([hubChain('model-a')]);
    mock.models.getAgentChain.mockResolvedValue(hubChain('model-a'));
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: mode,
    }));
    const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [
      { backend: 'claude' as const, cli_present: true, mode, menu_kind: 'fixed' as const },
    ] }) };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));
    const routeAction = await row('Claude Code').findByRole<HTMLButtonElement>('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
    });
    await waitFor(() => expect(routeAction.disabled).toBe(false));
    fireEvent.click(routeAction);
    const dialog = await screen.findByRole('dialog');
    mode = 'direct';
    const priorConnectionReads = mock.api.getBackendConnection.mock.calls.length;
    fireEvent.click(dialog.querySelector('.model-hub-route-close') as HTMLButtonElement);
    await waitFor(() => expect(mock.api.getBackendConnection.mock.calls.length).toBeGreaterThan(priorConnectionReads));
    await waitFor(() => expect(row('Claude Code').getByRole<HTMLButtonElement>('button', { name: 'API Key connected' }).disabled).toBe(false));
    expect(row('Claude Code').queryByText(en.onboarding.setup.ownershipChanged)).toBeNull();
    expect(row('Claude Code').queryByRole('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
    })).toBeNull();
  });

  it('shows a disabled builtin assistant its stored route without opening the editor', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.opencode.status = 'ok';
    saved.agents.opencode.enabled = false;
    const agent = { ...hubAgent(false), id: 'opencode-opencode', name: 'opencode',
      display_name: 'opencode', backend: 'opencode' as const, model: 'gpt-5.6-sol' };
    mock.api.listVibeAgents.mockImplementation(async ({ includeDisabled }) => ({
      ok: true, agents: includeDisabled ? [agent] : [], default_agent_name: null,
    }));
    mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent });
    let opencodeEnabled = false;
    mock.api.mutateConfig.mockImplementation(async () => {
      opencodeEnabled = true;
      return {};
    });
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: backend !== 'opencode' || opencodeEnabled, auth: 'api_key',
      application: 'applied', ready: backend !== 'opencode' || opencodeEnabled,
      entry_eligible: backend !== 'opencode' || opencodeEnabled, supply_mode: 'hub',
    }));
    mock.models.listSources.mockResolvedValue([{ id: 'src_a', state: { status: 'active' }, models: [{ id: 'gpt-5.6-sol', display_name: 'GPT-5.6-Sol' }] }]);
    mock.models.getAgentChains.mockResolvedValue([{ ...hubChain('gpt-5.6-sol'), backend: 'opencode', model_id: 'gpt-5.6-sol',
      chain: [
        { source_id: 'src_a', model_id: 'gpt-5.6-sol', channel: 'hub', health: 'healthy', runnable: true },
        { source_id: 'src_a', model_id: 'claude-opus-5-5', channel: 'hub', health: 'healthy', runnable: true },
      ],
    }]);
    const reads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [
      { backend: 'opencode' as const, cli_present: true, mode: 'hub' as const, menu_kind: 'open' as const },
    ] }) };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} flowState={INITIAL_SETUP_FLOW_STATE}
      setFlowState={vi.fn()} onNavigate={vi.fn()} agentReads={reads} />));
    const choice = await row('OpenCode').findByRole('button', { name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'OpenCode') });
    await waitFor(() => expect(row('OpenCode').getByText('GPT-5.6-Sol')).toBeTruthy());
    expect(choice.textContent).toContain('1 backup');
    expect(choice).toHaveProperty('disabled', true);
    fireEvent.click(choice);
    expect(screen.queryByRole('dialog')).toBeNull();
    expect(mock.api.listVibeAgents).toHaveBeenCalledWith({ cache: false, includeDisabled: true });
    fireEvent.click(row('OpenCode').getByRole('switch', { name: 'Enable OpenCode' }));
    await waitFor(() => expect(row('OpenCode').getByRole('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'OpenCode'),
    })).toHaveProperty('disabled', false));
  });

  it('keeps an explicitly Direct assistant out of Hub routing', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [hubAgent()], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent: hubAgent() });
    mock.models.getAgentChain.mockResolvedValue(hubChain('model-a'));
    mock.api.getBackendConnection.mockImplementation(async (backend) => ({
      ok: true, backend, installed: true, enabled: true, auth: 'api_key',
      application: 'applied', ready: true, entry_eligible: true, supply_mode: 'direct',
    }));
    const directReads = { ...hubReads, read: async () => ({ kind: 'current' as const, value: [{ backend: 'claude' as const, cli_present: true, mode: 'direct' as const, menu_kind: 'fixed' as const }] }) };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} flowState={INITIAL_SETUP_FLOW_STATE}
      setFlowState={vi.fn()} onNavigate={vi.fn()} agentReads={directReads} />));
    await waitFor(() => expect(mock.api.listVibeAgents).toHaveBeenCalled());
    expect(mock.models.getAgentChains).not.toHaveBeenCalled();
    expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.configureRoute })).toBeNull();
    expect(row('Claude Code').queryByText(en.onboarding.setup.defaultModel)).toBeNull();
  });

  it('cannot open a stale route while re-reading a changed Agent model on reentry', async () => {
    const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
    saved.agents.claude.status = 'ok';
    let designatedModel = 'model-A';
    const listed = { ...hubAgent(), model: designatedModel };
    mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [listed], default_agent_name: 'claude' });
    mock.api.getVibeAgent.mockImplementation(async () => ({ ok: true, agent: { ...listed, model: designatedModel } }));
    mock.models.getAgentChains.mockResolvedValue([{ ...hubChain('hop-A'), model_id: 'model-A' }]);
    const flowState = { ...INITIAL_SETUP_FLOW_STATE };
    const setFlowState = vi.fn();
    const props = { data: saved, onNext: vi.fn(), flowState, setFlowState, onNavigate: vi.fn(), agentReads: hubReads };
    const view = render(wrap(<AgentDetection {...props} active />));
    const routeAction = () => row('Claude Code').getByRole<HTMLButtonElement>('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
    });
    await waitFor(() => expect(row('Claude Code').getByText('hop-A')).toBeTruthy());
    expect(routeAction().disabled).toBe(false);
    view.rerender(wrap(<AgentDetection {...props} active={false} />, false));
    designatedModel = 'model-B';
    const delayed = pending<ReturnType<typeof hubChain>[]>();
    mock.models.getAgentChains.mockReturnValue(delayed.promise);
    view.rerender(wrap(<AgentDetection {...props} active />));
    await waitFor(() => expect(mock.models.getAgentChains).toHaveBeenCalledTimes(2));
    const pendingAction = row('Claude Code').getByRole<HTMLButtonElement>('button', {
      name: en.onboarding.setup.defaultModelNamed.replace('{{name}}', 'Claude Code'),
    });
    expect(pendingAction.disabled).toBe(true);
    expect(row('Claude Code').queryByText(en.onboarding.setup.noteNoModels)).toBeNull();
    pendingAction.removeAttribute('disabled');
    fireEvent.click(pendingAction);
    expect(screen.queryByRole('dialog')).toBeNull();

    await act(async () => delayed.resolve([{ ...hubChain('hop-B'), model_id: 'model-B' }]));
    await waitFor(() => expect(row('Claude Code').getByText('hop-B')).toBeTruthy());
    expect(routeAction().disabled).toBe(false);
    fireEvent.click(routeAction());
    expect(within(await screen.findByRole('dialog')).getByText('model-B · Route chain')).toBeTruthy();
  });

});

const pending = <T,>() => { let resolve!: (value: T) => void; let reject!: (reason: Error) => void; const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; };
const stateFor = (backend: string, enabled = true, application: BackendConnectionState['application'] = 'applied') => ({ ok: true, backend, enabled, installed: true, auth: 'api_key', application, ready: backend === 'claude' && enabled && application === 'applied', entry_eligible: backend === 'claude' && enabled && application === 'applied' });
/** The enable control is a `role="switch"` button, so its state is its aria-checked. */
const checkedOf = (node: HTMLElement) => node.getAttribute('aria-checked') === 'true';
describe('settled wizard enablement follows persistence and latest intent', () => {
  function mountReady() {
    const saved = data(); saved.agents.claude.status = 'ok';
    mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
    return row('Claude Code').getByRole('switch') as HTMLElement;
  }
  it.each(['rejected', 'committed-failed', 'unreadable'] as const)('reconciles a single toggle (%s) and Retry repairs enabled without another write', async (outcome) => {
    const checkbox = mountReady();
    await waitFor(() => expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false));
    if (outcome === 'committed-failed') {
      mock.api.mutateConfig.mockResolvedValue({ agents: { claude: { enabled: false } }, agent_backend_runtime: { hot_reconciled: false, restart_error: 'fixture apply failure' } });
      mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name, false, 'failed'));
    } else {
      mock.api.mutateConfig.mockRejectedValue(new Error('fixture persist failure'));
      if (outcome === 'unreadable') mock.api.getBackendConnection.mockRejectedValue(new Error('fixture read failure'));
    }
    fireEvent.click(checkbox);
    await row('Claude Code').findByRole('alert');
    expect(checkedOf(checkbox)).toBe(outcome === 'rejected');
    expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
    mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));
    fireEvent.click(row('Claude Code').getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(checkedOf(checkbox)).toBe(true));
    await waitFor(() => expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false));
    expect(mock.api.mutateConfig).toHaveBeenCalledOnce();
  });
  it('an older rejected off cannot replace queued on intent or accept a read started before the toggle', async () => {
    const checkbox = mountReady(); await row('Claude Code').findByRole('button', { name: 'API Key connected' });
    const oldRead = pending<ReturnType<typeof stateFor>>();
    mock.api.getBackendConnection.mockImplementation((name) => name === 'claude' ? oldRead.promise : Promise.resolve(stateFor(name)));
    fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));
    await waitFor(() => expect(mock.api.detectCli).toHaveBeenCalledWith('claude', 'claude'));
    const off = pending<unknown>(); const on = pending<unknown>();
    mock.api.mutateConfig.mockReturnValueOnce(off.promise).mockReturnValueOnce(on.promise);
    fireEvent.click(checkbox); fireEvent.click(checkbox);
    await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());
    await act(async () => oldRead.resolve(stateFor('claude', false)));
    expect(checkedOf(checkbox)).toBe(true);
    await act(async () => off.reject(new Error('old off rejected')));
    expect(checkedOf(checkbox)).toBe(true);
    expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
    mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));
    await act(async () => on.resolve({ agents: { claude: { enabled: true } } }));
    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', '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();
  });
  // The presence read is the last thing a queued enable does, and the only one that can
  // reject. A rejection used to settle the serial queue itself rejected, so every later
  // toggle chained onto a continuation that never ran: the next enable wrote nothing,
  // and nothing on the card said why. The write and the read after it answer separately.
  it('a presence read that failed is reported and still leaves the next toggle able to run', async () => {
    const saved = data(); saved.agents.claude.status = 'ok';
    let backendEnabled = true;
    mock.api.mutateConfig.mockImplementation(async () => { backendEnabled = !backendEnabled; return {}; });
    mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name, name === 'claude' ? backendEnabled : true));
    let presenceFails = true;
    const refresh = vi.fn(async () => {
      if (presenceFails) { presenceFails = false; throw new Error('fixture presence failure'); }
      return { kind: 'current' as const, value: [] };
    });
    const agentReads = { read: async () => ({ kind: 'current' as const, value: [] }), refresh, readValue: async () => [], invalidate: () => undefined };
    render(wrap(<AgentDetection data={saved} onNext={vi.fn()} agentReads={agentReads} />));
    const checkbox = row('Claude Code').getByRole('switch') as HTMLElement;
    const enter = screen.getByRole('button', { name: 'Enter workspace' });
    await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(false));

    fireEvent.click(checkbox);
    expect((await row('Claude Code').findByRole('alert')).textContent).toContain('fixture presence failure');
    await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());
    expect(enter.hasAttribute('disabled')).toBe(true);

    // Still a queue. The next toggle writes, and the connection read it carries settles
    // the card — which only happens once the finished write released its pending enable.
    fireEvent.click(checkbox);
    await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2));
    await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(false));
    expect(cardAlert()).toBeNull();
    expect(refresh).toHaveBeenCalledTimes(2);
    expect(checkedOf(checkbox)).toBe(true);
  });
  it('delayed modal config cannot undo a newer authoritative enablement result', async () => {
    const checkbox = mountReady(); await row('Claude Code').findByRole('button', { name: 'API Key connected' });
    const config = pending<unknown>(); mock.api.getConfig.mockReturnValue(config.promise);
    fireEvent.click(row('Claude Code').getByRole('button', { name: 'API Key connected' }));
    fireEvent.keyDown(await screen.findByRole('dialog'), { key: 'Escape' });
    mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name, false));
    mock.api.mutateConfig.mockResolvedValue({ agents: { claude: { enabled: false } } });
    fireEvent.click(checkbox);
    await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());
    await act(async () => config.resolve(data()));
    expect(checkedOf(checkbox)).toBe(false);
    expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
  });
});