The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdtempSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { CommanderMirror, type CommanderFrame, type CommanderMirrorOpts, type TierTurn } from './commander.js'
import type { Tier } from './notifyTier.js'
import { isLocalOnly, withoutUpdate } from './cardUpdate.js'
import type { LiveEvent } from './normalize.js'
import { BODY_MAX_CHARS, RECAP_MAX_CHARS, deriveTurnSummary } from './deviceRecap.js'
let dataDir = ''
describe('CommanderMirror recap events', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-commander-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
})
it('reports the latest assistant paragraph as `update` while tools continue running', () => {
const frames: CommanderFrame[] = []
const mirror = new CommanderMirror({ send: f => frames.push(f), sendWeb: () => {}, hasDevice: () => true,
summarize: async () => null, dataDir })
mirror.ingest([{ type: 'turn_started', payload: {} },
{ type: 'text_delta', payload: { content: 'CI passed for the integrated head too.' } },
{ type: 'tool_start', payload: { tool: 'Bash', input: { command: 'python3 check.py' } } } ] as LiveEvent[], 's')
expect(mirror.latestUpdate('s')).toBe('CI passed for the integrated head too.')
mirror.heartbeat('s')
expect(frames.some(f => f.payload.kind === 'processing' && f.payload.update === mirror.latestUpdate('s'))).toBe(true)
mirror.ingest([{ type: 'text_delta', payload: { content: 'The build is ready.' } }] as LiveEvent[], 's')
expect(mirror.latestUpdate('s')).toBe('The build is ready.')
mirror.ingest([{ type: 'turn_started', payload: {} }] as LiveEvent[], 's')
expect(mirror.latestUpdate('s')).toBe('')
})
it('emits a local-only reply_text card when a text delta changes the latest paragraph', () => {
const frames: CommanderFrame[] = []
const mirror = new CommanderMirror({ send: f => frames.push(f), sendWeb: () => {}, hasDevice: () => true,
summarize: async () => null, dataDir })
mirror.ingest([{ type: 'turn_started', payload: {} }] as LiveEvent[], 's')
const replies = () => frames.filter(f => f.payload.kind === 'reply_text')
expect(replies()).toHaveLength(0)
mirror.ingest([{ type: 'text_delta', payload: { content: 'Looking at ' } }] as LiveEvent[], 's')
mirror.ingest([{ type: 'text_delta', payload: { content: 'the spec.' } }] as LiveEvent[], 's')
expect(replies().map(f => f.payload.update)).toEqual(['Looking at', 'Looking at the spec.'])
expect(replies().every(f => isLocalOnly(f))).toBe(true)
// an empty delta changes nothing, and so says nothing
mirror.ingest([{ type: 'text_delta', payload: { content: '' } }] as LiveEvent[], 's')
expect(replies()).toHaveLength(2)
// a replay (history) is not a live turn
mirror.ingest([{ type: 'text_delta', payload: { content: ' More.' } }] as LiveEvent[], 's', { replay: true })
expect(replies()).toHaveLength(2)
// the heartbeat is unchanged
mirror.heartbeat('s')
expect(frames.some(f => f.payload.kind === 'processing' && f.payload.update === mirror.latestUpdate('s'))).toBe(true)
})
it('streams the TAIL of a long paragraph as reply_text, while latestUpdate keeps its head', () => {
const frames: CommanderFrame[] = []
const mirror = new CommanderMirror({ send: f => frames.push(f), sendWeb: () => {}, hasDevice: () => true,
summarize: async () => null, dataDir })
mirror.ingest([{ type: 'turn_started', payload: {} }] as LiveEvent[], 's')
const replies = () => frames.filter(f => f.payload.kind === 'reply_text').map(f => f.payload.update as string)
const long = 'xin chào đẹp '.repeat(40) + 'END' // multi-byte, ~500 bytes
for (let i = 0; i < long.length; i += 7) mirror.ingest([{ type: 'text_delta', payload: { content: long.slice(i, i + 7) } }] as LiveEvent[], 's')
const last = replies().at(-1) as string
expect(Buffer.byteLength(last, 'utf8')).toBeLessThanOrEqual(188)
expect(last.startsWith('\u2026')).toBe(true)
expect(last.endsWith('END')).toBe(true)
expect(last).not.toContain('\uFFFD')
expect(long.endsWith(last.slice(1))).toBe(true)
expect(mirror.latestUpdate('s').endsWith('\u2026')).toBe(true) // heads unchanged for other consumers
// a short paragraph is whole; a new paragraph replaces it
mirror.ingest([{ type: 'text_delta', payload: { content: '\n\nShort one.' } }] as LiveEvent[], 's')
expect(replies().at(-1)).toBe('Short one.')
})
it('withoutUpdate strips the sentence from a processing card and touches nothing else', () => {
const card = { type: 'commander_event', agentId: 'a', payload: { kind: 'processing', text: 'Working', update: 'x' } }
expect(withoutUpdate(card)).toEqual({ type: 'commander_event', agentId: 'a', payload: { kind: 'processing', text: 'Working' } })
expect(card.payload.update).toBe('x')
const summary = { type: 'commander_event', payload: { kind: 'summary', text: 'b' } }
expect(withoutUpdate(summary)).toBe(summary)
const other = { type: 'agent_deleted', payload: { agentId: 'a' } }
expect(withoutUpdate(other)).toBe(other)
})
it('leaves `update` off a processing card before the assistant has written anything', () => {
const frames: CommanderFrame[] = []
const mirror = new CommanderMirror({ send: f => frames.push(f), sendWeb: () => {}, hasDevice: () => true,
summarize: async () => null, dataDir })
mirror.ingest([{ type: 'turn_started', payload: {} }] as LiveEvent[], 's')
mirror.heartbeat('s')
for (const f of frames.filter(f => f.payload.kind === 'processing')) expect(f.payload).not.toHaveProperty('update')
})
it('keeps what the user ASKED, not only what the agent answered', async () => {
// The router reads these to decide where a spoken follow-up belongs, and a recap answers the wrong
// question for that: measured on this desk, "Chiến tranh thế giới thứ hai kết thúc vào năm nào?"
// recapped to "1945." — a correct summary of the reply carrying not one word of the subject. Ask
// about the FIRST world war a minute later and nothing connects the two.
const mirror = new CommanderMirror({
send: () => {},
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => '1945.',
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'Chiến tranh thế giới thứ hai kết thúc vào năm nào?' } },
{ type: 'text_delta', payload: { content: 'The war ended in 1945.' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'session-ask')
await vi.runAllTimersAsync()
await Promise.resolve()
expect(mirror.recentAsks('session-ask')).toEqual(['Chiến tranh thế giới thứ hai kết thúc vào năm nào?'])
// The recap is still exactly what it was — this adds a list, it does not change one.
expect(mirror.recent('session-ask', 3)[0].recap).toBe('1945.')
})
it('permanently removes only the selected conversation from persisted recap history', async () => {
const options = { send: () => {}, sendWeb: () => {}, hasDevice: () => true, summarize: async () => 'Fixture recap', dataDir }
const mirror = new CommanderMirror(options)
for (const id of ['selected', 'kept']) mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'question ' + id } },
{ type: 'text_delta', payload: { content: 'answer ' + id } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], id)
await vi.runAllTimersAsync()
mirror.deleteHistory('selected')
const reloaded = new CommanderMirror(options)
expect(reloaded.recent('selected')).toEqual([])
expect(reloaded.recentAsks('selected')).toEqual([])
expect(reloaded.recent('kept')).toHaveLength(1)
expect(reloaded.recentAsks('kept')).toEqual(['question kept'])
})
it('keeps the question even when the turn produces no summary at all', async () => {
// The fault this replaced: the ask was written in the summariser's success branch, so a turn with
// no assistant text — or a summariser that returned null — left no record of what was asked.
// Measured on a real machine: three of eight agents had any questions on record, and the missing
// ones were the NEWEST, which is the signal the router most needs.
const mirror = new CommanderMirror({
send: () => {},
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => null,
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'qua bong vang vietnam 2026 thuoc ve ai' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'session-nosummary')
await vi.runAllTimersAsync()
await Promise.resolve()
expect(mirror.recentAsks('session-nosummary')).toEqual(['qua bong vang vietnam 2026 thuoc ve ai'])
// …and there is genuinely no recap for it. The question stands on its own.
expect(mirror.recent('session-nosummary', 3)).toEqual([])
})
it('keeps the three newest questions, newest first', async () => {
const mirror = new CommanderMirror({
send: () => {},
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => null,
dataDir,
})
for (const q of ['one', 'two', 'three', 'four']) {
mirror.ingest([{ type: 'turn_started', payload: { userMessage: q } }] as LiveEvent[], 'session-many')
}
await vi.runAllTimersAsync()
expect(mirror.recentAsks('session-many')).toEqual(['four', 'three', 'two'])
})
it('fans a TodoWrite out to the device as a todo list, whatever engine produced it', () => {
// The device renders the checklist from `todos:[{c,s}]` folded onto a processing frame — nothing else
// carries it. Every engine reaches this through the SAME shape (`input.todos[{content,status}]`), which
// is why an engine whose planning tool is named differently silently loses its checklist: hermes calls
// its tool `todo`, and until that was mapped the device showed no list at all for it.
const deviceFrames: CommanderFrame[] = []
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => null,
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'plan it' } },
{
type: 'tool_start',
payload: {
id: 't1',
tool: 'TodoWrite',
input: { todos: [
{ content: 'In hello', status: 'completed' },
{ content: 'In world', status: 'in_progress' },
{ content: 'Tổng kết', status: 'pending' },
] },
},
},
] as LiveEvent[], 'session-todos')
const withTodos = deviceFrames.filter((f) => Array.isArray((f.payload as { todos?: unknown }).todos))
expect(withTodos).toHaveLength(1)
expect((withTodos[0].payload as { todos: Array<{ c: string; s: string }> }).todos).toEqual([
{ c: 'In hello', s: 'completed' },
{ c: 'In world', s: 'in_progress' },
{ c: 'Tổng kết', s: 'pending' },
])
})
it('keeps the todo list on the busy tile through the heartbeat', () => {
// The device clears a busy tile on a watchdog; the 5s heartbeat has to re-assert the SAME list or the
// checklist would vanish mid-turn while the agent is still working on it.
const deviceFrames: CommanderFrame[] = []
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => null,
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'plan it' } },
{ type: 'tool_start', payload: { id: 't1', tool: 'TodoWrite', input: { todos: [{ content: 'A', status: 'pending' }] } } },
] as LiveEvent[], 'session-hb')
deviceFrames.length = 0
expect(mirror.heartbeat('session-hb')).toBe(true)
expect(deviceFrames.some((f) => Array.isArray((f.payload as { todos?: unknown }).todos))).toBe(true)
})
it('feeds the device its sub-agent list, running then finished', () => {
// The firmware has always been able to draw this list (ui_project_set_agents) and never received one:
// nothing in the adapter, the node or the backend emitted `kind:'agents'`, for any engine. It renders
// each row verbatim, so the text and colour are decided here — `›` while running (the device scrolls
// that row into view), `✓ … · Ns` once done.
const deviceFrames: CommanderFrame[] = []
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => null,
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'delegate it' } },
{ type: 'tool_start', payload: { id: 'a1', tool: 'Task', input: { description: 'audit the parser' } } },
// claude's own tool is named `Agent`, not `Task` — both must open a row (measured on a live turn).
{ type: 'tool_start', payload: { id: 'a2', tool: 'Agent', input: { description: 'write the tests' } } },
] as LiveEvent[], 'session-agents')
const rowsOf = (): Array<{ text: string; color: string }> => {
const last = deviceFrames.filter((f) => f.payload.kind === 'agents').pop()
return (last?.payload.agents ?? []) as Array<{ text: string; color: string }>
}
expect(rowsOf().map((r) => r.text)).toEqual(['› audit the parser', '› write the tests'])
mirror.ingest([
{ type: 'tool_end', payload: { id: 'a1', tool: 'Task', output: 'ok', isError: false, summary: 'done', durationSeconds: 12 } },
] as LiveEvent[], 'session-agents')
expect(rowsOf().map((r) => r.text)).toEqual(['✓ audit the parser · 12s', '› write the tests'])
expect(rowsOf()[0].color).not.toBe(rowsOf()[1].color) // finished and running must be tellable apart
})
it('carries a still-RUNNING sub-agent into the next turn and drops the finished ones', () => {
// Finished rows must not sit above "Working…" on the next turn — but a running one is not finished
// just because the user typed again: claude's async sub-agents outlive the turn that spawned them,
// and cursor announces a Task through its HOOK ~60ms BEFORE the turn opens (measured live).
const deviceFrames: CommanderFrame[] = []
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => null,
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'one' } },
{ type: 'tool_start', payload: { id: 'a1', tool: 'Task', input: { description: 'first' } } },
{ type: 'tool_end', payload: { id: 'a1', tool: 'Task', output: 'done', isError: false, summary: '' } },
{ type: 'tool_start', payload: { id: 'a2', tool: 'Task', input: { description: 'still going' } } },
{ type: 'turn_started', payload: { userMessage: 'two' } },
{ type: 'tool_start', payload: { id: 'b1', tool: 'Task', input: { description: 'second' } } },
] as LiveEvent[], 'session-agents-2')
const last = deviceFrames.filter((f) => f.payload.kind === 'agents').pop()
expect((last?.payload.agents as Array<{ text: string }>).map((r) => r.text)).toEqual(['› still going', '› second'])
})
it('marks a sub-agent\'s turn end so the dial redraws the tile and tells nobody', async () => {
// An Orchestrator specialist (or the Director while specialists are still out): its `done`/`summary`
// carry `subagent: true`; the live stream does not, so the tile still moves.
const deviceFrames: CommanderFrame[] = []
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => 'Short recap\n\nLong body',
isSubagent: (sessionId) => sessionId === 'specialist',
dataDir,
})
for (const sessionId of ['specialist', 'director']) {
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'go' } },
{ type: 'text_delta', payload: { content: 'answered.' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], sessionId)
}
await vi.runAllTimersAsync()
await Promise.resolve()
const of = (id: string) => deviceFrames.filter((f) => f.dbSessionId === id)
expect(of('specialist').map((f) => [f.payload.kind, f.payload.subagent])).toEqual([
['turn_started', undefined], ['processing', undefined], ['reply_text', undefined], ['processing', undefined], ['done', true], ['summary', true],
])
expect(of('director').every((f) => f.payload.subagent === undefined)).toBe(true)
})
it('keeps holding the turn end past the old cap while a sub-agent is still writing, then gives up silently', async () => {
// A fixed ten minutes released the hold under long sub-agents: one ring for a turn that was not
// over, another when it was. Now the sub-agents' transcripts are asked every minute.
const deviceFrames: CommanderFrame[] = []
let writing = true
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => 'Short recap\n\nLong body',
subagentActive: (_sessionId, agentId) => agentId === 'a1' && writing,
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'delegate' } },
{ type: 'tool_start', payload: { id: 'a1', tool: 'Agent', input: { description: 'long job' } } },
{ type: 'tool_end', payload: { id: 'a1', tool: 'Agent', output: 'Async agent launched successfully.', isError: false, summary: '' } },
{ type: 'text_delta', payload: { content: 'Launched the long job.' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'session-long')
const ends = () => deviceFrames.filter((f) => f.payload.kind === 'summary')
await vi.advanceTimersByTimeAsync(25 * 60_000)
expect(ends()).toHaveLength(0) // 25 minutes in, still writing: still held
writing = false
await vi.advanceTimersByTimeAsync(2 * 60_000)
await vi.runAllTimersAsync()
await Promise.resolve()
expect(ends()).toHaveLength(1)
// Given up on, not done — silent, so the person is not rung for an answer that never came.
expect(ends()[0].payload).toMatchObject({ subagent: true, recap: 'Short recap' })
})
it('a sub-agent that finishes releases the hold with an ordinary, audible summary', async () => {
const deviceFrames: CommanderFrame[] = []
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => 'Short recap\n\nLong body',
subagentActive: () => true,
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'delegate' } },
{ type: 'tool_start', payload: { id: 'a1', tool: 'Agent', input: { description: 'short job' } } },
{ type: 'turn_ended', payload: {} },
{ type: 'subagent_finished', payload: { id: 'a1', status: 'completed' } },
{ type: 'text_delta', payload: { content: 'Both done.' } },
] as LiveEvent[], 'session-short')
mirror.noteEngineStopped('session-short')
await vi.runAllTimersAsync()
await Promise.resolve()
const ends = deviceFrames.filter((f) => f.payload.kind === 'summary')
expect(ends).toHaveLength(1)
expect(ends[0].payload).not.toHaveProperty('subagent')
})
it('emits done before summary when recap succeeds', async () => {
const deviceFrames: CommanderFrame[] = []
const webFrames: Record<string, unknown>[] = []
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: (frame) => webFrames.push(frame),
hasDevice: () => true,
summarize: async () => 'Short recap\n\nLong body',
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'what happened?' } },
{ type: 'text_delta', payload: { content: 'The assistant answered.' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'session-1')
await vi.runAllTimersAsync()
await Promise.resolve()
expect(deviceFrames.map((f) => f.payload.kind)).toEqual([
'turn_started',
'processing',
'reply_text',
'processing',
'done',
'summary',
])
expect(deviceFrames.at(-1)?.payload).toEqual({ kind: 'summary', text: 'Long body', recap: 'Short recap', notification: { id: expect.any(String), kind: 'done' } })
expect(webFrames.map((f) => f.type)).toEqual(['turn_summary_pending', 'turn_summary'])
})
it('with alwaysGenerate, persists a recap headless but streams NO cards to the absent device', async () => {
const deviceFrames: CommanderFrame[] = []
let summarizeCalls = 0
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => false, // no device connected
alwaysGenerate: true, // ...but generate + persist anyway
summarize: async () => { summarizeCalls++; return 'Scanned the LAN\n\nFound .143 root-equivalent.' },
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'scan the network' } },
{ type: 'text_delta', payload: { content: 'Found .143 — orangepi/orangepi, passwordless sudo.' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'session-headless')
await vi.runAllTimersAsync()
await Promise.resolve()
// Generated + persisted → a programmatic client (agent.recent) sees it.
expect(summarizeCalls).toBe(1)
expect(mirror.recent('session-headless', 1)[0].recap).toBe('Scanned the LAN')
// But emit() stays device-gated: nothing rode the wire to a device that is not there.
expect(deviceFrames).toHaveLength(0)
})
it('without alwaysGenerate and no device, generates nothing (the original gate)', async () => {
let summarizeCalls = 0
const mirror = new CommanderMirror({
send: () => {}, sendWeb: () => {},
hasDevice: () => false,
summarize: async () => { summarizeCalls++; return 'x\n\ny' },
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'q' } },
{ type: 'text_delta', payload: { content: 'a' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'session-off')
await vi.runAllTimersAsync()
await Promise.resolve()
expect(summarizeCalls).toBe(0)
expect(mirror.recent('session-off', 1)).toHaveLength(0)
})
it('reads the alwaysGenerate setting for each turn', async () => {
let enabled = false
const mirror = new CommanderMirror({
send: () => {}, sendWeb: () => {},
hasDevice: () => false,
alwaysGenerate: () => enabled,
summarize: async () => 'Fixed the flaky test\n\nPinned the clock in billing.spec.ts.',
dataDir,
})
const turn = [
{ type: 'turn_started', payload: { userMessage: 'fix it' } },
{ type: 'text_delta', payload: { content: 'done' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[]
mirror.ingest(turn, 'session-setting')
await vi.runAllTimersAsync()
await Promise.resolve()
expect(mirror.recent('session-setting', 1)).toHaveLength(0)
enabled = true
mirror.ingest(turn, 'session-setting')
await vi.runAllTimersAsync()
await Promise.resolve()
expect(mirror.recent('session-setting', 1)).toMatchObject([{ recap: 'Fixed the flaky test', text: 'Pinned the clock in billing.spec.ts.' }])
})
it('runs the recap once when a turn closes twice (Stop hook + watcher race)', async () => {
const deviceFrames: CommanderFrame[] = []
let summarizeCalls = 0
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => { summarizeCalls++; return 'Recap\n\nBody' },
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'who won?' } },
{ type: 'text_delta', payload: { content: 'Spain won.' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'session-race')
// Second turn_ended for the SAME turn (the other of hook/watcher) — must NOT start a second recap.
mirror.ingest([{ type: 'turn_ended', payload: {} }] as LiveEvent[], 'session-race')
await vi.runAllTimersAsync()
await Promise.resolve()
expect(summarizeCalls).toBe(1)
expect(deviceFrames.filter((f) => f.payload.kind === 'summary')).toHaveLength(1)
})
it('hands the summariser the previous turn\'s recap, and nothing on the first turn', async () => {
// recap = llm(instruct, previous_recap, ask, answer). The previous recap is read from the store
// BEFORE this turn's lands there — otherwise "previous" is the turn being summarised.
const previous: Array<string | undefined> = []
let turn = 0
const mirror = new CommanderMirror({
send: () => {},
sendWeb: () => {},
hasDevice: () => true,
summarize: async (_text, _signal, _ask, _sessionId, previousRecap) => {
previous.push(previousRecap)
turn++
return `Recap ${turn}\n\nBody ${turn}`
},
dataDir,
})
const oneTurn = (ask: string, answer: string) => mirror.ingest([
{ type: 'turn_started', payload: { userMessage: ask } },
{ type: 'text_delta', payload: { content: answer } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'session-prev')
oneTurn('fix the retry path', 'Fixed the retry path in client.ts.')
await vi.runAllTimersAsync()
await Promise.resolve()
oneTurn('same fix in the other file', 'Done, applied the same change to server.ts.')
await vi.runAllTimersAsync()
await Promise.resolve()
expect(previous).toEqual([undefined, 'Recap 1\n\nBody 1'])
expect(mirror.recent('session-prev', 3).map((r) => r.recap)).toEqual(['Recap 2', 'Recap 1'])
})
it('renders normalized Codex Task and child tools through the same device cards as Claude', () => {
const deviceFrames: CommanderFrame[] = []
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => null,
dataDir,
})
mirror.ingest([
{
type: 'tool_start',
payload: {
id: 'task-1',
tool: 'Task',
input: { subagent_type: 'explorer', description: 'Inspect the API' },
},
},
{
type: 'tool_start',
payload: {
id: 'child-1',
tool: 'Bash',
input: { command: 'rg TODO' },
parentToolUseId: 'task-1',
},
},
], 'session-codex')
expect(deviceFrames.map((frame) => frame.payload)).toEqual([
{
kind: 'tool',
text: 'Task',
recap: 'Inspect the API',
color: '#d19a66',
detail: 'subagent_type: explorer · description: Inspect the API',
},
// …and the same Task also opens a row in the device's sub-agent list, which is a separate surface
// from the tool card: the card scrolls away with the feed, the list stays above "Working…".
{ kind: 'agents', agents: [{ text: '› Inspect the API', color: '#ff9d00' }] },
{
kind: 'tool',
text: 'Bash',
recap: 'rg TODO',
color: '#e5c07b',
detail: 'command: rg TODO',
},
])
})
it('withdraws unverified busy heartbeats without reporting a completed turn', () => {
const frames: CommanderFrame[] = []
let verified = false
const mirror = new CommanderMirror({ send: frame => frames.push(frame), sendWeb: () => {},
hasDevice: () => true, summarize: async () => null, dataDir,
verifiedWorking: () => verified })
mirror.ingest([{ type: 'turn_started', payload: { userMessage: 'old unfinished turn' } }] as LiveEvent[], 'stale')
frames.length = 0
expect(mirror.heartbeat('stale')).toBe(true)
mirror.replayAll()
expect(frames).toEqual([])
expect(mirror.isBusy('stale')).toBe(true)
verified = true
mirror.heartbeat('stale')
expect(frames[0].payload.kind).toBe('processing')
})
it('heartbeat re-emits processing while a turn is open, nothing when idle', () => {
const deviceFrames: CommanderFrame[] = []
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => null,
dataDir,
})
// No such session → idle, emits nothing.
expect(mirror.heartbeat('nope')).toBe(false)
mirror.ingest([{ type: 'turn_started', payload: { userMessage: 'hi' } }] as LiveEvent[], 'session-hb')
deviceFrames.length = 0 // drop the turn_started processing frame
// Turn open → heartbeat re-asserts Processing and reports busy.
expect(mirror.heartbeat('session-hb')).toBe(true)
expect(deviceFrames).toEqual([{ type: 'commander_event', agentId: 'session-hb', dbSessionId: 'session-hb', payload: { kind: 'processing', text: 'Processing' } }])
})
it('heartbeat re-emits "Summarizing…" during the summarize window', async () => {
const deviceFrames: CommanderFrame[] = []
let releaseSummarize: (v: string) => void = () => {}
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: () => new Promise<string>((resolve) => { releaseSummarize = resolve }), // hangs until released
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'q' } },
{ type: 'text_delta', payload: { content: 'answer' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'session-sum')
await Promise.resolve() // let onTurnEnded kick off the (hanging) summarize → summarizing=true
deviceFrames.length = 0
// Turn closed but summarize in flight → heartbeat re-asserts Summarizing… and still reports busy.
expect(mirror.heartbeat('session-sum')).toBe(true)
// `update` is the agent's last sentence, which the Pro's working screen shows; other consumers ignore it.
expect(deviceFrames.map((f) => f.payload)).toEqual([{ kind: 'processing', text: 'Summarizing…', update: 'answer' }])
releaseSummarize('recap\n\nbody')
await vi.runAllTimersAsync()
await Promise.resolve()
// Summary done → idle → heartbeat emits nothing and reports not busy.
deviceFrames.length = 0
expect(mirror.heartbeat('session-sum')).toBe(false)
expect(deviceFrames).toEqual([])
})
it('says so in the log when a turn closes that was never opened', async () => {
// The real failure this guards: a first prompt landing while the session is being attached has
// its turn_started folded into history, so the live turn's close arrives with turnOpen false.
// That used to return in silence — a whole turn produced no recap and no trace of why.
const errors: string[] = []
const error = vi.spyOn(console, 'error').mockImplementation((line: unknown) => { errors.push(String(line)) })
const deviceFrames: CommanderFrame[] = []
let summarizeCalls = 0
const mirror = new CommanderMirror({
send: (frame) => deviceFrames.push(frame),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => { summarizeCalls++; return 'Recap\n\nBody' },
dataDir,
})
mirror.ingest([{ type: 'turn_ended', payload: {} }] as LiveEvent[], 'session-orphan')
await vi.runAllTimersAsync()
expect(summarizeCalls).toBe(0)
expect(deviceFrames).toEqual([])
expect(errors.join('\n')).toContain('turn-end · DROPPED')
error.mockRestore()
})
it('stays silent for the ordinary duplicate close', async () => {
// Every turn closes twice (watcher + Stop hook). That path must not start logging.
const errors: string[] = []
const error = vi.spyOn(console, 'error').mockImplementation((line: unknown) => { errors.push(String(line)) })
const mirror = new CommanderMirror({
send: () => {},
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => 'Recap\n\nBody',
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'q' } },
{ type: 'text_delta', payload: { content: 'answer' } },
{ type: 'turn_ended', payload: {} },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'session-dup')
await vi.runAllTimersAsync()
expect(errors.join('\n')).not.toContain('DROPPED')
error.mockRestore()
})
})
describe('device frames address the agent, not the session', () => {
beforeEach(() => { vi.useFakeTimers(); dataDir = mkdtempSync(join(tmpdir(), 'adapter-commander-id-')) })
afterEach(() => { vi.useRealTimers(); rmSync(dataDir, { recursive: true, force: true }) })
it('sends agentId = the agent and dbSessionId = the engine session', () => {
// These two are different values now. The device routes tiles by `agentId` (stable across a `/clear`)
// and keeps `dbSessionId` to echo back when cancelling a turn; the backend also keys its voice queue
// on dbSessionId, so it must stay the engine session id.
const frames: CommanderFrame[] = []
const mirror = new CommanderMirror({
send: (f) => frames.push(f),
sendWeb: () => {},
hasDevice: () => true,
summarize: async () => null,
agentIdFor: (sessionId) => (sessionId === 'engine-session' ? 'agent-uuid' : undefined),
dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'go' } },
] as LiveEvent[], 'engine-session')
expect(frames[0]).toMatchObject({ agentId: 'agent-uuid', dbSessionId: 'engine-session' })
})
})
describe('recap lookup spans both ids', () => {
beforeEach(() => { vi.useFakeTimers(); dataDir = mkdtempSync(join(tmpdir(), 'adapter-recent-')) })
afterEach(() => { vi.useRealTimers(); rmSync(dataDir, { recursive: true, force: true }) })
it('stores a recap under the session but serves it for the agent', async () => {
// The device restores a tile by AGENT id; the recap is filed under the ENGINE session id so a
// `--resume` under a new agent still finds it. Ask with the wrong one and every tile came back empty.
const mirror = new CommanderMirror({
send: () => {}, sendWeb: () => {}, hasDevice: () => true,
summarize: async () => 'Short recap\n\nLong body', dataDir,
})
mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'what happened?' } },
{ type: 'text_delta', payload: { content: 'It happened.' } },
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 'engine-session')
await vi.runAllTimersAsync()
expect(mirror.recent('engine-session')).toHaveLength(1)
// …and the daemon's provider resolves an agent id to that session before asking.
const resolve = (id: string) => (id === 'agent-uuid' ? 'engine-session' : id)
expect(mirror.recent(resolve('agent-uuid'))[0].recap).toBe('Short recap')
})
})
describe('CommanderMirror keeps the complete final answer beside the clipped one', () => {
// The answer that exposed this: a five-row event table whose intro line is the only part that survives
// deriveTurnSummary. A device reading it aloud stopped dead at "official sites:" and never reached a
// single event, because the stored body is flattened to one line and cut at 250 characters.
const ANSWER = [
'Here are five notable US events coming up in September–October 2026, with dates checked against official sites:',
'',
'| Event | Dates | Location |',
'| --- | --- | --- |',
'| US Open finals weekend | Sept. 12–13 | Queens, New York |',
'| State Fair of Texas | Sept. 25–Oct. 18 | Dallas, Texas |',
'| Austin City Limits Music Festival | Oct. 2–4 and 9–11 | Zilker Park, Austin, Texas |',
'| Albuquerque International Balloon Fiesta | Oct. 3–11 | Albuquerque, New Mexico |',
'| Great American Beer Festival | Oct. 10–11 | Denver, Colorado |',
].join('\n')
let dir = ''
beforeEach(() => { vi.useFakeTimers(); dir = mkdtempSync(join(tmpdir(), 'adapter-commander-full-')) })
afterEach(() => { vi.useRealTimers(); rmSync(dir, { recursive: true, force: true }) })
async function runTurn(mirror: CommanderMirror, sessionId: string, text: string): Promise<void> {
mirror.ingest([{ type: 'turn_started', payload: { userMessage: 'what is on' } }] as LiveEvent[], sessionId)
mirror.ingest([{ type: 'text_delta', payload: { content: text } }] as LiveEvent[], sessionId)
mirror.ingest([{ type: 'turn_ended', payload: {} }] as LiveEvent[], sessionId)
await vi.runOnlyPendingTimersAsync()
await vi.runOnlyPendingTimersAsync()
}
function build(dataDir: string): CommanderMirror {
return new CommanderMirror({
send: () => {},
sendWeb: () => {},
hasDevice: () => true,
// The shipped wiring: a local derivation, no model in the loop (cli.ts sets summarizeIsLocal).
summarize: async (text) => deriveTurnSummary(text),
summarizeIsLocal: true,
dataDir,
})
}
it('clips text to a preview while fullText keeps every event', async () => {
const mirror = build(dir)
await runTurn(mirror, 'session-full', ANSWER)
const [turn] = mirror.recent('session-full', 1) as Array<{ text: string; recap?: string; fullText?: string }>
expect(turn).toBeTruthy()
// What ships today, unchanged: one line, cut at the documented cap.
expect(turn.text.length).toBeLessThanOrEqual(BODY_MAX_CHARS)
expect(turn.text).not.toContain('Great American Beer Festival')
expect(turn.recap!.length).toBeLessThanOrEqual(RECAP_MAX_CHARS)
// What the new field adds: the answer as the person would read it on screen.
for (const event of ['US Open finals weekend', 'State Fair of Texas', 'Austin City Limits Music Festival',
'Albuquerque International Balloon Fiesta', 'Great American Beer Festival']) {
expect(turn.fullText).toContain(event)
}
// Structure survives too — the table is still a table, not one flattened run.
expect(turn.fullText).toContain('\n')
expect(mirror.lastFullText('session-full')).toBe(turn.fullText)
})
it('pairs each turn with its own answer, and survives a restart', async () => {
const mirror = build(dir)
await runTurn(mirror, 'session-two', 'First answer about the balloon fiesta.')
await runTurn(mirror, 'session-two', ANSWER)
const reloaded = build(dir)
const turns = reloaded.recent('session-two', 3) as Array<{ text: string; fullText?: string }>
expect(turns).toHaveLength(2)
// Newest first, and each row carries ITS OWN answer — the alignment bug this ordering invites.
expect(turns[0].fullText).toContain('Great American Beer Festival')
expect(turns[1].fullText).toBe('First answer about the balloon fiesta.')
})
it('truncates an oversized answer on a character boundary, not a byte one', async () => {
const mirror = build(dir)
// Every character is 3 bytes of UTF-8, so a byte-counted cut lands mid-sequence unless it is guarded.
await runTurn(mirror, 'session-big', 'Sự '.repeat(6000))
const full = mirror.lastFullText('session-big')!
expect(Buffer.byteLength(full, 'utf8')).toBeLessThanOrEqual(8192)
expect(full.endsWith('…')).toBe(true)
expect(full).not.toContain('�')
// A round trip through UTF-8 is lossless only if nothing was severed.
expect(Buffer.from(full, 'utf8').toString('utf8')).toBe(full)
})
})
describe('what the mirror holds, as its process tells the core', () => {
let dir = ''
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'adapter-commander-held-')) })
afterEach(() => { vi.restoreAllMocks(); rmSync(dir, { recursive: true, force: true }) })
it('says each change to a session\'s card or recaps, counts what was stored, and lists every session it holds', async () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
const changed = vi.fn()
const mirror = new CommanderMirror({ send: () => {}, sendWeb: () => {}, hasDevice: () => true, summarize: async () => 'Recap\n\nBody', dataDir: dir, changed })
expect(mirror.snapshot('s1')).toBeNull()
expect(mirror.busy('s1')).toBe(false)
expect(mirror.revision('s1')).toBe(0)
mirror.ingest([{ type: 'turn_started', payload: { userMessage: 'why?' } }] as LiveEvent[], 's1')
expect(mirror.busy('s1')).toBe(true)
expect(mirror.revision('s1')).toBe(1)
expect(mirror.snapshot('s1')).toEqual({ latest: null, history: [], fullTexts: [], asks: ['why?'], busy: true })
mirror.ingest([{ type: 'text_delta', payload: { content: 'Because.' } }, { type: 'turn_ended', payload: {} }] as LiveEvent[], 's1')
await vi.waitFor(() => expect(mirror.revision('s1')).toBe(2))
expect(mirror.snapshot('s1')).toEqual({ latest: 'Recap\n\nBody', history: ['Recap\n\nBody'], fullTexts: ['Because.'], asks: ['why?'], busy: false })
expect(changed.mock.calls.every(([sessionId]) => sessionId === 's1')).toBe(true)
const said = changed.mock.calls.length
mirror.cancel('s1')
mirror.forget('s1')
mirror.inheritSummary('s1', 's2')
expect(changed.mock.calls.slice(said).map(([sessionId]) => sessionId)).toEqual(['s1', 's1', 's2'])
expect(mirror.sessions().sort()).toEqual(['s1', 's2'])
mirror.deleteHistory('s1')
expect(mirror.snapshot('s1')).toBeNull()
expect(mirror.sessions()).toEqual(['s2'])
})
it('says a turn that ends with nothing to recap, and one whose recap failed or came back empty', async () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
const changed = vi.fn()
const summarize = vi.fn(async (): Promise<string | null> => null)
const mirror = new CommanderMirror({ send: () => {}, sendWeb: () => {}, hasDevice: () => true, summarize, dataDir: dir, changed })
const turn = (text: string) => mirror.ingest([
{ type: 'turn_started', payload: { userMessage: 'go' } },
...(text ? [{ type: 'text_delta', payload: { content: text } }] : []),
{ type: 'turn_ended', payload: {} },
] as LiveEvent[], 's1')
for (const [text, fail] of [['', false], ['an answer', false], ['an answer', true]] as const) {
if (fail) summarize.mockRejectedValueOnce(new Error('no'))
changed.mockClear()
turn(text)
await vi.waitFor(() => expect(mirror.busy('s1')).toBe(false))
expect(changed).toHaveBeenLastCalledWith('s1')
}
})
})
describe('CommanderMirror shell results for the turn stats', () => {
const frames: CommanderFrame[] = []
const make = () => {
frames.length = 0
return new CommanderMirror({ send: (f) => frames.push(f), sendWeb: () => {}, hasDevice: () => true, summarize: async () => null, dataDir: mkdtempSync(join(tmpdir(), 'adapter-commander-')) })
}
const ended = () => frames.filter((f) => f.payload.kind === 'tool_end').map((f) => f.payload)
it('emits a top-level shell result with its command, once', () => {
const mirror = make()
mirror.ingest([{ type: 'turn_started', payload: {} },
{ type: 'tool_start', payload: { id: 'b1', tool: 'Bash', input: { command: 'git commit -m x' } } },
{ type: 'tool_end', payload: { id: 'b1', tool: 'Bash', output: 'done', outputTail: 'tail', isError: false, summary: '' } },
{ type: 'tool_end', payload: { id: 'b1', tool: 'Bash', output: 'done', isError: false, summary: '' } },
{ type: 'tool_start', payload: { id: 'b2', tool: 'Bash', input: { command: 'ls' } } },
{ type: 'tool_end', payload: { id: 'b2', tool: 'Bash', output: 'out', isError: true, summary: '' } },
] as LiveEvent[], 's')
expect(ended()).toEqual([
{ kind: 'tool_end', id: 'b1', tool: 'Bash', command: 'git commit -m x', isError: false, outputTail: 'tail' },
{ kind: 'tool_end', id: 'b2', tool: 'Bash', command: 'ls', isError: true },
])
})
it('gives no outputTail when the engine had none (no stats from it)', () => {
const mirror = make()
mirror.ingest([{ type: 'turn_started', payload: {} },
{ type: 'tool_start', payload: { id: 'b1', tool: 'Bash', input: { command: 'npm test' } } },
{ type: 'tool_end', payload: { id: 'b1', tool: 'Bash', output: 'full output', isError: false, summary: '' } },
] as LiveEvent[], 's')
expect(ended()[0]).not.toHaveProperty('outputTail')
})
it('leaves a sub-agent\'s tools and a new turn\'s leftovers alone', () => {
const mirror = make()
mirror.ingest([{ type: 'turn_started', payload: {} },
{ type: 'tool_start', payload: { id: 'in', tool: 'Bash', input: { command: 'npm test' }, parentToolUseId: 'task' } },
{ type: 'tool_end', payload: { id: 'in', tool: 'Bash', output: 'x', isError: false, summary: '' } },
{ type: 'tool_start', payload: { id: 'old', tool: 'Bash', input: { command: 'npm test' } } },
{ type: 'turn_started', payload: {} },
{ type: 'tool_end', payload: { id: 'old', tool: 'Bash', output: 'x', isError: false, summary: '' } },
] as LiveEvent[], 's')
expect(ended()).toEqual([])
})
})
it('CommanderMirror tells the devices, locally, that a turn started', () => {
const frames: CommanderFrame[] = []
const mirror = new CommanderMirror({ send: (f) => frames.push(f), sendWeb: () => {}, hasDevice: () => true, summarize: async () => null, dataDir: mkdtempSync(join(tmpdir(), 'adapter-commander-')) })
mirror.ingest([{ type: 'turn_started', payload: {} }, { type: 'turn_started', payload: {} }] as LiveEvent[], 's')
expect(frames.filter((f) => f.payload.kind === 'turn_started')).toHaveLength(2)
expect(isLocalOnly(frames.find((f) => f.payload.kind === 'turn_started')!)).toBe(true)
})
it('isLocalOnly marks only the shell result card', () => {
expect(isLocalOnly({ type: 'commander_event', payload: { kind: 'turn_started' } })).toBe(true)
expect(isLocalOnly({ type: 'commander_event', payload: { kind: 'tool_end' } })).toBe(true)
expect(isLocalOnly({ type: 'commander_event', payload: { kind: 'reply_text' } })).toBe(true)
expect(isLocalOnly({ type: 'commander_event', payload: { kind: 'tool' } })).toBe(false)
expect(isLocalOnly({ type: 'commander_event' })).toBe(false)
expect(isLocalOnly({ type: 'agent_deleted', payload: { kind: 'tool_end' } })).toBe(false)
})
describe('CommanderMirror decides each finished turn\'s tier once, for every screen', () => {
let dir = ''
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(0)
dir = mkdtempSync(join(tmpdir(), 'adapter-commander-tier-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dir, { recursive: true, force: true })
})
const make = (decideTier: (turn: TierTurn) => Promise<Tier | null>, over: Partial<CommanderMirrorOpts> = {}) => {
const cards: CommanderFrame[] = []
const web: Record<string, unknown>[] = []
const mirror = new CommanderMirror({ send: (f) => cards.push(f), sendWeb: (f) => web.push(f), hasDevice: () => true,
summarize: async () => 'Deployed\n\nThe site is live.', summarizeIsLocal: true, dataDir: dir, decideTier, ...over })
vi.spyOn(console, 'log').mockImplementation(() => {})
const summaries = () => cards.filter((f) => f.payload.kind === 'summary').map((f) => f.payload)
const recaps = () => web.filter((f) => f.type === 'turn_summary').map((f) => f.payload as Record<string, unknown>)
return { mirror, cards, summaries, recaps }
}
const turnOf = (...events: Array<Record<string, unknown>>) => events as unknown as LiveEvent[]
const started = { type: 'turn_started', payload: { userMessage: 'ship it' } }
const reply = { type: 'text_delta', payload: { content: 'The site is live.' } }
const ended = { type: 'turn_ended', payload: {} }
it('carries the tier on the summary card and the apps\' recap, told the turn\'s duration, tests and commits', async () => {
const decideTier = vi.fn(async (_turn: TierTurn): Promise<Tier | null> => 'alert')
const { mirror, cards, summaries, recaps } = make(decideTier)
mirror.ingest(turnOf(started), 's')
vi.setSystemTime(125_000)
mirror.ingest(turnOf(
{ type: 'tool_start', payload: { id: 't1', tool: 'Bash', input: { command: 'npm test' } } },
{ type: 'tool_end', payload: { id: 't1', tool: 'Bash', output: '', outputTail: ' Tests 3 passed (3)', isError: false, summary: '' } },
{ type: 'tool_start', payload: { id: 'c1', tool: 'Bash', input: { command: 'git commit -m ship' } } },
{ type: 'tool_end', payload: { id: 'c1', tool: 'Bash', output: '', outputTail: '[main 1a2b] ship', isError: false, summary: '' } },
reply, ended,
), 's')
await vi.runAllTimersAsync()
expect(decideTier).toHaveBeenCalledExactlyOnceWith({ sessionId: 's', recap: 'Deployed', durationS: 125,
stats: { testsPassed: 3, testsFailed: 0, commits: 1 } })
expect(cards.map((f) => f.payload.kind).slice(-2)).toEqual(['done', 'summary'])
expect(summaries()).toEqual([{ kind: 'summary', text: 'The site is live.', recap: 'Deployed',
notification: { id: expect.any(String), kind: 'done' }, tier: 'alert' }])
expect(recaps()).toEqual([{ summary: 'Deployed\n\nThe site is live.', sessionId: 's',
notification: { id: expect.any(String), kind: 'done' }, tier: 'alert' }])
})
it('tells the decider the recap, or the body when the recap is empty; the card the body, or the recap', async () => {
const decideTier = vi.fn(async (_turn: TierTurn): Promise<Tier | null> => 'list')
// A recap with an empty body after it, then a body with no recap before it.
let summary = 'Deployed\n\n'
const { mirror, summaries } = make(decideTier, { summarize: async () => summary })
mirror.ingest(turnOf(started, reply, ended), 's')
await vi.runAllTimersAsync()
summary = '\n\nThe site is live.'
mirror.ingest(turnOf(started, reply, ended), 's')
await vi.runAllTimersAsync()
expect(decideTier.mock.calls.map(([turn]) => turn.recap)).toEqual(['Deployed', 'The site is live.'])
expect(summaries().map((card) => [card.text, card.recap])).toEqual([['Deployed', 'Deployed'], ['The site is live.', '']])
})
it('asks nobody about a turn that is not news: a sub-agent\'s is silent', async () => {
const decideTier = vi.fn(async (): Promise<Tier | null> => 'alert')
const { mirror, summaries, recaps } = make(decideTier, { isSubagent: () => true })
mirror.ingest(turnOf(started, reply, ended), 's')
await vi.runAllTimersAsync()
expect(decideTier).not.toHaveBeenCalled()
expect(summaries()).toEqual([expect.objectContaining({ subagent: true, notification: null, tier: 'silent' })])
expect(recaps()).toEqual([expect.objectContaining({ notification: null, tier: 'silent' })])
})
it('puts no tier on either frame when nobody is there to tell', async () => {
const { mirror, summaries, recaps } = make(async () => null)
mirror.ingest(turnOf(started, reply, ended), 's')
await vi.runAllTimersAsync()
expect(summaries()).toHaveLength(1)
expect(summaries()[0]).not.toHaveProperty('tier')
expect(recaps()[0]).not.toHaveProperty('tier')
})
it('does not hold a recap for a newer turn: it goes out at the fallback\'s tier before that turn\'s first card', async () => {
let answer: (tier: Tier | null) => void = () => {}
const decideTier = vi.fn(() => new Promise<Tier | null>((resolve) => { answer = resolve }))
const { mirror, cards, summaries, recaps } = make(decideTier)
mirror.ingest(turnOf(started), 's')
vi.setSystemTime(130_000)
mirror.ingest(turnOf(reply, ended), 's')
await vi.runAllTimersAsync()
expect(decideTier).toHaveBeenCalledTimes(1)
expect(summaries()).toEqual([])
mirror.ingest(turnOf(started), 's')
expect(cards.map((f) => f.payload.kind).slice(-4)).toEqual(['done', 'summary', 'turn_started', 'processing'])
expect(summaries()).toEqual([expect.objectContaining({ tier: 'list' })])
// The decision that arrives afterwards changes nothing: the recap was told once.
answer('alert')
await vi.runAllTimersAsync()
expect(summaries()).toHaveLength(1)
expect(recaps()).toEqual([expect.objectContaining({ tier: 'list' })])
})
it('falls back to the rule when the decider fails, and knows no duration for a turn picked up mid-way', async () => {
const decideTier = vi.fn(async (_turn: TierTurn): Promise<Tier | null> => { throw new Error('no decision') })
const { mirror, summaries } = make(decideTier)
// Attached mid-turn: its start is a replay, the rest of it is live and still news.
mirror.ingest(turnOf(started), 's', { replay: true })
vi.setSystemTime(600_000)
mirror.ingest(turnOf(reply, ended), 's')
await vi.runAllTimersAsync()
expect(decideTier.mock.calls[0][0]).toMatchObject({ durationS: null, stats: {} })
expect(summaries()).toEqual([expect.objectContaining({ tier: 'silent' })])
})
})