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
fix(cli): let the dial count as a device, and keep three turns of recap
0xdiego25b746ae1bcd04
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 80f9eac73..5feed0738 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -30,7 +30,7 @@ export interface CableHostWiring {sendTurn: (agentId: string, text: string) => voidstopTurn: (agentId: string) => voidanswer: (agentId: string, id: string, optionId: string) => void- /** Recaps of an agent's last `n` completed turns, for routing. */+ /** Recaps of an agent's last `n` completed turns — for routing, and for redrawing a reattached dial. */recent: (agentId: string, n: number) => RecentTurn[]/** The opaque runtime-v1 profile, which is where the dial's Model/Effort chips come from. */runtimeProfile?: (session: RegisteredSession) => string | null@@ -102,6 +102,14 @@ export class DaemonCableHost implements CableHost {this.wiring.updateAgent?.(agentId, model, effort)}+ /** The last few turns, newest first, in the shape the dial's tile draws: a headline and a body. */+ recentSummaries(agentId: string): Array<{ recap: string; text: string }> {+ return this.wiring+ .recent(agentId, 3)+ .map((r) => ({ recap: r?.recap ?? '', text: r?.text ?? '' }))+ .filter((s) => s.recap || s.text)+ }+async listModels(agentId: string): Promise<string[]> {const models = (await this.wiring.listModels?.(agentId)) ?? []return models.map((m) => m.id).filter(Boolean)diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex a77880158..61f212c78 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -76,6 +76,7 @@ function makeHost(over: Partial<CableHost> = {}) {focus: vi.fn(),updateAgent: vi.fn(),listModels: async () => ['runtime-v1:s1:claude:opus@high', 'runtime-v1:s1:claude:sonnet@low'],+ recentSummaries: () => [],transcribe: async () => 'fix the login screen',route: async () => ({ agentId: 'a1', confidence: 0.9, reason: 'name matched' }),log: () => {},@@ -223,6 +224,25 @@ describe('cable session', () => {await session.stop()})+ it('redraws a reattached dial with what each agent was last doing', async () => {+ // The summaries were on disk the whole time; a tile with a name and no recap has forgotten the work+ // it belongs to. Newest LAST on the wire so it ends up on top of the tile's stack.+ const host = makeHost({+ recentSummaries: (id) =>+ id === 'a1' ? [{ recap: 'newest', text: 'b2' }, { recap: 'older', text: 'b1' }] : [],+ })+ const { session, port } = await connect(host)+ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.types().filter((t) => t === 'summary')).toHaveLength(2))++ const restores = port.sent.filter((m) => m.t === 'summary')+ expect(restores.map((m) => m.recap)).toEqual(['older', 'newest'])+ // Every one is marked history. Without this, plugging the cable in announces every turn that+ // finished while it was unplugged — a beep and a notification each.+ expect(restores.every((m) => m.restore === true)).toBe(true)+ await session.stop()+ })+it('answers models.list even when the catalog is empty', async () => {// The dial BLOCKS on this one message — it cannot draw a picker until the catalog is in hand. Silence// strands it on a spinner until its own timeout, which reads as a hang rather than "no choices here".diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex f1e5abe6e..cc1307e67 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -77,6 +77,8 @@ export interface CableHost {route(transcript: string, agents: CableAgent[]): Promise<RouteDecision>/** The runtime model/effort catalog for one agent, as opaque profile ids the dial groups and shows. */listModels(agentId: string): Promise<string[]>+ /** One agent's last turn summaries, newest first — what a reattached dial needs to redraw its tiles. */+ recentSummaries(agentId: string): Array<{ recap: string; text: string }>/*** The image to offer a dial running `runningVersion`, or null for "nothing to do" — which covers a* dial that is current, a dev build that must not be touched, and an unreachable manifest.@@ -459,6 +461,22 @@ export class CableSession {await this.send({ t: 'agent', id: a.id, name: a.name, engine: a.engine ?? '', model: a.model ?? '', effort: a.effort ?? '' })}await this.send({ t: 'agents.end' })++ // Then what each of them was last doing. A tile with a name and no recap is a tile that has forgotten+ // the work it belongs to, and that is what a dial shows every time it is replugged or the daemon+ // restarts — the summaries were on disk the whole time, nobody had sent them.+ //+ // `restore: true` is the load-bearing part. It tells the dial this is history, not news: no beep, no+ // notification, no busy state. Without it, plugging the cable in announces every turn that finished+ // while it was unplugged.+ for (const a of agents) {+ const past = this.host.recentSummaries(a.id)+ // Oldest first, so the newest ends up on top of the tile's stack.+ for (const s of [...past].reverse()) {+ if (!s.recap && !s.text) continue+ await this.send({ t: 'summary', agentId: a.id, recap: s.recap, text: s.text, restore: true })+ }+ }}// Turn state is UNSOLICITED: the daemon reports every turn in every agent, including ones started at thediff --git a/cli/src/cli.ts b/cli/src/cli.tsindex f871c4760..e6f728bb1 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -152,6 +152,7 @@ const MACHINE_NAME_FILE = join(env.ADAPTER_DATA_DIR, 'machine-name')// The dial's session, held at module scope for the same reason `backendRef` is: shutdown() is defined// before the wiring that creates it, and the port has to be released on the way out.let cableRef: CableSession | null = null+// OpenCode's SQLite store — polled per session by OpencodeReader (no per-session transcript file).const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')// Kilo's SQLite store — same shape, its own file and its own reader (see engines/kilo/).@@ -831,6 +832,19 @@ async function runForeground(session: AuthSession): Promise<void> {})}, computerId())backendRef = backend++ /**+ * Is ANY device surface watching this machine?+ *+ * Two answers, both real: a device connected through the backend (`hasCommander`), and the dial on the+ * USB cable, which reaches this daemon directly over serial and is invisible to the socket that counts+ * the others.+ *+ * This gates the whole device mirror — the "Working…" card and the LLM recap. Reading it as+ * backend-only meant a dial plugged into a machine with no WiFi device saw a turn start in its tmux+ * pane and then nothing at all: the daemon skipped GENERATING the cards, so there was nothing to send.+ */+ const deviceIsWatching = (): boolean => backend.hasCommander() || cableRef?.isConnected === trueconst terminalStreams = new TerminalStreamManager({terminals,resolveAgent: (agentId) => registry.resolve(agentId),@@ -1317,7 +1331,7 @@ async function runForeground(session: AuthSession): Promise<void> {const questionWatcher = new QuestionWatcher({getSession: (id) => registry.resolve(id),capture: captureTerminal,- hasDevice: () => backend.hasCommander(),+ hasDevice: () => deviceIsWatching(),isDriving: (sessionId) => questions.isDriving(sessionId),onQuestion: (sessionId, requestId, shaped) => {questions.remember(requestId, sessionId)@@ -1335,8 +1349,10 @@ async function runForeground(session: AuthSession): Promise<void> {const mirror = new CommanderMirror({send: (frame) => backend.sendCommander(frame),sendWeb: (frame) => backend.send(frame), // turn_summary_pending / turn_summary → web indicator- hasDevice: () => backend.hasCommander(), // device-gate the LLM recap (mirror node)- active: () => backend.hasActiveCommander(), // stream live cards only to the actively-rendered machine+ hasDevice: () => deviceIsWatching(), // device-gate the LLM recap (mirror node)+ // Live cards stream to whatever is actually rendering. The dial has one screen and it is always the+ // one in front of the user, so a cable session counts as active by construction.+ active: () => backend.hasActiveCommander() || cableRef?.isConnected === true,summarize: async (text, signal, userMessage, sessionId) => {const session = sessionId ? registry.bySession(sessionId) : undefined// Gateway agents recap through OpenRouter directly (no vendor credential to spend). The probe isdiff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.tsindex c3cec1bca..9884cd0fd 100644--- a/cli/src/lib/commander.ts+++ b/cli/src/lib/commander.ts@@ -191,14 +191,30 @@ function splitSummary(summary: string): { recap: string; body: string } {return { recap, body }}+/** How many turn summaries are kept per session. Three is what the voice router reads: enough to tell one+ * agent's subject from another's, few enough that one chatty agent cannot crowd the others out. */+const RECENT_TURNS = 3+export class CommanderMirror {private states = new Map<string, SessionState>()- private summaries = new Map<string, string>() // sessionId → "recap\n\nbody"+ private summaries = new Map<string, string>() // sessionId → "recap\n\nbody" (the LATEST turn)+ /**+ * The last few turns, newest first — what a router reads to tell one agent from another.+ *+ * A SECOND file rather than widening the first, and the reason is rollback: this daemon self-updates,+ * and a published build that predates this change reads summaries.json with `typeof v === 'string'`.+ * Handed an array it keeps nothing and then rewrites the file — every stored recap gone, silently, on a+ * downgrade nobody asked for. The old file therefore keeps its exact old shape and meaning, and the+ * history lives beside it where an older reader simply never looks.+ */+ private history = new Map<string, string[]>()private file: string+ private historyFile: stringprivate saveTimer: NodeJS.Timeout | null = nullconstructor(private opts: CommanderMirrorOpts) {this.file = join(opts.dataDir, 'summaries.json')+ this.historyFile = join(opts.dataDir, 'summaries-history.json')this.load()}@@ -527,6 +543,7 @@ export class CommanderMirror {st.summarizing = falseif (summary) {this.summaries.set(sessionId, summary)+ this.remember(sessionId, summary)this.saveSoon()const { recap, body } = splitSummary(summary)this.trace(sessionId, `${sid} done in ${ms}ms · recap="${recap}" · bodyLen=${body.length}`)@@ -586,12 +603,36 @@ export class CommanderMirror {return false}- /** Device tile restore at boot (project_recent): the stored last summary, split for the tile. */- recent(sessionId: string, _n = 2): Array<{ kind: string; text: string; recap?: string }> {- const summary = this.summaries.get(sessionId)- if (!summary || !summary.trim()) return []- const { recap, body } = splitSummary(summary)- return [{ kind: 'summary', text: body || recap, recap }]+ /**+ * The session's last `n` turn summaries, newest first — for a device restoring its tile at boot and for+ * the voice router deciding which agent a spoken sentence belongs to.+ *+ * `n` is honoured now. It used to be ignored and this always returned one, which made every caller+ * asking for more a promise nobody kept: the router in particular was told it had three turns of+ * context and was given one.+ *+ * Falls back to the single latest summary when the history is empty, so the recaps already on disk from+ * before this existed are usable on the first run rather than after three more turns.+ */+ recent(sessionId: string, n = 2): Array<{ kind: string; text: string; recap?: string }> {+ const want = Math.max(1, n)+ const stored = this.history.get(sessionId) ?? []+ const latest = this.summaries.get(sessionId)+ // The latest lives in both places once a turn has run under this build; dedupe so it is not read twice.+ const all = stored.length ? stored : latest ? [latest] : []+ return all+ .slice(0, want)+ .filter((summary) => summary && summary.trim())+ .map((summary) => {+ const { recap, body } = splitSummary(summary)+ return { kind: 'summary', text: body || recap, recap }+ })+ }++ /** Keep the last few turns for this session, newest first. */+ private remember(sessionId: string, summary: string): void {+ const kept = [summary, ...(this.history.get(sessionId) ?? [])].slice(0, RECENT_TURNS)+ this.history.set(sessionId, kept)}/** Turn cancelled (web/device C-c). The claude turn is killed with no end_turn line, so no turn_ended@@ -624,6 +665,10 @@ export class CommanderMirror {const summary = this.summaries.get(fromSessionId)if (!summary || this.summaries.get(toSessionId)) returnthis.summaries.set(toSessionId, summary)+ // The history moves with it. A rotation is the same agent in the same pane — losing what it was doing+ // is exactly what this method exists to prevent, and the router reads the history, not the latest.+ const past = this.history.get(fromSessionId)+ if (past?.length && !this.history.get(toSessionId)?.length) this.history.set(toSessionId, past)this.save()}@@ -647,6 +692,12 @@ export class CommanderMirror {const obj = JSON.parse(readFileSync(this.file, 'utf-8')) as Record<string, string>for (const [k, v] of Object.entries(obj)) if (typeof v === 'string') this.summaries.set(k, v)} catch { /* no file yet */ }+ try {+ const obj = JSON.parse(readFileSync(this.historyFile, 'utf-8')) as Record<string, unknown>+ for (const [k, v] of Object.entries(obj)) {+ if (Array.isArray(v)) this.history.set(k, v.filter((x): x is string => typeof x === 'string').slice(0, RECENT_TURNS))+ }+ } catch { /* no history yet — recent() falls back to the latest summary */ }}private saveSoon(): void {@@ -658,6 +709,7 @@ export class CommanderMirror {try {mkdirSync(this.opts.dataDir, { recursive: true, mode: 0o700 })writeFileSync(this.file, JSON.stringify(Object.fromEntries(this.summaries), null, 2))+ writeFileSync(this.historyFile, JSON.stringify(Object.fromEntries(this.history), null, 2))} catch (err) {console.error('[commander] save summaries failed:', err)}