Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

54.9 KB
Raw Blame
import {
  appendFileSync,
  existsSync,
  mkdirSync,
  readFileSync,
  realpathSync,
  writeFileSync,
} from 'node:fs';
import path from 'node:path';
import type { Page } from '@playwright/test';

import { openSidebarEntry, expect, test, type OrkasTestApp } from './fixtures/orkas';
import { estimateBudgetTokens } from '../../src/main/util/token-estimate';

async function createCliAgent(
  app: OrkasTestApp,
  name: string,
  cli: 'opencode' | 'hermes' | 'codex' | 'claude',
): Promise<{ page: Page; agentId: string }> {
  const created = await app.invoke<{ agent: { agent_id: string } }>('agents.create', {
    name,
    description: `Deterministic ${cli} E2E agent`,
    category: 'general',
    runtime: { kind: 'cli', cli },
  });
  if (!app.page) throw new Error('Orkas renderer is unavailable');
  const page = app.page;
  await page.locator('#new-chat-btn').click();
  return { page, agentId: created.agent.agent_id };
}

async function sendNewChat(page: Page, text: string): Promise<string> {
  await page.locator('#new-chat-input').fill(text);
  await page.locator('#new-chat-send-btn').click();
  await expect(page.locator('#panel-conversation')).toHaveClass(/\bactive\b/);
  const conversationId = await page.locator('#conversation-list .conv-item').first().getAttribute('data-cid');
  if (!conversationId) throw new Error('New CLI conversation did not appear in the sidebar');
  return conversationId;
}

async function sendFollowUp(page: Page, text: string): Promise<void> {
  await page.locator('#chat-input').fill(text);
  await page.locator('#chat-input').press('Enter');
}

async function selectAiOption(page: Page, mountSelector: string, value: string): Promise<void> {
  await page.locator(`${mountSelector} .ai-select-trigger`).click();
  await page.locator(`.ai-select-popover:visible .ai-select-item[data-value="${value}"]`).click();
}

function cliSessionFile(app: OrkasTestApp, conversationId: string): string {
  return path.join(
    app.workspaceRoot,
    'account-e2e',
    'local',
    'cli-sessions',
    `${conversationId}.json`,
  );
}

function appendCanonicalMessages(
  app: OrkasTestApp,
  conversationId: string,
  rows: Array<Record<string, unknown>>,
): void {
  const file = path.join(
    app.workspaceRoot,
    'account-e2e',
    'cloud',
    'chats',
    `${conversationId}.jsonl`,
  );
  appendFileSync(file, `${rows.map((row) => JSON.stringify(row)).join('\n')}\n`, 'utf8');
}

test.describe('CLI Agent runtime settings', () => {
  test.describe.configure({ timeout: 120_000 });

  test('runs a first OpenCode task in the custom directory shown on its Agent detail page', async ({ cliOrkas }) => {
    const agentName = 'OpenCodeProjectDirE2E';
    const { page, agentId } = await createCliAgent(cliOrkas, agentName, 'opencode');
    const selectedProjectDirCandidate = path.join(
      cliOrkas.workspaceRoot,
      'selected OpenCode project',
    );
    mkdirSync(selectedProjectDirCandidate, { recursive: true });
    // macOS exposes /var as a symlink to /private/var. Select the canonical
    // directory so the user-visible setting, argv, process.cwd(), and PWD all
    // share the same identity instead of comparing two aliases.
    const selectedProjectDir = realpathSync(selectedProjectDirCandidate);
    writeFileSync(path.join(selectedProjectDir, 'CLAUDE.md'), '# E2E project instructions\n');

    const saved = await cliOrkas.invoke<{
      ok: boolean;
      info?: { mode?: string; path?: string; exists?: boolean };
    }>('agents.cliProjectDir.set', {
      agent_id: agentId,
      path: selectedProjectDir,
    });
    expect(saved).toMatchObject({
      ok: true,
      info: { mode: 'custom', path: selectedProjectDir, exists: true },
    });

    await openSidebarEntry(page, '#agents-btn');
    const card = page.locator(`.agent-card[data-id="${agentId}"]`);
    await expect(card).toBeVisible({ timeout: 30_000 });
    await card.click();
    await expect(page.locator('#agents-detail-project-dir-section')).toBeVisible();
    await expect(page.locator('#agents-detail-project-dir .agent-project-dir-path'))
      .toHaveText(selectedProjectDir);

    await page.locator('#agent-use-btn').click();
    await expect(page.locator('#panel-new-chat')).toHaveClass(/\bactive\b/);
    await sendNewChat(page, 'E2E_OPENCODE_CUSTOM_PROJECT_DIR');
    await expect.poll(() => cliOrkas.readCliState().invocations.filter(
      (item) => item.prompt.includes('E2E_OPENCODE_CUSTOM_PROJECT_DIR'),
    ).length).toBe(1);
    await expect(page.locator('#chat-history .chat-input-form')).toHaveCount(0);
    const reply = page.locator('#chat-history .chat-message.assistant', {
      hasText: 'E2E_CLI_DEFAULT_OK',
    });
    await expect(reply.locator('.chat-bubble > :is(.markdown-body, [data-role="final"])')).toBeVisible({ timeout: 30_000 });
    // This scenario inspects a completed task's persisted process output.
    // A streamed answer can be visible before canonical settlement replaces
    // the live process rail; wait for the real terminal UI before opening it.
    await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);

    const processRail = reply.locator('.stream-process');
    await expect(processRail).toBeVisible();
    if (!await processRail.evaluate((element: HTMLDetailsElement) => element.open)) {
      await processRail.locator('.stream-process-summary').click();
    }
    await processRail.locator('.stream-process-compact-summary').click();
    const commandRow = processRail.locator(
      '.stream-process-line[data-process-call-id="cli:e2e-result-command"]',
    );
    const writeRow = processRail.locator(
      '.stream-process-line[data-process-call-id="cli:e2e-result-write"]',
    );
    await expect(commandRow).toContainText('Run command · head -60 CLAUDE.md · Done · 5ms');
    await expect(writeRow).toContainText('Edit file · snake.html · Done · 25ms');
    await expect(commandRow).not.toContainText(selectedProjectDir);
    await expect(writeRow).not.toContainText('private event body');
    await expect(reply.locator('.chat-msg-produced-item')).toContainText('snake.html');
    await commandRow.click();
    await expect(commandRow).toHaveAttribute('aria-expanded', 'true');
    await expect(commandRow.locator('xpath=following-sibling::*[1]'))
      .toContainText('deterministic command output');

    const invocation = cliOrkas.readCliState().invocations.find(
      (item) => item.prompt.includes('E2E_OPENCODE_CUSTOM_PROJECT_DIR'),
    );
    expect(invocation).toBeDefined();
    if (!invocation) throw new Error('OpenCode task invocation was not recorded');
    expect(invocation).toMatchObject({
      cli: 'opencode',
      cwd: selectedProjectDir,
    });
    if (process.platform !== 'win32') expect(invocation.pwd).toBe(selectedProjectDir);
    const directoryFlags = invocation.args.filter(
      (arg) => arg === '--dir' || arg.startsWith('--dir='),
    );
    expect(directoryFlags).toEqual(['--dir']);
    const directoryIndex = invocation.args.indexOf('--dir');
    expect(invocation.args[directoryIndex + 1]).toBe(selectedProjectDir);

    const conversationId = await page.locator('#conversation-list .conv-item').first()
      .getAttribute('data-cid');
    expect(conversationId).toBeTruthy();
    const relaunchedPage = await cliOrkas.relaunch();
    await relaunchedPage.locator(`#conversation-list .conv-item[data-cid="${conversationId}"]`).click();
    const restoredReply = relaunchedPage.locator('#chat-history .chat-message.assistant', {
      hasText: 'E2E_CLI_DEFAULT_OK',
    });
    const restoredRail = restoredReply.locator('.stream-process');
    await expect(restoredRail).toBeVisible();
    await restoredRail.locator('.stream-process-summary').click();
    await restoredRail.locator('.stream-process-compact-summary').click();
    const restoredCommand = restoredRail.locator(
      '.stream-process-line[data-process-call-id="cli:e2e-result-command"]',
    );
    await expect(restoredCommand)
      .toContainText('Run command · head -60 CLAUDE.md · Done · 5ms');
    await restoredCommand.press('Enter');
    await expect(restoredCommand).toHaveAttribute('aria-expanded', 'true');
    await expect(restoredCommand.locator('xpath=following-sibling::*[1]'))
      .toContainText('deterministic command output');
  });

  test('persists overrides, resets model-specific thinking, and restores CLI defaults', async ({ cliOrkas }) => {
    // Three cold application launches are fixture preparation, not a single
    // interaction's latency budget. Keep each model/element wait unchanged.
    test.setTimeout(240_000);
    const agentName = 'CodexRuntimeSettingsE2E';
    const { page, agentId } = await createCliAgent(cliOrkas, agentName, 'codex');
    await cliOrkas.invoke('agents.update', {
      agent_id: agentId,
      updates: { icon: 'code', color: 'lime' },
    });
    await openSidebarEntry(page, '#agents-btn');
    const card = page.locator(`.agent-card[data-id="${agentId}"]`);
    await expect(card).toBeVisible({ timeout: 30_000 });
    await card.click();

    const model = page.locator('#agents-detail-cli-settings [data-role="model"]');
    await expect(model.locator('.ai-select-trigger'))
      .toContainText('GPT E2E Default', { timeout: 30_000 });
    await expect(page.locator('#agents-detail-cli-settings-section .agents-detail-section-desc')).toHaveCount(0);
    await expect(page.locator('#agents-detail-cli-settings .agents-detail-cli-note')).toHaveCount(0);
    await expect(page.locator('#agents-detail-project-dir-section')).toBeVisible();
    await expect.poll(() => cliOrkas.readCliState().modelListResponses).toBe(1);

    await model.locator('.ai-select-trigger').click();
    const defaultModelOption = page.locator(
      '.ai-select-popover:visible .ai-select-item[data-value=""]',
    );
    await expect(defaultModelOption.locator('.ai-select-item-label')).toContainText('GPT E2E Default');
    await expect(defaultModelOption.locator('.ai-select-item-hint')).toHaveText('Default');
    await expect(page.locator('.ai-select-popover:visible')).not.toContainText('Resolved by');
    await page.locator('#agents-detail-cli-settings-section .agents-detail-label').click();

    const thinking = page.locator('#agents-detail-cli-settings [data-role="thinking"]');
    await expect(thinking.locator('.ai-select-trigger')).toContainText('low');
    await thinking.locator('.ai-select-trigger').click();
    const defaultThinkingOption = page.locator(
      '.ai-select-popover:visible .ai-select-item[data-value=""]',
    );
    await expect(defaultThinkingOption.locator('.ai-select-item-label')).toHaveText('low');
    await expect(defaultThinkingOption.locator('.ai-select-item-hint')).toHaveText('Default');
    await expect(page.locator('.ai-select-popover:visible')).not.toContainText('Resolved by');
    await page.locator('#agents-detail-cli-settings-section .agents-detail-label').click();

    await page.locator('#agents-back-btn').click();
    await expect(card).toBeVisible();
    await card.click();
    await expect(model.locator('.ai-select-trigger'))
      .toContainText('GPT E2E Default');
    await expect(page.locator('#agents-detail-cli-settings .agents-detail-cli-loading')).toHaveCount(0);
    // The second live response is deliberately delayed. Seeing the selector
    // while only the first response exists proves the cached catalog rendered
    // before the forced refresh completed.
    expect(cliOrkas.readCliState().modelListResponses).toBe(1);
    await expect.poll(() => cliOrkas.readCliState().modelListResponses, { timeout: 15_000 }).toBe(2);
    await model.locator('.ai-select-trigger').click();
    await expect(page.locator(
      '.ai-select-popover:visible .ai-select-item[data-value="gpt-e2e-fresh"]',
    )).toBeVisible();
    await page.locator('#agents-detail-cli-settings-section .agents-detail-label').click();

    await page.locator('#agents-back-btn').click();
    await expect(card).toBeVisible();
    await card.click();
    await expect.poll(() => cliOrkas.readCliState().modelListResponses).toBe(3);
    await model.locator('.ai-select-trigger').click();
    // The third live catalog is empty; the last successful cache must remain
    // usable instead of replacing the selector with a transient failure.
    await expect(page.locator(
      '.ai-select-popover:visible .ai-select-item[data-value="gpt-e2e-fresh"]',
    )).toBeVisible();
    await page.locator('#agents-detail-cli-settings-section .agents-detail-label').click();

    await selectAiOption(page, '#agents-detail-cli-settings [data-role="model"]', 'gpt-e2e-deep');
    await expect(page.locator('#agents-detail-cli-settings [data-role="model"]'))
      .toHaveAttribute('data-value', 'gpt-e2e-deep');

    // The model value is optimistic. Its dependent effort menu is ready only
    // after the saved runtime remounts the model-specific default.
    await expect(thinking.locator('.ai-select-trigger')).toHaveText('high');

    await selectAiOption(page, '#agents-detail-cli-settings [data-role="thinking"]', 'low');
    await expect(page.locator('#agents-detail-cli-settings [data-role="thinking"]'))
      .toHaveAttribute('data-value', 'low');

    // Thinking levels are model-specific. Switching models must clear the old
    // override instead of silently carrying an incompatible value forward.
    await selectAiOption(page, '#agents-detail-cli-settings [data-role="model"]', '');
    await expect(page.locator('#agents-detail-cli-settings [data-role="model"]'))
      .toHaveAttribute('data-value', '');
    await expect(page.locator('#agents-detail-cli-settings [data-role="thinking"]'))
      .toHaveAttribute('data-value', '');
    // The selector updates optimistically; its data-value does not acknowledge
    // the asynchronous agents.update persistence boundary.
    const persistedRuntime = async () => (await cliOrkas.invoke<{ agent: { runtime: Record<string, unknown> } }>(
      'agents.get', { agent_id: agentId },
    )).agent.runtime;
    await expect.poll(persistedRuntime).toEqual({ kind: 'cli', cli: 'codex' });

    await selectAiOption(page, '#agents-detail-cli-settings [data-role="model"]', 'gpt-e2e-deep');
    await expect(page.locator('#agents-detail-cli-settings [data-role="model"]'))
      .toHaveAttribute('data-value', 'gpt-e2e-deep');
    await expect(thinking.locator('.ai-select-trigger')).toHaveText('high');
    await selectAiOption(page, '#agents-detail-cli-settings [data-role="thinking"]', 'low');
    await expect(page.locator('#agents-detail-cli-settings [data-role="thinking"]'))
      .toHaveAttribute('data-value', 'low');

    await expect.poll(persistedRuntime).toEqual({
      kind: 'cli', cli: 'codex', model_override: 'gpt-e2e-deep', thinking_level: 'low',
    });
    const relaunchedPage = await cliOrkas.relaunch();
    await openSidebarEntry(relaunchedPage, '#agents-btn');
    await relaunchedPage.locator(`.agent-card[data-id="${agentId}"]`).click();
    await expect(relaunchedPage.locator('#agents-detail-cli-settings [data-role="model"]'))
      .toHaveAttribute('data-value', 'gpt-e2e-deep', { timeout: 30_000 });
    await expect(relaunchedPage.locator('#agents-detail-cli-settings [data-role="thinking"]'))
      .toHaveAttribute('data-value', 'low');

    await relaunchedPage.locator('#new-chat-btn').click();
    await sendNewChat(
      relaunchedPage,
      `@${agentName} E2E_CODEX_RUNTIME_SETTINGS`,
    );
    await expect(relaunchedPage.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CODEX_DEFAULT_OK',
    })).toBeVisible({ timeout: 30_000 });
    const agentReplies = relaunchedPage.locator(
      `#chat-history .chat-message.assistant[data-from-actor="${agentId}"]`,
    );
    await expect(agentReplies).toHaveCount(1);
    const firstAvatar = agentReplies.first().locator('.chat-msg-header .avatar-circle');
    await expect(firstAvatar).toHaveAttribute('style', /--avatar-bg:#bef264/);
    const avatarBeforeSettingsReset = await firstAvatar.evaluate((element) => ({
      style: element.getAttribute('style'),
      html: element.innerHTML,
    }));
    expect(cliOrkas.readCliState().invocations.at(-1)).toMatchObject({
      cli: 'codex',
      model: 'gpt-e2e-deep',
      effort: 'low',
    });

    // Clear each override through the real candidates tagged as defaults, then
    // prove the persisted runtime and the next native turn both omit the fields.
    await openSidebarEntry(relaunchedPage, '#agents-btn');
    await relaunchedPage.locator(`.agent-card[data-id="${agentId}"]`).click();
    await expect(relaunchedPage.locator('#agents-detail-cli-settings [data-role="thinking"]'))
      .toHaveAttribute('data-value', 'low', { timeout: 30_000 });
    await selectAiOption(relaunchedPage, '#agents-detail-cli-settings [data-role="thinking"]', '');
    await expect(relaunchedPage.locator('#agents-detail-cli-settings [data-role="thinking"]'))
      .toHaveAttribute('data-value', '');
    await expect.poll(persistedRuntime).toEqual({
      kind: 'cli', cli: 'codex', model_override: 'gpt-e2e-deep',
    });

    await selectAiOption(relaunchedPage, '#agents-detail-cli-settings [data-role="model"]', '');
    await expect(relaunchedPage.locator('#agents-detail-cli-settings [data-role="model"]'))
      .toHaveAttribute('data-value', '');
    await expect.poll(persistedRuntime).toEqual({ kind: 'cli', cli: 'codex' });

    await relaunchedPage.locator('#agent-use-btn').click();
    await sendNewChat(relaunchedPage, 'E2E_CODEX_AVATAR_AFTER_RUNTIME_SETTINGS');
    const replyAfterSettingsReset = relaunchedPage.locator(
      `#chat-history .chat-message.assistant[data-from-actor="${agentId}"]`,
    );
    await expect(replyAfterSettingsReset).toHaveCount(1, { timeout: 30_000 });
    const avatarAfterSettingsReset = await replyAfterSettingsReset.first()
      .locator('.chat-msg-header .avatar-circle')
      .evaluate((element) => ({
        style: element.getAttribute('style'),
        html: element.innerHTML,
      }));
    expect(avatarAfterSettingsReset).toEqual(avatarBeforeSettingsReset);

    const defaultPage = await cliOrkas.relaunch();
    await openSidebarEntry(defaultPage, '#agents-btn');
    await defaultPage.locator(`.agent-card[data-id="${agentId}"]`).click();
    await expect(defaultPage.locator('#agents-detail-cli-settings [data-role="model"]'))
      .toHaveAttribute('data-value', '', { timeout: 30_000 });
    await expect(defaultPage.locator('#agents-detail-cli-settings [data-role="thinking"]'))
      .toHaveAttribute('data-value', '');

    await defaultPage.locator('#new-chat-btn').click();
    await sendNewChat(defaultPage, `@${agentName} E2E_CODEX_RUNTIME_DEFAULTS`);
    await expect(defaultPage.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CODEX_DEFAULT_OK',
    })).toBeVisible({ timeout: 30_000 });
    const defaultInvocation = cliOrkas.readCliState().invocations.at(-1);
    expect(defaultInvocation).toMatchObject({ cli: 'codex' });
    expect(defaultInvocation?.model).toBeUndefined();
    expect(defaultInvocation?.effort).toBeUndefined();
  });

  test.describe('Claude body streaming', () => {

    test('paints Claude body chunks after thinking before the full assistant record or result exists', async ({ cliOrkas }, testInfo) => {
      const name = 'ClaudeStreamingBodyE2E';
      const { page, agentId } = await createCliAgent(cliOrkas, name, 'claude');
      const gate = cliOrkas.cliStatePath + '.claude-stream-stage';
      writeFileSync(gate, '0');
      const cid = await sendNewChat(page, `@${name} E2E_CLAUDE_STREAM_BODY`);
      const body = page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body');
      // The CLI withholds both the full text record and result. A renderer
      // that paints only on completion cannot satisfy either prefix assertion.
      await expect(body).toContainText('First paragraph.', { timeout: 30_000 });
      await expect(body).not.toContainText('Second paragraph.');
      await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
      writeFileSync(gate, '1');
      await expect(body).toContainText('Second paragraph.');
      await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
      await expect(page.locator('#chat-history .chat-message.assistant')).toHaveCount(1);
      const live = await cliOrkas.invoke<any>('conversations.history', { cid });
      expect(live.history.filter((row: any) => row.from === agentId)).toHaveLength(0);
      await page.screenshot({ path: testInfo.outputPath('claude-streaming-body.png') });
      writeFileSync(gate, '2');
      await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
      const settledBody = page.locator('#chat-history .chat-message.assistant .chat-bubble')
        .locator(':scope > .markdown-body, :scope > [data-role="final"] > .markdown-body');
      await expect(settledBody.locator('h2')).toHaveText('Report');
      await expect(settledBody.locator('p')).toHaveText(['First paragraph.', 'Second paragraph.']);
      const saved = await cliOrkas.invoke<any>('conversations.history', { cid });
      expect(saved.history.filter((row: any) => row.from === agentId).map((row: any) => row.text))
        .toEqual(['## Report\n\nFirst paragraph.\n\nSecond paragraph.']);
      expect(cliOrkas.readCliState().invocations.filter(run => run.cli === 'claude')).toHaveLength(1);
    });
  });

  test('labels Claude aliases and remembers only the matching concrete model', async ({ cliOrkas }) => {
    const agentName = 'ClaudeModelAliasE2E';
    const { page, agentId } = await createCliAgent(cliOrkas, agentName, 'claude');
    await cliOrkas.invoke('agents.update', {
      agent_id: agentId,
      updates: {
        runtime: { kind: 'cli', cli: 'claude', model_override: 'sonnet' },
      },
    });

    await openSidebarEntry(page, '#agents-btn');
    await page.locator(`.agent-card[data-id="${agentId}"]`).click();
    const model = page.locator('#agents-detail-cli-settings [data-role="model"]');
    await expect(model.locator('.ai-select-trigger'))
      .toContainText('Sonnet · claude-sonnet-4-6', { timeout: 30_000 });
    await model.locator('.ai-select-trigger').click();
    const sonnet = page.locator(
      '.ai-select-popover:visible .ai-select-item[data-value="sonnet"]',
    );
    await expect(sonnet.locator('.ai-select-item-hint'))
      .toHaveText('Automatically follows Claude Code updates');
    await page.locator('#agents-detail-cli-settings-section .agents-detail-label').click();

    await page.locator('#new-chat-btn').click();
    await sendNewChat(page, `@${agentName} E2E_CLAUDE_MODEL_ALIAS`);
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CLAUDE_MODEL_RESOLVED',
    })).toBeVisible({ timeout: 30_000 });
    expect(cliOrkas.readCliState().invocations.at(-1)).toMatchObject({
      cli: 'claude',
      model: 'sonnet',
    });

    const relaunchedPage = await cliOrkas.relaunch();
    await openSidebarEntry(relaunchedPage, '#agents-btn');
    await relaunchedPage.locator(`.agent-card[data-id="${agentId}"]`).click();
    const relaunchedModel = relaunchedPage.locator(
      '#agents-detail-cli-settings [data-role="model"]',
    );
    await expect(relaunchedModel.locator('.ai-select-trigger'))
      .toContainText('Sonnet · claude-sonnet-4-6', { timeout: 30_000 });

    await selectAiOption(
      relaunchedPage,
      '#agents-detail-cli-settings [data-role="model"]',
      'opus',
    );
    await expect(relaunchedModel).toHaveAttribute('data-value', 'opus');
    await expect(relaunchedModel.locator('.ai-select-trigger')).toContainText('Opus · claude-opus-4-6');
    await expect(relaunchedModel.locator('.ai-select-trigger')).not.toContainText('claude-sonnet-4-6');
  });
});

test.describe('CLI failed-turn recovery', () => {
  // These tests include Electron shutdown/startup plus a real child-process
  // handshake. Loaded CI hosts can spend most of the global 60s default in
  // app lifecycle work even though each product assertion has a tighter
  // bounded wait below.
  test.describe.configure({ timeout: 120_000 });

  for (const fault of ['version_unknown', 'initialize_exit'] as const) {
    test(`Hermes ${fault} remains visible after reopening and recovers once after repair`, async ({ cliOrkas }, testInfo) => {
      const name = 'HermesStartupRecoveryE2E';
      const { page, agentId } = await createCliAgent(cliOrkas, name, 'hermes');
      const agentsBefore = await cliOrkas.invoke<{ agents: Array<{ agent_id: string }> }>('agents.list');
      // Finish any startup version probe before changing its executable's
      // response: force-detect intentionally joins an already running probe.
      expect((await cliOrkas.invoke<any>('localAgents.detect', { type: 'hermes' })).entry.available).toBe(true);
      writeFileSync(cliOrkas.cliStatePath, JSON.stringify({ ...cliOrkas.readCliState(), hermesFault: fault }));
      const detected = await cliOrkas.invoke<any>('localAgents.detect', { type: 'hermes' });
      expect(detected.entry).toMatchObject(fault === 'version_unknown'
        ? { available: false, error: 'version_unknown' }
        : { available: true, version: '99.0.0' });
      const cid = await sendNewChat(page, `@${name} Only reply OK. Do not call tools.`);
      const failureText = fault === 'version_unknown'
        ? 'could not be identified' : 'stopped before completing the task';
      const failedBubble = page.locator('#chat-history .chat-message.assistant');
      await expect(failedBubble).toContainText(failureText, { timeout: 30_000 });
      await expect(failedBubble.locator('.bubble-retry-btn')).toBeVisible();
      await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
      const before = cliOrkas.readCliState();
      expect(before.hermesInitializations || 0).toBe(fault === 'initialize_exit' ? 1 : 0);
      expect(before.nextSession).toBe(0);
      expect(before.invocations).toHaveLength(0);
      const saved = await cliOrkas.invoke<any>('conversations.history', { cid });
      const failures = saved.history.filter((row: any) => row.from === agentId);
      expect(failures).toHaveLength(1);
      expect(failures[0]).toMatchObject({
        failure_kind: fault === 'version_unknown' ? 'dependency' : 'runtime',
        failure_code: fault === 'version_unknown' ? 'version_unknown' : 'cli_failed',
      });
      expect(failures[0].text).toContain(failureText);

      const reopened = await cliOrkas.relaunch();
      await reopened.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
      await expect(reopened.locator('#chat-history .chat-message.assistant')).toContainText(failureText);
      expect(cliOrkas.readCliState().hermesInitializations || 0).toBe(before.hermesInitializations || 0);
      await reopened.screenshot({ path: testInfo.outputPath(`hermes-${fault}-reopened.png`) });
      writeFileSync(cliOrkas.cliStatePath, JSON.stringify({ ...cliOrkas.readCliState(), hermesFault: undefined }));
      const repaired = await cliOrkas.invoke<any>('localAgents.detect', { type: 'hermes' });
      expect(repaired.entry).toMatchObject({ available: true, version: '99.0.0' });
      const retry = reopened.locator('#chat-history .bubble-retry-btn').last();
      await retry.locator('xpath=ancestor::*[contains(@class, "chat-message")]').hover();
      await retry.click();
      await expect(reopened.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
        hasText: 'E2E_HERMES_FIRST_OK',
      })).toHaveCount(1, { timeout: 30_000 });
      await expect(reopened.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
      const after = cliOrkas.readCliState();
      expect(after.hermesInitializations).toBe((before.hermesInitializations || 0) + 1);
      expect(after.nextSession).toBe(1);
      expect(after.invocations).toHaveLength(1);
      expect(after.toolExecutions).toBe(0);
      const history = await cliOrkas.invoke<any>('conversations.history', { cid });
      expect(history.history.filter((row: any) => row.from === agentId && row.text === 'E2E_HERMES_FIRST_OK')).toHaveLength(1);
      const agentsAfter = await cliOrkas.invoke<{ agents: Array<{ agent_id: string }> }>('agents.list');
      expect(agentsAfter.agents.map(agent => agent.agent_id).sort()).toEqual(agentsBefore.agents.map(agent => agent.agent_id).sort());
    });
  }

  test('persists tool-state provenance across app relaunch and resumes the same native session', async ({ cliOrkas }) => {
    const { page } = await createCliAgent(cliOrkas, 'OpenCodeResumeE2E', 'opencode');
    const conversationId = await sendNewChat(page, '@OpenCodeResumeE2E E2E_CLI_RESUME_AFTER_RELAUNCH');

    await expect(page.locator('#chat-history .bubble-retry-btn').last()).toBeVisible({ timeout: 30_000 });
    const beforeRelaunch = cliOrkas.readCliState();
    expect(beforeRelaunch.invocations).toHaveLength(1);
    expect(beforeRelaunch.invocations[0]).toMatchObject({
      cli: 'opencode',
      resumeSessionId: null,
      toolExecuted: true,
    });
    expect(beforeRelaunch.toolExecutions).toBe(1);

    const bindingBefore = JSON.parse(readFileSync(cliSessionFile(cliOrkas, conversationId), 'utf8')) as Record<
      string,
      { sessionId: string; sourceMessageId?: string; terminalStatus?: string }
    >;
    const persisted = Object.values(bindingBefore)[0];
    expect(persisted).toMatchObject({
      sessionId: beforeRelaunch.invocations[0].sessionId,
      terminalStatus: 'failed',
    });
    expect(persisted.sourceMessageId).toBeTruthy();

    const relaunchedPage = await cliOrkas.relaunch();
    const conversation = relaunchedPage.locator(`#conversation-list .conv-item[data-cid="${conversationId}"]`);
    await expect(conversation).toBeVisible();
    await conversation.click();
    const retry = relaunchedPage.locator('#chat-history .bubble-retry-btn').last();
    await expect(retry).toBeVisible();
    await retry.locator('xpath=ancestor::*[contains(@class, "chat-message")]').hover();
    await retry.click();

    await expect(relaunchedPage.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CLI_RESUMED_WITHOUT_DUPLICATE_TOOL',
    })).toBeVisible({ timeout: 30_000 });
    const recovered = cliOrkas.readCliState();
    expect(recovered.invocations).toHaveLength(2);
    expect(recovered.invocations[1].resumeSessionId).toBe(recovered.invocations[0].sessionId);
    expect(recovered.invocations[1].sessionId).toBe(recovered.invocations[0].sessionId);
    expect(recovered.toolExecutions).toBe(1);
  });

  test('drops a stale binding and starts fresh when the failed attempt never established a session', async ({ cliOrkas }) => {
    const { page } = await createCliAgent(cliOrkas, 'OpenCodeRestartE2E', 'opencode');
    const conversationId = await sendNewChat(page, '@OpenCodeRestartE2E E2E_CLI_ESTABLISH_SESSION');
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CLI_SESSION_ESTABLISHED',
    })).toBeVisible({ timeout: 30_000 });

    await sendFollowUp(page, '@OpenCodeRestartE2E E2E_CLI_RESTART_STALE_BINDING');
    const retry = page.locator('#chat-history .bubble-retry-btn').last();
    await expect(retry).toBeVisible({ timeout: 30_000 });
    const failed = cliOrkas.readCliState();
    expect(failed.invocations).toHaveLength(2);
    expect(failed.invocations[1].resumeSessionId).toBe(failed.invocations[0].sessionId);

    await retry.locator('xpath=ancestor::*[contains(@class, "chat-message")]').hover();
    await retry.click();
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CLI_FRESH_RESTART_OK',
    })).toBeVisible({ timeout: 30_000 });

    const restarted = cliOrkas.readCliState();
    expect(restarted.invocations).toHaveLength(3);
    expect(restarted.invocations[2].resumeSessionId).toBeNull();
    expect(restarted.invocations[2].sessionId).not.toBe(restarted.invocations[0].sessionId);
    const bindingAfter = JSON.parse(readFileSync(cliSessionFile(cliOrkas, conversationId), 'utf8')) as Record<
      string,
      { sessionId: string; terminalStatus?: string }
    >;
    expect(Object.values(bindingAfter)[0]).toMatchObject({
      sessionId: restarted.invocations[2].sessionId,
      terminalStatus: 'completed',
    });
  });

  test('Hermes always creates a fresh ACP session and receives bridged visible history', async ({ cliOrkas }, testInfo) => {
    const { page } = await createCliAgent(cliOrkas, 'HermesHistoryE2E', 'hermes');
    const conversationId = await sendNewChat(page, '@HermesHistoryE2E Remember E2E_HERMES_PRIOR_FACT=blue-orbit');
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body', {
      hasText: 'E2E_HERMES_FIRST_OK',
    })).toBeVisible({ timeout: 30_000 });

    await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
    await sendFollowUp(page, '@HermesHistoryE2E E2E_HERMES_CONTINUE and use the prior fact');
    await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
    try {
      await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body', {
        hasText: 'E2E_HERMES_HISTORY_BRIDGED',
      })).toBeVisible({ timeout: 30_000 });
    } finally {
      await testInfo.attach('hermes-display-state', {
        contentType: 'application/json',
        body: Buffer.from(JSON.stringify(await page.evaluate(`({
          pending: pendingConvs.has(currentCid), polling: pollTimers.has(currentCid),
          runtimeBusy: isGroupConversationBusy(currentCid),
          primaryBusy: _convChatCtrls.get(currentCid)?.isBusy?.() || false,
          liveFinals: document.querySelectorAll('#chat-history [data-role="final"]').length,
          assistantRows: document.querySelectorAll('#chat-history .chat-message.assistant').length
        })`))),
      });
      // Observe persistence only after the display assertion, so diagnostics
      // cannot trigger a history reconciliation that masks the original race.
      const persisted = await cliOrkas.invoke<{ history: Array<Record<string, any>> }>(
        'conversations.history', { cid: conversationId, limit: 20 },
      );
      await testInfo.attach('hermes-history-state', {
        contentType: 'application/json',
        body: Buffer.from(JSON.stringify(persisted.history.map(row => ({
          user: row.from === 'user', textChars: String(row.text || '').length,
          expectedReply: row.text === 'E2E_HERMES_HISTORY_BRIDGED',
          systemKind: row.system_kind || '', turnEnd: row.turn_end,
          hasSourceMessageId: !!row.source_message_id, segment: row.seg,
        })))),
      });
    }

    const state = cliOrkas.readCliState();
    const hermesRuns = state.invocations.filter((item) => item.cli === 'hermes');
    expect(hermesRuns).toHaveLength(2);
    expect(hermesRuns[0].sessionId).not.toBe(hermesRuns[1].sessionId);
    expect(hermesRuns.every((item) => item.resumeSessionId === null)).toBe(true);
    expect(hermesRuns.every((item) => item.args.join(' ') === 'acp')).toBe(true);
    expect(hermesRuns.every((item) => !item.prompt.includes('## Sexual safety boundary'))).toBe(true);
    expect(hermesRuns[1].prompt).toContain('E2E_HERMES_PRIOR_FACT');
    expect(existsSync(cliSessionFile(cliOrkas, conversationId))).toBe(false);
  });

  test('sends production-bounded long history through the real Hermes child-process boundary', async ({ cliOrkas }) => {
    const agentName = 'HermesBoundedHistoryE2E';
    const { page } = await createCliAgent(cliOrkas, agentName, 'hermes');
    const conversationId = await sendNewChat(
      page,
      `@${agentName} E2E_HERMES_LIMITS_BOOTSTRAP`,
    );
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_HERMES_FIRST_OK',
    })).toBeVisible({ timeout: 30_000 });

    const rows = Array.from({ length: 25 }, (_, index) => {
      const turn = index + 1;
      const id = String(turn).padStart(2, '0');
      const userText = turn === 25
        ? `E2E_HISTORY_NEWEST_FACT=violet-orbit\n${'界'.repeat(6_000)}`
        : `E2E_HISTORY_OLD_${id} ${'x'.repeat(900)}`;
      return [
        {
          id: `e2e-history-user-${id}`,
          ts: `2026-08-05T02:${id}:00.000Z`,
          from: 'user',
          to: ['commander'],
          text: userText,
        },
        {
          id: `e2e-history-commander-${id}`,
          ts: `2026-08-05T02:${id}:01.000Z`,
          from: 'commander',
          to: ['user'],
          text: `E2E_HISTORY_REPLY_${id} ${'y'.repeat(400)}`,
        },
      ];
    }).flat();
    appendCanonicalMessages(cliOrkas, conversationId, rows);

    await sendFollowUp(page, `@${agentName} E2E_HERMES_LIMITS_CURRENT_TASK`);
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_HERMES_LIMITS_OK',
    })).toBeVisible({ timeout: 30_000 });

    const hermesRuns = cliOrkas.readCliState().invocations.filter((item) => item.cli === 'hermes');
    expect(hermesRuns).toHaveLength(2);
    const prompt = hermesRuns[1].prompt;
    const historyStart = prompt.indexOf('## Conversation context recovered by Orkas');
    const taskStart = prompt.lastIndexOf('E2E_HERMES_LIMITS_CURRENT_TASK');
    expect(historyStart).toBeGreaterThanOrEqual(0);
    expect(taskStart).toBeGreaterThan(historyStart);
    const historyBlock = prompt.slice(historyStart, taskStart).trim();
    expect(estimateBudgetTokens(historyBlock)).toBeLessThanOrEqual(30_000);
    expect((historyBlock.match(/^### Turn /gm) || []).length).toBeLessThanOrEqual(5);
    expect(historyBlock).toContain('E2E_HISTORY_NEWEST_FACT=violet-orbit');
    // The newest message fits the token window and must survive intact.
    expect(historyBlock).toContain('界'.repeat(6_000));
    expect(historyBlock).toMatch(/older turns? omitted/);
    expect(historyBlock).not.toContain('E2E_HISTORY_OLD_01');
    expect(prompt).toContain('E2E_HERMES_LIMITS_CURRENT_TASK');
  });

  test('sends only the post-reply canonical delta through a resumed Codex child process', async ({ cliOrkas }) => {
    const agentName = 'CodexCanonicalDeltaE2E';
    const { page } = await createCliAgent(cliOrkas, agentName, 'codex');
    const conversationId = await sendNewChat(
      page,
      `@${agentName} E2E_CODEX_CONTEXT_FIRST_TASK`,
    );
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CODEX_DEFAULT_OK',
    })).toBeVisible({ timeout: 30_000 });

    // The rendered final can become visible just before the canonical JSONL
    // append completes. Wait for that durable boundary before simulating rows
    // written by another participant, or the late first-turn write can race
    // with and replace the fixture rows.
    await expect.poll(async () => {
      const result = await cliOrkas.invoke<{ history: Array<Record<string, unknown>> }>(
        'conversations.history',
        { cid: conversationId, limit: 20 },
      );
      return JSON.stringify(result.history).includes('E2E_CODEX_DEFAULT_OK');
    }, { timeout: 30_000 }).toBe(true);

    appendCanonicalMessages(cliOrkas, conversationId, [
      {
        id: 'e2e-codex-delta-user',
        ts: '2026-08-05T03:00:00.000Z',
        from: 'user',
        to: ['commander'],
        text: 'E2E_CODEX_INTERPOSED_USER_FACT=amber-field',
      },
      {
        id: 'e2e-codex-delta-commander',
        ts: '2026-08-05T03:00:01.000Z',
        from: 'commander',
        to: ['user'],
        text: 'E2E_CODEX_INTERPOSED_COMMANDER_FACT=blue-river',
      },
    ]);
    await expect.poll(async () => {
      const result = await cliOrkas.invoke<{ history: Array<Record<string, unknown>> }>(
        'conversations.history',
        { cid: conversationId, limit: 20 },
      );
      return JSON.stringify(result.history);
    }).toContain('E2E_CODEX_INTERPOSED_COMMANDER_FACT=blue-river');

    await sendFollowUp(page, `@${agentName} E2E_CODEX_CONTEXT_SECOND_TASK`);
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CODEX_DEFAULT_OK',
    })).toHaveCount(2, { timeout: 30_000 });

    const codexRuns = cliOrkas.readCliState().invocations.filter((item) => item.cli === 'codex');
    expect(codexRuns).toHaveLength(2);
    expect(codexRuns[1].resumeSessionId).toBe(codexRuns[0].sessionId);
    expect(codexRuns[1].prompt).toContain('## Conversation updates since the previous CLI turn');
    expect(codexRuns[1].prompt).toContain('E2E_CODEX_INTERPOSED_USER_FACT=amber-field');
    expect(codexRuns[1].prompt).toContain('E2E_CODEX_INTERPOSED_COMMANDER_FACT=blue-river');
    expect(codexRuns[1].prompt).toContain('E2E_CODEX_CONTEXT_SECOND_TASK');
    expect(codexRuns[1].prompt).not.toContain('E2E_CODEX_CONTEXT_FIRST_TASK');
    expect(codexRuns[1].prompt).not.toContain('E2E_CODEX_DEFAULT_OK');
  });

  test('continues a hung Codex resume in a fresh process with canonical recovery context and saves its replacement session', async ({ cliOrkas }, testInfo) => {
    const agentName = 'CodexBootstrapRecoveryE2E';
    const { page, agentId } = await createCliAgent(cliOrkas, agentName, 'codex');
    const cid = await sendNewChat(page, `@${agentName} Earlier requirement: use amber-field.`);
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CODEX_DEFAULT_OK',
    })).toHaveCount(1, { timeout: 30_000 });
    await expect.poll(() => {
      try { return JSON.parse(readFileSync(cliSessionFile(cliOrkas, cid), 'utf8'))[agentId]?.sessionId; }
      catch { return null; }
    }).toBe(cliOrkas.readCliState().invocations[0].sessionId);
    writeFileSync(cliOrkas.cliStatePath, JSON.stringify({ ...cliOrkas.readCliState(), codexResumeHangs: 1 }));
    await cliOrkas.electronApp!.evaluate(() => { process.env.ORKAS_CODEX_BOOTSTRAP_TIMEOUT_MS = '1500'; });
    await sendFollowUp(page, `@${agentName} Continue the earlier requirement.`);
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CODEX_DEFAULT_OK',
    })).toHaveCount(2, { timeout: 30_000 });
    await expect(page.locator('#chat-history .bubble-retry-btn')).toHaveCount(0);
    const state = cliOrkas.readCliState();
    const runs = state.invocations.filter(run => run.cli === 'codex');
    expect(runs).toHaveLength(2); // The hung child never received the task.
    expect(state.codexThreadRequests?.map(request => request.method)).toEqual(['thread/start', 'thread/resume', 'thread/start']);
    expect(state.codexThreadRequests?.[1].pid).not.toBe(state.codexThreadRequests?.[2].pid);
    expect(runs[1].resumeSessionId).toBeNull();
    expect(runs[1].sessionId).not.toBe(runs[0].sessionId);
    expect(runs[1].prompt).toContain('Earlier requirement: use amber-field.');
    expect(runs[1].prompt).toContain('Continue the earlier requirement.');
    await expect.poll(() => JSON.parse(readFileSync(cliSessionFile(cliOrkas, cid), 'utf8'))[agentId]?.sessionId)
      .toBe(runs[1].sessionId);
    await expect.poll(async () => JSON.stringify((await cliOrkas.invoke<{ history: unknown[] }>('conversations.history', { cid, limit: 20 })).history))
      .toContain('cli-bootstrap-timeout');
    await page.screenshot({ path: testInfo.outputPath('codex-bootstrap-recovered.png'), fullPage: true });
    await sendFollowUp(page, `@${agentName} Check the saved requirement.`);
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CODEX_DEFAULT_OK',
    })).toHaveCount(3, { timeout: 30_000 });
    expect(cliOrkas.readCliState().invocations[2].resumeSessionId).toBe(runs[1].sessionId);
  });

  test('steers a composer update into the active Codex App Server turn without starting another CLI run', async ({ cliOrkas }) => {
    // Queue absorption retired the local queue rows and their per-row "Send
    // now": steering the live turn is the composer steer button, visible only
    // while the composer's single target has a steerable running turn.
    const agentName = 'CodexSendNowE2E';
    const { page } = await createCliAgent(cliOrkas, agentName, 'codex');
    await sendNewChat(page, `@${agentName} E2E_CODEX_SEND_NOW_ACTIVE`);
    await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);

    const input = page.locator('#chat-input');
    await input.fill('E2E_CODEX_SEND_NOW_UPDATE');
    await input.press('Enter');
    // The busy send parks as a queued board row; its Send now action folds
    // it into the live Codex App Server turn (composer shortcut removed).
    const queuedRow = page.locator('#chat-task-board-list .chat-queue-item', {
      hasText: 'E2E_CODEX_SEND_NOW_UPDATE',
    });
    await expect(queuedRow.locator('[data-act="task-send-now"]')).toBeVisible({ timeout: 10_000 });
    await queuedRow.locator('[data-act="task-send-now"]').click();

    await expect(page.locator('#chat-history .chat-message.user', {
      hasText: 'E2E_CODEX_SEND_NOW_UPDATE',
    })).toBeVisible();
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CODEX_STEER_APPLIED',
    })).toBeVisible({ timeout: 30_000 });

    const state = cliOrkas.readCliState();
    const codexRuns = state.invocations.filter((item) => item.cli === 'codex');
    expect(codexRuns).toHaveLength(1);
    expect(codexRuns[0].steers).toHaveLength(1);
    expect(codexRuns[0].steers?.[0].text).toContain('E2E_CODEX_SEND_NOW_UPDATE');
  });

  test.describe('native question history', () => {

    test('stops a running CLI from the composer, withdraws its question and remains usable after reload', async ({ cliOrkas }, testInfo) => {
      const name = 'CodexStopRecovery';
      const { page, agentId } = await createCliAgent(cliOrkas, name, 'codex');
      const cid = await sendNewChat(page, `@${name} E2E_CODEX_SEND_NOW_ACTIVE E2E_CODEX_ASYNC_QUESTION`);
      const question = page.locator('#chat-cli-questions');
      await expect(question.getByRole('button', { name: 'Send answer', exact: true })).toBeVisible();
      const childPid = cliOrkas.readCliState().codexThreadRequests?.at(-1)?.pid;
      if (!childPid) throw new Error('The running CLI process was not recorded');
      expect(() => process.kill(childPid, 0)).not.toThrow();
      const stop = page.locator('#chat-send-btn');
      await expect(stop).toHaveClass(/\bstreaming\b/);
      await stop.click();
      await expect(question).toBeHidden();
      await expect(stop).not.toHaveClass(/\b(streaming|aborting)\b/, { timeout: 15_000 });
      await expect(stop).toBeEnabled();
      await expect.poll(() => {
        try { process.kill(childPid, 0); return false; }
        catch (error) {
          if ((error as NodeJS.ErrnoException).code === 'ESRCH') return true;
          throw error;
        }
      }, { timeout: 15_000 }).toBe(true);
      await expect.poll(() => {
        try { return JSON.parse(readFileSync(cliSessionFile(cliOrkas, cid), 'utf8'))[agentId]?.terminalStatus; }
        catch { return null; }
      }).toBe('cancelled');
      expect(cliOrkas.readCliState().invocations).toHaveLength(1);
      expect(cliOrkas.readCliState().invocations[0].questionAnswers).toBeUndefined();

      await Promise.all([
        page.waitForEvent('domcontentloaded'),
        cliOrkas.electronApp!.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].webContents.reload()),
      ]);
      await page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
      await expect(question).toBeHidden();
      await expect(stop).not.toHaveClass(/\b(streaming|aborting)\b/);
      await sendFollowUp(page, `@${name} E2E_CODEX_AFTER_STOP`);
      await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
        hasText: 'E2E_CODEX_DEFAULT_OK',
      })).toBeVisible({ timeout: 30_000 });
      expect(cliOrkas.readCliState().invocations).toHaveLength(2);
      expect(cliOrkas.readCliState().invocations[1].prompt.trimEnd()).toMatch(/E2E_CODEX_AFTER_STOP$/);
      await expect.poll(() => JSON.parse(readFileSync(cliSessionFile(cliOrkas, cid), 'utf8'))[agentId]?.terminalStatus)
        .toBe('completed');
      await page.screenshot({ path: testInfo.outputPath('cli-stop-recovered.png'), fullPage: true });
    });
    for (const cli of ['claude', 'codex'] as const) {
      test(`shows a native ${cli} answer once in the conversation and retains it after reload`, async ({ cliOrkas }, testInfo) => {
        const name = cli === 'claude' ? 'ClaudeQuestionHistory' : 'CodexQuestionHistory';
        const { page } = await createCliAgent(cliOrkas, name, cli);
        const cid = await sendNewChat(page, `@${name} E2E_CLI_NATIVE_QUESTION`);
        const card = page.locator('#chat-cli-questions');
        await expect(card.getByRole('textbox', { name: 'Which scope?' })).toBeVisible({ timeout: 30_000 });
        await card.getByRole('button', { name: 'Current', exact: true }).click();
        await card.getByRole('button', { name: 'Send answer', exact: true }).click();
        await expect(card).toBeHidden();
        const answer = page.locator('#chat-history .chat-message.user', { hasText: 'Which scope?' });
        await expect(answer).toHaveCount(1);
        await expect(answer).toContainText('Current');
        await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
          hasText: 'E2E_CLI_QUESTION_CONTINUED',
        })).toBeVisible({ timeout: 30_000 });
        const history = await cliOrkas.invoke<{ history: Array<{ from: string; text: string }> }>('conversations.history', { cid, limit: 20 });
        expect(history.history.filter(row => row.from === 'user' && row.text === 'Which scope?\nCurrent')).toHaveLength(1);
        await page.screenshot({ path: testInfo.outputPath('native-question-answer.png'), fullPage: true });
        await Promise.all([
          page.waitForEvent('domcontentloaded'),
          cliOrkas.electronApp!.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].webContents.reload()),
        ]);
        await page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
        await expect(answer).toHaveCount(1);
        await expect(answer).toContainText('Current');
        await expect(card).toBeHidden();
        const runs = cliOrkas.readCliState().invocations.filter(item => item.cli === cli);
        expect(runs).toHaveLength(1);
        expect(runs[0].questionAnswers).toEqual(cli === 'claude'
          ? { 'Which scope?': 'Current' } : { scope: { answers: ['Current'] } });
      });
    }
  });

  test('cancels a live Codex question without an answer and keeps it dismissed after switching and reload', async ({ cliOrkas }) => {
    const { page } = await createCliAgent(cliOrkas, 'CancelQuestionCodex', 'codex');
    const cid = await sendNewChat(page, '@CancelQuestionCodex E2E_CODEX_SEND_NOW_ACTIVE E2E_CODEX_ASYNC_QUESTION');
    try {
      const card = page.locator('#chat-cli-questions');
      await expect(card.getByRole('button', { name: 'Send answer', exact: true })).toBeDisabled();
      await card.getByRole('button', { name: 'Cancel', exact: true }).click();
      await expect(card).toBeHidden();
      await expect.poll(async () => {
        const result = await cliOrkas.invoke<{ history: Array<{ cli_question?: { cancelled?: boolean } }> }>('conversations.history', { cid, limit: 20 });
        return result.history.some(row => row.cli_question?.cancelled === true);
      }).toBe(true);
      await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
      await page.locator('#new-chat-btn').click();
      await page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
      await expect(card).toBeHidden();
      await Promise.all([
        page.waitForEvent('domcontentloaded'),
        cliOrkas.electronApp!.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].webContents.reload()),
      ]);
      await page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
      await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
      await expect(card).toBeHidden();
      const history = await cliOrkas.invoke<{ history: Array<{ from: string; cli_answer?: unknown }> }>('conversations.history', { cid, limit: 20 });
      expect(history.history.filter(row => row.from === 'user')).toHaveLength(1);
      expect(history.history.some(row => row.cli_answer)).toBe(false);
      const runs = cliOrkas.readCliState().invocations.filter(item => item.cli === 'codex');
      expect(runs).toHaveLength(1);
      expect(runs[0].steers).toHaveLength(0);
    } finally {
      await cliOrkas.invoke('groupChat.abort', { cid });
    }
  });

  test('offers no steer for an unsupported one-shot CLI and runs the busy send as the next native turn', async ({ cliOrkas }) => {
    // OpenCode's one-shot adapter has no active-turn ingress: the steer
    // button must never appear, and a message sent while the turn runs goes
    // to the backend board, waiting for the same-agent serial rule to admit
    // it as the next native turn.
    const agentName = 'OpenCodeSendNowE2E';
    const { page } = await createCliAgent(cliOrkas, agentName, 'opencode');
    await sendNewChat(page, `@${agentName} E2E_CLI_SEND_NOW_ACTIVE`);
    await expect.poll(() => cliOrkas.readCliState().invocations.length, { timeout: 30_000 }).toBe(1);
    await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);

    const input = page.locator('#chat-input');
    await input.fill('E2E_CLI_SEND_NOW_FOLLOWUP');
    await input.press('Enter');

    // The busy send parks as a queued board task behind the running one; its
    // bubble waits for execution (queued-until-execution, 2026-08-27), and a
    // one-shot CLI has no live-turn ingress so the row offers no Send now.
    await expect(page.locator('#chat-task-board-list .chat-queue-item')).toHaveCount(2);
    await expect(page.locator('#chat-task-board-list [data-act="task-send-now"]')).toHaveCount(0);
    const users = page.locator('#chat-history .chat-message.user');
    await expect(users).toHaveCount(1);
    await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
    // Same-agent serial: no second CLI child starts while the first runs.
    expect(cliOrkas.readCliState().invocations).toHaveLength(1);

    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CLI_SEND_NOW_ACTIVE_OK',
    })).toBeVisible({ timeout: 30_000 });
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
      hasText: 'E2E_CLI_SEND_NOW_FOLLOWUP_OK',
    })).toBeVisible({ timeout: 30_000 });

    await expect(users).toHaveCount(2);
    await expect(users.nth(1)).toContainText('E2E_CLI_SEND_NOW_FOLLOWUP');

    const state = cliOrkas.readCliState();
    expect(state.invocations).toHaveLength(2);
    expect(state.invocations[1]).toMatchObject({
      cli: 'opencode',
      resumeSessionId: state.invocations[0].sessionId,
      sessionId: state.invocations[0].sessionId,
    });
    expect(state.invocations[1].prompt).toContain('E2E_CLI_SEND_NOW_FOLLOWUP');
  });
});