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
Add an attention feed, a panic stop and the fleet command API to the daemon
bubu-dudu082be5467dc1
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 88e24ad5a..e11d362e9 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -304,6 +304,7 @@ import {import { probeGatewayRuntime } from './lib/gatewayRuntime.js'import { probeGridAssignment, sameGridAssignment } from './lib/gridAssignment.js'import { agentFrame, lastActivityAt, type AgentFrame } from './lib/agentFrame.js'+import { FleetControl, type FleetSessionLike } from './fleet/control.js'import { agentTokenUsage } from './lib/agentTokenUsage.js'import { SessionInputController } from './lib/sessionInput.js'import { DeviceResultJournal } from './lib/autonomous-device/resultJournal.js'@@ -454,7 +455,10 @@ Machine:harness stop stop the background adapter (keeps the SSO session)harness reset stop the adapter and clear local CLI stateharness status show whether it's running (+ version)- harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktop+ harness attention [--kanban] every agent's state: working, waiting on you, needs permission, failed, done+ harness stop-all [--except=<agentId>]+ cancel every agent's turn on this computer (the panic stop)+ harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktopharness tui all of Harness in this terminal: swarms, panes, every machine (⌥O ⌥P ⌥N)harness new [agent] [@machine] [folder|name] [-- task]make a harness from a shell: \`harness new\` is claude here; see \`harness new -h\`@@ -2477,6 +2481,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {): void => {if (events.length) queuedSessionEvents.push({ sessionId, events, opts })}+ // The fleet controls (attention, stop-all, local commands; cli/src/fleet/control.ts). Built next to the+ // hook server below; the taps before that point reach it through this slot, so an event that lands+ // during start-up is dropped instead of reaching an object that does not exist yet.+ let fleetControlRef: FleetControl | null = null/*** A turn died inside the engine instead of finishing. Neither devin nor commandcode has a StopFailure* hook, so nothing else would tell the clients: the web would sit on the typing indicator and the@@ -2490,6 +2498,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {deviceMessage = message,): void => {console.log(`[turn] ${sid(sessionId)} aborted by ${engine} error · ${preview(message)}`)+ fleetControlRef?.attention.failed(agentIdFor(sessionId), message)backend.send({ type: 'error', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { message } })backend.sendCommander({type: 'commander_event',@@ -2944,7 +2953,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Hold the working state across the gap too: the CLI needs a moment to move to the next question, and// that gap is exactly where the stale recap used to flash back.const target = payload.sessionId || payload.agentId- if (typeof target === 'string' && target) showAwaitingAnswer(target)+ if (typeof target === 'string' && target) { showAwaitingAnswer(target); fleetControlRef?.attention.answered(agentIdFor(target)) }// Returned so the client that answered hears a refusal — STALE_QUESTION when the dialog changed// before its answer arrived — as `question_response_result`.return questions.answer(payload)@@ -2963,6 +2972,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {isDriving: (sessionId) => questions.isDriving(sessionId),onQuestion: (sessionId, requestId, shaped, detail) => {deviceInput.setUserAction(agentIdFor(sessionId), true)+ fleetControlRef?.attention.question(agentIdFor(sessionId), detail?.permission === true, shaped[0]?.q ?? '')questions.remember(requestId, sessionId)showAwaitingAnswer(sessionId)const asked = {@@ -3323,6 +3333,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The phone notifies on neither. Absent = false, so a client that predates these reads every end as// it always did.if (event.type === 'turn_ended') {+ if (!opts?.resumed && !opts?.replay) fleetControlRef?.attention.turnEnded(agentId, { aborted: event.payload.aborted === true })if (opts?.resumed || opts?.replay) frame.replay = true// The pair harness is the daemon talking to you, not work finishing: no app notifies on it.if (isSubagentSession(sessionId) || isPairHarnessSession(sessionId)) frame.subagent = true@@ -3338,6 +3349,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {}if (event.type === 'turn_started') {if (daemons.on()) zooTurnCounter.started(sessionId, { replay: !!(opts?.resumed || opts?.replay) })+ if (!opts?.resumed && !opts?.replay) fleetControlRef?.attention.turnStarted(agentId, event.payload.userMessage)turnStartedAt.set(sessionId, Date.now())console.log(`[turn] ${sid(sessionId)} started · engine=${registry.bySession(sessionId)?.engine ?? 'claude'} · bytes=${Buffer.byteLength(event.payload.userMessage, 'utf8')}`)input.onTurnStarted(agentIdFor(sessionId), event.payload.userMessage)@@ -4184,6 +4196,19 @@ async function runForeground(session: AuthSession | null): Promise<void> {return { status: 200, body: withStaleMarker(cached.body, cached.fetchedAt) }}+ // Built here so the hook server below can hand it tool calls, and everything after can tap it.+ const fleetSession = (s: RegisteredSession): FleetSessionLike => ({+ agentId: s.agentId, sessionId: s.sessionId, engine: s.engine, active: s.active, tmuxPane: s.tmuxPane,+ cwd: s.cwd ?? undefined, transcriptPath: s.transcriptPath ?? undefined, model: (s as { model?: string | null }).model ?? null, name: projectDisplayName(s),+ })+ const fleetControl = new FleetControl({+ machineId: () => backend.machineId,+ machineName: () => terminalHintMachineName(),+ sessions: () => registry.advertised().map(fleetSession),+ sendLocal: (frame) => backend.sendLocal(frame),+ cancelAgent: (agentId, confirmed) => cancelAgent(agentId, confirmed),+ })+ fleetControlRef = fleetControlconst { server: hookServer, port: hookPort, localSocket } = await startHookServer(daemonPort(), {onPromptContext: async (agentId, prompt) => {@@ -4206,6 +4231,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {return result},onCommandBar: commandBarService,+ onAttention: () => fleetControl.attentionPayload(),+ onStopAll: (except) => fleetControl.stopAll(except),+ onFleet: (action, args) => fleetControl.command(action, args),onAutonomousDeviceRequest: async (method, target, body) => {if (!autonomousDeviceService) return { status: 503, body: { error: { code: 'UNAVAILABLE', message: 'Autonomous device service is starting' } } }return autonomousDeviceLocalRequest({@@ -4307,6 +4335,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {onTurnStop: ({ sessionId, status }) => {const session = registry.resolve(sessionId)if (!session) return+ if (status === 'error') fleetControl.attention.failed(session.agentId, 'engine ended the turn with an error')if (session.engine === 'cursor') {void (async () => {await cursorTaskHooks.wait(sessionId)@@ -5318,7 +5347,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The window looked at a harness, so the dial's drawer row for it is stale.// The dial's own tap already reaches the window (`agent.open`); this is the// return leg, and the pair is what keeps the badge and the pill equal.- onAgentSeen: (agentId, readToken) => { void cableRef?.agentSeen(agentId, readToken) },+ onAgentSeen: (agentId, readToken) => { fleetControlRef?.attention.seen(agentId); void cableRef?.agentSeen(agentId, readToken) },// Agents the window has a tile for. A finished turn on one of these is// already in front of the person, so the dial updates its tile in silence// rather than beeping about something being looked at.@@ -6059,6 +6088,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const sessionId = record?.sessionId ?? idconst st = turnStates.get(sessionId)if (st) st.turnOpen = false+ fleetControlRef?.attention.cancelled(record?.agentId ?? sessionId)codexNormalizers.get(sessionId)?.closeTurn()cursorNormalizers.get(sessionId)?.closeTurn()opencodeReaders.get(sessionId)?.closeTurn()@@ -7934,6 +7964,46 @@ async function daemonCall(method: 'GET' | 'POST', path: string, body?: unknown):return { res, json }}+/**+ * The fleet commands (cli/src/fleet/control.ts; first written by Fred Nix in the nixfred fork): every one+ * is a POST to the daemon's local /api/fleet with an action name, so the CLI never needs the registry or+ * the E2EE state. `--json` prints the raw reply.+ */+async function fleetCommand(cmd: string, args: string[], flags: string[]): Promise<void> {+ const json = flags.includes('--json')+ const flag = (name: string): string | undefined => flags.find((f) => f.startsWith(`--${name}=`))?.slice(name.length + 3)+ let action = cmd+ let body: Record<string, unknown> = {}+ switch (cmd) {+ case 'attention': break+ case 'stop-all': body = { except: flag('except') ?? args[0] ?? null }; break+ default: action = args[0] ?? ''; body = {}; if (!action) { console.error('Usage: harness fleet <action> [--key=value ...]'); process.exit(1) }+ for (const f of flags) { const m = /^--([a-zA-Z-]+)=(.*)$/.exec(f); if (m) body[m[1]!] = m[2] }+ }+ const { res, json: reply } = await daemonCall('POST', '/api/fleet', { action, ...body })+ if (json) { console.log(JSON.stringify(reply, null, 2)); process.exit(res.ok ? 0 : 1) }+ if (!res.ok || reply.ok === false) { console.error(`✗ ${String(reply.error ?? res.statusText)}`); process.exit(1) }+ const result = reply.result as unknown+ if (action === 'attention' && result && typeof result === 'object') {+ const r = result as { hostname: string; summary: { state: string; count: number }; agents: Array<{ glyph: string; name: string; engine: string; state: string; label: string; detail: string }> }+ if (flags.includes('--kanban')) {+ // Columns in the order a person works them: what needs me, what broke, what finished, what runs.+ const columns: Array<[string, string[]]> = [['NEEDS YOU', ['permission', 'waiting']], ['FAILED', ['failed']], ['DONE, UNREVIEWED', ['done']], ['WORKING', ['working']], ['IDLE', ['idle', 'offline']]]+ for (const [title, states] of columns) {+ const rows = r.agents.filter((a) => states.includes(a.state))+ if (!rows.length) continue+ console.log(`${title} (${rows.length})`)+ for (const a of rows) console.log(` ${a.glyph} ${a.name.padEnd(28)} ${a.engine.padEnd(10)}${a.detail ? ` ${a.detail}` : ''}`)+ }+ return+ }+ console.log(`${r.hostname}: ${r.summary.count} ${r.summary.state}`)+ for (const a of r.agents) console.log(` ${a.glyph} ${a.name.padEnd(28)} ${a.engine.padEnd(10)} ${a.label}${a.detail ? ` ${a.detail}` : ''}`)+ return+ }+ console.log(typeof result === 'string' ? result : JSON.stringify(result, null, 2))+}+/** `harness pair <code>` — send a browser/device pairing code to the running daemon (localhost). */async function pairCommand(code: string | undefined): Promise<void> {if (!code) {@@ -9159,6 +9229,9 @@ switch (cmd) {case 'reset':resetCommand().catch(onError)break+ case 'attention': case 'stop-all': case 'fleet':+ fleetCommand(cmd, args, flags).catch(onError)+ breakcase 'status':status().catch(onError)breakdiff --git a/cli/src/fleet/control.spec.ts b/cli/src/fleet/control.spec.tsnew file mode 100644index 000000000..b99c9fb4b--- /dev/null+++ b/cli/src/fleet/control.spec.ts@@ -0,0 +1,64 @@+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT), as nixfredWiring.spec.ts.++import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { FleetControl, type FleetControlDeps, type FleetSessionLike } from './control.js'++const session = (agentId: string, extra: Partial<FleetSessionLike> = {}): FleetSessionLike => ({+ agentId, sessionId: `s-${agentId}`, engine: 'claude', active: true, tmuxPane: '%3', cwd: '/tmp/proj', name: agentId, model: 'claude-sonnet', ...extra,+})++describe('FleetControl', () => {+ let dir: string+ let sent: Array<{ type: string; payload: Record<string, unknown> }>+ let cancelled: string[]+ let sessions: FleetSessionLike[]+ let fleet: FleetControl+ let now: number++ const deps = (): FleetControlDeps => ({+ dataDir: dir,+ machineId: () => 'm-1',+ machineName: () => 'gus',+ sessions: () => sessions,+ sendLocal: (f) => { sent.push(f) },+ cancelAgent: async (id) => { cancelled.push(id); return true },+ now: () => now,+ })++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'fleet-'))+ sent = []; cancelled = []; now = Date.UTC(2026, 8, 26, 16, 0)+ sessions = [session('a'), session('b')]+ fleet = new FleetControl(deps())+ })+ afterEach(() => { rmSync(dir, { recursive: true, force: true }) })++ it('turns attention changes into a local frame with a summary and glyphs', () => {+ fleet.attention.turnStarted('a', 'fix login')+ fleet.attention.question('b', true, 'Bash: git push')+ const last = sent.at(-1)!+ expect(last.type).toBe('attention')+ const p = last.payload as { hostname: string; summary: { state: string; agentId: string }; agents: Array<{ agentId: string; state: string; glyph: string }> }+ expect(p.hostname).toBe('gus')+ expect(p.summary).toMatchObject({ state: 'permission', agentId: 'b' })+ expect(p.agents.map((a) => `${a.agentId}:${a.state}:${a.glyph}`)).toEqual(['b:permission:!', 'a:working:~'])+ })++ it('stopAll cancels every active agent but the one kept', async () => {+ const out = await fleet.stopAll('b')+ expect(out.cancelled).toEqual(['a'])+ expect(cancelled).toEqual(['a'])+ expect(fleet.attention.get('a')?.state).toBe('idle')+ })++ it('exposes the local command surface', async () => {+ await expect(fleet.command('nope', {})).rejects.toThrow(/unknown fleet action/)+ const att = await fleet.command('attention', {}) as { agents: unknown[] }+ expect(att.agents).toHaveLength(2)+ const stopped = await fleet.command('stop-all', { except: 'a' }) as { cancelled: string[] }+ expect(stopped.cancelled).toEqual(['b'])+ })+})diff --git a/cli/src/fleet/control.ts b/cli/src/fleet/control.tsnew file mode 100644index 000000000..7db75ecfa--- /dev/null+++ b/cli/src/fleet/control.ts@@ -0,0 +1,91 @@+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT), where it was+// `nixfredWiring.ts`. Ported here without the device firmware frames, Orca watch mode or Hermes parts.++/**+ * The fleet controls, wired as one object the daemon calls at a handful of points. Everything here is+ * built from pure modules (lib/attention, ...) so the daemon's own files change as little as possible:+ *+ * attention turn/question/cancel taps → `attention` frames to local windows, `GET /api/attention`+ * stop-all cancel every agent turn on this machine (`POST /api/stop-all`, `harness stop-all`)+ * commands the `harness <command>` local API behind `POST /api/fleet`+ */+import { mkdirSync } from 'node:fs'+import { env } from '../config/env.js'+import { AttentionTracker, summarizeAttention, type AttentionRow } from '../lib/attention.js'++export interface FleetSessionLike {+ agentId: string+ sessionId: string+ engine: string+ active: boolean+ tmuxPane?: string+ cwd?: string+ transcriptPath?: string+ model?: string | null+ name: string+}++export interface FleetControlDeps {+ dataDir?: string+ machineId: () => string+ machineName: () => string+ sessions: () => FleetSessionLike[]+ /** Push a frame to every local window (desktop). */+ sendLocal: (frame: { type: string; payload: Record<string, unknown> }) => void+ cancelAgent: (agentId: string, confirmed: boolean) => Promise<boolean>+ now?: () => number+}++export class FleetControl {+ readonly attention: AttentionTracker+ protected readonly dataDir: string+ protected readonly now: () => number++ constructor(protected readonly deps: FleetControlDeps) {+ this.now = deps.now ?? Date.now+ this.dataDir = deps.dataDir ?? env.ADAPTER_DATA_DIR+ mkdirSync(this.dataDir, { recursive: true })+ this.attention = new AttentionTracker(this.now)+ this.attention.onChange(() => this.pushAttention())+ }++ // ── attention ───────────────────────────────────────────────────────────────────────────────────++ snapshot(): AttentionRow[] { return this.attention.snapshot(this.deps.sessions(), this.deps.machineName()) }++ attentionPayload(): Record<string, unknown> {+ const agents = this.snapshot()+ return { machineId: this.deps.machineId(), hostname: this.deps.machineName(), at: this.now(), summary: summarizeAttention(agents), agents }+ }++ /** Every local window hears each real transition; the bar widget polls `GET /api/attention` instead. */+ protected pushAttention(): void {+ this.deps.sendLocal({ type: 'attention', payload: this.attentionPayload() })+ }++ // ── panic stop ─────────────────────────────────────────────────────────────────────────────────++ async stopAll(exceptAgentId: string | null): Promise<{ cancelled: string[] }> {+ const cancelled: string[] = []+ for (const s of this.deps.sessions()) {+ if (!s.active || s.agentId === exceptAgentId) continue+ try { if (await this.deps.cancelAgent(s.agentId, true)) cancelled.push(s.agentId) } catch { /* next */ }+ this.attention.cancelled(s.agentId)+ }+ console.log(`[fleet] panic stop: cancelled ${cancelled.length} agent(s), kept ${exceptAgentId ?? 'none'}`)+ return { cancelled }+ }++ // ── the local command surface (`POST /api/fleet`) ──────────────────────────────────────────────++ async command(action: string, args: Record<string, unknown>): Promise<unknown> {+ const str = (k: string): string => (typeof args[k] === 'string' ? args[k] as string : '')+ switch (action) {+ case 'attention': return this.attentionPayload()+ case 'stop-all': return this.stopAll(str('except') || null)+ default: throw new Error(`unknown fleet action: ${action}`)+ }+ }+}++export type { AttentionRow }diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex 293795607..4530b007b 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -802,3 +802,34 @@ describe('the device history and dismiss endpoints', () => {expect((await post({ confirm: true, head: 'x' })).status).toBe(400)})})++describe('fleet controls: /api/attention, /api/stop-all, /api/fleet', () => {+ const local = { 'content-type': 'application/json', 'x-adapter-local': '1' }+ it('serves the attention snapshot read-only, and an empty one when nothing is wired', async () => {+ const { base } = await start({ onAttention: () => ({ agents: [{ agentId: 'a', state: 'waiting' }] }) })+ expect(await (await fetch(`${base}/api/attention`)).json()).toEqual({ agents: [{ agentId: 'a', state: 'waiting' }] })+ server?.close()+ const bare = await start()+ expect(await (await fetch(`${bare.base}/api/attention`)).json()).toEqual({ agents: [] })+ })+ it('runs the panic stop only for a local caller, keeping the agent named', async () => {+ const onStopAll = vi.fn(async () => ({ cancelled: ['b'] }))+ const { base } = await start({ onStopAll })+ expect((await fetch(`${base}/api/stop-all`, { method: 'POST', body: '{}' })).status).toBe(403)+ expect(onStopAll).not.toHaveBeenCalled()+ const res = await fetch(`${base}/api/stop-all`, { method: 'POST', headers: local, body: JSON.stringify({ except: 'a' }) })+ expect(await res.json()).toEqual({ cancelled: ['b'] })+ expect(onStopAll).toHaveBeenCalledExactlyOnceWith('a')+ })+ it('hands a named action to the fleet handler and reports its error', async () => {+ const onFleet = vi.fn(async (action: string) => { if (action === 'boom') throw new Error('no such thing'); return { action } })+ const { base } = await start({ onFleet })+ const ok = await fetch(`${base}/api/fleet`, { method: 'POST', headers: local, body: JSON.stringify({ action: 'attention', x: 1 }) })+ expect(await ok.json()).toEqual({ ok: true, result: { action: 'attention' } })+ expect(onFleet).toHaveBeenCalledWith('attention', { x: 1 })+ const bad = await fetch(`${base}/api/fleet`, { method: 'POST', headers: local, body: JSON.stringify({ action: 'boom' }) })+ expect(bad.status).toBe(400)+ expect(await bad.json()).toEqual({ ok: false, error: 'no such thing' })+ expect((await fetch(`${base}/api/fleet`, { method: 'POST', headers: local, body: JSON.stringify({}) })).status).toBe(400)+ })+})diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 2928a960e..2b1f98b85 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -116,6 +116,12 @@ export interface HookServerHandlers {toolName: stringinput: unknown}) => void+ /** GET /api/attention: every agent's attention state for the bar widget and other local readers. */+ onAttention?: () => unknown+ /** POST /api/stop-all: cancel every agent's turn except one (the panic stop). */+ onStopAll?: (exceptAgentId: string | null) => Promise<{ cancelled: string[] }>+ /** POST /api/fleet {action, ...args}: the local command surface behind the fleet `harness` commands. */+ onFleet?: (action: string, args: Record<string, unknown>) => Promise<unknown>onTurnStop?: (body: {sessionId: stringstatus?: string@@ -500,6 +506,33 @@ export function startHookServer(if (req.method === 'GET' && url === '/api/status') {json(200, handlers.onStatus ? await handlers.onStatus() : { supported: false }); return}+ // Attention snapshot for the bar widget and any local reader: loopback only, read-only, no+ // secrets (names, engines, states). Same trust as /api/status.+ if (req.method === 'GET' && url === '/api/attention') {+ json(200, handlers.onAttention ? handlers.onAttention() : { agents: [] }); return+ }+ // Panic stop: every agent's turn is cancelled except the one named. Mutating, so the same+ // same-origin guard as the other local mutations.+ if (req.method === 'POST' && url === '/api/stop-all') {+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }+ if (!handlers.onStopAll) { json(503, { error: 'UNAVAILABLE' }); return }+ let body: { except?: string } = {}+ try { const raw = await readBody(req); body = raw ? JSON.parse(raw) as { except?: string } : {} } catch { json(400, { error: 'bad json' }); return }+ try { json(200, await handlers.onStopAll(typeof body.except === 'string' && body.except ? body.except : null)) }+ catch (e) { json(500, { error: e instanceof Error ? e.message : 'INTERNAL' }) }+ return+ }+ if (req.method === 'POST' && url === '/api/fleet') {+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }+ if (!handlers.onFleet) { json(503, { error: 'UNAVAILABLE' }); return }+ let body: { action?: unknown } & Record<string, unknown>+ try { body = JSON.parse(await readBody(req)) as typeof body } catch { json(400, { error: 'bad json' }); return }+ if (typeof body.action !== 'string' || !/^[a-z][a-z0-9-]{1,40}$/.test(body.action)) { json(400, { error: 'MISSING_ACTION' }); return }+ const { action, ...args } = body+ try { json(200, { ok: true, result: await handlers.onFleet(action, args) }) }+ catch (e) { json(400, { ok: false, error: e instanceof Error ? e.message : String(e) }) }+ return+ }if (req.method === 'GET' && url === '/api/logs') {res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end(handlers.onLogs ? handlers.onLogs() : ''); return}diff --git a/cli/src/lib/attention.spec.ts b/cli/src/lib/attention.spec.tsnew file mode 100644index 000000000..5cf988c10--- /dev/null+++ b/cli/src/lib/attention.spec.ts@@ -0,0 +1,62 @@+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).++import { describe, expect, it } from 'vitest'+import { AttentionTracker, summarizeAttention } from './attention.js'++const s = (agentId: string, active = true, engine = 'claude') => ({ agentId, sessionId: `s-${agentId}`, engine, active, tmuxPane: '%1', name: agentId })++describe('AttentionTracker', () => {+ it('walks a turn: working, waiting, working, done, then reviewed', () => {+ let t = 1000+ const tr = new AttentionTracker(() => t)+ const seen: string[] = []+ tr.onChange((e, prev) => seen.push(`${prev ?? 'none'}>${e.state}`))+ tr.turnStarted('a', 'fix the login flow')+ t = 2000; tr.question('a', false, 'Which branch?')+ t = 3000; tr.answered('a')+ t = 4000; tr.turnEnded('a')+ t = 5000; tr.seen('a')+ expect(seen).toEqual(['none>working', 'working>waiting', 'waiting>working', 'working>done', 'done>idle'])+ expect(tr.get('a')).toEqual({ agentId: 'a', state: 'idle', since: 5000, detail: 'reviewed' })+ })+ it('keeps `since` when the state repeats and ignores identical sets', () => {+ let t = 10+ const tr = new AttentionTracker(() => t)+ let changes = 0+ tr.onChange(() => changes++)+ tr.turnStarted('a', 'x'); t = 20; tr.turnStarted('a', 'x')+ expect(changes).toBe(1)+ expect(tr.get('a')?.since).toBe(10)+ })+ it('permission is its own state and answered() only clears asking states', () => {+ const tr = new AttentionTracker(() => 1)+ tr.question('a', true, 'Bash: git push')+ expect(tr.get('a')?.state).toBe('permission')+ tr.turnEnded('a')+ tr.answered('a')+ expect(tr.get('a')?.state).toBe('done')+ })+ it('failed and cancelled are distinct from done', () => {+ const tr = new AttentionTracker(() => 1)+ tr.turnEnded('a', { error: 'API 529 overloaded' })+ tr.turnEnded('b', { aborted: true })+ expect(tr.get('a')).toMatchObject({ state: 'failed', detail: 'API 529 overloaded' })+ expect(tr.get('b')).toMatchObject({ state: 'idle', detail: 'cancelled' })+ })+ it('snapshot orders by priority, marks inactive sessions offline, and carries glyph and label', () => {+ let t = 1+ const tr = new AttentionTracker(() => t++)+ tr.turnStarted('w'); tr.question('q', false); tr.question('p', true); tr.turnEnded('d'); tr.failed('f', 'boom')+ const rows = tr.snapshot([s('w'), s('q'), s('p'), s('d'), s('f'), s('o', false), s('n')], 'gus')+ expect(rows.map((r) => `${r.agentId}:${r.state}`)).toEqual(['p:permission', 'q:waiting', 'f:failed', 'd:done', 'w:working', 'n:idle', 'o:offline'])+ expect(rows[0]).toMatchObject({ glyph: '!', label: 'needs permission', machine: 'gus', tmuxPane: '%1' })+ expect(rows.at(-1)).toMatchObject({ glyph: '.', detail: '' })+ })+ it('summarizes a fleet by the most urgent state', () => {+ const tr = new AttentionTracker(() => 1)+ tr.turnStarted('a'); tr.turnStarted('b'); tr.question('c', false)+ const rows = tr.snapshot([s('a'), s('b'), s('c')], 'gus')+ expect(summarizeAttention(rows)).toEqual({ state: 'waiting', count: 1, agentId: 'c' })+ expect(summarizeAttention([])).toEqual({ state: 'offline', count: 0, agentId: null })+ })+})diff --git a/cli/src/lib/attention.ts b/cli/src/lib/attention.tsnew file mode 100644index 000000000..0f0e40c33--- /dev/null+++ b/cli/src/lib/attention.ts@@ -0,0 +1,117 @@+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).++/**+ * One typed answer to "what does this agent need from me right now", derived from signals the daemon+ * already has: turn start/end, the question watcher, permission dialogs, cancels, engine errors and+ * whether a window has looked at the agent since it finished. Today the frame only says active or+ * offline; the bar, the device, the brakes and the inbox all need this instead.+ *+ * Pure: no I/O. The daemon feeds it and asks for snapshots. Every state carries a non-colour glyph and a+ * short label so a screen with no colour, or a person who cannot tell red from green, reads the same thing.+ */+export type AttentionState = 'working' | 'waiting' | 'permission' | 'failed' | 'done' | 'idle' | 'offline'++export interface AttentionEntry {+ agentId: string+ state: AttentionState+ since: number+ detail: string+}++export interface AttentionRow extends AttentionEntry {+ name: string+ engine: string+ machine: string+ sessionId: string+ tmuxPane: string | null+ glyph: string+ label: string+}++export const ATTENTION_GLYPH: Record<AttentionState, string> = {+ working: '~', waiting: '?', permission: '!', failed: 'x', done: '*', idle: '-', offline: '.',+}+export const ATTENTION_LABEL: Record<AttentionState, string> = {+ working: 'working', waiting: 'waiting on you', permission: 'needs permission', failed: 'failed',+ done: 'done, unreviewed', idle: 'idle', offline: 'offline',+}++/** States that deserve a human's attention, in priority order (first wins when summarising a fleet). */+export const ATTENTION_PRIORITY: AttentionState[] = ['permission', 'waiting', 'failed', 'done', 'working', 'idle', 'offline']++export interface AttentionSessionLike {+ agentId: string+ sessionId: string+ engine: string+ active: boolean+ tmuxPane?: string+ name: string+}++export class AttentionTracker {+ private readonly entries = new Map<string, AttentionEntry>()+ private readonly listeners = new Set<(row: AttentionEntry, previous: AttentionState | null) => void>()++ constructor(private readonly now: () => number = Date.now) {}++ onChange(cb: (row: AttentionEntry, previous: AttentionState | null) => void): () => void {+ this.listeners.add(cb)+ return () => { this.listeners.delete(cb) }+ }++ get(agentId: string): AttentionEntry | undefined { return this.entries.get(agentId) }++ /** Set the state; a no-op when unchanged so listeners only hear real transitions. */+ set(agentId: string, state: AttentionState, detail = ''): AttentionEntry {+ const prev = this.entries.get(agentId)+ if (prev && prev.state === state && prev.detail === detail) return prev+ const entry: AttentionEntry = { agentId, state, since: prev?.state === state ? prev.since : this.now(), detail }+ this.entries.set(agentId, entry)+ for (const cb of this.listeners) cb(entry, prev?.state ?? null)+ return entry+ }++ turnStarted(agentId: string, userMessage = ''): void { this.set(agentId, 'working', userMessage.slice(0, 120)) }+ question(agentId: string, permission: boolean, detail = ''): void { this.set(agentId, permission ? 'permission' : 'waiting', detail.slice(0, 120)) }+ answered(agentId: string): void { if (this.isAsking(agentId)) this.set(agentId, 'working', 'answer delivered') }+ turnEnded(agentId: string, opts: { aborted?: boolean; error?: string } = {}): void {+ if (opts.error) this.set(agentId, 'failed', opts.error.slice(0, 120))+ else if (opts.aborted) this.set(agentId, 'idle', 'cancelled')+ else this.set(agentId, 'done', '')+ }+ failed(agentId: string, message: string): void { this.set(agentId, 'failed', message.slice(0, 120)) }+ cancelled(agentId: string): void { this.set(agentId, 'idle', 'cancelled') }+ /** A window showed this agent: "done, unreviewed" is reviewed now. Other states are unchanged. */+ seen(agentId: string): void { if (this.entries.get(agentId)?.state === 'done') this.set(agentId, 'idle', 'reviewed') }+ offline(agentId: string): void { this.set(agentId, 'offline', '') }+ forget(agentId: string): void { this.entries.delete(agentId) }++ isAsking(agentId: string): boolean {+ const s = this.entries.get(agentId)?.state+ return s === 'waiting' || s === 'permission'+ }++ /** Rows for every session the daemon advertises, in fleet priority order then by recency. */+ snapshot(sessions: AttentionSessionLike[], machine: string): AttentionRow[] {+ const rows = sessions.map((s): AttentionRow => {+ const e = this.entries.get(s.agentId)+ const state: AttentionState = !s.active ? 'offline' : e?.state ?? 'idle'+ return {+ agentId: s.agentId, sessionId: s.sessionId, engine: s.engine, machine, name: s.name,+ tmuxPane: s.tmuxPane ?? null,+ state, since: e?.since ?? 0, detail: state === 'offline' ? '' : e?.detail ?? '',+ glyph: ATTENTION_GLYPH[state], label: ATTENTION_LABEL[state],+ }+ })+ return rows.sort((a, b) => ATTENTION_PRIORITY.indexOf(a.state) - ATTENTION_PRIORITY.indexOf(b.state) || b.since - a.since)+ }+}++/** The one thing a fleet-level indicator shows: the most urgent state present, and how many share it. */+export function summarizeAttention(rows: AttentionRow[]): { state: AttentionState; count: number; agentId: string | null } {+ for (const state of ATTENTION_PRIORITY) {+ const hits = rows.filter((r) => r.state === state)+ if (hits.length) return { state, count: hits.length, agentId: hits[0]!.agentId }+ }+ return { state: 'offline', count: 0, agentId: null }+}