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
feat: implement DeviceFleet for machine management and integrate into cable host logic
0xken15540c3a2be111
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 15b3cb7a7..9e23ec132 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -16,7 +16,8 @@ import { fetchRelease, loadImage, shouldOffer } from './fwPush.js'import { routeVoiceTask, type RouterAgent } from '../lib/voiceRouter.js'import { env } from '../config/env.js'-import type { CableAgent, CableHost, RouteDecision } from './cableSession.js'+import type { CableAgent, CableHost, CableMachine, CableMachineSource, RouteDecision } from './cableSession.js'+import { FleetError, type FleetMachine, type MachineFleet } from './machineFleet.js'/** One completed turn's recap, as the mirror keeps them. */export interface RecentTurn {@@ -26,10 +27,16 @@ export interface RecentTurn {export interface CableHostWiring {machineName: () => string+ /** This computer's machineId, or '' when the daemon has never resolved one (signed out). */+ machineId: () => string+ /** A stable id for this computer, used to name the local row when there is no machineId yet. */+ computerId: () => string+ /** How many agents this computer is running — the local row's count, free to read. */+ localAgentCount: () => number/** Deliver text into an agent. The SAME path the web and the WiFi device use — see cli.ts. */sendTurn: (agentId: string, text: string) => voidstopTurn: (agentId: string) => void- answer: (agentId: string, id: string, optionId: string) => void+ answer: (agentId: string, requestId: string, answers: Record<string, string>) => void/** 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. */@@ -44,6 +51,17 @@ export interface CableHostWiring {log: (line: string) => void}+/** How the local row names itself before the daemon has ever resolved a machineId for this computer. */+function localFallbackId(computerId: string): string {+ return `cable:${computerId}`+}++/** A fleet row as the wire carries it. `authMode` does not travel: the dial has no use for the word, and+ * `remote` is just `!local`, which the row already says. */+function toCableMachine(m: FleetMachine): CableMachine {+ return { id: m.machineId, name: m.name, state: m.state, local: false, agents: m.agentCount }+}+/** Split `runtime-v1:<sid>:<engine>:<model>@<effort>` back into the two words the dial's chips show. */function chipsFromProfile(profile: string | null | undefined): { model?: string; effort?: string } {if (!profile || !profile.startsWith('runtime-v1:')) return {}@@ -54,7 +72,76 @@ function chipsFromProfile(profile: string | null | undefined): { model?: string;}export class DaemonCableHost implements CableHost {- constructor(private readonly wiring: CableHostWiring) {}+ /**+ * The machine whose agents are on the dial right now. Defaults to — and falls back to — the local one:+ * it is the only machine that is certainly reachable, so it is the honest thing to land on.+ *+ * Held in memory only. The dial deliberately does not remember a selection across its own reboot (a+ * restored id is meaningless until you know whose computer the cable is in), and this side does not+ * remember across a daemon restart either — that is when the registry reloads anyway.+ */+ private selected = ''++ /** `undefined` = no lane to any other machine exists; the wheel is the local row and nothing else. */+ constructor(private readonly wiring: CableHostWiring, private readonly fleet?: MachineFleet) {}++ /** The identity of the computer at the other end of the cable. */+ localMachine(): { id: string; name: string } {+ return { id: this.localId(), name: this.wiring.machineName() }+ }++ private localId(): string {+ return this.wiring.machineId() || localFallbackId(this.wiring.computerId())+ }++ /** Whether the dial is looking at THIS computer. Everything forks on this one question. */+ isLocalSelected(): boolean {+ return this.selectedMachine() === this.localId()+ }++ selectedMachine(): string {+ return this.selected || this.localId()+ }++ async listMachines(): Promise<{ machines: CableMachine[]; source: CableMachineSource }> {+ const local: CableMachine = {+ id: this.localId(),+ name: this.wiring.machineName(),+ // Always ready: the cable IS the evidence. Nothing else on this list can say that about itself.+ state: 'ready',+ local: true,+ agents: this.wiring.localAgentCount(),+ }+ if (!this.fleet) return { machines: [local], source: 'signed-out' }+ const { machines, source } = await this.fleet.list()+ const rows: CableMachine[] = [local]+ for (const m of machines) {+ // The backend list contains THIS computer too. Keep its id and name — they are the canonical ones —+ // but the liveness and the agent count come from here, where they are facts rather than a snapshot.+ if (m.machineId === local.id) { local.name = m.name || local.name; continue }+ rows.push(toCableMachine(m))+ }+ return { machines: rows, source }+ }++ async selectMachine(machineId: string): Promise<{ ok: true } | { ok: false; code: string; message: string }> {+ if (machineId === this.localId()) {+ this.fleet?.release()+ this.selected = machineId+ return { ok: true }+ }+ if (!this.fleet) {+ return { ok: false, code: 'UNAVAILABLE', message: 'Sign in on this computer to reach other machines' }+ }+ try {+ await this.fleet.select(machineId)+ } catch (err) {+ if (err instanceof FleetError) return { ok: false, code: err.code, message: err.message }+ return { ok: false, code: 'UNREACHABLE', message: (err as Error).message }+ }+ this.selected = machineId+ return { ok: true }+ }machineName(): string {return this.wiring.machineName()@@ -72,6 +159,7 @@ export class DaemonCableHost implements CableHost {}async listAgents(): Promise<CableAgent[]> {+ if (!this.isLocalSelected()) return this.fleet!.listAgents(this.selectedMachine())const sessions = registry.list()// Oldest → newest: a stable order that does not reshuffle as agents become active, which matters more// on a carousel than on a list — a tile that moves under a swipe is a tile you cannot aim at.@@ -85,21 +173,28 @@ export class DaemonCableHost implements CableHost {}sendTurn(agentId: string, text: string): void {+ if (!this.isLocalSelected()) { this.fleet!.sendTurn(this.selectedMachine(), agentId, text); return }this.wiring.sendTurn(agentId, text)}stopTurn(agentId: string): void {+ if (!this.isLocalSelected()) { this.fleet!.stopTurn(this.selectedMachine(), agentId); return }this.wiring.stopTurn(agentId)}- answer(agentId: string, id: string, optionId: string): void {- this.wiring.answer(agentId, id, optionId)+ answer(agentId: string, requestId: string, answers: Record<string, string>): void {+ if (!this.isLocalSelected()) { this.fleet!.answer(this.selectedMachine(), agentId, requestId, answers); return }+ this.wiring.answer(agentId, requestId, answers)}focus(agentId: string): void {// A statement about where the user is looking, and the desktop window follows it: turning the dial to// an agent switches the terminal on screen to the same one. The daemon still has no window of its own// — it forwards, and the app decides what following means for it.+ // Local only, and not an oversight: this says where a hand at THIS desk is looking. There is no+ // window here to move for an agent running on another computer, and moving one there is not what the+ // person turning the dial asked for.+ if (!this.isLocalSelected()) returnthis.wiring.log(`cable: focus ${agentId}`)this.wiring.focused?.(agentId)}@@ -110,6 +205,7 @@ export class DaemonCableHost implements CableHost {// protocol is most exposed to is a stroke that never CLOSES — the far side then holds a drag forever// and its list stops answering the mouse — and that failure is invisible without a matching pair to// look for. Two lines per swipe buys the one thing worth seeing.+ if (!this.isLocalSelected()) return // same reasoning as focus(): a finger on this glass, this deskif (phase !== 'move') {this.wiring.log(phase === 'down' ? 'cable: scroll ↓' : `cable: scroll ↑ (v=${velocity})`)}@@ -117,18 +213,20 @@ export class DaemonCableHost implements CableHost {}updateAgent(agentId: string, model?: string, effort?: string): void {+ if (!this.isLocalSelected()) { this.fleet!.updateAgent(this.selectedMachine(), agentId, model, effort); return }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 recentSummaries(agentId: string): Promise<Array<{ recap: string; text: string }>> {+ const raw = this.isLocalSelected()+ ? this.wiring.recent(agentId, 3)+ : await this.fleet!.recentSummaries(this.selectedMachine(), agentId)+ return raw.map((r) => ({ recap: r?.recap ?? '', text: r?.text ?? '' })).filter((s) => s.recap || s.text)}async listModels(agentId: string): Promise<string[]> {+ if (!this.isLocalSelected()) return this.fleet!.listModels(this.selectedMachine(), agentId)const models = (await this.wiring.listModels?.(agentId)) ?? []return models.map((m) => m.id).filter(Boolean)}@@ -157,16 +255,18 @@ export class DaemonCableHost implements CableHost {* which is the whole reason voice on the cable does not inherit the hosted path's failure modes.*/async route(transcript: string, agents: CableAgent[]): Promise<RouteDecision> {- const candidates: RouterAgent[] = agents.map((a) => ({+ // The recaps must come from the SELECTED machine. Scored against this computer's history instead, a+ // spoken turn meant for a remote agent is routed by what the agents HERE were last doing — which is+ // both wrong and completely invisible, because the router always answers with something.+ const candidates: RouterAgent[] = await Promise.all(agents.map(async (a) => ({id: a.id,name: a.name,engine: a.engine,- recentSummary: this.wiring- .recent(a.id, 3)- .map((r) => r?.recap || r?.text || '')+ recentSummary: (await this.recentSummaries(a.id))+ .map((r) => r.recap || r.text || '').filter(Boolean).join(' · '),- }))+ })))const decision = await routeVoiceTask(transcript, candidates)return { agentId: decision.agentId, confidence: decision.confidence, reason: decision.reason }}@@ -287,3 +387,20 @@ export function cableEventFor(if (kind !== 'processing' && kind !== 'done' && kind !== 'summary' && kind !== 'error') return nullreturn { kind, agentId: frame.agentId, text: frame.payload?.text ?? '', recap: frame.payload?.recap ?? '' }}++/**+ * Translate one device-bound `commander_question` into the dial's `question`.+ *+ * A sibling of `cableEventFor` rather than a branch inside it, because the shapes have nothing in common+ * — this one carries a requestId and an option list, not a card. Until this existed the dial's whole+ * question screen was complete, wired and unreachable: nothing on this side ever produced the message.+ */+export function cableQuestionFor(+ frame: { type?: string; agentId?: string; payload?: { requestId?: string; questions?: unknown } },+): { agentId: string; requestId: string; questions: unknown } | null {+ if (frame.type !== 'commander_question' || !frame.agentId) return null+ const requestId = frame.payload?.requestId+ const questions = frame.payload?.questions+ if (typeof requestId !== 'string' || !requestId || !Array.isArray(questions)) return null+ return { agentId: frame.agentId, requestId, questions }+}diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex 32defb548..bd97139e1 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -12,7 +12,7 @@ import { join } from 'node:path'import { describe, expect, it, vi } from 'vitest'import { CableDecoder, CableType, encodeCableFrame } from './cableFrame.js'-import { CableSession, type CableAgent, type CableHost, type CablePort } from './cableSession.js'+import { CableSession, type CableAgent, type CableHost, type CableMachine, type CablePort } from './cableSession.js'/** A port whose two ends are both in this process. */class LoopbackPort implements CablePort {@@ -20,6 +20,8 @@ class LoopbackPort implements CablePort {isOpen = true/** Everything the daemon wrote, decoded back into messages. */readonly sent: Array<Record<string, unknown>> = []+ /** The raw bytes of every frame written, so a test can assert the 8 KB cap holds. */+ readonly frames: Uint8Array[] = []closedWith: string | null = nullprivate decoder = new CableDecoder()@@ -27,6 +29,7 @@ class LoopbackPort implements CablePort {constructor(private readonly onData: (chunk: Buffer) => void) {}async write(bytes: Uint8Array): Promise<void> {+ this.frames.push(bytes)this.decoder.feed(Buffer.from(bytes), (frame) => {if (frame.type === CableType.Json) {this.sent.push(JSON.parse(Buffer.from(frame.payload).toString('utf8')) as Record<string, unknown>)@@ -59,6 +62,8 @@ class LoopbackPort implements CablePort {}}+const LOCAL_ROW: CableMachine = { id: 'mac-local', name: 'MacBook Pro', state: 'ready', local: true, agents: 2 }+const AGENTS: CableAgent[] = [{ id: 'a1', name: 'Fix login screen', engine: 'claude' },{ id: 'a2', name: 'Device firmware voice', engine: 'codex' },@@ -66,7 +71,10 @@ const AGENTS: CableAgent[] = [function makeHost(over: Partial<CableHost> = {}) {const host: CableHost = {- machineName: () => 'MacBook Pro',+ localMachine: () => ({ id: 'mac-local', name: 'MacBook Pro' }),+ listMachines: async () => ({ machines: [LOCAL_ROW], source: 'backend' as const }),+ selectedMachine: () => 'mac-local',+ selectMachine: async () => ({ ok: true as const }),appName: () => 'harness',voiceLang: () => 'en',listAgents: async () => AGENTS,@@ -77,7 +85,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: () => [],+ recentSummaries: async () => [],transcribe: async () => 'fix the login screen',route: async () => ({ agentId: 'a1', confidence: 0.9, reason: 'name matched' }),log: () => {},@@ -107,12 +115,16 @@ describe('cable session', () => {port.say({ t: 'hello', fw: '0.1.0', proto: 1, mac: 'aa:bb' })await vi.waitFor(() => expect(port.types()).toContain('agents.end'))- expect(port.types()).toEqual(['welcome', 'agents.begin', 'agent', 'agent', 'agents.end'])+ expect(port.types()).toEqual(+ // Machines FIRST: the dial paints its machine name from this list, so an agent list that lands+ // ahead of it shows a nameless placeholder for a frame.+ ['welcome', 'machines.begin', 'machine', 'machines.end', 'agents.begin', 'agent', 'agent', 'agents.end'],+ )const welcome = port.sent[0]expect(welcome).toMatchObject({ t: 'welcome', app: 'harness', machine: { name: 'MacBook Pro' } })// Streamed one per message: a hundred agents do not fit in one 8 KB frame, and the dial must not have// to reassemble anything.- expect(port.sent[2]).toMatchObject({ t: 'agent', id: 'a1', name: 'Fix login screen', engine: 'claude' })+ expect(port.sent.find((m) => m.t === 'agent')).toMatchObject({ t: 'agent', id: 'a1', name: 'Fix login screen', engine: 'claude' })await session.stop()})@@ -138,7 +150,11 @@ describe('cable session', () => {port.say({ t: 'hello', mac: 'cc:dd' })await vi.waitFor(() => expect(port.types()).toContain('agents.end'))- expect(port.types()).toEqual(['welcome', 'agents.begin', 'agent', 'agent', 'agents.end'])+ expect(port.types()).toEqual(+ // Machines FIRST: the dial paints its machine name from this list, so an agent list that lands+ // ahead of it shows a nameless placeholder for a frame.+ ['welcome', 'machines.begin', 'machine', 'machines.end', 'agents.begin', 'agent', 'agent', 'agents.end'],+ )await session.stop()})@@ -295,7 +311,7 @@ describe('cable session', () => {// 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) =>+ recentSummaries: async (id) =>id === 'a1' ? [{ recap: 'newest', text: 'b2' }, { recap: 'older', text: 'b1' }] : [],})const { session, port } = await connect(host)@@ -355,4 +371,220 @@ describe('cable session', () => {expect(host.sendTurn).not.toHaveBeenCalled()await session.stop()})+ // ── the machine wheel ─────────────────────────────────────────────────────────────────────────────++ it('streams the machine list and names the selected one', async () => {+ const { session, port } = await connect()+ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.types()).toContain('machines.end'))++ expect(port.sent.find((m) => m.t === 'machine')).toMatchObject({+ t: 'machine', id: 'mac-local', name: 'MacBook Pro', state: 'ready', local: true,+ })+ expect(port.sent.find((m) => m.t === 'machines.end')).toMatchObject({ selected: 'mac-local', source: 'backend' })+ await session.stop()+ })++ it('names the CABLED computer in welcome, not the dial', async () => {+ // Until proto 2 this carried the dial's own MAC as the machine id — a value nothing could ever select.+ const { session, port } = await connect()+ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.types()).toContain('welcome'))+ expect(port.sent[0]).toMatchObject({ t: 'welcome', machine: { id: 'mac-local' }, selected: 'mac-local' })+ await session.stop()+ })++ it('says nothing about machines when nothing changed', async () => {+ // The 15s hello cadence and every port reopen would otherwise re-push a list the dial already has —+ // the flap that measured out at 31 session restarts an hour, with the agent list wiped each time.+ const { session, port } = await connect()+ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.types()).toContain('machines.end'))+ const before = port.types().filter((t) => t === 'machines.begin').length++ port.say({ t: 'hello', mac: 'aa:bb' }) // same dial, same firmware: a keepalive+ await settle()+ expect(port.types().filter((t) => t === 'machines.begin')).toHaveLength(before)+ await session.stop()+ })++ it('acks a select, then pushes THAT machine\'s agents', async () => {+ const other: CableMachine = { id: 'm2', name: 'office-imac', state: 'ready', local: false, agents: 3 }+ const remote: CableAgent[] = [{ id: 'r1', name: 'api refactor', engine: 'codex' }]+ let selected = 'mac-local'+ const host = makeHost({+ listMachines: async () => ({ machines: [LOCAL_ROW, other], source: 'backend' as const }),+ selectedMachine: () => selected,+ selectMachine: async (id: string) => { selected = id; return { ok: true as const } },+ listAgents: async () => (selected === 'm2' ? remote : AGENTS),+ })+ const { session, port } = await connect(host)+ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.types()).toContain('agents.end'))+ port.sent.length = 0++ port.say({ t: 'machine.select', machineId: 'm2' })+ await vi.waitFor(() => expect(port.types()).toContain('machine.selected'))+ await vi.waitFor(() => expect(port.types()).toContain('agents.end'))+ expect(port.sent.filter((m) => m.t === 'agent')).toHaveLength(1)+ expect(port.sent.find((m) => m.t === 'agent')).toMatchObject({ id: 'r1' })+ await session.stop()+ })++ it('sends the new list even when it hashes identically to the old one', async () => {+ // Two machines whose agents share names and engines produce an EQUAL agentsKey. Without resetting it+ // on a switch, the dial would keep the previous machine's tiles and nothing would ever correct it.+ const twin: CableAgent[] = [...AGENTS]+ let selected = 'mac-local'+ const host = makeHost({+ listMachines: async () => ({+ machines: [LOCAL_ROW, { id: 'm2', name: 'twin', state: 'ready' as const, local: false, agents: 2 }],+ source: 'backend' as const,+ }),+ selectedMachine: () => selected,+ selectMachine: async (id: string) => { selected = id; return { ok: true as const } },+ listAgents: async () => twin,+ })+ const { session, port } = await connect(host)+ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.types()).toContain('agents.end'))+ port.sent.length = 0++ port.say({ t: 'machine.select', machineId: 'm2' })+ await vi.waitFor(() => expect(port.types()).toContain('agents.end'))+ expect(port.sent.filter((m) => m.t === 'agent')).toHaveLength(2)+ await session.stop()+ })++ it('reports a refused select and leaves the selection alone', async () => {+ const host = makeHost({+ selectMachine: async () => ({ ok: false as const, code: 'NEEDS_LINK', message: 'Run harness link import' }),+ })+ const { session, port } = await connect(host)+ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.types()).toContain('agents.end'))+ port.sent.length = 0++ port.say({ t: 'machine.select', machineId: 'm2' })+ await vi.waitFor(() => expect(port.types()).toContain('machine.error'))+ expect(port.sent.find((m) => m.t === 'machine.error')).toMatchObject({+ machineId: 'm2', code: 'NEEDS_LINK', message: 'Run harness link import',+ })+ expect(port.types()).not.toContain('agents.begin') // the old machine's tiles stay put+ await session.stop()+ })++ it('answers a select of the machine already selected instead of going quiet', async () => {+ // Silence here strands the dial on its spinner until its own deadline, which reads as a hang.+ const { session, port } = await connect()+ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.types()).toContain('agents.end'))+ port.sent.length = 0++ port.say({ t: 'machine.select', machineId: 'mac-local' })+ await vi.waitFor(() => expect(port.types()).toContain('machine.selected'))+ await session.stop()+ })++ it('shows one row and says why when there is no lane to anywhere else', async () => {+ const host = makeHost({ listMachines: async () => ({ machines: [LOCAL_ROW], source: 'signed-out' as const }) })+ const { session, port } = await connect(host)+ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.types()).toContain('machines.end'))+ expect(port.sent.filter((m) => m.t === 'machine')).toHaveLength(1)+ expect(port.sent.find((m) => m.t === 'machines.end')).toMatchObject({ source: 'signed-out' })+ await session.stop()+ })++ it('forwards a question answer verbatim, keyed by the QUESTION keys', async () => {+ // The dial has always sent {agentId, requestId, answers}; this case used to demand {id, optionId} and+ // silently dropped every answer the question screen produced.+ const host = makeHost()+ const { session, port } = await connect(host)+ port.say({ t: 'hello', mac: 'aa:bb' })+ await settle()++ port.say({ t: 'answer', agentId: 'a1', requestId: 'req-7', answers: { scope: 'wide', mode: 'plan' } })+ await vi.waitFor(() => expect(host.answer).toHaveBeenCalled())+ expect(host.answer).toHaveBeenCalledWith('a1', 'req-7', { scope: 'wide', mode: 'plan' })+ await session.stop()+ })++ it('fits ten machines with long names into single frames', async () => {+ const many: CableMachine[] = Array.from({ length: 10 }, (_, i) => ({+ id: `machine-${String(i).padStart(30, 'x')}`,+ name: 'x'.repeat(39),+ state: 'ready' as const,+ local: i === 0,+ agents: 99,+ }))+ const host = makeHost({ listMachines: async () => ({ machines: many, source: 'backend' as const }) })+ const { session, port } = await connect(host)+ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.sent.filter((m) => m.t === 'machine')).toHaveLength(10))+ for (const frame of port.frames) expect(frame.length).toBeLessThan(8192)+ await session.stop()+ })+ it('never interleaves two streamed pushes', async () => {+ // MEASURED ON HARDWARE, 2026-08-25, first plug-in of the proto-2 firmware: the dial reported EIGHT+ // machines while the daemon's own log said it had sent four, three times.+ //+ // `onMessage` is fired from the decoder and never awaited, so a dial that greets and then asks for+ // both lists has three pushes in flight at once — and each row parks on an await. Unserialised, the+ // wire carried `begin begin begin row×6 end end end`: the dial reset its staging on every begin,+ // accumulated every push's rows, and committed the pile on the first end.+ //+ // THE SLOW PORT IS THE TEST. With a write that resolves synchronously the three pushes run to+ // completion one at a time and this passes with or without the fix — which is exactly what the first+ // version of this test did, and why it proved nothing. A real tty accepts a few hundred bytes at a+ // time; every frame parks.+ class SlowPort implements CablePort {+ readonly path = 'slow'+ isOpen = true+ readonly sent: Array<Record<string, unknown>> = []+ private decoder = new CableDecoder()+ constructor(private readonly onData: (chunk: Buffer) => void) {}+ async write(bytes: Uint8Array): Promise<void> {+ await new Promise((r) => setTimeout(r, 0))+ this.decoder.feed(Buffer.from(bytes), (frame) => {+ if (frame.type === CableType.Json) this.sent.push(JSON.parse(Buffer.from(frame.payload).toString('utf8')))+ })+ }+ async close(): Promise<void> { this.isOpen = false }+ say(msg: Record<string, unknown>): void {+ this.onData(Buffer.from(encodeCableFrame(CableType.Json, Buffer.from(JSON.stringify(msg), 'utf8'))))+ }+ }++ const rows: CableMachine[] = [+ LOCAL_ROW,+ { id: 'm2', name: 'office-imac', state: 'ready', local: false, agents: 3 },+ ]+ const host = makeHost({ listMachines: async () => ({ machines: rows, source: 'backend' as const }) })+ let port!: SlowPort+ const session = new CableSession(host, '/dev/null', async (onData) => {+ port = new SlowPort(onData)+ return port+ })+ session.start()+ await vi.waitFor(() => expect(port).toBeTruthy())++ port.say({ t: 'hello', mac: 'aa:bb' })+ port.say({ t: 'machines.list' })+ port.say({ t: 'agents.list' })+ await vi.waitFor(() => {+ expect(port.sent.filter((m) => m.t === 'machines.end').length).toBeGreaterThanOrEqual(3)+ })++ // Walk the wire: a `begin` may never open inside another, and each pair must hold the rows of ONE list.+ let open = false+ let seen = 0+ for (const m of port.sent) {+ if (m.t === 'machines.begin') { expect(open, 'a begin arrived inside another begin').toBe(false); open = true; seen = 0 }+ else if (m.t === 'machine') { expect(open, 'a row arrived outside a begin/end pair').toBe(true); seen++ }+ else if (m.t === 'machines.end') { expect(open).toBe(true); expect(seen).toBe(rows.length); open = false }+ }+ expect(open, 'a begin was never closed').toBe(false)+ await session.stop()+ })})diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex 93c3cc5db..24b205d82 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -28,13 +28,16 @@ import { FirmwareTransfer } from './fwPush.js'import { SerialLink, findDialPort } from './serial.js'/** Bumped when the VOCABULARY changes. Separate from the frame version, which is the envelope. */-export const CABLE_PROTO_VERSION = 1+export const CABLE_PROTO_VERSION = 2const PING_EVERY_MS = 5_000/** No bytes of any kind for this long → the handle is dead. Longer than the dial's own 15 s window, so a* single late message cannot trip both sides at once and have each conclude the other left. */const SILENCE_MS = 20_000const REOPEN_EVERY_MS = 2_000+/** How often the machine list is re-read. Slower than the agent list because it is an HTTP read, not a+ * map lookup — and because a machine appearing is not something anyone is waiting on a stopwatch for. */+const MACHINES_POLL_MS = 15_000/** What a `voice.begin` without an `sr` is assumed to be — firmware old enough not to say. */const DEFAULT_VOICE_RATE = 16_000@@ -50,6 +53,26 @@ export interface CableAgent {effort?: string}+/**+ * One row of the dial's machine wheel.+ *+ * `state` is the ONLY liveness word on the wire, deliberately as one tri-value rather than an `online`+ * boolean beside a `known` one: one field cannot contradict itself, two can — and would, the first time a+ * list refresh fails halfway through.+ */+export interface CableMachine {+ id: string+ name: string+ state: 'ready' | 'offline' | 'unknown' | 'needs-link'+ /** Exactly one row carries this: the computer at the other end of the cable. */+ local: boolean+ /** −1 when unknown. Sent only when it is free to know — never worth a round trip per machine. */+ agents: number+}++/** Why the list is as short as it is. The dial renders this, instead of drawing an empty wheel. */+export type CableMachineSource = 'backend' | 'local' | 'signed-out'+export interface RouteDecision {agentId: stringconfidence: number@@ -62,13 +85,29 @@ export interface RouteDecision {* and a network to prove that `hello` gets a `welcome`.*/export interface CableHost {- machineName(): string+ /** The computer at the other end of the cable — its identity, not "the" machine's. */+ localMachine(): { id: string; name: string }+ /** Every machine the owner has, local row included. Never rejects: `source` explains a short list. */+ listMachines(): Promise<{ machines: CableMachine[]; source: CableMachineSource }>+ /** Which one the agent list currently belongs to. */+ selectedMachine(): string+ /**+ * Switch. Resolves to a discriminated result and NEVER throws — a refusal is data here, the same way+ * `firmwareFor()` returning null is. `code` is the daemon's; `message` is shown to a person verbatim,+ * so the dial needs no table for a set it does not own.+ */+ selectMachine(machineId: string): Promise<{ ok: true } | { ok: false; code: string; message: string }>appName(): stringvoiceLang(): stringlistAgents(): Promise<CableAgent[]>sendTurn(agentId: string, text: string): voidstopTurn(agentId: string): void- answer(agentId: string, id: string, optionId: string): void+ /**+ * The user answered a `question`. `answers` is keyed by the QUESTION keys the daemon itself asked with+ * and travels verbatim — re-deriving it, or keying it by the requestId, is how a rename at either end+ * becomes an answer nobody gave.+ */+ answer(agentId: string, requestId: string, answers: Record<string, string>): voidfocus(agentId: string): void/** A finger moving on the dial's glass, on its way to whatever window is open on this computer. */scrolled(phase: 'down' | 'move' | 'up', dy: number, velocity: number): void@@ -80,7 +119,7 @@ export interface CableHost {/** 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 }>+ recentSummaries(agentId: string): Promise<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.@@ -129,6 +168,30 @@ export class CableSession {/** What the dial was last told the agent list is. Empty = it has been told nothing. */private lastAgentsKey = ''+ /** The same, for the machine wheel. Both reset together on any new port — see `tryOpen`. */+ private lastMachinesKey = ''+ /** Throttle for the machine list, which costs an HTTP read where the agent list costs a map lookup. */+ private machinesAt = 0+ /**+ * Serialises every STREAMED push (begin / rows / end).+ *+ * ⚠️ NOT a precaution. `onMessage` is fired from the decoder callback and never awaited, so a dial that+ * greets and then asks for both lists has three pushes in flight at once — each awaiting a write+ * between every row. Their frames interleave, and the far end sees `begin, begin, 8 rows, end, end`:+ * it stages one machine list twice over and reports eight machines where the daemon sent four.+ *+ * Measured on hardware 2026-08-25, first plug-in of the proto-2 firmware. The dial's own hash gate does+ * not help here — it faithfully gates a list that was already shredded on the way in.+ */+ private pushChain: Promise<void> = Promise.resolve()++ /** Run `body` after every push already queued, and before any queued later. */+ private queued(body: () => Promise<void>): Promise<void> {+ const next = this.pushChain.then(body)+ // The tail swallows so one failed push cannot strand the ones behind it; the caller still sees it.+ this.pushChain = next.catch(() => {})+ return next+ }/** A firmware transfer in flight, and the versions already tried this session. */private transfer: FirmwareTransfer | null = null@@ -188,7 +251,15 @@ export class CableSession {// Without this the list was sent ONCE per session and never corrected — and a daemon that has just// restarted greets the dial before its registry has finished loading, so the one thing it ever said// was "no agents". The dial removed both tiles and sat empty while the daemon knew about two.- if (this.greetedMac !== null) await this.syncAgents()+ if (this.greetedMac !== null) {+ // Machines FIRST. The dial paints its Overview eyebrow from the machine list, so an agent list that+ // lands first shows a nameless "Machine" for a frame.+ if (Date.now() - this.machinesAt >= MACHINES_POLL_MS) {+ this.machinesAt = Date.now()+ await this.syncMachines()+ }+ await this.syncAgents()+ }}private openAt = 0@@ -246,7 +317,9 @@ export class CableSession {this.decoder.reset()this.greetedMac = nullthis.greetedFw = null- this.lastAgentsKey = '' // a new port is a new dial until proven otherwise; tell it everything+ // A new port is a new dial until proven otherwise; tell it everything.+ this.lastAgentsKey = ''+ this.lastMachinesKey = ''this.lastRx = Date.now()this.host.log(`cable: open on ${opened.path}`)}@@ -257,6 +330,7 @@ export class CableSession {this.greetedMac = nullthis.greetedFw = nullthis.lastAgentsKey = ''+ this.lastMachinesKey = ''this.voice = null// The dial keeps its running image; the half-written slot is erased again by the next accepted offer.this.transfer?.finish('interrupted by the port closing')@@ -306,7 +380,12 @@ export class CableSession {t: 'welcome',proto: CABLE_PROTO_VERSION,app: this.host.appName(),- machine: { id: mac, name: this.host.machineName() },+ // The CABLED computer's identity — no longer "the one machine". It was the dial's own mac here+ // until proto 2, which was simply wrong: a mac is not a machine id and nothing could select it.+ machine: this.host.localMachine(),+ // Stated up front so the ✓ is correct from the first frame, before any list arrives — which+ // matters after a dial reboot that lands mid-session on a remote selection.+ selected: this.host.selectedMachine(),voiceLang: this.host.voiceLang(),})// Log a dial that is new OR that came back running something else. The version half of that test@@ -336,6 +415,12 @@ export class CableSession {case 'agents.list':await this.pushAgents()return+ case 'machines.list':+ await this.syncMachines(true)+ return+ case 'machine.select':+ await this.selectMachine(str('machineId') ?? '')+ returncase 'models.list': {// The one round trip in this protocol: the dial cannot draw a picker until the catalog is in hand,// so it waits on this — briefly, and off its own UI task.@@ -371,11 +456,22 @@ export class CableSession {case 'turn.stop':if (str('agentId')) this.host.stopTurn(str('agentId')!)return- case 'answer':- if (str('agentId') && str('id') && str('optionId')) {- this.host.answer(str('agentId')!, str('id')!, str('optionId')!)+ case 'answer': {+ // `answers` is the dial's own object, one entry per question, keyed by the keys WE asked with. It+ // travels verbatim. Until proto 2 this case demanded `{id, optionId}` — a shape the dial has never+ // sent — so every answer from the question screen was silently dropped on the floor.+ const agentId = str('agentId')+ const requestId = str('requestId')+ const answers = msg.answers+ if (agentId && requestId && answers && typeof answers === 'object' && !Array.isArray(answers)) {+ const flat: Record<string, string> = {}+ for (const [k, v] of Object.entries(answers as Record<string, unknown>)) {+ if (typeof v === 'string') flat[k] = v+ }+ this.host.answer(agentId, requestId, flat)}return+ }case 'agent.update':if (str('agentId')) this.host.updateAgent(str('agentId')!, str('model'), str('effort'))return@@ -535,6 +631,10 @@ export class CableSession {* the honest answer at that instant is "no agents". Something has to say the true one a second later.*/async syncAgents(force = false): Promise<void> {+ return this.queued(() => this.syncAgentsNow(force))+ }++ private async syncAgentsNow(force: boolean): Promise<void> {const agents = await this.host.listAgents()const key = CableSession.agentsKey(agents)if (!force && key === this.lastAgentsKey) return@@ -564,8 +664,12 @@ export class CableSession {* rename would replay a week of recaps.*/async pushRestores(): Promise<void> {+ return this.queued(() => this.pushRestoresNow())+ }++ private async pushRestoresNow(): Promise<void> {for (const a of await this.host.listAgents()) {- const past = this.host.recentSummaries(a.id)+ const past = await 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@@ -576,10 +680,91 @@ export class CableSession {/** Attach: tell the dial everything, whether or not any of it looks unchanged from here. */async pushAgents(): Promise<void> {+ await this.syncMachines(true)await this.syncAgents(true)await this.pushRestores()}+ // ── machines ──────────────────────────────────────────────────────────────────────────────────────++ /** What the dial has been told about the wheel, as one comparable string. Order counts: it is render+ * order, so two lists that differ only by a swap are a real change. */+ private static machinesKey(machines: CableMachine[], source: string, selected: string): string {+ return `${source}|${selected}|${machines+ .map((m) => `${m.id}:${m.name}:${m.state}:${m.agents}:${m.local ? 1 : 0}`)+ .join('|')}`+ }++ /**+ * Push the machine wheel IF it differs from what the dial was last told.+ *+ * The diff is not an optimisation. `ui_local_machine_set` on the dial once rebuilt its wheel on every+ * arriving greeting, on the USB reader task, and that measured out at 31 session restarts an hour with+ * the agent list wiped each time — the screen sat on "0 agents" while the daemon believed it had said+ * otherwise. The dial hashes the rows again on its side; this is the half that stops the bytes leaving.+ */+ async syncMachines(force = false): Promise<void> {+ return this.queued(() => this.syncMachinesNow(force))+ }++ private async syncMachinesNow(force: boolean): Promise<void> {+ const { machines, source } = await this.host.listMachines()+ const selected = this.host.selectedMachine()+ const key = CableSession.machinesKey(machines, source, selected)+ if (!force && key === this.lastMachinesKey) return+ this.lastMachinesKey = key+ this.host.log(`cable: machines → ${machines.length} (${source})${force ? ' [push]' : ''}`)++ await this.send({ t: 'machines.begin' })+ for (const m of machines) {+ await this.send({ t: 'machine', id: m.id, name: m.name, state: m.state, local: m.local, agents: m.agents })+ }+ await this.send({ t: 'machines.end', selected, source })+ }++ /**+ * Switch the dial to another machine.+ *+ * Always answered, including for the machine already selected: silence strands the dial on a spinner+ * until its own deadline, which reads as a hang rather than as "done, nothing changed" — the same rule+ * `models.list` follows.+ */+ private async selectMachine(machineId: string): Promise<void> {+ if (!machineId) return+ if (machineId === this.host.selectedMachine()) {+ await this.send({ t: 'machine.selected', machineId })+ await this.syncAgents(true)+ await this.pushRestores()+ return+ }+ const result = await this.host.selectMachine(machineId)+ if (!result.ok) {+ this.host.log(`cable: machine.select ${machineId} refused (${result.code})`)+ await this.send({ t: 'machine.error', machineId, code: result.code, message: result.message })+ return+ }+ this.host.log(`cable: machine.select → ${machineId}`)+ // REQUIRED, not hygiene: two machines whose agents happen to share names and engines produce an equal+ // agentsKey, and the new machine's list would then never be sent at all.+ this.lastAgentsKey = ''+ await this.send({ t: 'machine.selected', machineId })+ await this.syncAgents(true)+ await this.pushRestores()+ await this.syncMachines(true) // the ✓ moved, and the agent counts with it+ }++ /** One row changed — liveness, a rename, a count. Cheaper than re-streaming the wheel. */+ async machineState(machine: CableMachine): Promise<void> {+ await this.send({+ t: 'machine.updated',+ id: machine.id,+ name: machine.name,+ state: machine.state,+ local: machine.local,+ agents: machine.agents,+ })+ }+// Turn state is UNSOLICITED: the daemon reports every turn in every agent, including ones started at the// keyboard. A dial that only saw answers to its own sends would sit idle through most of what the// machine actually does.diff --git a/cli/src/cable/machineFleet.ts b/cli/src/cable/machineFleet.tsnew file mode 100644index 000000000..cd639e71d--- /dev/null+++ b/cli/src/cable/machineFleet.ts@@ -0,0 +1,65 @@+// The daemon's view of the OTHER machines the owner has, and the one lane that reaches them.+//+// Split out of cableHost.ts so the cable protocol layer never learns the word "relay": everything the dial+// can ask for is answered either from this process (the cabled computer's own registry) or through this+// interface, and `DaemonCableHost` is the single place that decides which.+//+// THE LOCAL MACHINE NEVER COMES THROUGH HERE. Its agents, turns and recaps are in this process already;+// routing them through the cloud to reach a dial plugged into this very computer would add a network+// round trip, a failure mode and an audience — for nothing.+import type { CableAgent } from './cableSession.js'+import type { RecentTurn } from './cableHost.js'++/** One of the owner's machines, as the fleet knows it. The local row is added by the host, not here. */+export interface FleetMachine {+ machineId: string+ name: string+ /** `ready` = reachable now · `offline` = known but not reachable · `unknown` = the list itself is stale+ * · `needs-link` = reachable, but this daemon holds no pinned key for it, so nothing can be read. */+ state: 'ready' | 'offline' | 'unknown' | 'needs-link'+ agentCount: number+ authMode: 'self' | 'managed' | 'remote' | 'provider'+}++/** A refusal that a person can act on. `message` reaches the dial's screen verbatim. */+export class FleetError extends Error {+ constructor(readonly code: string, message: string) {+ super(message)+ this.name = 'FleetError'+ }+}++/** A card from an attached machine, already translated into the dial's four kinds. */+export type FleetEvent =+ | { machineId: string; kind: 'processing' | 'done' | 'summary' | 'error'; agentId: string; text: string; recap: string }+ | { machineId: string; kind: 'question'; agentId: string; requestId: string; questions: unknown }+ | { machineId: string; kind: 'state'; state: FleetMachine['state']; agentCount?: number }++/**+ * Everything the dial needs from a machine that is NOT this computer.+ *+ * Deliberately an interface: it lets the whole cable half be built, tested and flashed against a fleet+ * that knows only the local machine, long before a lane to anywhere else exists.+ */+export interface MachineFleet {+ /**+ * The owner's machines, EXCLUDING this computer.+ *+ * Must resolve rather than reject when the backend is unreachable — `source` is how a short list+ * explains itself, and a dial whose daemon is offline still has one machine that works perfectly.+ */+ list(): Promise<{ machines: FleetMachine[]; source: 'backend' | 'local' | 'signed-out' }>+ /** Attach to a machine. Throws `FleetError` on refusal. */+ select(machineId: string): Promise<void>+ /** Release whatever `select` acquired. Called when the dial goes back to the local machine. */+ release(): void+ listAgents(machineId: string): Promise<CableAgent[]>+ sendTurn(machineId: string, agentId: string, text: string): void+ stopTurn(machineId: string, agentId: string): void+ answer(machineId: string, agentId: string, requestId: string, answers: Record<string, string>): void+ updateAgent(machineId: string, agentId: string, model?: string, effort?: string): void+ listModels(machineId: string, agentId: string): Promise<string[]>+ recentSummaries(machineId: string, agentId: string): Promise<RecentTurn[]>+ /** Cards + liveness from the attached machine. Returns an unsubscribe. */+ onEvent(cb: (event: FleetEvent) => void): () => void+}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 75af4add6..2077b21cf 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -27,7 +27,10 @@ import { sqlitePreflightMessage } from './lib/sqliteAvailability.js'import { ensureUtf8Locale } from './lib/childLocale.js'import { binaryOnPath } from './lib/binaryOnPath.js'import { CableSession } from './cable/cableSession.js'-import { DaemonCableHost, cableEventFor } from './cable/cableHost.js'+import { DaemonCableHost, cableEventFor, cableQuestionFor } from './cable/cableHost.js'+import { MachineListCache } from './device/machineList.js'+import { DeviceLink } from './device/deviceLink.js'+import { DeviceFleet } from './device/deviceFleet.js'import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installAgyHooks, installCopilotHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'import { PID_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'@@ -156,6 +159,11 @@ 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+/** The same object the session holds — module scope so the recap gates can ask which machine is selected+ * without threading it through every constructor between here and there. */+let cableHostRef: DaemonCableHost | null = null+/** Module scope for the same reason cableRef is: shutdown() has to release the socket. */+let deviceLinkRef: DeviceLink | 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')@@ -918,7 +926,11 @@ async function runForeground(session: AuthSession): Promise<void> {* 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 === true+ // The cable half is gated on the dial actually LOOKING at this computer. A dial turned to another+ // machine is watching that machine's cards, not ours, so generating recaps here would spend an LLM call+ // per turn on something nobody renders.+ const cableWatchingLocal = (): boolean => cableRef?.isConnected === true && cableHostRef?.isLocalSelected() === true+ const deviceIsWatching = (): boolean => backend.hasCommander() || cableWatchingLocal()const terminalStreams = new TerminalStreamManager({terminals,resolveAgent: (agentId) => registry.resolve(agentId),@@ -1426,7 +1438,7 @@ async function runForeground(session: AuthSession): Promise<void> {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,+ active: () => backend.hasActiveCommander() || cableWatchingLocal(),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 is@@ -2742,6 +2754,7 @@ async function runForeground(session: AuthSession): Promise<void> {// Release the serial port first. It is exclusive, and a daemon that exits still holding it makes// esptool fail in a way that reads exactly like dead hardware.void cableRef?.stop()+ deviceLinkRef?.stop()updater?.stop()agentReconciler.stop()clearInterval(logTrimTimer)@@ -2799,13 +2812,58 @@ async function runForeground(session: AuthSession): Promise<void> {// of any of those is a second set of bugs.//// Deliberately not fatal and not blocking: an unplugged cable is this daemon's ordinary state.+ // ── the lane to the owner's OTHER machines ───────────────────────────────────────────────────────+ //+ // Three independent things, on purpose. The LIST is a REST read that works while the backend socket is+ // down; `local` is derived from the computer id and needs no network at all; and the LANE is a device+ // socket that only exists while the dial is actually looking at another machine.+ const machineList = new MachineListCache(+ () => proxyBackend('GET', '/api/machines'),+ computerId,+ (line) => console.log(`[cable] ${line}`),+ )+ void machineList.refresh()+ const machineListTimer = setInterval(() => void machineList.refresh(), 60_000)+ machineListTimer.unref?.()++ const machinePeers = new MachinePeerStore()+ const deviceLink = new DeviceLink({+ auth,+ backendWsBase: env.BACKEND_WS_URL,+ computerId: computerId(),+ autonomousEnv: readAuthSession()?.autonomousEnv ?? session.autonomousEnv,+ // The SAME identity `harness link create` publishes and `harness link import` verifies against, so+ // one link ceremony covers the desktop app's relay and the dial's lane alike.+ identity: relayIdentityStore.getIdentity(),+ // Read FRESH on every attach: `harness link import` runs as a separate process, so a value captured+ // at daemon start would keep answering "not linked" until the next restart.+ peer: (machineId) => machinePeers.get(machineId),+ log: (line) => console.log(`[device] ${line}`),+ })+ deviceLinkRef = deviceLink++ const fleet = new DeviceFleet({+ list: machineList,+ link: deviceLink,+ // Read FRESH on every call, never cached: `harness link import` runs as a separate process, so a+ // cached answer would keep saying "not linked" for as long as this daemon lives.+ hasPeerLink: (machineId) => machinePeers.get(machineId) !== null,+ log: (line) => console.log(`[device] ${line}`),+ })+const cableHost = new DaemonCableHost({machineName: () => { try { return readFileSync(MACHINE_NAME_FILE, 'utf8').trim() || 'This machine' } catch { return 'This machine' } },+ machineId: () => backend.machineId,+ computerId: () => computerId(),+ localAgentCount: () => registry.list().length,// The SAME handlers the backend socket drives, called directly rather than reimplemented: the// slash-command adaptation, the turn bookkeeping and the question plumbing all live in them.sendTurn: (agentId, text) => backend.onMessage?.(agentId, text),stopTurn: (agentId) => backend.onCancel?.(agentId),- answer: (agentId, id, optionId) => backend.onQuestionAnswer?.({ agentId, requestId: id, answers: { [id]: optionId } }),+ // The dial's own object, forwarded verbatim. It used to be rebuilt here as `{ [requestId]: optionId }`+ // — keyed by the REQUEST id rather than by the question key `onQuestionAnswer` expects, so the answer+ // named a question that does not exist.+ answer: (agentId, requestId, answers) => backend.onQuestionAnswer?.({ agentId, requestId, answers }),recent: (id, n) => mirror.recent(registry.resolve(id)?.sessionId || id, n),runtimeProfile: (session) => runtimeProfiles.selectedModel(session),updateAgent: (agentId, model, effort) => {@@ -2822,13 +2880,20 @@ async function runForeground(session: AuthSession): Promise<void> {focused: (agentId) => backend.sendLocal({ type: 'dial_focus', payload: { agentId } }),scrolled: (phase, dy, velocity) => backend.sendLocal({ type: 'dial_scroll', payload: { phase, dy, velocity } }),log: (line) => console.log(`[cable] ${line}`),- })+ }, fleet)+ cableHostRef = cableHostconst cable = new CableSession(cableHost, join(env.ADAPTER_DATA_DIR, 'dial.log'))cableRef = cable// Every card bound for the WiFi device goes down the cable too, translated once. Teeing beats emitting// again at each call site: a new event kind reaches the dial the day it reaches the socket.backend.onOutboundCommander = (frame) => {+ // THIS COMPUTER'S cards, by definition. When the dial is showing another machine they must not be+ // painted: agent ids are bare local UUIDs with no machine component, so the tile they land on is+ // either the wrong agent's or nobody's.+ if (!cableHost.isLocalSelected()) return+ const question = cableQuestionFor(frame as { type?: string; agentId?: string; payload?: { requestId?: string; questions?: unknown } })+ if (question) { void cable.question(question.agentId, question.requestId, question.questions); return }const event = cableEventFor(frame as { type?: string; agentId?: string; payload?: { kind?: string; text?: string; recap?: string } })// Logged at the fork, not at the send: this is the one place that can answer "did the daemon even// decide to tell the dial", which is a different question from "did the wire carry it" and was the@@ -2843,6 +2908,18 @@ async function runForeground(session: AuthSession): Promise<void> {else void cable.turnError(event.agentId, event.text)}+ // A remote machine's cards reach the dial through the SAME four calls the local tee uses, so a new+ // event kind lands on both surfaces the day it lands on either.+ fleet.onEvent((event) => {+ if (cableHost.isLocalSelected()) return // the dial came back to this computer mid-flight+ if (event.kind === 'question') { void cable.question(event.agentId, event.requestId, event.questions); return }+ if (event.kind === 'state') { void cable.syncMachines(true); return }+ if (event.kind === 'processing') void cable.turnStarted(event.agentId, event.text)+ else if (event.kind === 'done') void cable.turnDone(event.agentId)+ else if (event.kind === 'summary') void cable.summary(event.agentId, event.recap || event.text, event.text)+ else void cable.turnError(event.agentId, event.text)+ })+if (env.CABLE_DISABLE) console.log('[cable] disabled (CABLE_DISABLE=true) — the serial port is left alone')else cable.start()}diff --git a/cli/src/device/deviceFleet.spec.ts b/cli/src/device/deviceFleet.spec.tsnew file mode 100644index 000000000..20c30a042--- /dev/null+++ b/cli/src/device/deviceFleet.spec.ts@@ -0,0 +1,144 @@+// The fan-out between the machine list and the one device socket.+//+// The cases here are the ones that fail SILENTLY: a machine with no pinned key answering an empty+// carousel instead of an instruction, and another machine's turn card painting a tile on the machine the+// dial is actually showing.+import { describe, expect, it, vi } from 'vitest'++import { DeviceFleet } from './deviceFleet.js'+import { FleetError, type FleetEvent } from '../cable/machineFleet.js'+import type { DeviceFrame } from './deviceLink.js'++type Listed = { machineId: string; name: string; state: string; agentCount: number; authMode: string; local: boolean }++function listOf(rows: Partial<Listed>[]): Listed[] {+ return rows.map((r) => ({+ machineId: 'm1', name: 'office-imac', state: 'ready', agentCount: 2, authMode: 'remote', local: false, ...r,+ })) as Listed[]+}++function make(over: { rows?: Partial<Listed>[]; linked?: string[]; rpc?: (t: string, p: Record<string, unknown>) => Promise<Record<string, unknown>> } = {}) {+ const rows = listOf(over.rows ?? [{}])+ let frameCb: ((f: DeviceFrame) => void) | null = null+ const sent: DeviceFrame[] = []+ const link = {+ selectedMachine: 'm1',+ onFrame: (cb: (f: DeviceFrame) => void) => { frameCb = cb; return () => {} },+ attach: vi.fn(async () => {}),+ release: vi.fn(),+ send: (f: DeviceFrame) => { sent.push(f) },+ rpc: over.rpc ?? (async () => ({})),+ }+ const fleet = new DeviceFleet({+ list: {+ list: () => ({ machines: rows, source: 'backend' as const }),+ find: (id: string) => rows.find((r) => r.machineId === id),+ } as never,+ link: link as never,+ hasPeerLink: (id: string) => (over.linked ?? ['m1']).includes(id),+ log: () => {},+ })+ return { fleet, link, sent, say: (f: DeviceFrame) => frameCb?.(f) }+}++describe('DeviceFleet', () => {+ it('hides this computer from the fleet list — the host adds it back with real facts', async () => {+ const { fleet } = make({ rows: [{ machineId: 'mine', local: true }, { machineId: 'other' }], linked: ['other'] })+ const { machines } = await fleet.list()+ expect(machines.map((m) => m.machineId)).toEqual(['other'])+ })++ it('marks an unlinked remote machine needs-link instead of leaving it looking ready', async () => {+ // Reachable but unreadable: everything on it is encrypted to a key this daemon does not hold. Saying+ // "ready" would send the user into an empty carousel with nothing explaining it.+ const { fleet } = make({ rows: [{ machineId: 'm1', authMode: 'remote' }], linked: [] })+ const { machines } = await fleet.list()+ expect(machines[0].state).toBe('needs-link')+ })++ it('leaves a cloud machine alone — E2EE is a remote-machine rule, not a universal one', async () => {+ const { fleet } = make({ rows: [{ machineId: 'm1', authMode: 'managed' }], linked: [] })+ const { machines } = await fleet.list()+ expect(machines[0].state).toBe('ready')+ })++ it('refuses an unlinked select LOCALLY, without dialling anything', async () => {+ const { fleet, link } = make({ rows: [{ machineId: 'm1', name: 'imac', authMode: 'remote' }], linked: [] })+ await expect(fleet.select('m1')).rejects.toMatchObject({ code: 'NEEDS_LINK' })+ expect(link.attach).not.toHaveBeenCalled() // the guide appears instantly, not after a doomed connect+ })++ it('refuses a machine that is not on the account', async () => {+ const { fleet } = make()+ await expect(fleet.select('nope')).rejects.toBeInstanceOf(FleetError)+ })++ it('maps the far end’s refusal onto a code and words a person can act on', async () => {+ const { fleet, link } = make()+ link.attach = vi.fn(async () => { throw new Error('NOT_YOUR_MACHINE') })+ await expect(fleet.select('m1')).rejects.toMatchObject({ code: 'NOT_YOURS' })+ })++ it('sends a turn in the shape the backend dispatches', async () => {+ const { fleet, sent } = make()+ fleet.sendTurn('m1', 'a1', 'ship it')+ expect(sent[0]).toMatchObject({ type: 'message', payload: { content: 'ship it', agentId: 'a1', resumeLatest: true } })+ })++ it('forwards a question answer keyed by the question keys', async () => {+ const { fleet, sent } = make()+ fleet.answer('m1', 'a1', 'req-1', { scope: 'wide' })+ expect(sent[0]).toMatchObject({ type: 'question_response', payload: { agentId: 'a1', requestId: 'req-1', answers: { scope: 'wide' } } })+ })++ it('turns an agents_list_result into tiles, chips and all', async () => {+ const { fleet } = make({+ rpc: async () => ({ agents: [{ id: 'a1', name: 'api refactor', engine: 'codex', selectedModel: 'runtime-v1:s1:codex:opus@high' }] }),+ })+ const agents = await fleet.listAgents('m1')+ expect(agents[0]).toMatchObject({ id: 'a1', name: 'api refactor', engine: 'codex', model: 'opus', effort: 'high' })+ })++ it('drops a card tagged for a machine the dial is not showing', () => {+ // Agent ids are bare UUIDs with no machine component, so a stray card either paints the wrong tile or+ // none at all — and both look like the dial simply missing a turn.+ const { fleet, say } = make()+ const seen: FleetEvent[] = []+ fleet.onEvent((e) => seen.push(e))+ say({ type: 'commander_event', machineId: 'other', agentId: 'a1', payload: { kind: 'summary', recap: 'nope' } })+ expect(seen).toHaveLength(0)++ say({ type: 'commander_event', machineId: 'm1', agentId: 'a1', payload: { kind: 'summary', recap: 'yes', text: 'body' } })+ expect(seen).toEqual([{ machineId: 'm1', kind: 'summary', agentId: 'a1', text: 'body', recap: 'yes' }])+ })++ it('ignores card kinds the dial has no use for', () => {+ const { fleet, say } = make()+ const seen: FleetEvent[] = []+ fleet.onEvent((e) => seen.push(e))+ say({ type: 'commander_event', machineId: 'm1', agentId: 'a1', payload: { kind: 'tool', text: 'grep' } })+ expect(seen).toHaveLength(0)+ })++ it('surfaces a question and a presence flip', () => {+ const { fleet, say } = make()+ const seen: FleetEvent[] = []+ fleet.onEvent((e) => seen.push(e))+ say({ type: 'commander_question', machineId: 'm1', agentId: 'a1', payload: { requestId: 'r1', questions: [{ key: 'k' }] } })+ say({ type: 'node_status', machineId: 'm1', payload: { online: false } })+ expect(seen.map((e) => e.kind)).toEqual(['question', 'state'])+ })++ it('caches recaps so a redraw does not re-ask the far machine for every tile', async () => {+ const rpc = vi.fn(async () => ({ events: [{ kind: 'summary', recap: 'r', text: 't' }] }))+ const { fleet } = make({ rpc })+ await fleet.recentSummaries('m1', 'a1')+ await fleet.recentSummaries('m1', 'a1')+ expect(rpc).toHaveBeenCalledTimes(1)+ })++ it('answers an empty history rather than throwing when a recap RPC fails', async () => {+ const { fleet } = make({ rpc: async () => { throw new Error('timed out') } })+ await expect(fleet.recentSummaries('m1', 'a1')).resolves.toEqual([])+ })+})diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.tsnew file mode 100644index 000000000..3cf146d5f--- /dev/null+++ b/cli/src/device/deviceFleet.ts@@ -0,0 +1,229 @@+// `MachineFleet` for real: the REST machine list, plus one device socket to whichever machine the dial is+// currently on.+//+// The split is deliberate and load-bearing. The LIST costs an HTTP read and works signed-in-but-offline;+// the LANE costs a cloud socket and only exists while the user is actually looking at another machine. A+// dial parked on the local machine — which is where it sits most of the time — holds no socket at all.+import { FleetError, type FleetEvent, type FleetMachine, type MachineFleet } from '../cable/machineFleet.js'+import type { CableAgent } from '../cable/cableSession.js'+import type { RecentTurn } from '../cable/cableHost.js'+import type { MachineListCache } from './machineList.js'+import type { DeviceFrame, DeviceLink } from './deviceLink.js'++/** How long the socket lingers after the dial goes back to local, so flicking between two machines does+ * not pay a full dial each way. Mirrors RemoteRelayPool's own linger for the same reason. */+const LINGER_MS = 60_000++/** Split `runtime-v1:<sid>:<engine>:<model>@<effort>` into the two words the dial's chips show. */+function chipsFromProfile(profile: unknown): { model?: string; effort?: string } {+ if (typeof profile !== 'string' || !profile.startsWith('runtime-v1:')) return {}+ const tail = profile.split(':').slice(3).join(':')+ if (!tail) return {}+ const [model, effort] = tail.split('@')+ return { model: model || undefined, effort: effort || undefined }+}++/** Map an `agents_list_result` row onto the cable's agent shape. */+function toCableAgent(raw: unknown): CableAgent {+ const r = (raw ?? {}) as Record<string, unknown>+ return {+ id: typeof r.id === 'string' ? r.id : '',+ name: typeof r.name === 'string' ? r.name : '',+ engine: typeof r.engine === 'string' ? r.engine : '',+ ...chipsFromProfile(r.selectedModel),+ }+}++export interface DeviceFleetOpts {+ list: MachineListCache+ link: DeviceLink+ /** Whether this daemon holds a pinned E2EE key for a machine — see `harness link import`. */+ hasPeerLink: (machineId: string) => boolean+ log: (line: string) => void+}++export class DeviceFleet implements MachineFleet {+ private lingerTimer: NodeJS.Timeout | null = null+ private readonly recapCache = new Map<string, RecentTurn[]>()+ private readonly listeners = new Set<(e: FleetEvent) => void>()++ constructor(private readonly opts: DeviceFleetOpts) {+ this.opts.link.onFrame((frame) => this.onFrame(frame))+ }++ async list(): Promise<{ machines: FleetMachine[]; source: 'backend' | 'local' | 'signed-out' }> {+ const { machines, source } = this.opts.list.list()+ return {+ // The local row is added by the host, which knows facts about this computer that a snapshot cannot.+ machines: machines.filter((m) => !m.local).map((m) => ({+ ...m,+ // A machine with no pinned key is reachable but UNREADABLE: its agent list, its recaps and its+ // turn cards are all encrypted to a key this daemon does not hold. Saying so in the row is what+ // lets the wheel dim it and the guide behind it say which two commands fix it — far better than+ // letting the user tap it and meet an empty carousel.+ state: m.authMode === 'remote' && !this.opts.hasPeerLink(m.machineId) ? 'needs-link' as const : m.state,+ })),+ source,+ }+ }++ async select(machineId: string): Promise<void> {+ const row = this.opts.list.find(machineId)+ if (!row) throw new FleetError('UNKNOWN_MACHINE', 'That machine is not on your account')+ if (row.authMode === 'remote' && !this.opts.hasPeerLink(machineId)) {+ // Checked HERE, locally and for free, so the guide appears instantly instead of after a connect+ // that was always going to fail.+ throw new FleetError('NEEDS_LINK', `Link ${row.name} to this computer first`)+ }+ if (this.lingerTimer) { clearTimeout(this.lingerTimer); this.lingerTimer = null }+ try {+ await this.opts.link.attach(machineId)+ } catch (err) {+ const message = (err as Error).message+ throw new FleetError(this.codeFor(message), this.messageFor(message, row.name))+ }+ this.recapCache.clear()+ // Prefetch the recaps SERIALLY. Not caution — the contract: the agent list stays metadata-only and+ // recaps are fetched one at a time precisely so no giant frame is ever built.+ void this.prefetchRecaps(machineId)+ }++ release(): void {+ if (this.lingerTimer) clearTimeout(this.lingerTimer)+ this.lingerTimer = setTimeout(() => {+ this.lingerTimer = null+ this.opts.link.release()+ this.recapCache.clear()+ }, LINGER_MS)+ }++ async listAgents(machineId: string): Promise<CableAgent[]> {+ const res = await this.opts.link.rpc('agents_list', {})+ void machineId+ const raw = Array.isArray(res.agents) ? res.agents : []+ return raw.map(toCableAgent).filter((a) => a.id)+ }++ sendTurn(machineId: string, agentId: string, text: string): void {+ void machineId+ // `resumeLatest` matches what the backend's own voice path dispatches, so a dial turn and a spoken+ // turn land on the same session rather than one of them starting a new one.+ this.opts.link.send({ type: 'message', payload: { content: text, agentId, mode: 'auto', resumeLatest: true } })+ }++ stopTurn(machineId: string, agentId: string): void {+ void machineId+ this.opts.link.send({ type: 'cancel', payload: { agentId } })+ }++ answer(machineId: string, agentId: string, requestId: string, answers: Record<string, string>): void {+ void machineId+ this.opts.link.send({ type: 'question_response', payload: { agentId, requestId, answers } })+ }++ updateAgent(machineId: string, agentId: string, model?: string, effort?: string): void {+ void machineId+ if (!model) return+ // The far end owns what the profile means; this only reassembles the opaque string it round-trips.+ const row = this.opts.list.find(this.opts.link.selectedMachine)+ void row+ const selectedModel = `runtime-v1:${agentId}:claude:${model}@${effort || 'auto'}`+ void this.opts.link.rpc('agent_update', { agentId, selectedModel })+ .catch((err) => this.opts.log(`device: agent_update failed (${(err as Error).message})`))+ }++ async listModels(machineId: string, agentId: string): Promise<string[]> {+ void machineId+ // `compact` is what keeps the catalog inside the dial's picker; the backend trims to ≤24 entries.+ const res = await this.opts.link.rpc('models_list', { agentId, compact: true })+ const raw = Array.isArray(res.models) ? res.models : []+ return raw.map((m) => (typeof m === 'string' ? m : String((m as Record<string, unknown>)?.id ?? ''))).filter(Boolean)+ }++ async recentSummaries(machineId: string, agentId: string): Promise<RecentTurn[]> {+ void machineId+ const cached = this.recapCache.get(agentId)+ if (cached) return cached+ try {+ const res = await this.opts.link.rpc('agent_recent', { agentId, n: 3 })+ const events = Array.isArray(res.events) ? res.events : []+ const turns = events.map((e) => {+ const r = (e ?? {}) as Record<string, unknown>+ return { recap: typeof r.recap === 'string' ? r.recap : '', text: typeof r.text === 'string' ? r.text : '' }+ })+ this.recapCache.set(agentId, turns)+ return turns+ } catch (err) {+ this.opts.log(`device: agent_recent ${agentId} failed (${(err as Error).message})`)+ return []+ }+ }++ onEvent(cb: (event: FleetEvent) => void): () => void {+ this.listeners.add(cb)+ return () => this.listeners.delete(cb)+ }++ // ── internals ───────────────────────────────────────────────────────────────────────────────────++ private async prefetchRecaps(machineId: string): Promise<void> {+ try {+ const agents = await this.listAgents(machineId)+ for (const a of agents) await this.recentSummaries(machineId, a.id)+ } catch (err) {+ this.opts.log(`device: recap prefetch failed (${(err as Error).message})`)+ }+ }++ private onFrame(frame: DeviceFrame): void {+ const selected = this.opts.link.selectedMachine+ // The hub stamps `machineId` on every frame it fans out to a commander client. Anything wearing+ // another machine's tag is a card for a machine the dial is not showing — dropped at the source, which+ // is what keeps the agent id space flat and unscoped everywhere else.+ if (frame.machineId && selected && frame.machineId !== selected) return++ const payload = (frame.payload ?? {}) as Record<string, unknown>+ if (frame.type === 'commander_event' && frame.agentId) {+ const kind = payload.kind+ if (kind !== 'processing' && kind !== 'done' && kind !== 'summary' && kind !== 'error') return+ this.emit({+ machineId: selected,+ kind,+ agentId: frame.agentId,+ text: typeof payload.text === 'string' ? payload.text : '',+ recap: typeof payload.recap === 'string' ? payload.recap : '',+ })+ return+ }+ if (frame.type === 'commander_question' && frame.agentId) {+ const requestId = payload.requestId+ if (typeof requestId !== 'string' || !Array.isArray(payload.questions)) return+ this.emit({ machineId: selected, kind: 'question', agentId: frame.agentId, requestId, questions: payload.questions })+ return+ }+ if (frame.type === 'node_status') {+ this.emit({ machineId: selected, kind: 'state', state: payload.online === true ? 'ready' : 'offline' })+ }+ }++ private emit(event: FleetEvent): void {+ for (const cb of this.listeners) cb(event)+ }++ /** Map the far end's words onto a code the dial can act on. Unknown reasons stay unreachable. */+ private codeFor(message: string): string {+ if (message.includes('NOT_YOUR_MACHINE')) return 'NOT_YOURS'+ if (message.includes('MACHINE_ENV_MISMATCH')) return 'NOT_YOURS'+ if (message.includes('PAYMENT') || message.includes('SUBSCRIPTION')) return 'BILLING'+ if (message.includes('START_FAILED')) return 'UNREACHABLE'+ return 'UNREACHABLE'+ }++ private messageFor(message: string, name: string): string {+ if (message.includes('NOT_YOUR_MACHINE') || message.includes('MACHINE_ENV_MISMATCH')) {+ return `${name} is not on this account`+ }+ if (message.includes('PAYMENT') || message.includes('SUBSCRIPTION')) return `${name} needs a subscription`+ return `Can’t reach ${name}`+ }+}diff --git a/cli/src/device/deviceLink.ts b/cli/src/device/deviceLink.tsnew file mode 100644index 000000000..8cce832b3--- /dev/null+++ b/cli/src/device/deviceLink.ts@@ -0,0 +1,372 @@+// The daemon as a DEVICE on the backend's device plane, held on the dial's behalf.+//+// This is the only thing in the CLI that reaches a machine that is not this computer. It exists because+// the dial has no network of its own: everything it can ask for about another machine is asked here and+// answered back over the cable.+//+// ── WHAT THIS IS NOT ────────────────────────────────────────────────────────────────────────────────+// It is NOT the daemon's own backend socket. `BackendSocket` (/api/adapter-ws) holds the NODE role for+// this computer's machine and is the sole writer of its down-channel; this holds the COMMANDER role on+// somebody else's. Different endpoint, different role, different lifetime — and no conflict, because the+// backend keys hub clients by (machineId, kind).+//+// Three rules, each paid for:+//+// 1. THE LOCAL MACHINE NEVER COMES THROUGH HERE. Its agents are in this process. Routing them to a dial+// plugged into this very computer via the cloud would add a round trip, a failure mode and an+// audience, for nothing. `attach()` refuses it outright rather than trusting callers.+//+// 2. NEVER CLEAR THE AUTH SESSION. `BackendSocket.onRevoked` owns that decision. Two sockets racing to+// wipe a session on the same 401 is a bug waiting for a bad afternoon; a dead DeviceLink must+// degrade to "other machines unavailable" and leave the cabled machine working.+//+// 3. LOG EVERY ERROR AND EVERY DROPPED FRAME. This feature's characteristic bug is SILENT EMPTINESS —+// an RPC answered with an error nobody printed, a card arriving in a shape nobody recognised. All of+// them render as "the carousel is empty", and none of them says so anywhere by default.+import { hostname } from 'node:os'+import { randomUUID } from 'node:crypto'++import WebSocket from 'ws'++import type { AuthSessionManager } from '../lib/authSession.js'+import { b64d, type Identity } from '../lib/e2ee/core.js'+import { RelaySessionCrypto } from '../lib/e2ee/relayClient.js'+import type { MachinePeer } from '../lib/e2ee/machinePeers.js'+import { VERSION } from '../version.js'++/** One frame on the wire. The backend's own vocabulary, unchanged. */+export interface DeviceFrame {+ type?: string+ machineId?: string+ agentId?: string+ payload?: Record<string, unknown>+ [key: string]: unknown+}++const RPC_TIMEOUT_MS = 15_000+const PING_EVERY_MS = 15_000+const BASE_DELAY_MS = 1_000+const MAX_DELAY_MS = 30_000++export type DeviceLinkStatus = 'idle' | 'connecting' | 'ready' | 'error'++export interface DeviceLinkOpts {+ auth: AuthSessionManager+ backendWsBase: string+ computerId: string+ autonomousEnv: string+ /** This daemon's own E2EE identity — the same one `harness link create/import` signs with. */+ identity: Identity+ /** The pinned key for a machine, read FRESH: `harness link import` runs as a separate process. */+ peer: (machineId: string) => MachinePeer | null+ log: (line: string) => void+}++export class DeviceLink {+ private ws: WebSocket | null = null+ private attached = ''+ private wanted = ''+ private attempts = 0+ private reconnectTimer: NodeJS.Timeout | null = null+ private pingTimer: NodeJS.Timeout | null = null+ private state: DeviceLinkStatus = 'idle'+ private readonly pending = new Map<string, { resolve: (v: Record<string, unknown>) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>()+ private readonly listeners = new Set<(frame: DeviceFrame) => void>()+ /** Resolves when `machine_selected` lands, so callers can await the attach rather than poll for it. */+ private selectWaiter: { resolve: () => void; reject: (e: Error) => void; timer: NodeJS.Timeout } | null = null+ /**+ * The session for the attached machine, or null when none is needed.+ *+ * Only REMOTE machines (another computer running this same daemon) require one: a cloud machine's RPCs+ * are answered by the backend itself and its cards are plaintext, so there is nothing to establish and+ * nobody at the far end to establish it with.+ */+ private crypto: RelaySessionCrypto | null = null+ private cryptoWaiter: { resolve: () => void; reject: (e: Error) => void; timer: NodeJS.Timeout } | null = null++ constructor(private readonly opts: DeviceLinkOpts) {}++ status(): DeviceLinkStatus { return this.state }+ get selectedMachine(): string { return this.attached }++ onFrame(cb: (frame: DeviceFrame) => void): () => void {+ this.listeners.add(cb)+ return () => this.listeners.delete(cb)+ }++ /** Dial if needed, then select `machineId`. Rejects with a plain Error the caller maps to a code. */+ async attach(machineId: string): Promise<void> {+ if (!machineId) throw new Error('no machine to attach to')+ this.wanted = machineId+ if (this.attached === machineId && this.ws?.readyState === WebSocket.OPEN) return+ await this.connect()+ await this.select(machineId)+ await this.establish(machineId)+ }++ /**+ * Bring up the E2EE session for a machine that needs one.+ *+ * The trust anchor is the PINNED key from `harness link import`, never anything the backend hands over:+ * a key directory would make the relay the trust anchor, which is the exact property end-to-end+ * encryption exists to deny it.+ */+ private async establish(machineId: string): Promise<void> {+ this.crypto = null+ const peer = this.opts.peer(machineId)+ if (!peer) return // a cloud machine, or one whose RPCs the backend answers itself+ const crypto = new RelaySessionCrypto({ machineId, selfIdentity: this.opts.identity, peerPub: b64d(peer.pub) })+ this.crypto = crypto+ await new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.cryptoWaiter = null+ reject(new Error('the machine did not answer the E2EE hello'))+ }, RPC_TIMEOUT_MS)+ this.cryptoWaiter = { resolve, reject, timer }+ this.send(crypto.helloFrame() as DeviceFrame)+ })+ this.opts.log(`device: e2e session ready ${machineId}`)+ }++ /** Let go of whatever is attached. The socket is closed: nothing else on it is being watched. */+ release(): void {+ this.wanted = ''+ this.attached = ''+ if (this.ws?.readyState === WebSocket.OPEN) {+ this.send({ type: 'machine_deselect' })+ }+ this.teardown('released')+ }++ stop(): void {+ this.wanted = ''+ this.teardown('daemon stopping')+ }++ /** Fire-and-forget. Dropped with a line rather than thrown: a turn is not worth an unhandled rejection. */+ send(frame: DeviceFrame): void {+ if (this.ws?.readyState !== WebSocket.OPEN) {+ this.opts.log(`device: dropped ${frame.type ?? '?'} — no link`)+ return+ }+ // Wrapped only once the session is up. `e2e_*` frames are the handshake itself and must go in clear,+ // or the far end would need the key to learn the key.+ const out = this.crypto?.ready && !String(frame.type ?? '').startsWith('e2e_')+ ? (this.crypto.wrapOutgoing(frame as Record<string, unknown>) as DeviceFrame)+ : frame+ try { this.ws.send(JSON.stringify(out)) } catch (err) {+ this.opts.log(`device: send ${frame.type ?? '?'} failed (${(err as Error).message})`)+ }+ }++ /** One request/response, correlated by `requestId`. Rejects on timeout or an `error` in the reply. */+ async rpc(type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> {+ if (this.ws?.readyState !== WebSocket.OPEN) throw new Error('not connected')+ const requestId = randomUUID()+ return new Promise<Record<string, unknown>>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(requestId)+ this.opts.log(`device: ${type} timed out after ${RPC_TIMEOUT_MS} ms`)+ reject(new Error(`${type} timed out`))+ }, RPC_TIMEOUT_MS)+ this.pending.set(requestId, { resolve, reject, timer })+ this.send({ type, payload: { ...payload, requestId } })+ })+ }++ // ── connection ──────────────────────────────────────────────────────────────────────────────────++ private async connect(): Promise<void> {+ if (this.ws?.readyState === WebSocket.OPEN) return+ if (this.ws?.readyState === WebSocket.CONNECTING) return this.waitOpen()+ this.state = 'connecting'+ const base = this.opts.backendWsBase.replace(/\/$/, '')+ const url = `${base}/api/device-ws?computer=${encodeURIComponent(this.opts.computerId)}`+ + `&label=${encodeURIComponent(hostname())}`+ + `&autonomousEnv=${encodeURIComponent(this.opts.autonomousEnv)}`++ let token = await this.opts.auth.accessToken()+ this.opts.log(`device: connecting → ${base}/api/device-ws`)+ try {+ await this.open(url, token)+ } catch (err) {+ // Exactly ONE forced refresh, and only for a 401. Anything else is not a token problem, and a+ // refresh loop against a backend that is simply down burns the refresh token for nothing.+ if (!/401/.test(String((err as Error).message))) throw err+ token = await this.opts.auth.accessToken({ force: true, failedToken: token })+ await this.open(url, token)+ }+ }++ private open(url: string, token: string): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ const ws = new WebSocket(url, [token])+ this.ws = ws+ const onError = (err: Error): void => { cleanup(); reject(err) }+ const onOpen = (): void => {+ cleanup()+ this.attempts = 0+ this.state = 'ready'+ // `e2ee_data` says this side can decrypt an encrypted `*_result` — which it can, via+ // RelaySessionCrypto below. Advertising it before that was true would turn a clean+ // E2EE_REQUIRED error into a hang, which is why it went in only once the session did.+ //+ // `multi_machine` is deliberately NOT advertised: it would attach a commander to EVERY machine,+ // including this computer's own, whose daemon would then burn an LLM recap on turns nobody is+ // watching and echo its own cards back to itself through the cloud.+ this.send({+ type: 'device_hello',+ payload: { chip: 'harness-cli', firmwareVersion: VERSION, caps: ['e2ee_data'] },+ })+ this.armPing()+ resolve()+ }+ const cleanup = (): void => {+ ws.off('error', onError)+ ws.off('open', onOpen)+ }+ ws.once('error', onError)+ ws.once('open', onOpen)+ ws.on('message', (raw) => this.onMessage(raw))+ ws.on('close', (code) => this.onClose(code))+ })+ }++ private waitOpen(): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ const ws = this.ws+ if (!ws) return reject(new Error('no socket'))+ ws.once('open', () => resolve())+ ws.once('error', (err) => reject(err))+ })+ }++ private select(machineId: string): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.selectWaiter = null+ reject(new Error('the machine did not answer'))+ }, RPC_TIMEOUT_MS)+ this.selectWaiter = { resolve, reject, timer }+ this.send({ type: 'machine_select', payload: { machineId } })+ })+ }++ private onWelcome(payload: Record<string, unknown>): void {+ if (!this.crypto) return+ if (!this.crypto.handleWelcome(payload)) { this.failCrypto(new Error('E2EE_HANDSHAKE_FAILED')); return }+ if (this.cryptoWaiter) { clearTimeout(this.cryptoWaiter.timer); this.cryptoWaiter.resolve(); this.cryptoWaiter = null }+ }++ private failCrypto(err: Error): void {+ this.crypto = null+ if (this.cryptoWaiter) { clearTimeout(this.cryptoWaiter.timer); this.cryptoWaiter.reject(err); this.cryptoWaiter = null }+ }++ private armPing(): void {+ if (this.pingTimer) clearInterval(this.pingTimer)+ // App-level, not a WS ping: the backend refreshes device presence on any inbound frame, and a socket+ // that stops being present is dropped from every machine it is attached to.+ this.pingTimer = setInterval(() => this.send({ type: 'ping' }), PING_EVERY_MS)+ }++ private teardown(why: string): void {+ if (this.pingTimer) { clearInterval(this.pingTimer); this.pingTimer = null }+ if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null }+ for (const [, p] of this.pending) { clearTimeout(p.timer); p.reject(new Error(why)) }+ this.pending.clear()+ if (this.selectWaiter) { clearTimeout(this.selectWaiter.timer); this.selectWaiter.reject(new Error(why)); this.selectWaiter = null }+ this.failCrypto(new Error(why))+ const ws = this.ws+ this.ws = null+ this.attached = ''+ this.state = 'idle'+ try { ws?.close() } catch { /* already gone */ }+ }++ private onClose(code: number): void {+ this.opts.log(`device: closed (${code})`)+ const wanted = this.wanted+ this.teardown(`socket closed (${code})`)+ if (!wanted) return+ // 401/403 after the one refresh above is a decision, not a hiccup: stop, and let the cabled machine+ // carry on. Clearing the session here is NOT this class's call — see rule 2 in the header.+ if (code === 4401 || code === 4403) {+ this.state = 'error'+ this.opts.log('device: not authorized — other machines are unavailable until the next sign-in')+ return+ }+ const delay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.min(this.attempts++, 5))+ this.reconnectTimer = setTimeout(() => {+ void this.attach(wanted).catch((err) => this.opts.log(`device: reattach failed (${(err as Error).message})`))+ }, delay)+ }++ private onMessage(raw: WebSocket.RawData): void {+ let frame: DeviceFrame+ try { frame = JSON.parse(raw.toString()) as DeviceFrame } catch { return }++ if (frame.type === 'e2e_welcome') { this.onWelcome((frame.payload ?? {}) as Record<string, unknown>); return }+ if (frame.type === 'e2e_rekey') { this.crypto?.handleRekey((frame.payload ?? {}) as Record<string, unknown>); return }+ if (frame.type === 'e2e_denied') {+ // The far end knows this daemon's key and rejected it — the pin is stale, not merely missing.+ this.opts.log('device: e2e denied — re-run `harness link import` for this machine')+ this.failCrypto(new Error('E2EE_DENIED'))+ return+ }++ if (this.crypto?.ready) {+ const plain = this.crypto.unwrapIncoming(frame as Record<string, unknown>)+ if (!plain) {+ // The single most misleading failure this lane has: an undecryptable card is indistinguishable+ // from no card at all, and the dial just sits through a whole turn showing nothing.+ this.opts.log(`device: could not decrypt ${frame.type ?? '?'} — dropped`)+ return+ }+ frame = plain as DeviceFrame+ }+ const type = frame.type ?? ''+ const payload = (frame.payload ?? {}) as Record<string, unknown>++ if (type === 'machine_selected') {+ this.attached = typeof payload.machineId === 'string' ? payload.machineId : this.wanted+ this.opts.log(`device: machine_selected ${this.attached}`)+ if (this.selectWaiter) { clearTimeout(this.selectWaiter.timer); this.selectWaiter.resolve(); this.selectWaiter = null }+ return+ }+ if (type === 'machine_select_error') {+ const code = typeof payload.error === 'string' ? payload.error : 'SELECT_FAILED'+ this.opts.log(`device: machine_select_error ${code}`)+ if (this.selectWaiter) { clearTimeout(this.selectWaiter.timer); this.selectWaiter.reject(new Error(code)); this.selectWaiter = null }+ return+ }+ if (type === 'device_revoked') {+ this.opts.log('device: revoked — this dial was removed from the account')+ this.wanted = ''+ this.teardown('revoked')+ return+ }++ if (type.endsWith('_result')) {+ const requestId = typeof payload.requestId === 'string' ? payload.requestId : ''+ const waiter = requestId ? this.pending.get(requestId) : undefined+ if (!waiter) {+ // Not noise worth suppressing: a reply nobody is waiting for is either a timeout that already+ // fired or a frame the hub filtered and re-sent, and both are worth seeing while this is young.+ this.opts.log(`device: unmatched ${type}`)+ return+ }+ this.pending.delete(requestId)+ clearTimeout(waiter.timer)+ if (typeof payload.error === 'string') {+ this.opts.log(`device: ${type} error=${payload.error}`)+ waiter.reject(new Error(payload.error))+ return+ }+ waiter.resolve(payload)+ return+ }++ for (const cb of this.listeners) cb(frame)+ }+}diff --git a/cli/src/device/machineList.spec.ts b/cli/src/device/machineList.spec.tsnew file mode 100644index 000000000..09d268a76--- /dev/null+++ b/cli/src/device/machineList.spec.ts@@ -0,0 +1,118 @@+// The machine list, and the one comparison the whole feature hangs on.+//+// `local` is derived, not declared, and getting it wrong is invisible: every machine — including this+// computer's own — silently reads as remote, so the dial's own row goes missing and the daemon opens a+// cloud socket to reach agents that are in this very process.+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it, vi } from 'vitest'++import { MachineListCache, sameComputer } from './machineList.js'++const DIR = (): string => mkdtempSync(join(tmpdir(), 'machines-'))++/** The shape `GET /api/machines` actually answers with (MachineService.toOwner). */+function row(over: Record<string, unknown> = {}): Record<string, unknown> {+ return { machineId: 'm1', computerId: 'aabbccdd', name: 'office-imac', status: 'running', agentCount: 3, authMode: 'remote', ...over }+}++function ok(machines: Record<string, unknown>[]) {+ return async () => ({ status: 200, body: { machines } as Record<string, unknown> })+}++describe('sameComputer', () => {+ it('matches across the dash-and-case difference between the two sides', () => {+ // The CLI mints a dashed randomUUID; the backend de-dashes and lowercases before storing. A raw ===+ // never matches, and the symptom is that this computer never recognises itself.+ expect(sameComputer('7C9E6679-7425-40DE-944B-E07FC1F90AE7', '7c9e6679742540de944be07fc1f90ae7')).toBe(true)+ })++ it('is false for two different computers, and for nothing at all', () => {+ expect(sameComputer('aaaa', 'bbbb')).toBe(false)+ expect(sameComputer('', '')).toBe(false) // two blanks are not the same computer+ expect(sameComputer(undefined, 'aaaa')).toBe(false)+ })+})++describe('MachineListCache', () => {+ it('marks the row whose computerId is this computer as local', async () => {+ const cache = new MachineListCache(+ ok([row({ machineId: 'mine', computerId: 'AA-BB-CC-DD' }), row({ machineId: 'other', computerId: 'ffff' })]),+ () => 'aabbccdd',+ () => {},+ DIR(),+ )+ await cache.refresh()+ expect(cache.find('mine')?.local).toBe(true)+ expect(cache.find('other')?.local).toBe(false)+ })++ it('reads `status` as liveness', async () => {+ const cache = new MachineListCache(+ ok([row({ machineId: 'up', status: 'running' }), row({ machineId: 'down', status: 'stopped' }), row({ machineId: 'huh', status: '' })]),+ () => 'zzzz', () => {}, DIR(),+ )+ await cache.refresh()+ expect(cache.find('up')?.state).toBe('ready')+ expect(cache.find('down')?.state).toBe('offline')+ expect(cache.find('huh')?.state).toBe('unknown')+ })++ it('keeps the last known rows when the backend goes away, and stops calling them live', async () => {+ // The dial must still show the machines the user saw; what it must NOT do is keep claiming they are+ // reachable. Emptying the wheel on a network blip would read as "your machines are gone".+ let fail = false+ const cache = new MachineListCache(+ async () => { if (fail) throw new Error('ECONNREFUSED'); return { status: 200, body: { machines: [row()] } } },+ () => 'zzzz', () => {}, DIR(),+ )+ await cache.refresh()+ expect(cache.list().source).toBe('backend')++ fail = true+ await cache.refresh()+ expect(cache.list().machines).toHaveLength(1)+ expect(cache.list().source).toBe('local')+ expect(cache.find('m1')?.state).toBe('unknown')+ })++ it('reports signed-out on a 401, with no rows', async () => {+ const cache = new MachineListCache(async () => ({ status: 401, body: {} }), () => 'z', () => {}, DIR())+ await cache.refresh()+ expect(cache.list()).toEqual({ machines: [], source: 'signed-out' })+ })++ it('survives a daemon restart offline by reloading its cache — as unknown, never as live', async () => {+ const dir = DIR()+ const first = new MachineListCache(ok([row()]), () => 'zzzz', () => {}, dir)+ await first.refresh()++ const second = new MachineListCache(async () => { throw new Error('offline') }, () => 'zzzz', () => {}, dir)+ expect(second.find('m1')?.name).toBe('office-imac')+ expect(second.find('m1')?.state).toBe('unknown')+ })++ it('falls back to hostname, then to a short id, for a machine with no name', async () => {+ const cache = new MachineListCache(+ ok([row({ machineId: 'a', name: '', hostname: 'thinkpad' }), row({ machineId: 'bcdef0123', name: '', hostname: '' })]),+ () => 'z', () => {}, DIR(),+ )+ await cache.refresh()+ expect(cache.find('a')?.name).toBe('thinkpad')+ expect(cache.find('bcdef0123')?.name).toBe('machine-bcdef0')+ })++ it('drops a row with no machineId rather than carrying a blank one onto the wheel', async () => {+ const cache = new MachineListCache(ok([row(), row({ machineId: undefined })]), () => 'z', () => {}, DIR())+ await cache.refresh()+ expect(cache.list().machines).toHaveLength(1)+ })++ it('does not reject when the response is nonsense', async () => {+ const log = vi.fn()+ const cache = new MachineListCache(async () => ({ status: 200, body: { nope: true } }), () => 'z', log, DIR())+ await expect(cache.refresh()).resolves.toBeUndefined()+ expect(cache.list().source).toBe('local')+ })+})diff --git a/cli/src/device/machineList.ts b/cli/src/device/machineList.tsnew file mode 100644index 000000000..5fc67500e--- /dev/null+++ b/cli/src/device/machineList.ts@@ -0,0 +1,147 @@+// The owner's machines, and which of them is this computer.+//+// A REST read, not a socket subscription — and that is the point. `GET /api/machines` is already proxied+// by this daemon with its own SSO session (cli.ts `proxyBackend`), which is exactly what the desktop app+// consumes; reusing it means the dial's wheel and the app's machine list cannot disagree, and it means the+// wheel exists before any lane to another machine does.+//+// The cache is SYNCHRONOUS to read. The cable session ticks every second and must never await a network+// call to decide whether to redraw a list that has not changed.+import { readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'++import { env } from '../config/env.js'+import type { FleetMachine } from '../cable/machineFleet.js'++/** What `GET /api/machines` returns per row (MachineService.toOwner). Only the fields the dial uses. */+interface OwnerMachine {+ machineId?: unknown+ computerId?: unknown+ name?: unknown+ hostname?: unknown+ status?: unknown+ agentCount?: unknown+ authMode?: unknown+}++/** A fleet row plus the flag the wheel needs; `local` is derived here and nowhere else. */+export type ListedMachine = FleetMachine & { local: boolean }++/**+ * Compare two computer ids the way the backend stores them.+ *+ * BOTH sides must be normalized and it is not defensive padding: this CLI mints a dashed `randomUUID()`+ * while the backend de-dashes and lowercases before storing, so a raw `===` never matches and every+ * machine — including this computer's own — reads as remote.+ */+export function sameComputer(a: string | null | undefined, b: string | null | undefined): boolean {+ const norm = (s: string | null | undefined): string => (s ?? '').trim().toLowerCase().replace(/-/g, '')+ const na = norm(a)+ return na.length > 0 && na === norm(b)+}++export type MachineSource = 'backend' | 'local' | 'signed-out'++function stateOf(status: string): FleetMachine['state'] {+ // `toOwner.status` is resolved live for computer-backed machines (`applyRemoteStatus`), so it is a real+ // presence signal for exactly the machines where presence is a question.+ if (status === 'running') return 'ready'+ if (status === 'stopped' || status === 'offline') return 'offline'+ return 'unknown'+}++export class MachineListCache {+ private machines: ListedMachine[] = []+ private source: MachineSource = 'local'+ private readonly path: string++ constructor(+ private readonly fetchMachines: () => Promise<{ status: number; body: Record<string, unknown> }>,+ private readonly localComputerId: () => string,+ private readonly log: (line: string) => void,+ dataDir = env.ADAPTER_DATA_DIR,+ ) {+ this.path = join(dataDir, 'machines.json')+ this.loadCache()+ }++ /** Synchronous by contract — see the file header. */+ list(): { machines: ListedMachine[]; source: MachineSource } {+ return { machines: this.machines, source: this.source }+ }++ find(machineId: string): ListedMachine | undefined {+ return this.machines.find((m) => m.machineId === machineId)+ }++ /**+ * Re-read the list.+ *+ * Never throws. A daemon that cannot reach the backend still has one machine that works perfectly — the+ * one on the other end of the cable — so an outage downgrades `source` and keeps the last known rows+ * rather than emptying the wheel.+ */+ async refresh(): Promise<void> {+ let res: { status: number; body: Record<string, unknown> }+ try {+ res = await this.fetchMachines()+ } catch (err) {+ this.degrade(`unreachable (${(err as Error).message})`)+ return+ }+ if (res.status === 401 || res.status === 403) { this.signedOut(); return }+ if (res.status >= 400) { this.degrade(`HTTP ${res.status}`); return }++ const raw = (res.body?.machines ?? (res.body?.data as Record<string, unknown> | undefined)?.machines) as unknown+ if (!Array.isArray(raw)) { this.degrade('no machines in the response'); return }++ const mine = this.localComputerId()+ this.machines = raw.map((r) => this.toListed(r as OwnerMachine, mine)).filter((m) => m.machineId)+ this.source = 'backend'+ this.saveCache()+ }++ private toListed(r: OwnerMachine, mine: string): ListedMachine {+ const machineId = typeof r.machineId === 'string' ? r.machineId : ''+ const name = typeof r.name === 'string' && r.name.trim() ? r.name.trim()+ : typeof r.hostname === 'string' && r.hostname.trim() ? r.hostname.trim()+ : `machine-${machineId.slice(0, 6)}`+ const authMode = r.authMode === 'managed' || r.authMode === 'remote' || r.authMode === 'provider' ? r.authMode : 'self'+ return {+ machineId,+ name,+ state: stateOf(typeof r.status === 'string' ? r.status : ''),+ agentCount: typeof r.agentCount === 'number' ? r.agentCount : -1,+ authMode,+ // Derived, never declared — the same rule the desktop app follows.+ local: sameComputer(typeof r.computerId === 'string' ? r.computerId : '', mine),+ }+ }++ /** The list is stale but not wrong: keep the rows, stop claiming they are live. */+ private degrade(why: string): void {+ if (this.source !== 'local') this.log(`machines: ${why} — showing the last known list`)+ this.source = 'local'+ for (const m of this.machines) m.state = 'unknown'+ }++ private signedOut(): void {+ if (this.source !== 'signed-out') this.log('machines: not signed in')+ this.source = 'signed-out'+ this.machines = []+ }++ /** So a daemon that starts offline still draws the list the user saw last time. */+ private loadCache(): void {+ try {+ const parsed = JSON.parse(readFileSync(this.path, 'utf8')) as { machines?: ListedMachine[] }+ if (Array.isArray(parsed.machines)) {+ this.machines = parsed.machines.map((m) => ({ ...m, state: 'unknown' as const }))+ }+ } catch { /* no cache yet, or unreadable — an empty wheel plus the local row is correct */ }+ }++ private saveCache(): void {+ try { writeFileSync(this.path, JSON.stringify({ machines: this.machines }), { mode: 0o600 }) } catch { /* best effort */ }+ }+}