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.

48.2 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as vm from 'node:vm';

/**
 * Pure decision logic of the renderer task board (task-board.js):
 * which rows render, in what order, and when the bar surfaces at all.
 *
 * Scenario value: the board must lead with actually-running work, retain only
 * the current batch's useful terminal context, and stay invisible for an
 * ordinary single running/waiting turn. Lone queued/blocked rows remain as
 * task-trace and recovery surfaces (plan conversation-task-board.md §3/§4.9).
 */

const source = fs.readFileSync(
  path.join(__dirname, '../../src/renderer/modules/task-board.js'),
  'utf8',
);

function extractFunction(name: string): string {
  const marker = `function ${name}`;
  const start = source.indexOf(marker);
  if (start < 0) throw new Error(`missing ${name}`);
  const braceStart = source.indexOf('{', start);
  if (braceStart < 0) throw new Error(`missing body for ${name}`);
  let depth = 0;
  for (let i = braceStart; i < source.length; i += 1) {
    const ch = source[i];
    if (ch === '{') depth += 1;
    else if (ch === '}') {
      depth -= 1;
      if (depth === 0) return source.slice(start, i + 1);
    }
  }
  throw new Error(`unterminated ${name}`);
}

function runLiveRows(tasks: unknown): any[] {
  return vm.runInNewContext(
    `${extractFunction('_taskBoardLiveRows')}; _taskBoardLiveRows(${JSON.stringify(tasks)});`,
    {},
  );
}

function runVisibility(liveRows: unknown): { visible: boolean } {
  return vm.runInNewContext(
    `${extractFunction('_taskBoardVisibility')}; _taskBoardVisibility(${JSON.stringify(liveRows)});`,
    {},
  );
}

/** Run the real renderer against an inert panel/list pair. */
function boardHarness() {
  const list: any = { dataset: {}, style: {}, innerHTML: '', querySelectorAll: () => [], addEventListener() {} };
  const panel: any = { style: {}, querySelector: () => null, addEventListener() {} };
  const context: any = {
    console, Map, Set, Array, String, Object, JSON, Date, setTimeout, clearTimeout,
    document: {
      addEventListener() {},
      getElementById: (id: string) => (id === 'chat-task-board' ? panel : id === 'chat-task-board-list' ? list : null),
    },
    window: {}, currentCid: 'c1',
    t: (key: string, params?: Record<string, unknown>) => (params && 'name' in params ? `${key}:${params.name}` : key),
    escapeHtml: (value: unknown) => String(value ?? ''),
    uiIconHtml: () => '',
  };
  vm.createContext(context);
  vm.runInContext(source, context, { filename: 'task-board.js' });
  return { context, panel, list, board: context.window.TaskBoard };
}

function renderBoardRows(tasks: Array<Record<string, unknown>>): string {
  const { context, list } = boardHarness();
  context.__tasks = tasks;
  vm.runInContext("for (const task of __tasks) _taskBoardMapFor('c1').set(task.task_id, task);", context);
  context._taskBoardRender('c1');
  return list.innerHTML;
}

function runStatusLabel(status: string, labels: Record<string, string>): string {
  return vm.runInNewContext(
    `${extractFunction('_taskBoardStatusLabel')}; _taskBoardStatusLabel(${JSON.stringify(status)});`,
    { t: (key: string) => labels[key] || key },
  );
}

describe('renderer task board › live rows', () => {
  it('filters terminal rows and orders running > waiting_input > blocked > queued', () => {
    const rows = runLiveRows([
      { task_id: 'q1', status: 'queued', created_at: '2026-01-01T00:00:01Z' },
      { task_id: 'd1', status: 'done', created_at: '2026-01-01T00:00:00Z' },
      { task_id: 'r1', status: 'running', created_at: '2026-01-01T00:00:05Z' },
      { task_id: 'c1', status: 'cancelled', created_at: '2026-01-01T00:00:00Z' },
      { task_id: 'w1', status: 'waiting_input', created_at: '2026-01-01T00:00:02Z' },
      { task_id: 'b1', status: 'blocked', created_at: '2026-01-01T00:00:03Z' },
      { task_id: 'f1', status: 'failed', created_at: '2026-01-01T00:00:00Z' },
    ]);
    expect(rows.map((r) => r.task_id)).toEqual(['r1', 'w1', 'b1', 'q1']);
  });

  it('orders same-status rows by creation time so the queue reads top-down', () => {
    const rows = runLiveRows([
      { task_id: 'q-late', status: 'queued', created_at: '2026-01-01T00:00:09Z' },
      { task_id: 'q-early', status: 'queued', created_at: '2026-01-01T00:00:01Z' },
    ]);
    expect(rows.map((r) => r.task_id)).toEqual(['q-early', 'q-late']);
  });

  it('orders queued rows by their explicit scan position before creation time (P4 reorder)', () => {
    // Events can deliver rewritten `order` values in any arrival order; the
    // panel must show the real admission scan order or the user reorders
    // against a lie. Legacy rows without `order` fall back behind ordered
    // ones only via creation time among themselves.
    const rows = runLiveRows([
      { task_id: 'q-old-first', status: 'queued', order: 3, created_at: '2026-01-01T00:00:01Z' },
      { task_id: 'q-moved-up', status: 'queued', order: 1, created_at: '2026-01-01T00:00:09Z' },
      { task_id: 'q-middle', status: 'queued', order: 2, created_at: '2026-01-01T00:00:05Z' },
      { task_id: 'r1', status: 'running', created_at: '2026-01-01T00:00:00Z' },
    ]);
    expect(rows.map((r) => r.task_id)).toEqual(['r1', 'q-moved-up', 'q-middle', 'q-old-first']);
  });

  it('drops rows with unknown status instead of rendering them', () => {
    const rows = runLiveRows([
      { task_id: 'x', status: 'sprinting', created_at: 't' },
      { task_id: 'r', status: 'running', created_at: 't' },
    ]);
    expect(rows.map((r) => r.task_id)).toEqual(['r']);
  });

  it('does not render a queue task absorbed into an existing live turn as a second execution', () => {
    const rows = runLiveRows([
      { task_id: 'primary', status: 'running', created_at: 't1' },
      {
        task_id: 'absorbed', status: 'running', created_at: 't2',
        absorbed_into_turn_id: 'live-turn',
      },
    ]);
    expect(rows.map((r) => r.task_id)).toEqual(['primary']);
  });
});
describe('renderer task board › Send now eligibility', () => {
  function canSend(task: unknown, activeTurns: unknown[]): boolean {
    return vm.runInNewContext(
      `const _latestActiveTurns = new Map([['c1', ${JSON.stringify(activeTurns)}]]);
       ${extractFunction('_taskBoardDeps')};
       ${extractFunction('_taskBoardCanSendNow')};
       _taskBoardCanSendNow('c1', ${JSON.stringify(task)});`,
      { Map },
    );
  }

  it('offers Send now only for a user queued task with matching steerable live actor', () => {
    const task = { task_id: 'q1', status: 'queued', created_by: 'user', assignee: 'agentA' };
    expect(canSend(task, [{ actor: 'agentA', steerable: true }])).toBe(true);
    expect(canSend(task, [{ actor: 'agentB', steerable: true }])).toBe(false);
    expect(canSend(task, [{ actor: 'agentA', steerable: false }])).toBe(false);
    expect(canSend({ ...task, created_by: 'commander' }, [{ actor: 'agentA', steerable: true }])).toBe(false);
    expect(canSend({ ...task, status: 'running' }, [{ actor: 'agentA', steerable: true }])).toBe(false);
    // A dependent row keeps its start order (§4.8) — folding would jump it,
    // whether the snapshot carries a legacy single id or a D29 list.
    expect(canSend({ ...task, after: 't0' }, [{ actor: 'agentA', steerable: true }])).toBe(false);
    expect(canSend({ ...task, after: ['t0', 't1'] }, [{ actor: 'agentA', steerable: true }])).toBe(false);
    expect(canSend({ ...task, after: [] }, [{ actor: 'agentA', steerable: true }])).toBe(true);
  });

  it('wires the eligible row action to the backend task promotion endpoint', () => {
    const index = fs.readFileSync(path.join(__dirname, '../../src/renderer/index.html'), 'utf8');
    expect(index).not.toContain('id="chat-steer-btn"');
    expect(source).toContain('data-act="task-send-now"');
    expect(source).toContain('/tasks/send-now`');
    expect(source).toContain("'chat.queue_send_now'");
  });

  it('shows Send now on a user correction while the same Agent runs a Commander-dispatched task', () => {
    const { context, list, board } = boardHarness();
    context._latestActiveTurns = new Map([['c1', [{ actor: 'agentA', steerable: true }]]]);
    board.onEvent('c1', { task: { task_id: 'child', assignee: 'agentA', created_by: 'commander',
      status: 'running', instruction: 'Implement the feature.' } });
    board.onEvent('c1', { task: { task_id: 'correction', assignee: 'agentA', created_by: 'user',
      status: 'queued', instruction: 'Discuss the plan first.' } });
    const queuedRow = list.innerHTML.split('data-task-id="correction"')[1];
    expect(queuedRow).toContain('data-act="task-send-now"');
    expect(queuedRow).toContain('data-act="task-edit"');
    expect(queuedRow).toContain('data-act="task-cancel"');
    expect(list.innerHTML.match(/data-act="task-send-now"/g)).toHaveLength(1);
  });

  it('finishes sending on persistence without waiting for model acceptance, and restores failed sends', async () => {
    const sendNow = `async ${extractFunction('_taskBoardSendNow')}`;
    const run = async (result: any) => {
      const sending = new Set<string>();
      const renders: string[] = [];
      const alerts: string[] = [];
      const task = { task_id: 'q1', status: 'queued' };
      const messages: unknown[] = [];
      await vm.runInNewContext(
        `${sendNow}; _taskBoardSendNow('c1', 'q1');`,
        {
          _taskBoardSendingNow: sending,
          _taskBoardRender: (cid: string) => renders.push(cid),
          _taskBoardOnEvent: (_cid: string, event: any) => Object.assign(task, event.task),
          _renderOrClaimPersistedUserMessage: (_cid: string, message: any) => messages.push(message),
          apiFetch: async () => ({ status: 409, json: async () => result }),
          t: (_key: string, params: any) => `failed: ${params?.msg || ''}`,
          uiAlert: (message: string) => alerts.push(message),
          encodeURIComponent,
        },
      );
      const draggable = vm.runInNewContext(
        `${extractFunction('_taskBoardCanDrag')}; _taskBoardCanDrag('c1', 'q1');`,
        {
          _taskBoardMapFor: () => new Map([['q1', task]]),
          _taskBoardSendingNow: sending,
        },
      );
      return { sending, renders, alerts, draggable, messages };
    };

    const message = { id: 'm1', from: 'user', text: 'Correction' };
    const accepted = await run({ ok: true, turn_id: 'live-turn', message,
      task: { task_id: 'q1', status: 'queued', message_sent_at: '2026-10-21T12:00:00Z' } });
    expect([...accepted.sending]).toEqual([]);
    expect(accepted.renders).toEqual(['c1', 'c1']);
    expect(accepted.messages).toEqual([message]);
    expect(accepted.alerts).toEqual([]);
    expect(accepted.draggable).toBe(false);

    const rejected = await run({ ok: false, error: 'turn_not_steerable' });
    expect([...rejected.sending]).toEqual([]);
    expect(rejected.renders).toEqual(['c1', 'c1']);
    expect(rejected.alerts).toEqual(['failed: turn_not_steerable']);
    expect(rejected.draggable).toBe(true);
    expect(rejected.messages).toEqual([]);
  });

  it('hides sent queue rows across stale events and resync while retaining fallback execution', () => {
    const { context, list, panel, board } = boardHarness();
    const queued = { task_id: 'q1', assignee: 'agentA', created_by: 'user', status: 'queued', instruction: 'Correction' };
    const sent = { ...queued, message_sent_at: '2026-10-21T12:00:00Z' };
    board.onEvent('c1', { task: queued });
    expect(list.innerHTML).toContain('Correction');
    board.onEvent('c1', { task: sent });
    expect(panel.style.display).toBe('none');
    board.onEvent('c1', { task: queued });
    expect(panel.style.display).toBe('none');
    context.__sent = sent;
    vm.runInContext("_taskBoardTasks.clear(); _taskBoardMergeSeedRows(_taskBoardMapFor('c1'), [__sent]); _taskBoardRender('c1');", context);
    expect(panel.style.display).toBe('none');
    // A FIFO fallback is still a real execution; sending never claims absorption.
    expect(runLiveRows([{ ...sent, status: 'running' }])).toHaveLength(1);
  });
});

describe('renderer task board › assignee label', () => {
  function runLabel(task: unknown, memberNames: Array<[string, string]>, allAgents: unknown[] = []): string {
    return vm.runInNewContext(
      `${extractFunction('_taskBoardAssigneeLabel')}; _taskBoardAssigneeLabel('c1', ${JSON.stringify(task)});`,
      {
        _taskBoardMemberNames: new Map([['c1', new Map(memberNames)]]),
        _taskBoardAllAgents: allAgents,
        t: (k: string) => k,
      },
    );
  }

  it('uses the member or Agent catalog name, with stable commander and raw-id fallbacks', () => {
    const agents = [{ id: 'agent02', name: 'Agent Two' }];
    expect(runLabel({ assignee: 'agent01' }, [['agent01', 'Agent One']])).toBe('Agent One');
    expect(runLabel({ assignee: 'agent02' }, [], agents)).toBe('Agent Two');
    expect(runLabel({ assignee: 'ghost01' }, [])).toBe('ghost01');
    expect(runLabel({ assignee: 'commander' }, [])).toBe('chat.recipient_commander');
  });

  it('keeps queued assignment and dependency read-only after admission', () => {
    // Assignment/order choices belong to the composer before send. The board
    // must still explain a dependency without wiring mutation controls.
    const html = renderBoardRows([
      { task_id: 'run1', status: 'running', assignee: 'agentA', instruction: 'first', created_at: '2026-01-01T00:00:00Z' },
      { task_id: 'q1', status: 'queued', assignee: 'agentB', instruction: 'second', after: 'run1', created_at: '2026-01-01T00:00:01Z' },
    ]);
    expect(html).toContain('data-task-id="q1"');
    expect(html).toContain('chat.task_waiting_on:agentA');
    // The row keeps its legitimate control, so the absence below is not vacuous.
    expect(html).toContain('data-act="task-cancel"');
    expect(html).not.toMatch(/data-act="task-(reassign|after)"/);
    expect(html).not.toMatch(/<select|<input|contenteditable/);
  });

  it('names every unfinished predecessor of a multi-dependency row and drops finished ones (D29)', () => {
    const html = renderBoardRows([
      { task_id: 'a1', status: 'running', assignee: 'agentA', instruction: 'draft A', created_at: '2026-01-01T00:00:00Z' },
      { task_id: 'b1', status: 'done', assignee: 'agentB', instruction: 'draft B', created_at: '2026-01-01T00:00:01Z' },
      { task_id: 'c1', status: 'running', assignee: 'agentC', instruction: 'draft C', created_at: '2026-01-01T00:00:02Z' },
      { task_id: 'merge', status: 'queued', assignee: 'agentD', instruction: 'merge drafts', after: ['a1', 'b1', 'c1'], created_at: '2026-01-01T00:00:03Z' },
    ]);
    expect(html).toContain('chat.task_waiting_on:agentA and agentC');
    expect(html).not.toContain('agentB and');
  });
});

describe('renderer task board › agent groups and queued drag order', () => {
  // Grouping is by recipient, including dispatched work. Each agent retains
  // its visible status/scan order without stealing another agent's rows.
  it('groups interleaved work by agent id, preserving every row and its per-agent order', () => {
    const tasks = [
      { task_id: 'cmd', assignee: 'commander', status: 'running' },
      { task_id: 'a-run', assignee: 'a', status: 'running', parent_task_id: 'cmd' },
      { task_id: 'b-run', assignee: 'b', status: 'running' },
      { task_id: 'a-next', assignee: 'a', status: 'queued', parent_task_id: 'gone' },
      { task_id: 'b-next', assignee: 'b', status: 'queued' },
      { task_id: 'cmd-next', assignee: 'commander', status: 'queued' },
    ];
    const groups = vm.runInNewContext(
      `${extractFunction('_taskBoardAgentGroups')}; _taskBoardAgentGroups(${JSON.stringify(tasks)});`,
      {},
    );
    expect(groups.map((group: any) => [group.assignee, group.tasks.map((task: any) => task.task_id)]))
      .toEqual([
        ['commander', ['cmd', 'cmd-next']],
        ['a', ['a-run', 'a-next']],
        ['b', ['b-run', 'b-next']],
      ]);
  });

  const tasks = [
    { task_id: 'a-run', assignee: 'a', status: 'running' },
    { task_id: 'a1', assignee: 'a', status: 'queued', order: 1 },
    { task_id: 'b1', assignee: 'b', status: 'queued', order: 2 },
    { task_id: 'a2', assignee: 'a', status: 'queued', order: 3 },
    { task_id: 'a3', assignee: 'a', status: 'queued', order: 4 },
    { task_id: 'a-blocked', assignee: 'a', status: 'blocked' },
    { task_id: 'a-cancelled', assignee: 'a', status: 'cancelled' },
    { task_id: 'absorbed', assignee: 'a', status: 'queued', absorbed_into_turn_id: 'live' },
  ];
  function drop(sourceId: string, targetId: string, after: boolean, rows: unknown = tasks) {
    return vm.runInNewContext(
      `${extractFunction('_taskBoardLiveRows')};
       ${extractFunction('_taskBoardDropOrder')};
       _taskBoardDropOrder(${JSON.stringify(rows)}, ${JSON.stringify(sourceId)}, ${JSON.stringify(targetId)}, ${after});`,
      {},
    );
  }

  it('supports dropping before, between, and after queued peers in either direction', () => {
    expect(drop('a3', 'a1', false)).toEqual({ task_id: 'a3', before_task_id: 'a1' });
    expect(drop('a3', 'a1', true)).toEqual({ task_id: 'a3', before_task_id: 'a2' });
    expect(drop('a1', 'a2', true)).toEqual({ task_id: 'a1', before_task_id: 'a3' });
    expect(drop('a1', 'a3', true)).toEqual({ task_id: 'a1', before_task_id: '' });
  });

  it('rejects cross-agent, non-queued, missing, self and unchanged drops without a command', () => {
    for (const [sourceId, targetId] of [
      ['a1', 'b1'], ['a-run', 'a1'], ['a1', 'a-run'], ['missing', 'a1'],
      ['a1', 'missing'], ['a1', 'a1'], ['a-blocked', 'a1'],
      ['a1', 'a-cancelled'], ['absorbed', 'a1'],
    ]) expect(drop(sourceId, targetId, false)).toBeNull();
    expect(drop('a1', 'a2', false)).toBeNull();
    expect(drop('a3', 'a2', true)).toBeNull();

    // Admission between dragstart and drop invalidates the gesture.
    expect(drop('a3', 'a1', false, tasks.map((task) => (
      task.task_id === 'a3' ? { ...task, status: 'running' } : task
    )))).toBeNull();
  });
});

describe('renderer task board › seed/resync merge (terminal-wins)', () => {
  // Scenario value: a terminal `task_state` emitted while no events stream
  // was attached is lost, and the once-per-conversation seed never re-read —
  // a cancelled task stayed painted "running" with a dead Stop button
  // (on-device 2026-08-23). The resync re-seed must let disk terminals
  // overwrite stale live-looking snapshots WITHOUT clobbering a fresher
  // running/waiting snapshot a concurrent event already wrote.
  function runMerge(mapEntries: Array<[string, any]>, rows: unknown): Array<[string, any]> {
    return vm.runInNewContext(
      `const _TASK_BOARD_TERMINAL = new Set(['done', 'stopped', 'failed', 'cancelled']);
       ${extractFunction('_taskBoardMergeSeedRows')};
       const map = new Map(${JSON.stringify(mapEntries)});
       _taskBoardMergeSeedRows(map, ${JSON.stringify(rows)});
       [...map.entries()];`,
      {},
    );
  }

  it('a disk terminal overwrites a stale running snapshot (the ghost-row fix)', () => {
    const merged = new Map(runMerge(
      [['t1', { task_id: 't1', status: 'running' }]],
      [{ task_id: 't1', status: 'cancelled' }],
    ));
    expect(merged.get('t1').status).toBe('cancelled');
  });

  it('treats stopped as an absorbing disk terminal', () => {
    const merged = new Map(runMerge(
      [['t1', { task_id: 't1', status: 'running' }]],
      [{ task_id: 't1', status: 'stopped' }],
    ));
    expect(merged.get('t1').status).toBe('stopped');
  });

  it('does not let a stale admission seed hide an already confirmed queue or revive a running task', () => {
    for (const status of ['queued', 'running']) {
      const merged = new Map(runMerge(
        [['t1', { task_id: 't1', status }]],
        [{ task_id: 't1', status: 'queued', admission_pending: true }],
      ));
      expect(merged.get('t1')).toEqual({ task_id: 't1', status });
    }
  });

  it('a non-terminal disk row never clobbers an existing snapshot but fills gaps', () => {
    const merged = new Map(runMerge(
      [['t1', { task_id: 't1', status: 'waiting_input' }]],
      [
        { task_id: 't1', status: 'running' },   // event snapshot is fresher — keep
        { task_id: 't2', status: 'queued' },    // unseen row — insert
      ],
    ));
    expect(merged.get('t1').status).toBe('waiting_input');
    expect(merged.get('t2').status).toBe('queued');
  });

  it('ignores malformed rows and non-array input', () => {
    const merged = new Map(runMerge(
      [['t1', { task_id: 't1', status: 'running' }]],
      [null, { status: 'done' }, 'junk'],
    ));
    expect([...merged.keys()]).toEqual(['t1']);
    expect(new Map(runMerge([], null)).size).toBe(0);
  });
});

describe('renderer task board › visibility (multi-task only, adjudicated 2026-09-04)', () => {
  it.each([
    { terminal: 'done', settlement: 'event' },
    { terminal: 'done', settlement: 'list' },
    { terminal: 'failed', settlement: 'event' },
    { terminal: 'stopped', settlement: 'list' },
    { terminal: 'cancelled', settlement: 'event' },
  ])(
    'does not revive a $terminal task from delayed stream events after $settlement settlement', async ({ terminal, settlement }) => {
      const { context, panel, board } = boardHarness();
      const old = { task_id: 'old', assignee: 'commander', status: 'running' };
      board.onEvent('c1', { task: old });
      if (settlement === 'event') board.onEvent('c1', { task: { ...old, status: terminal } });
      else {
        context.apiFetch = async () => ({ json: async () => ({ ok: true, tasks: [{ ...old, status: terminal }] }) });
        await board.sync('c1');
      }
      // A second observer can still be draining the previous turn. Its old
      // running row must not count as concurrent work when a new send arrives.
      for (const status of ['running', 'waiting_input', 'queued', 'blocked']) {
        board.onEvent('c1', { task: { ...old, status } });
        expect(panel.style.display).toBe('none');
      }
      const next = { task_id: 'next', assignee: 'commander', status: 'queued', admission_pending: true };
      board.onEvent('c1', { task: next });
      expect(panel.style.display).toBe('none');
      board.onEvent('c1', { task: { ...next, status: 'running', admission_pending: undefined } });
      expect(panel.style.display).toBe('none');
      // Genuine concurrency still needs the execution panel.
      board.onEvent('c1', { task: { task_id: 'parallel', assignee: 'other', status: 'running' } });
      expect(panel.style.display).toBe('');
    },
  );

  it('ignores old queue events after admission without hiding confirmed queue controls or form resumption', () => {
    const { panel, list, board } = boardHarness();
    const pending = { task_id: 'send', assignee: 'commander', status: 'queued', admission_pending: true };
    const confirmed = { ...pending, admission_pending: undefined };
    board.onEvent('c1', { task: pending });
    expect(panel.style.display).toBe('none');
    board.onEvent('c1', { task: confirmed });
    expect(panel.style.display).toBe('');
    board.onEvent('c1', { task: pending });
    expect(panel.style.display).toBe('');
    expect(list.innerHTML).toContain('data-act="task-cancel"');
    board.onEvent('c1', { task: { ...confirmed, status: 'running' } });
    for (const stale of [pending, confirmed]) {
      board.onEvent('c1', { task: stale });
      expect(panel.style.display).toBe('none');
    }
    board.onEvent('c1', { task: { ...confirmed, status: 'waiting_input' } });
    board.onEvent('c1', { task: confirmed });
    expect(panel.style.display).toBe('none');
    board.onEvent('c1', { task: { ...confirmed, status: 'running' } });
    board.onEvent('c1', { task: { task_id: 'parallel', assignee: 'other', status: 'running' } });
    expect(list.innerHTML.match(/chat.task_status_running/g)).toHaveLength(2);
  });

  it('keeps a send absorbed into its active turn hidden when its old queue event arrives', () => {
    const { panel, list, board } = boardHarness();
    const queued = { task_id: 'update', assignee: 'commander', status: 'queued' };
    board.onEvent('c1', { task: { task_id: 'active', assignee: 'commander', status: 'running' } });
    board.onEvent('c1', { task: queued });
    expect(panel.style.display).toBe('');
    const absorbed = { ...queued, status: 'running', absorbed_into_turn_id: 'active-turn' };
    board.onEvent('c1', { task: absorbed });
    board.onEvent('c1', { task: queued });
    expect(panel.style.display).toBe('none');
    board.onEvent('c1', { task: { task_id: 'parallel', assignee: 'other', status: 'running' } });
    expect(panel.style.display).toBe('');
    expect(list.innerHTML).not.toContain('data-task-id="update"');
  });

  it.each(['ack-first', 'running-first', 'done-first'])(
    'preserves blocked recovery when delivery is %s', async (order) => {
      const { context, panel, list, board } = boardHarness();
      const task = { task_id: 'blocked', assignee: 'commander', status: 'blocked', after: 'stopped-predecessor' };
      board.onEvent('c1', { task });
      expect(list.innerHTML).toContain('data-act="task-run-anyway"');
      context.apiFetch = async () => {
        if (order !== 'ack-first') {
          board.onEvent('c1', { task: { ...task, after: undefined, status: 'running' } });
          if (order === 'done-first') board.onEvent('c1', { task: { ...task, after: undefined, status: 'done' } });
        }
        return { json: async () => ({ ok: true }) };
      };
      await context._taskBoardResumeBlocked('c1', task.task_id);
      if (order === 'ack-first') {
        expect(panel.style.display).toBe('');
        expect(list.innerHTML).toContain('chat.task_status_queued');
        expect(list.innerHTML).not.toContain('data-act="task-run-anyway"');
        board.onEvent('c1', { task: { ...task, after: undefined, status: 'running' } });
      }
      expect(panel.style.display).toBe('none');
      board.onEvent('c1', { task }); // A delayed pre-recovery blocked snapshot.
      expect(panel.style.display).toBe('none');
      // The completed task must not remain as a phantom second execution.
      if (order === 'done-first') {
        board.onEvent('c1', { task: { task_id: 'new', assignee: 'commander', status: 'running' } });
        expect(panel.style.display).toBe('none');
      }
    },
  );

  it('keeps blocked recovery controls available after a failed request, then accepts a successful retry', async () => {
    const { context, panel, list, board } = boardHarness();
    const task = { task_id: 'blocked', assignee: 'commander', status: 'blocked' };
    board.onEvent('c1', { task });
    context.apiFetch = async () => ({ json: async () => ({ ok: false }) });
    await context._taskBoardResumeBlocked('c1', task.task_id);
    expect(panel.style.display).toBe('');
    expect(list.innerHTML).toContain('data-act="task-run-anyway"');
    expect(list.innerHTML).toContain('data-act="task-cancel"');
    context.apiFetch = async () => ({ json: async () => ({ ok: true }) });
    await context._taskBoardResumeBlocked('c1', task.task_id);
    board.onEvent('c1', { task: { ...task, status: 'running' } });
    expect(panel.style.display).toBe('none');
  });

  it('stays hidden for no work and ordinary single running or waiting-input turns', () => {
    expect(runVisibility([])).toEqual({ visible: false });
    expect(runVisibility([{ status: 'running' }])).toEqual({ visible: false });
    expect(runVisibility([{ status: 'waiting_input' }])).toEqual({ visible: false });
  });

  it('surfaces once a second live task exists', () => {
    expect(runVisibility([{ status: 'running' }, { status: 'waiting_input' }]))
      .toEqual({ visible: true });
  });

  it('retracts when a multi-task run drains to one ordinary task or becomes idle, then resurfaces', () => {
    const states = [
      [{ status: 'running' }, { status: 'running' }],
      [{ status: 'running' }],
      [],
      [{ status: 'running' }, { status: 'waiting_input' }],
    ];
    expect(states.map(runVisibility)).toEqual([
      { visible: true },
      { visible: false },
      { visible: false },
      { visible: true },
    ]);
  });

  it('keeps a lone queued or blocked task visible only until admission or terminal settlement', () => {
    // These are user journeys, not just a status truth table: queued is the
    // only trace before its bubble is persisted; blocked owns recovery. Once
    // either task starts, the ordinary live bubble takes over, and terminal
    // settlement must not leave an empty control surface behind.
    const lifecycleTasks = [
      [{ task_id: 'queued-flow', status: 'queued' }],
      [{ task_id: 'queued-flow', status: 'running' }],
      [{ task_id: 'queued-flow', status: 'done' }],
      [{ task_id: 'blocked-flow', status: 'blocked' }],
      [{ task_id: 'blocked-flow', status: 'queued' }],
      [{ task_id: 'blocked-flow', status: 'running' }],
      [{ task_id: 'blocked-flow', status: 'cancelled' }],
    ];
    expect(lifecycleTasks.map((tasks) => runVisibility(runLiveRows(tasks)))).toEqual([
      { visible: true },
      { visible: false },
      { visible: false },
      { visible: true },
      { visible: true },
      { visible: false },
      { visible: false },
    ]);
  });

  it('does not treat an ordinary admission as a standalone queue, regardless of elapsed time', () => {
    const pending = [{ task_id: 'ordinary-send', status: 'queued', admission_pending: true }];
    expect(runVisibility(pending)).toEqual({ visible: false });
    expect(runVisibility([{ ...pending[0], admission_pending: false }])).toEqual({ visible: true });
    expect(runVisibility([{ ...pending[0], status: 'running' }])).toEqual({ visible: false });
    expect(runVisibility([{ ...pending[0], status: 'blocked' }])).toEqual({ visible: true });
    expect(runVisibility([...pending, { task_id: 'other', status: 'running' }])).toEqual({ visible: false });
  });

  it.each(['event', 'seed'])(
    'does not flash when a fresh send overlaps the prior turn settlement through %s', async (settlement) => {
      const { context, panel, list, board } = boardHarness();
      const prior = { task_id: 'prior', assignee: 'commander', status: 'running' };
      const next = { task_id: 'next', assignee: 'commander', status: 'queued', admission_pending: true };
      board.onEvent('c1', { task: prior });
      expect(panel.style.display).toBe('none');
      // The prior terminal can arrive after the new task's creation. No
      // scheduler has confirmed waiting or a second execution at this point.
      board.onEvent('c1', { task: next });
      expect(panel.style.display).toBe('none');
      expect(list.innerHTML).toBe('');
      const done = { ...prior, status: 'done' };
      if (settlement === 'event') board.onEvent('c1', { task: done });
      else {
        context.apiFetch = async () => ({ json: async () => ({ ok: true, tasks: [done, next] }) });
        await board.sync('c1');
      }
      expect(panel.style.display).toBe('none');
      board.onEvent('c1', { task: { ...next, status: 'running', admission_pending: undefined } });
      expect(panel.style.display).toBe('none');
    },
  );

  it('waits for admission facts across multiple fresh sends but exposes real concurrency and recovery', () => {
    const { panel, list, board } = boardHarness();
    const first = { task_id: 'first', assignee: 'commander', status: 'queued', admission_pending: true };
    const second = { ...first, task_id: 'second', assignee: 'other' };
    board.onEvent('c1', { task: first });
    board.onEvent('c1', { task: second });
    expect(panel.style.display).toBe('none');
    board.onEvent('c1', { task: { ...first, status: 'running', admission_pending: undefined } });
    expect(panel.style.display).toBe('none');
    board.onEvent('c1', { task: { ...second, status: 'running', admission_pending: undefined } });
    expect(panel.style.display).toBe('');
    expect(list.innerHTML.match(/chat.task_status_running/g)).toHaveLength(2);
    board.onEvent('c1', { task: { ...second, status: 'done', admission_pending: undefined } });
    expect(panel.style.display).toBe('none');
    board.onEvent('c1', { task: { task_id: 'blocked', assignee: 'other', status: 'blocked' } });
    expect(panel.style.display).toBe('');
    expect(list.innerHTML).toContain('data-act="task-run-anyway"');
  });

  it.each(['event-first', 'seed-first'])(
    'keeps a slow ordinary send hidden with %s delivery, then exposes a confirmed queue', async (order) => {
      vi.useFakeTimers();
      try {
        const list: any = { dataset: {}, style: {}, innerHTML: '', querySelectorAll: () => [], addEventListener() {} };
        const panel: any = { style: {}, querySelector: () => null, addEventListener() {} };
        let snapshot: any = { task_id: 'send', assignee: 'commander', status: 'queued', admission_pending: true };
        const context: any = {
          window: {}, currentCid: 'c1', setTimeout, clearTimeout,
          document: { addEventListener() {}, getElementById: (id: string) => id === 'chat-task-board' ? panel : id === 'chat-task-board-list' ? list : null },
          t: (key: string) => key, escapeHtml: (v: unknown) => String(v ?? ''), uiIconHtml: () => '',
          apiFetch: async () => ({ json: async () => ({ ok: true, tasks: [snapshot] }) }),
        };
        vm.createContext(context);
        vm.runInContext(source, context);
        const board = context.window.TaskBoard;
        if (order === 'seed-first') await board.sync('c1');
        board.onEvent('c1', { type: 'task_created', task: snapshot });
        if (order === 'event-first') await board.sync('c1');
        expect(panel.style.display).toBe('none');
        await vi.advanceTimersByTimeAsync(60_000);
        expect(panel.style.display).toBe('none');
        // Recover a missed queue confirmation through the task-list response.
        snapshot = { task_id: 'send', assignee: 'commander', status: 'queued' };
        board.resync('c1');
        await vi.runAllTimersAsync();
        expect(panel.style.display).toBe('');
        expect(list.innerHTML).toContain('data-act="task-cancel"');
        board.onEvent('c1', { type: 'task_state', task: { ...snapshot, status: 'running' } });
        expect(panel.style.display).toBe('none');
        // Retraction is not a latch: later concurrency in this same board
        // resurfaces, and its terminal rows cannot keep the panel visible.
        const other = { task_id: 'second', assignee: 'commander', status: 'queued', admission_pending: true };
        board.onEvent('c1', { type: 'task_created', task: other });
        expect(panel.style.display).toBe('none');
        board.onEvent('c1', { type: 'task_state', task: { ...other, admission_pending: undefined } });
        expect(panel.style.display).toBe('');
        board.onEvent('c1', { type: 'task_state', task: { ...other, status: 'cancelled', admission_pending: undefined } });
        expect(panel.style.display).toBe('none');
        board.onEvent('c1', { type: 'task_state', task: { ...snapshot, status: 'done' } });
        expect(panel.style.display).toBe('none');
      } finally { vi.useRealTimers(); }
    },
  );

  it('counts only filtered live work, so terminal or absorbed batch rows cannot pin the board', () => {
    const taskSets = [
      [
        { task_id: 'done', status: 'done' },
        { task_id: 'failed', status: 'failed' },
      ],
      [
        { task_id: 'live', status: 'running' },
        { task_id: 'done', status: 'done' },
        { task_id: 'stopped', status: 'stopped' },
      ],
      [
        { task_id: 'live', status: 'running' },
        { task_id: 'absorbed', status: 'running', absorbed_into_turn_id: 'live-turn' },
      ],
      [
        { task_id: 'queued', status: 'queued' },
        { task_id: 'done', status: 'done' },
      ],
    ];
    expect(taskSets.map((tasks) => runVisibility(runLiveRows(tasks)))).toEqual([
      { visible: false },
      { visible: false },
      { visible: false },
      { visible: true },
    ]);
  });

  it('surfaces the default 4+1 capacity case as “运行中 4 · 排队 1” and labels the fifth row “排队中”', () => {
    const rows = runLiveRows([
      { task_id: 'r1', status: 'running', created_at: 't1' },
      { task_id: 'r2', status: 'running', created_at: 't2' },
      { task_id: 'r3', status: 'running', created_at: 't3' },
      { task_id: 'r4', status: 'running', created_at: 't4' },
      { task_id: 'q5', status: 'queued', created_at: 't5' },
    ]);
    const running = rows.filter((task) => task.status === 'running').length;
    const queued = rows.filter((task) => task.status === 'queued').length;
    expect(runVisibility(rows)).toEqual({ visible: true });
    expect(rows.map((task) => task.task_id)).toEqual(['r1', 'r2', 'r3', 'r4', 'q5']);

    const zh = JSON.parse(fs.readFileSync(
      path.join(__dirname, '../../src/renderer/locales/zh.json'),
      'utf8',
    ));
    const summary = String(zh['chat.task_board_counts'])
      .replace('{running}', String(running))
      .replace('{queued}', String(queued));
    expect(summary).toBe('运行中 4 · 排队 1');
    expect(runStatusLabel('queued', zh)).toBe('排队中');
  });
});

describe('renderer task board › latest-batch display while the multi-task board is visible', () => {
  function runBatchAfterCreate(
    batchIds: string[],
    tasks: Array<Record<string, unknown>>,
    createdId: string,
  ): string[] {
    return vm.runInNewContext(
      `const _TASK_BOARD_TERMINAL = new Set(['done', 'stopped', 'failed', 'cancelled']);
       ${extractFunction('_taskBoardBatchAfterCreate')};
       const byId = new Map(${JSON.stringify(tasks)}.map((t) => [t.task_id, t]));
       [..._taskBoardBatchAfterCreate(new Set(${JSON.stringify(batchIds)}), byId, ${JSON.stringify(createdId)})];`,
      {},
    );
  }

  function runDisplayRows(tasks: unknown, batchIds: string[]): string[] {
    return vm.runInNewContext(
      `const _TASK_BOARD_TERMINAL = new Set(['done', 'stopped', 'failed', 'cancelled']);
       ${extractFunction('_taskBoardLiveRows')};
       ${extractFunction('_taskBoardDisplayRows')};
       _taskBoardDisplayRows(${JSON.stringify(tasks)}, new Set(${JSON.stringify(batchIds)})).map((t) => t.task_id);`,
      {},
    );
  }

  it('a create while the tracked batch is still live JOINS the batch; all-terminal starts a fresh one', () => {
    const tasks = [
      { task_id: 'a', status: 'running' },
      { task_id: 'b', status: 'done' },
    ];
    expect(runBatchAfterCreate(['a', 'b'], tasks, 'c').sort()).toEqual(['a', 'b', 'c']);
    const finished = [
      { task_id: 'a', status: 'done' },
      { task_id: 'b', status: 'cancelled' },
    ];
    expect(runBatchAfterCreate(['a', 'b'], finished, 'c')).toEqual(['c']);
  });

  it('removes completed and cancelled messages while retaining the batch failure context', () => {
    const rows = runDisplayRows([
      { task_id: 'old-done', status: 'done', created_at: '2026-01-01T00:00:00Z' },
      { task_id: 'step1', status: 'done', created_at: '2026-01-01T00:01:00Z' },
      { task_id: 'step2', status: 'cancelled', created_at: '2026-01-01T00:02:00Z' },
      { task_id: 'step3', status: 'running', created_at: '2026-01-01T00:03:00Z' },
      { task_id: 'step4', status: 'queued', created_at: '2026-01-01T00:04:00Z' },
      { task_id: 'failure', status: 'failed', created_at: '2026-01-01T00:05:00Z' },
    ], ['step1', 'step2', 'step3', 'step4', 'failure']);
    expect(rows).toEqual(['failure', 'step3', 'step4']);
  });

  it('keeps an absorbed task out of the pinned terminal batch after the shared turn settles', () => {
    const rows = runDisplayRows([
      { task_id: 'primary', status: 'failed', created_at: 't1' },
      {
        task_id: 'absorbed', status: 'failed', created_at: 't2',
        absorbed_into_turn_id: 'live-turn',
      },
    ], ['primary', 'absorbed']);
    expect(rows).toEqual(['primary']);
  });
});


describe('renderer task board › editing queued messages', () => {
  it('keeps the editing message cancellable when it is the only queued item', async () => {
    const { context, panel, list, board } = boardHarness();
    context._queueComposerEditFor = () => ({ taskId: 'q' });
    context._latestActiveTurns = new Map([['c1', [{ actor: 'commander', steerable: true }]]]);
    board.onEvent('c1', { task: { task_id: 'q', status: 'queued', created_by: 'user', assignee: 'commander', instruction: 'original' } });
    expect(panel.style.display).not.toBe('none');
    expect(list.innerHTML).toContain('data-act="task-cancel"');
    expect(list.innerHTML).not.toContain('data-act="task-send-now"');
    context._deleteQueueItemEdit = vi.fn(async () => true);
    context.apiFetch = vi.fn();
    await context._taskBoardCancel('c1', 'q');
    expect(context._deleteQueueItemEdit).toHaveBeenCalledWith('c1');
    expect(context.apiFetch).not.toHaveBeenCalled();
    expect(context._taskBoardMapFor('c1').get('q').status).toBe('cancelled');
  });

  it('leaves the editing message available when cancellation fails or a save is pending', async () => {
    const { context, list, board } = boardHarness();
    context._queueComposerEditFor = () => ({ taskId: 'q' });
    board.onEvent('c1', { task: { task_id: 'q', status: 'queued', created_by: 'user', assignee: 'commander', instruction: 'original' } });
    context._deleteQueueItemEdit = vi.fn(async () => false);
    context.apiFetch = vi.fn();
    await context._taskBoardCancel('c1', 'q');
    expect(context.apiFetch).not.toHaveBeenCalled();
    expect(context._taskBoardMapFor('c1').get('q').status).toBe('queued');
    expect(list.innerHTML).toContain('data-act="task-cancel"');
  });

  it('orders the user controls Send now, Edit, Cancel and does not edit running or dispatched contracts', () => {
    const { context, list, board } = boardHarness();
    context._latestActiveTurns = new Map([['c1', [{ actor: 'commander', steerable: true }]]]);
    board.onEvent('c1', { task: { task_id: 'q', status: 'queued', created_by: 'user', assignee: 'commander', instruction: 'draft' } });
    expect([...list.innerHTML.matchAll(/data-act="([^"]+)"/g)].map((match: any) => match[1]))
      .toEqual(['task-send-now', 'task-edit', 'task-cancel']);
    expect(renderBoardRows([{ task_id: 'child', status: 'queued', created_by: 'commander', assignee: 'a' }]))
      .not.toContain('task-edit');
  });

  it('opens the queued message in the shared composer', async () => {
    const { context, board } = boardHarness();
    board.onEvent('c1', { task: { task_id: 'q', status: 'queued', created_by: 'user', assignee: 'commander', instruction: 'original' } });
    context._startQueueItemEdit = vi.fn(async () => {});
    await context._taskBoardEdit('c1', 'q');
    expect(context._startQueueItemEdit).toHaveBeenCalledWith('c1', 'q');
  });

  it('retains the revised text across delayed task events and resync', async () => {
    const { context, board } = boardHarness();
    const task = { task_id: 'q', status: 'queued', created_by: 'user', assignee: 'commander', instruction: 'original' };
    board.onEvent('c1', { task });
    context.apiFetch = vi.fn();
    expect(context.apiFetch).not.toHaveBeenCalled();
    board.onEvent('c1', { task: { ...task, instruction: 'saved', instruction_revision: 1 } });
    board.onEvent('c1', { task });
    expect(context._taskBoardMapFor('c1').get('q').instruction).toBe('saved');
    context._taskBoardMergeSeedRows(context._taskBoardMapFor('c1'), [{ ...task, instruction: 'saved again', instruction_revision: 2 }]);
    expect(context._taskBoardMapFor('c1').get('q').instruction).toBe('saved again');
  });
});

describe('renderer task board › arranging a planned send (D29)', () => {
  // Planning a send to several actors takes seconds before any row exists.
  // The board must show that the send is being arranged from the host's start
  // signal, hand over to the real rows without blinking out, and never keep
  // showing "arranging" after planning ended.
  const PLANNING = 'chat.task_status_planning';
  const start = (preview = 'Write a draft, then review it') => (
    { type: 'dispatch_planning', cid: 'c1', message_id: 'm1', active: true, preview });
  const end = { type: 'dispatch_planning', cid: 'c1', message_id: 'm1', active: false };
  const row = (task_id: string, assignee: string, extra: Record<string, unknown> = {}) => ({ task: {
    task_id, assignee, status: 'queued', admission_pending: true, created_by: 'user',
    instruction: `${task_id} part`, source_msg_id: 'm1', created_at: `2026-10-19T00:00:0${task_id.length}Z`, ...extra,
  } });

  it('shows the send as being arranged as soon as planning starts', () => {
    const { panel, list, board } = boardHarness();
    board.onEvent('c1', start());
    expect(panel.style.display).toBe('');
    expect(list.innerHTML).toContain(PLANNING);
    expect(list.innerHTML).toContain('Write a draft, then review it');
    expect(list.innerHTML).not.toContain('data-task-id');
  });

  it('hands over to the planned rows without hiding the board in between', () => {
    const { panel, list, board } = boardHarness();
    board.onEvent('c1', start());
    board.onEvent('c1', row('a', 'writer'));
    board.onEvent('c1', row('bb', 'reviewer', { after: ['a'] }));
    board.onEvent('c1', end);
    // Planning is over but neither row has been admitted yet.
    expect(panel.style.display).toBe('');
    expect(list.innerHTML).not.toContain(PLANNING);
    board.onEvent('c1', row('a', 'writer', { status: 'running', admission_pending: false }));
    expect(panel.style.display).toBe('');
    board.onEvent('c1', row('bb', 'reviewer', { after: ['a'], admission_pending: false }));
    expect(panel.style.display).toBe('');
    expect(list.innerHTML).toContain('data-task-id="a"');
    expect(list.innerHTML).toContain('data-task-id="bb"');
    expect(list.innerHTML).not.toContain(PLANNING);
  });

  it('retracts for a single planned task once it runs, as for any lone running task', () => {
    const { panel, board } = boardHarness();
    board.onEvent('c1', start());
    board.onEvent('c1', row('a', 'writer'));
    board.onEvent('c1', end);
    board.onEvent('c1', row('a', 'writer', { status: 'running', admission_pending: false }));
    expect(panel.style.display).toBe('none');
  });

  it('clears the arranging row when planning ends without any task', () => {
    const { panel, list, board } = boardHarness();
    board.onEvent('c1', start());
    board.onEvent('c1', end);
    expect(panel.style.display).toBe('none');
    expect(list.innerHTML).toBe('');
  });

  it('does not revive a send whose planning ended when a second stream repeats the start', () => {
    const { panel, board } = boardHarness();
    board.onEvent('c1', start());
    board.onEvent('c1', end);
    board.onEvent('c1', start());
    expect(panel.style.display).toBe('none');
  });

  it('keeps another conversation\'s planning off the visible board', () => {
    const { context, panel, list, board } = boardHarness();
    board.onEvent('c2', { ...start(), cid: 'c2' });
    expect(list.innerHTML).toBe('');
    context.currentCid = 'c2';
    context._taskBoardRender('c2');
    expect(panel.style.display).toBe('');
    expect(list.innerHTML).toContain(PLANNING);
  });

  function stubTaskList(context: any) {
    const answers: Array<(planning: unknown[]) => void> = [];
    context.apiFetch = vi.fn(async (url: string) => {
      if (!url.endsWith('/tasks')) return { json: async () => ({}) };
      const planning = await new Promise<unknown[]>((resolve) => answers.push(resolve));
      return { json: async () => ({ ok: true, tasks: [], planning }) };
    });
    return answers;
  }

  it('lets only a list read after the start retire an arranging send', async () => {
    const { context, panel, board } = boardHarness();
    const answers = stubTaskList(context);
    const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
    // Read sent before the start arrived: it may predate planning entirely.
    board.resync('c1');
    board.onEvent('c1', start());
    await vi.waitFor(() => expect(answers).toHaveLength(1));
    answers[0]([]);
    await settle();
    expect(context.apiFetch).toHaveBeenCalledTimes(3);
    expect(panel.style.display).toBe('');
    // A read sent after the start (Stop's resync) is authoritative.
    board.resync('c1');
    await vi.waitFor(() => expect(answers).toHaveLength(2));
    answers[1]([]);
    await vi.waitFor(() => expect(panel.style.display).toBe('none'));
  });

  it('restores an arranging send from the host list after the renderer reloads', async () => {
    const { context, list, board } = boardHarness();
    const answers = stubTaskList(context);
    board.resync('c1');
    await vi.waitFor(() => expect(answers).toHaveLength(1));
    answers[0]([{ message_id: 'm1', preview: 'Write a draft, then review it' }]);
    await vi.waitFor(() => expect(list.innerHTML).toContain(PLANNING));
    // The end event that follows still retires it.
    board.onEvent('c1', end);
    expect(list.innerHTML).not.toContain(PLANNING);
  });
});