Skip to content

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.

Devices in a process of their own: the dial, the window bridges and the fleet (step 9, D2) (#928)

Dee62cfbbd3a2cc
diff --git a/cli/e2e/deviceCompat.e2e.ts b/cli/e2e/deviceCompat.e2e.ts
index 1dde3a70d..f454dc0f8 100644
--- a/cli/e2e/deviceCompat.e2e.ts
+++ b/cli/e2e/deviceCompat.e2e.ts
@@ -53,6 +53,8 @@ interface Heard {
shapes: Map<string, Set<string>>
/** What the scenario checked by value, as it found it. */
values: Record<string, unknown>
+ /** Everything the dial and the window heard, in order, for reading a difference (COMPAT_REPORT). */
+ order: string[]
}
function hear(into: Heard, key: string, value: unknown): void {
@@ -66,7 +68,7 @@ async function scenario(scriptPath: string | undefined, label: string): Promise<
const dial = await FakeDial.open()
const daemon = await IsolatedDaemon.create({ ...(scriptPath ? { scriptPath } : {}), env: { CABLE_DISABLE: 'false', HARNESSD_TEST_DIAL_PORT: dial.path } })
onTestFailed(() => { console.log(`---- ${label} daemon log\n${daemon.log().split('\n').slice(-120).join('\n')}\n---- the dial heard\n${dial.messages.map((m) => m.t).join(' ')}`) })
- const heard: Heard = { shapes: new Map(), values: {} }
+ const heard: Heard = { shapes: new Map(), values: {}, order: [] }
try {
await daemon.start()
const window = await LocalClient.connect(daemon)
@@ -79,6 +81,10 @@ async function scenario(scriptPath: string | undefined, label: string): Promise<
// The window opens a tab with the agent on it, as the desktop does on every change.
window.send('app_swarms', { active: 't1', swarms: [{ id: 't1', name: 'Tab', agentIds: [agentId], panes: 1 }, { id: 't2', name: 'Other', agentIds: [], panes: 0 }], tiles: [] })
window.send('app_panes', { agentIds: [agentId], foreground: true })
+ // A moment for the tab to reach the devices, a process away from the window since step 9: a dial that
+ // greets in the same millisecond is first shown the empty desk it was plugged into, then the tab. A dial
+ // plugged in after the window opened its tab, as people do, is shown the tab.
+ await new Promise((resolve) => setTimeout(resolve, 1_000))
await dial.greet()
await dial.next((m) => m.t === 'agents.end', 30_000, 'the agent list')
// A turn from the window: the dial is told it started and ended, and its recap.
@@ -127,6 +133,7 @@ async function scenario(scriptPath: string | undefined, label: string): Promise<
for (const message of dial.messages as DialMessage[]) {
if (message.t === 'ping') continue
hear(heard, `dial ${message.t}`, message)
+ heard.order.push(`dial ${JSON.stringify(message).slice(0, 160)}`)
}
for (const frame of window.frames as Frame[]) {
if (!frame.type.startsWith('dial_') && frame.type !== 'harness_devices_changed' && frame.type !== 'voice_route_request') continue
@@ -155,7 +162,7 @@ describe.skipIf(!FROM)('the devices\' frames, against another build\'s', () => {
const before = await scenario(FROM, 'released')
const after = await scenario(process.env.E2E_BUNDLE_PATH, 'this build')
if (process.env.COMPAT_REPORT) {
- const side = (heard: Heard) => ({ shapes: Object.fromEntries([...heard.shapes].map(([key, set]) => [key, [...set].map((s) => JSON.parse(s))])), values: heard.values })
+ const side = (heard: Heard) => ({ shapes: Object.fromEntries([...heard.shapes].map(([key, set]) => [key, [...set].map((s) => JSON.parse(s))])), values: heard.values, order: heard.order })
writeFileSync(process.env.COMPAT_REPORT, JSON.stringify({ before: side(before), after: side(after) }, null, 2))
}
const differences: string[] = []
diff --git a/cli/e2e/devicesProcess.e2e.ts b/cli/e2e/devicesProcess.e2e.ts
new file mode 100644
index 000000000..05d68befc
--- /dev/null
+++ b/cli/e2e/devicesProcess.e2e.ts
@@ -0,0 +1,345 @@
+/**
+ * The devices in a process of their own (services/devicesProcess.ts, docs/design/2026-10-06-core-boundary-
+ * next.md, step 9), on the real daemon, with fake dials on pseudo-terminals (harness/fakeDial.ts) that greet
+ * on the firmware's own cadence. One device failing never fails the core, another device or a running agent:
+ * - the devices' process killed, hung, leaking or crashing on every start costs the dials alone, the core
+ * never restarts, ⌘K says so at once, and when the master brings the process back the dial comes back to
+ * its open question and its working tile;
+ * - two dials are two devices: each its own settings and its own fate, the desk's cards on both;
+ * - a dial unplugged and plugged in again and again, a dial whose session throws on every call, and a dial
+ * flooding its port with what no dial sends are each dropped alone, and come back.
+ */
+import { execFileSync } from 'node:child_process'
+import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+import { FakeDial, type DialMessage } from './harness/fakeDial.js'
+
+const SETTINGS = { brightness: 60, character: 0, face: 466, muted: false, quiet: false, straightTitle: false, focusFace: false, scrollReversed: false, round: true, voiceLang: 'en' }
+
+const row = async (client: LocalClient, agentId: string) =>
+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)
+ .find((agent) => agent.id === agentId)
+async function create(daemon: IsolatedDaemon, client: LocalClient, folder: string): Promise<string> {
+ const cwd = join(daemon.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ await until(`${folder} to bind its conversation`, async () => {
+ const agent = await row(client, created.agent.id)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500)
+ return created.agent.id
+}
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ await ended
+}
+/** This daemon's devices processes, by the pids its master logged: `harnessd-devices` alone would match every
+ * daemon's on the machine, another file's in a parallel run. */
+function devicesPids(d: IsolatedDaemon): number[] {
+ const ours = new Set([...d.log().matchAll(/\[harnessd\] service devices started \(pid (\d+)\)/g)].map((match) => Number(match[1])))
+ const table = execFileSync('ps', ['-A', '-o', 'pid=,command=']).toString().trim().split('\n')
+ return table.map((line) => line.trim().match(/^(\d+)\s+(.*)$/)).filter((match): match is RegExpMatchArray => !!match)
+ .filter(([, pid, command]) => command.trim() === 'harnessd-devices' && ours.has(Number(pid))).map(([, pid]) => Number(pid))
+}
+const restarts = (d: IsolatedDaemon) => d.log().split('\n').filter((line) => /\[harnessd\] service devices started .* restart \d+/.test(line)).length
+const connections = (d: IsolatedDaemon) => d.log().split('\n').filter((line) => line.includes('[services] devices connected')).length
+/** ⌘K's pick for a typed task: `route_task` answers as `route_result`, under the asker's request id. */
+async function routeTask(client: LocalClient, text: string): Promise<Record<string, any>> {
+ const requestId = `route-${Math.random().toString(36).slice(2)}`
+ const answered = client.next((frame) => frame.type === 'route_result' && frame.payload?.requestId === requestId, 40_000, 'route_result')
+ client.send('route_task', { requestId, text })
+ return (await answered).payload as Record<string, any>
+}
+
+/** The dials this daemon finds, written where its discovery reads them at every scan. */
+class Desk {
+ constructor(readonly file: string, private readonly plugged = new Map<string, FakeDial>()) {}
+ async plug(serial: string, mac: string): Promise<FakeDial> {
+ const dial = await FakeDial.open({ mac, settings: SETTINGS })
+ this.plugged.set(serial, dial)
+ this.write()
+ dial.keepGreeting()
+ return dial
+ }
+ async unplug(serial: string): Promise<void> {
+ const dial = this.plugged.get(serial)
+ this.plugged.delete(serial)
+ this.write()
+ await dial?.close()
+ }
+ async close(): Promise<void> {
+ for (const serial of [...this.plugged.keys()]) await this.unplug(serial)
+ }
+ private write(): void {
+ writeFileSync(this.file, JSON.stringify([...this.plugged].map(([serial, dial]) => ({ serial, path: dial.path }))))
+ }
+}
+
+describe('the devices in their own process', () => {
+ let daemon: IsolatedDaemon | undefined
+ let desk: Desk | undefined
+ afterEach(async () => {
+ await desk?.close()
+ await daemon?.close()
+ daemon = undefined
+ desk = undefined
+ })
+ const fresh = async (env: Record<string, string> = {}): Promise<{ d: IsolatedDaemon; desk: Desk }> => {
+ const d = await IsolatedDaemon.create({ env: {
+ CABLE_DISABLE: 'false',
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',
+ HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',
+ ...env,
+ } })
+ daemon = d
+ const file = join(d.root, 'dials.json')
+ d.env.HARNESSD_TEST_DIAL_PORT = file
+ desk = new Desk(file)
+ writeFileSync(file, '[]')
+ const theDesk = desk
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-200).join('\n')}`) })
+ await d.start()
+ await until('the devices to connect to the core', () => connections(d) >= 1 || null, 30_000, 200)
+ return { d, desk: theDesk }
+ }
+ /** A window with a tab holding these agents, as the desktop says it on every change. */
+ const onTab = (window: LocalClient, agentIds: string[]): void => {
+ window.send('app_swarms', { active: 't1', swarms: [{ id: 't1', name: 'Tab', agentIds, panes: agentIds.length }], tiles: [] })
+ window.send('app_panes', { agentIds, foreground: true })
+ }
+ const heard = (dial: FakeDial, t: string, since = 0, agentId?: string, ms = 45_000): Promise<DialMessage> =>
+ dial.next((m) => m.t === t && (agentId === undefined || m.agentId === agentId), ms, t, since)
+
+ it('runs the dial: a turn\'s cards, a hand on the dial, and the Devices tab, from a process of its own', async () => {
+ const { d, desk } = await fresh()
+ const window = await LocalClient.connect(d)
+ const agentId = await create(d, window, 'devices-dial')
+ onTab(window, [agentId])
+ const dial = await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')
+ await heard(dial, 'agents.end')
+ const since = dial.messages.length
+ await turn(window, agentId, 'hello from the window')
+ await heard(dial, 'turn.started', since, agentId)
+ await heard(dial, 'summary', since, agentId)
+ dial.send({ t: 'focus', agentId })
+ await window.waitFor((f) => f.type === 'dial_focus' && f.payload?.agentId === agentId, 15_000, 'dial_focus')
+ const listed = await window.request('harness_devices_list', {})
+ expect(listed).toMatchObject({ protocol: 1, status: { attached: true } })
+ expect(listed.status.devices).toHaveLength(1)
+ // It is its own process, under the core's master.
+ const [pid] = devicesPids(d)
+ expect(pid).toBeGreaterThan(0)
+ expect(d.coresStarted()).toBe(1)
+ window.close()
+ })
+
+ it('killed outright: agents and windows go on, ⌘K says so at once, and the dial comes back to its question and its working tile', async () => {
+ const { d, desk } = await fresh()
+ const window = await LocalClient.connect(d)
+ const asking = await create(d, window, 'devices-asking')
+ const other = await create(d, window, 'devices-other')
+ onTab(window, [asking, other])
+ const dial = await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')
+ await heard(dial, 'agents.end')
+ // A question, mid-turn: the tile is working and the dial is asked.
+ window.send('message', { agentId: asking, content: '!ask' })
+ const question = await heard(dial, 'question', 0, asking)
+ for (const pid of devicesPids(d)) process.kill(pid, 'SIGKILL')
+ // Asked while they are down: an answer, not a hang.
+ const started = Date.now()
+ const sent = await window.request('route_send', { agentId: other, text: 'while the devices are down' }, 15_000)
+ expect(sent.ok === false || sent.ok === true, JSON.stringify(sent)).toBe(true)
+ expect(Date.now() - started).toBeLessThan(8_000)
+ // The agents never noticed.
+ await turn(window, other, 'the devices are gone and nothing else cares')
+ await until('the master to restart the devices', () => restarts(d) >= 1 || null, 30_000, 200)
+ await until('the devices to connect again', () => connections(d) >= 2 || null, 30_000, 200)
+ // The dial greets on its own cadence, is welcomed by the new process, and is shown what was open.
+ const back = dial.messages.length
+ await dial.welcomeAfter(back, 45_000)
+ const again = await heard(dial, 'question', back, asking)
+ expect(again.id).toBe(question.id)
+ await heard(dial, 'turn.started', back, asking)
+ // Answered on the dial, as before the restart: the agent gets it.
+ const shaped = (again.questions as Array<{ q: string }>)[0]
+ const ended = window.next(isTurn('turn_ended', asking), 45_000, 'the asking turn ending')
+ dial.send({ t: 'answer', agentId: asking, requestId: again.id, answers: { [shaped.q]: 'Coffee' } })
+ await ended
+ await heard(dial, 'question.close', back, asking)
+ expect(await d.capture(String((await row(window, asking))?.tmuxPane))).toContain('you chose Coffee')
+ expect(d.coresStarted()).toBe(1)
+ window.close()
+ })
+
+ it('hung: the core never waits on it, the master kills it, and the dial comes back', async () => {
+ const { d, desk } = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '2000' })
+ const window = await LocalClient.connect(d)
+ const agentId = await create(d, window, 'devices-hung')
+ onTab(window, [agentId])
+ const dial = await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')
+ await heard(dial, 'agents.end')
+ for (const pid of devicesPids(d)) process.kill(pid, 'SIGSTOP')
+ // ⌘K is the devices' to answer: it says it cannot, within its deadline, and typing never waited on it.
+ const started = Date.now()
+ expect(await window.request('route_send', { agentId, text: 'not delivered' }, 15_000)).toMatchObject({ ok: false, reason: 'the devices service is unavailable' })
+ expect(Date.now() - started).toBeLessThan(8_000)
+ await turn(window, agentId, 'the core never waited on the devices')
+ await until('the master to find the devices hung', () => d.log().includes('[harnessd] service devices sent no heartbeat') || null, 30_000, 200)
+ await until('the devices to be started again', () => restarts(d) >= 1 || null, 30_000, 200)
+ const back = dial.messages.length
+ await dial.welcomeAfter(back, 45_000)
+ await turn(window, agentId, 'and the dial is back')
+ await heard(dial, 'summary', back, agentId)
+ expect(d.coresStarted()).toBe(1)
+ window.close()
+ })
+
+ it('leaking: restarted at its memory budget, before it can hurt anything else', async () => {
+ const { d } = await fresh({ HARNESSD_TEST_FAULTS: 'devices.leak', HARNESSD_SERVICE_HEAP_LIMIT_MIB: '128' })
+ const window = await LocalClient.connect(d)
+ const agentId = await create(d, window, 'devices-leaking')
+ await until('the master to restart the devices for memory', () => /\[harnessd\] service devices: (its heap is at|it is using)/.test(d.log()) || null, 60_000, 250)
+ await until('the devices to be started again', () => restarts(d) >= 1 || null, 30_000, 200)
+ await turn(window, agentId, 'the leak was the devices\' alone')
+ expect(d.coresStarted()).toBe(1)
+ window.close()
+ })
+
+ it('crashing on every start: parked, its requests say so, and the agents go on', async () => {
+ const d = await IsolatedDaemon.create({ env: { CABLE_DISABLE: 'false', HARNESSD_TEST_FAULTS: 'devices.crash', HARNESSD_SERVICE_PARK_CRASHES: '3',
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000' } })
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ await d.start()
+ const window = await LocalClient.connect(d)
+ const agentId = await create(d, window, 'devices-crash-loop')
+ await until('the master to park the devices', () => d.log().includes('[harnessd] service devices ended 3 times') || null, 60_000, 250)
+ expect(await window.request('harness_devices_list', {}, 10_000)).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'devices', retryable: true })
+ expect(await routeTask(window, 'fix the parser')).toMatchObject({ agentId: '', reason: 'the devices service is unavailable' })
+ await turn(window, agentId, 'the devices are parked and nothing else cares')
+ expect(d.coresStarted()).toBe(1)
+ window.close()
+ })
+
+ it('two dials are two devices: each its own settings and fate, the desk\'s cards on both', async () => {
+ const { d, desk } = await fresh()
+ const window = await LocalClient.connect(d)
+ const agentId = await create(d, window, 'devices-two')
+ onTab(window, [agentId])
+ const a = await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')
+ const b = await desk.plug('E2E-B', 'e2:e0:00:00:00:0b')
+ await heard(a, 'agents.end')
+ await heard(b, 'agents.end')
+ const listed = await until('both dials on the Devices tab', async () => {
+ const answer = await window.request('harness_devices_list', {})
+ return (answer.status?.devices as unknown[] | undefined)?.length === 2 ? answer : null
+ }, 30_000, 500)
+ expect((listed.status.devices as Array<{ id: string }>).map((device) => device.id).sort()).toEqual(['E2E-A', 'E2E-B'])
+ // A setting belongs to the glass it is set on.
+ const sinceA = a.messages.length
+ const sinceB = b.messages.length
+ expect(await window.request('harness_device_settings', { id: 'E2E-B', patch: { brightness: 20 } })).toMatchObject({ ok: true })
+ await heard(b, 'settings.set', sinceB)
+ // The desk's work reaches both: they show the same desktop.
+ await turn(window, agentId, 'both dials hear this')
+ await heard(a, 'summary', sinceA, agentId)
+ await heard(b, 'summary', sinceB, agentId)
+ expect(a.messages.slice(sinceA).some((m) => m.t === 'settings.set')).toBe(false)
+ // One unplugged: the other goes on, and the tab still names the one that left.
+ await desk.unplug('E2E-A')
+ await until('A to read as unplugged', async () => {
+ const answer = await window.request('harness_devices_list', {})
+ return (answer.status?.devices as Array<{ id: string; attached: boolean }> | undefined)?.find((device) => device.id === 'E2E-A')?.attached === false || null
+ }, 30_000, 500)
+ const stillB = b.messages.length
+ await turn(window, agentId, 'b alone now')
+ await heard(b, 'summary', stillB, agentId)
+ // Plugged in again: welcomed as a dial that knows nothing.
+ const again = await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')
+ await heard(again, 'agents.end')
+ expect(restarts(d)).toBe(0)
+ expect(d.coresStarted()).toBe(1)
+ window.close()
+ })
+
+ it('unplugged and plugged in again and again: the other dial, the agents and the devices\' process carry on', async () => {
+ const { d, desk } = await fresh()
+ const window = await LocalClient.connect(d)
+ const agentId = await create(d, window, 'devices-storm')
+ onTab(window, [agentId])
+ const b = await desk.plug('E2E-B', 'e2:e0:00:00:00:0b')
+ await heard(b, 'agents.end')
+ for (let i = 0; i < 12; i++) {
+ await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')
+ await new Promise((resolve) => setTimeout(resolve, 150 + (i % 3) * 400))
+ await desk.unplug('E2E-A')
+ }
+ const since = b.messages.length
+ await turn(window, agentId, 'after the storm')
+ await heard(b, 'summary', since, agentId)
+ const a = await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')
+ await heard(a, 'agents.end')
+ expect(restarts(d)).toBe(0)
+ expect(d.coresStarted()).toBe(1)
+ window.close()
+ })
+
+ it('a dial whose session throws on every call is dropped alone, and its port looked at again', async () => {
+ const { d, desk } = await fresh({ HARNESSD_TEST_FAULTS: 'dial.E2E-A' })
+ const window = await LocalClient.connect(d)
+ const agentId = await create(d, window, 'devices-throwing')
+ onTab(window, [agentId])
+ const b = await desk.plug('E2E-B', 'e2:e0:00:00:00:0b')
+ await heard(b, 'agents.end')
+ await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')
+ await until('A to be dropped', () => /cable: \S+ dropped \(\d+ faults in a minute: injected fault: dial\.E2E-A\) — this dial alone/.test(d.log()) || null, 60_000, 250)
+ const opened = () => d.log().split('\n').filter((line) => /cable: open on .* \[usb E2E-A\]/.test(line)).length
+ const first = opened()
+ await until('A\'s port to be looked at again', () => opened() > first || null, 30_000, 250)
+ // The other dial never noticed.
+ const since = b.messages.length
+ await turn(window, agentId, 'b carries on')
+ await heard(b, 'summary', since, agentId)
+ expect(restarts(d)).toBe(0)
+ expect(d.coresStarted()).toBe(1)
+ window.close()
+ })
+
+ it('a dial flooding its port with what no dial sends is dropped alone, and comes back once it stops', async () => {
+ const { d, desk } = await fresh()
+ const window = await LocalClient.connect(d)
+ const agentId = await create(d, window, 'devices-flooding')
+ onTab(window, [agentId])
+ const a = await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')
+ const b = await desk.plug('E2E-B', 'e2:e0:00:00:00:0b')
+ await heard(a, 'agents.end')
+ await heard(b, 'agents.end')
+ const flooded = Date.now()
+ const pingsFrom = b.messages.length
+ a.flood(Buffer.alloc(256 * 1024, 0x55))
+ await until('A to be dropped for flooding', () => /dropped \(flooding the port: .*\) — this dial alone.*\[usb E2E-A\]/.test(d.log()) || null, 30_000, 250)
+ const since = b.messages.length
+ await turn(window, agentId, 'b carries on through the flood')
+ await heard(b, 'summary', since, agentId)
+ // The other dial's keepalive kept its beat through the flood: what a dial reads as its daemon alive.
+ await heard(b, 'ping', b.messages.length, undefined, 15_000)
+ const pings = b.messages.map((m, at) => ({ m, at: b.arrivedAt[at] })).slice(pingsFrom).filter(({ m }) => m.t === 'ping').map(({ at }) => at)
+ const gaps = pings.slice(1).map((at, i) => at - pings[i])
+ const dropped = d.log().match(/(\d\d:\d\d:\d\d\.\d{3}) \[cable\] cable: \S+ dropped \(flooding/)
+ // `E2E_MEASURE=<file>`: what the pull request reports of the flood, kept.
+ if (process.env.E2E_MEASURE) appendFileSync(process.env.E2E_MEASURE, `flood: dropped at ${dropped?.[1]} (sent ${new Date(flooded).toISOString().slice(11, 23)} UTC); the other dial's ping gaps ${gaps.join(', ')} ms\n`)
+ expect(Math.max(...gaps)).toBeLessThan(10_000)
+ // Quiet again, it is welcomed again on its next greeting once its wait is over.
+ const back = a.messages.length
+ await a.welcomeAfter(back, 60_000)
+ expect(restarts(d)).toBe(0)
+ expect(d.coresStarted()).toBe(1)
+ window.close()
+ })
+})
diff --git a/cli/e2e/harness/fakeDial.ts b/cli/e2e/harness/fakeDial.ts
index 54e7f9956..8f0100958 100644
--- a/cli/e2e/harness/fakeDial.ts
+++ b/cli/e2e/harness/fakeDial.ts
@@ -15,24 +15,44 @@ const here = dirname(fileURLToPath(import.meta.url))
export type DialMessage = Record<string, unknown> & { t?: string }
+export interface FakeDialOptions {
+ /** What it calls itself in its greeting; two dials on one desk differ by it. */
+ mac?: string
+ /** The settings it says it holds when it greets, as the firmware reads them from its flash. */
+ settings?: Record<string, unknown>
+}
+
export class FakeDial {
readonly messages: DialMessage[] = []
+ /** When each message arrived, ms since the epoch: the gaps are what a dial reads as its daemon's health. */
+ readonly arrivedAt: number[] = []
private readonly decoder = new CableDecoder()
+ private readonly mac: string
+ private readonly settings?: Record<string, unknown>
+ /** When the daemon last said anything, and whether it has welcomed this dial since it last went quiet. */
+ private heardAt = 0
+ private welcomed = false
+ private cadence: ReturnType<typeof setInterval> | null = null
- private constructor(private readonly bridge: ChildProcess, readonly path: string) {
+ private constructor(private readonly bridge: ChildProcess, readonly path: string, options: FakeDialOptions) {
+ this.mac = options.mac ?? 'e2:e0:00:00:00:01'
+ this.settings = options.settings
bridge.stdout!.on('data', (chunk: Buffer) => {
this.decoder.feed(chunk, (frame) => {
if (frame.type !== CableType.Json) return
let message: DialMessage
try { message = JSON.parse(Buffer.from(frame.payload).toString('utf8')) as DialMessage } catch { return }
this.messages.push(message)
+ this.arrivedAt.push(Date.now())
+ this.heardAt = Date.now()
+ if (message.t === 'welcome') this.welcomed = true
// A dial that stops answering for 20 seconds is taken as unplugged (cableSession SILENCE_MS).
if (message.t === 'ping') this.send({ t: 'pong' })
})
})
}
- static async open(): Promise<FakeDial> {
+ static async open(options: FakeDialOptions = {}): Promise<FakeDial> {
const bridge = spawn('python3', [join(here, 'ptyBridge.py')], { stdio: ['pipe', 'pipe', 'pipe'] })
const path = await new Promise<string>((resolve, reject) => {
let said = ''
@@ -44,7 +64,11 @@ export class FakeDial {
})
bridge.once('exit', (code) => { clearTimeout(timer); reject(new Error(`the pseudo-terminal bridge exited (${code}): ${said}`)) })
})
- return new FakeDial(bridge, path)
+ return new FakeDial(bridge, path, options)
+ }
+
+ private hello(): DialMessage {
+ return { t: 'hello', product: 'harness', proto: 3, mac: this.mac, fw: '0.0.0-e2e', hw: 'e2e', ...(this.settings ? { settings: this.settings } : {}) }
}
send(message: DialMessage): void {
@@ -66,19 +90,51 @@ export class FakeDial {
* Greet the daemon as the firmware does, again and again until it answers: the daemon opens the port
* on its own scan, and a greeting sent before then lands on nobody.
*/
- async greet(ms = 60_000): Promise<DialMessage> {
- const hello: DialMessage = { t: 'hello', product: 'harness', proto: 3, mac: 'e2:e0:00:00:00:01', fw: '0.0.0-e2e', hw: 'e2e' }
+ async greet(ms = 60_000, since = 0): Promise<DialMessage> {
const deadline = Date.now() + ms
for (;;) {
- this.send(hello)
- const welcome = this.messages.find((m) => m.t === 'welcome')
+ this.send(this.hello())
+ const welcome = this.messages.slice(since).find((m) => m.t === 'welcome')
if (welcome) return welcome
if (Date.now() > deadline) throw new Error(`the daemon never welcomed the dial (heard: ${this.messages.map((m) => m.t).join(', ') || 'nothing'})`)
await new Promise((done) => setTimeout(done, 500))
}
}
+ /**
+ * Greet as the firmware does, on its own, for as long as the dial is plugged in: every two seconds until
+ * the daemon welcomes it, then every fifteen, welcomed or not — which is how a dial finds a daemon that
+ * started again behind the same port, since it has no port-open event to wait on and the new daemon's
+ * pings sound like the old one's (cableSession.ts, rule 1). Fifteen seconds without a word from the
+ * daemon (the dial's own window) and it is no longer welcomed.
+ */
+ keepGreeting(): void {
+ if (this.cadence) return
+ let greetedAt = 0
+ const tick = (): void => {
+ if (this.welcomed && Date.now() - this.heardAt > 15_000) this.welcomed = false
+ const every = this.welcomed ? 15_000 : 2_000
+ if (Date.now() - greetedAt < every) return
+ greetedAt = Date.now()
+ this.send(this.hello())
+ }
+ this.cadence = setInterval(tick, 500)
+ tick()
+ }
+
+ /** Bytes that are no frames, straight onto the port: what a broken or hostile board sends. */
+ flood(bytes: Buffer): void {
+ this.bridge.stdin!.write(bytes)
+ }
+
+ /** The first welcome after `since`, waiting up to `ms`: a daemon that started again behind the port. */
+ welcomeAfter(since: number, ms = 60_000): Promise<DialMessage> {
+ return this.next((m) => m.t === 'welcome', ms, 'a welcome', since)
+ }
+
async close(): Promise<void> {
+ if (this.cadence) clearInterval(this.cadence)
+ this.cadence = null
if (this.bridge.exitCode !== null) return
const exited = new Promise<void>((done) => this.bridge.once('exit', () => done()))
this.bridge.stdin!.end()
diff --git a/cli/e2e/harness/ptyBridge.py b/cli/e2e/harness/ptyBridge.py
index 18e546b38..f1ff6f9b0 100644
--- a/cli/e2e/harness/ptyBridge.py
+++ b/cli/e2e/harness/ptyBridge.py
@@ -28,7 +28,9 @@ os.set_blocking(stdin, False)
os.set_blocking(master, False)
pending = b''
while True:
- readable, _, _ = select.select([master, stdin], [], [], 0.05)
+ # Woken as soon as the terminal can take more, so a test's burst reaches the daemon at the speed a
+ # terminal carries it, not one buffer every 50 ms.
+ readable, writable, _ = select.select([master, stdin], [master] if pending else [], [], 0.05)
if stdin in readable:
try:
chunk = os.read(stdin, 65536)
diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.ts
index 467025d37..ee44aab68 100644
--- a/cli/e2e/services.e2e.ts
+++ b/cli/e2e/services.e2e.ts
@@ -358,12 +358,13 @@ describe('a failing service never takes the core down', () => {
}
})
- it('with the devices not starting, or the Devices tab failing, the dial, ⌘K and the tab say so and the core runs on', async () => {
+ it('with the devices not starting in the core\'s process, or the Devices tab failing, ⌘K and the tab say so and the core runs on', async () => {
+ // In their own process this is e2e/devicesProcess.e2e.ts's crash loop; here, the service host's guard.
for (const [faults, said] of [
['devices', '[services] devices did not start · injected fault: devices · the core runs without it'],
['devices.harness_devices_list', '[services] devices.harness_devices_list failed · injected fault: devices.harness_devices_list'],
]) {
- daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: faults } })
+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: faults, ...IN_THE_CORE } })
const d = daemon
onTestFailed(() => { console.log(`---- daemon log (${faults})\n${d.log().split('\n').slice(-80).join('\n')}`) })
await d.start()
diff --git a/cli/e2e/shell.e2e.ts b/cli/e2e/shell.e2e.ts
index 51c8cc517..ae75dbd4b 100644
--- a/cli/e2e/shell.e2e.ts
+++ b/cli/e2e/shell.e2e.ts
@@ -72,6 +72,10 @@ describe('opening connected shells', () => {
const d = w.machine.daemon
onTestFailed(() => console.log(d.log().split('\n').slice(-100).join('\n')))
const options = { backend: w.backend, machineId: w.machine.machineId, machinePub: w.machine.identity.pub, ...w.phone }
+ // The machine on the relay first, as a phone finds it: a hello sent before then reaches nobody, and the
+ // relay client here does not say it again (gatewayProcess.e2e.ts waits the same way). The services'
+ // processes start together, so the gateway's link can come up a moment after the core says it is ready.
+ await until('the machine to be on the relay', () => w.backend.nodeUp(w.machine.machineId) || null, 30_000)
const phone = new RelayPhone(options); clients.push(phone); await phone.open()
const witness = new RelayPhone(options); clients.push(witness); await witness.open()
const fixture = shell(d)
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index 8d3b96f7e..4a2faf9a8 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -148,9 +148,10 @@ const WALK_TIMEOUT_MS = 60_000
* name it worked out and the model lists it built moved to the models service, 1,457 → 1,391 lines.
*
* Lowered to 2,230 the same day (step 9, D1): the dial's host, its window bridges and the fleet left
- * runForeground for the devices' own service (services/devices.ts), 2,375 lines to 2,213.
+ * runForeground for the devices' own service (services/devices.ts), 2,375 lines to 2,213. Then 2,240 (step 9,
+ * D2): the devices' link to their own process and its routes, as every service there has, 2,213 to 2,232.
*/
-const RUN_FOREGROUND_BUDGET = 2_230
+const RUN_FOREGROUND_BUDGET = 2_240
/** Lowered from 2,180 when the relay and its E2EE left the socket for the gateway (step 10, R1: 1,440).
* The Wi-Fi device's relay came back to it in R2, beside the device service it answers for, over the
* gateway's sessions (lib/autonomous-device/overGateway.ts): 1,460. Models' grid commands, grid name and
@@ -255,7 +256,13 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {
// core/api.ts). runForeground lost their wiring and the pane writer lock came into the core
// (core/deviceInput.ts). D2 runs the devices in a process of their own, which takes them out: the dial,
// the window bridges, the fleet's router and lane, and the voice router, about 10,000 lines.
-const CORE_CLOSURE_BUDGET = 88_040
+//
+// Then at 77,669 in 358 (step 9, D2), from 87,941 in 389: the devices run in a process of their own
+// (services/devicesProcess.ts; the core's side is core/devicesLink.ts), and the core loads their code only
+// to run them in its process instead (services/inline.ts). With them went the dial (cable/), the window
+// bridges, the fleet's router and its lane to the owner's other machines, and the voice router with its
+// engine worker pool, and the E2EE code the fleet read the linked machines with (lib/e2ee/machinePeers.ts).
+const CORE_CLOSURE_BUDGET = 77_800
/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */
const EDGE: RegExp[] = [
@@ -280,32 +287,7 @@ const EDGE: RegExp[] = [
* can carry an install's progress back to it, or it leaves with the device (step 10). */
const STORE_BYPASS = 'step 10: the Wi-Fi device\'s own way into the Store, until it goes through the Store\'s process'
-/** The devices run behind their port in the core's process (step 9, D1): their own process takes them out
- * (D2), the dial, its window bridges and the fleet's router and lane with them. */
-const D2 = 'step 9, D2: the devices (the dial, the window bridges, the fleet), in a process of their own'
-
const CORE_MAY_REACH: Record<string, string> = {
- 'cable/cableFleet.ts': D2,
- 'cable/cableFrame.ts': D2,
- 'cable/cableHost.ts': D2,
- 'cable/cableSession.ts': D2,
- 'cable/companionProtocol.ts': D2,
- 'cable/dialLog.ts': D2,
- 'cable/dialPortVerdicts.ts': D2,
- 'cable/fwPush.ts': D2,
- 'cable/machineFleet.ts': D2,
- 'cable/notificationRead.ts': D2,
- 'cable/passageCarry.ts': D2,
- 'cable/questionInbox.ts': D2,
- 'cable/serial.ts': D2,
- 'cable/usbConsoleUser.ts': D2,
- 'cable/voiceDraft.ts': D2,
- 'cable/windowForm.ts': D2,
- 'cable/windowRoute.ts': D2,
- 'cable/windowSelection.ts': D2,
- 'cable/windowVisit.ts': D2,
- 'device/deviceFleet.ts': D2,
- 'device/deviceLink.ts': D2,
'device/machineList.ts': 'the account\'s machine list, which /api/machines answers from and the trust group reads: with the account proxies (step 10)',
'dsh/builtins.ts': 'the bundled harnesses are put in place by the core\'s start, which cli.js carries them for anyway; in the Store\'s lean process they cost a second copy (core/main.ts)',
'dsh/catalog.ts': STORE_BYPASS,
@@ -328,15 +310,9 @@ const CORE_MAY_REACH: Record<string, string> = {
'lib/autonomous-device/storeContract.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',
'lib/autonomous-device/storeRuntime.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',
'lib/autonomous-device/stream.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',
- 'lib/e2ee/core.ts': 'with lib/e2ee/machinePeers.ts (step 9)',
- 'lib/e2ee/machinePeers.ts': 'step 9: the fleet reads which machines are linked (their public keys, no credential), beside the dial',
'lib/sessionSearch/sessionTurns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads',
'lib/sessionSearch/transcript.ts': 'the readers of other engines\' sessions keep this helper: it moves beside them, out of search\'s folder',
'lib/sessionSearch/turns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads',
- 'services/devices.ts': D2,
- 'services/devicesGuard.ts': D2,
- 'services/fleet.ts': D2,
- 'services/fleetRouter.ts': D2,
'services/shell.ts': 'shell setup and launch receipts, in the edge host; only the argv launch stays in the core (#893)',
'sharing/viewer.ts': 'the windows\' interactive viewers capture with it (lib/interactiveViewer.ts): headless Chrome belongs with the viewers\' process (plan, "Sharing")',
}
diff --git a/cli/src/cable/__fixtures__/serialGone.py b/cli/src/cable/__fixtures__/serialGone.py
new file mode 100644
index 000000000..897f43f86
--- /dev/null
+++ b/cli/src/cable/__fixtures__/serialGone.py
@@ -0,0 +1,26 @@
+"""Drive an owned PTY whose far end goes away; never enumerate or open a real device.
+
+`gone`: the slave is held open here (as a daemon still holding its port would), the master closed, and then
+the worker opens the slave: it must refuse at once, not wait in open() for a master that is not coming.
+`early`: the master writes before the worker opens the slave, and then more: the worker gets both, in order.
+"""
+import os
+import pty
+import subprocess
+import sys
+import time
+
+node, worker, mode = sys.argv[1:]
+master, slave = pty.openpty()
+path = os.ttyname(slave)
+if mode == 'gone':
+ os.close(master)
+else:
+ os.write(master, b'before ')
+child = subprocess.Popen([node, worker, path, mode], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True)
+if mode == 'early':
+ time.sleep(0.15)
+ os.write(master, b'after')
+out, err = child.communicate(timeout=10)
+sys.stdout.write(out)
+sys.stderr.write(err)
diff --git a/cli/src/cable/__fixtures__/serialGone.ts b/cli/src/cable/__fixtures__/serialGone.ts
new file mode 100644
index 000000000..16c837d8c
--- /dev/null
+++ b/cli/src/cable/__fixtures__/serialGone.ts
@@ -0,0 +1,17 @@
+// Paired with serialGone.py: only that driver's disposable PTY is opened.
+import { SerialLink } from '../serial.js'
+
+const [path, mode] = process.argv.slice(2)
+const timeout = setTimeout(() => { console.log(JSON.stringify({ mode, hung: true })); process.exit(1) }, 5_000)
+const started = Date.now()
+try {
+ const received: Buffer[] = []
+ const link = await SerialLink.open(path, (chunk) => { received.push(chunk) }, () => {})
+ // What the dial sent before the port was opened arrives first, and nothing is lost after it.
+ await new Promise((resolve) => setTimeout(resolve, 300))
+ await link.close('done')
+ console.log(JSON.stringify({ mode, opened: true, received: Buffer.concat(received).toString('utf8') }))
+} catch (error) {
+ console.log(JSON.stringify({ mode, opened: false, code: (error as NodeJS.ErrnoException).code ?? null, ms: Date.now() - started }))
+}
+clearTimeout(timeout)
diff --git a/cli/src/cable/cableFleet.spec.ts b/cli/src/cable/cableFleet.spec.ts
index 58b4969fd..5f93c6ec6 100644
--- a/cli/src/cable/cableFleet.spec.ts
+++ b/cli/src/cable/cableFleet.spec.ts
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { describe, expect, it, vi } from 'vitest'
-import { CableFleet as SourceFleet, testDialDiscovery } from './cableFleet.js'
+import { CableFleet as SourceFleet, testDialDiscovery, type CableFleetOptions } from './cableFleet.js'
import { CableSession, type CableHost, type CablePort } from './cableSession.js'
import { CableDecoder, CableType, encodeCableFrame } from './cableFrame.js'
import { DialLog } from './dialLog.js'
@@ -26,10 +26,11 @@ class Peer implements CablePort {
}) }
async close(why = 'disconnected') { if (this.isOpen) { this.isOpen = false; this.onClosed(why) } }
say(message: Record<string, unknown>) { this.onData(Buffer.from(encodeCableFrame(CableType.Json, Buffer.from(JSON.stringify(message))))) }
+ raw(bytes: Buffer) { this.onData(bytes) }
pcm(value: number) { this.onData(Buffer.from(encodeCableFrame(CableType.Pcm, Buffer.alloc(3200, value)))) }
}
-function fixture() {
+function fixture(extra: Partial<CableFleetOptions> = {}, Log: typeof DialLog = DialLog) {
let present = [device('/dev/tim', 'AA:01'), device('/dev/tux', 'BB:02')]
const ports: Peer[] = []
const host: CableHost = {
@@ -50,12 +51,15 @@ function fixture() {
const logs = mkdtempSync(join(tmpdir(), 'usb-fleet-'))
const options = {
canUseUsb: vi.fn(() => true),
+ // Nobody else holds these ports. The default asks `lsof`, a process per port per scan, which on a
+ // loaded machine outlasts the second a test waits for both dials.
+ inUse: vi.fn(async () => false),
discover: vi.fn(async () => present), intervalMs: 60_000,
open: vi.fn(async (path: string, onData: (chunk: Buffer) => void, onClosed: (why: string) => void) => {
const port = new Peer(path, onData, onClosed); ports.push(port); return port
}),
}
- const fleet = new CableFleet(CableSession, host, logs, DialLog, options)
+ const fleet = new CableFleet(CableSession, host, logs, Log, { ...options, ...extra })
async function start() { fleet.start(); await vi.waitFor(() => expect(ports).toHaveLength(2)); await greet(ports) }
async function greet(peers: Peer[]) {
for (const p of peers) p.say({ t: 'hello', product: 'harness', mac: p.path, fw: 'fixture', proto: 3 })
@@ -71,6 +75,105 @@ describe('the end-to-end suite\'s dial', () => {
const { discover } = testDialDiscovery('/dev/ttys042')
expect(await discover!()).toEqual([{ path: '/dev/ttys042', vendorId: 0x303a, productId: 0x1001, serialNumber: 'E2E-DIAL' }])
})
+
+ it('are the pseudo-terminals a file lists, read at every scan, so a test can plug and unplug them', async () => {
+ let listed = '[{"path":"/dev/ttys001","serial":"E2E-1"},{"path":"/dev/ttys002","serial":"E2E-2"},{"path":7},null]'
+ const { discover } = testDialDiscovery('/tmp/dials.json', () => listed)
+ expect((await discover!()).map((port) => [port.path, port.serialNumber])).toEqual([['/dev/ttys001', 'E2E-1'], ['/dev/ttys002', 'E2E-2']])
+ listed = '{"not": "a list"}'
+ expect(await discover!()).toEqual([])
+ listed = 'half a file'
+ expect(await discover!()).toEqual([])
+ })
+})
+
+describe('one dial failing', () => {
+ it('is dropped alone after five faults, its port looked at again after a wait, while the other dial goes on', async () => {
+ const f = fixture({ faults: new Set(['dial.AA:01']), dropBackoffMs: 300 })
+ const scan = () => (f.fleet as unknown as { scan(): Promise<void> }).scan()
+ try {
+ f.fleet.start()
+ await vi.waitFor(() => expect(f.ports).toHaveLength(2))
+ const [faulty, healthy] = f.ports
+ await f.greet([healthy])
+ // Every greeting the faulty dial sends fails in its session, as its firmware greets on a cadence.
+ for (let i = 0; i < 5; i++) faulty.say({ t: 'hello', product: 'harness', mac: faulty.path, fw: 'fixture', proto: 3 })
+ await vi.waitFor(() => expect(faulty.isOpen).toBe(false))
+ expect(f.host.log).toHaveBeenCalledWith(expect.stringMatching(/cable: \/dev\/tim dropped \(5 faults in a minute: injected fault: dial\.AA:01\) — this dial alone; its port is looked at again in 0 s \[usb AA:01\]/))
+ // The other dial is untouched: still attached, still told the desk's work.
+ expect(healthy.isOpen).toBe(true)
+ healthy.sent.length = 0
+ await f.fleet.turnStarted('a', 'working')
+ await vi.waitFor(() => expect(healthy.sent.some((m) => m.t === 'turn.started')).toBe(true))
+ expect(f.fleet.isConnected).toBe(true)
+ // Not before its wait is over; then it is opened again.
+ await scan()
+ expect(f.ports).toHaveLength(2)
+ await new Promise((resolve) => setTimeout(resolve, 350))
+ await scan()
+ expect(f.ports).toHaveLength(3)
+ } finally { await f.fleet.stop() }
+ })
+
+ it('is dropped at once when it floods the port with what no dial sends, and waits longer each time it does again', async () => {
+ const f = fixture({ dropBackoffMs: 100 })
+ const scan = () => (f.fleet as unknown as { scan(): Promise<void> }).scan()
+ try {
+ await f.start()
+ const [flooding, healthy] = f.ports
+ flooding.raw(Buffer.alloc(70 * 1024, 0x41))
+ await vi.waitFor(() => expect(flooding.isOpen).toBe(false))
+ expect(f.host.log).toHaveBeenCalledWith(expect.stringMatching(/cable: flooded · 716\d\d B that are no frames in a second, more than a dial sends/))
+ expect(f.host.log).toHaveBeenCalledWith(expect.stringMatching(/\/dev\/tim dropped \(flooding the port: .*\) — this dial alone; its port is looked at again in 0 s/))
+ expect(healthy.isOpen).toBe(true)
+ await new Promise((resolve) => setTimeout(resolve, 150))
+ await scan()
+ expect(f.ports).toHaveLength(3)
+ // Again, soon after: the wait doubles.
+ f.ports[2].raw(Buffer.alloc(70 * 1024, 0x41))
+ await vi.waitFor(() => expect(f.host.log).toHaveBeenCalledWith(expect.stringMatching(/\/dev\/tim dropped .* looked at again in 0 s/)))
+ await vi.waitFor(() => expect(f.ports[2].isOpen).toBe(false))
+ await new Promise((resolve) => setTimeout(resolve, 120))
+ await scan()
+ expect(f.ports).toHaveLength(3)
+ await new Promise((resolve) => setTimeout(resolve, 150))
+ await scan()
+ expect(f.ports).toHaveLength(4)
+ } finally { await f.fleet.stop() }
+ })
+
+ it('is dropped for a flood of frames, or for frames that take the decoder too long', async () => {
+ const f = fixture({ dropBackoffMs: 60_000 })
+ try {
+ await f.start()
+ const [chatty, healthy] = f.ports
+ const ping = Buffer.from(encodeCableFrame(CableType.Json, Buffer.from('{"t":"pong"}')))
+ chatty.raw(Buffer.concat(Array.from({ length: 2_100 }, () => ping)))
+ await vi.waitFor(() => expect(chatty.isOpen).toBe(false))
+ expect(f.host.log).toHaveBeenCalledWith(expect.stringMatching(/\d{4} frames in a second, more than a dial sends/))
+ expect(healthy.isOpen).toBe(true)
+ const budget = CableSession.BUDGET.decodeMs
+ ;(CableSession.BUDGET as { decodeMs: number }).decodeMs = -1
+ try {
+ healthy.say({ t: 'pong' })
+ await vi.waitFor(() => expect(healthy.isOpen).toBe(false))
+ expect(f.host.log).toHaveBeenCalledWith(expect.stringMatching(/ms of decoding in a second/))
+ } finally { (CableSession.BUDGET as { decodeMs: number }).decodeMs = budget }
+ } finally { await f.fleet.stop() }
+ })
+
+ it('keeps its own fault when what it sends throws as it is read, and the process goes on', async () => {
+ class ThrowingLog extends DialLog { device(): void { throw new Error('the log could not be written') } }
+ const f = fixture({ dropBackoffMs: 60_000 }, ThrowingLog)
+ try {
+ await f.start()
+ const [noisy, quiet] = f.ports
+ for (let i = 0; i < 5; i++) noisy.raw(Buffer.from(encodeCableFrame(CableType.Log, Buffer.from('I (12) boot: line'))))
+ await vi.waitFor(() => expect(noisy.isOpen).toBe(false))
+ expect(f.host.log).toHaveBeenCalledWith(expect.stringContaining('cable: fault · the log could not be written'))
+ expect(quiet.isOpen).toBe(true)
+ } finally { await f.fleet.stop() }
+ })
})
describe('USB dial fleet', () => {
diff --git a/cli/src/cable/cableFleet.ts b/cli/src/cable/cableFleet.ts
index fde14bec1..b2ff34506 100644
--- a/cli/src/cable/cableFleet.ts
+++ b/cli/src/cable/cableFleet.ts
@@ -1,5 +1,6 @@
// One protocol session per USB dial, sharing the desktop's event source.
// Voice buffers, decoding, firmware transfers and disconnects remain per dial.
+import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { DialVerdicts } from './dialPortVerdicts.js'
import { findDialPorts, portInUse, SerialLink, type DialPort } from './serial.js'
@@ -9,7 +10,7 @@ import type { DialLog } from './dialLog.js'
type Surface = Pick<CableSession, keyof CableSession>
type SessionConstructor = new (host: CableHost, log: DialLog, open: PortOpener) => Surface
-type Entry = { port: DialPort; session: Surface; attached: boolean; status: DialStatus }
+type Entry = { port: DialPort; session: Surface; attached: boolean; status: DialStatus; faults: number[] }
type OpenPort = (path: string, onData: (chunk: Buffer) => void, onClosed: (why: string) => void) => Promise<CablePort>
export interface CableFleetOptions {
discover?: () => Promise<DialPort[]>
@@ -25,16 +26,40 @@ export interface CableFleetOptions {
canUseUsb?: () => boolean
/** How often a board ruled out is checked for another program working on it. */
watchEveryMs?: number
+ /** `HARNESSD_TEST_FAULTS`: `dial.<serial>` makes every call that dial's session makes into the desk throw,
+ * for the end-to-end suite's proof that one dial failing costs the others nothing. */
+ faults?: ReadonlySet<string>
+ /** The first wait before a dropped dial's port is looked at again (tests shorten it). */
+ dropBackoffMs?: number
}
+/** Faults within a minute that drop one dial; a hostile stream drops it at once. */
+const FAULTS_TO_DROP = 5
+/** How long a dropped dial's port is left alone before it is looked at again: from here, doubling to the
+ * most, and back to here once it has stayed up for `DROP_FORGIVEN_MS`. */
+const DROP_BACKOFF_MS = 5_000
+const DROP_BACKOFF_MAX_MS = 60_000
+const DROP_FORGIVEN_MS = 300_000
+
/**
- * Discovery for the end-to-end suite's dial, a pseudo-terminal (e2e/harness/fakeDial.ts) named by
- * `HARNESSD_TEST_DIAL_PORT`: it is not on the USB bus that discovery reads, and it is the only port then
- * looked at. Nothing otherwise: a real daemon finds its dials on USB.
+ * Discovery for the end-to-end suite's dials, pseudo-terminals (e2e/harness/fakeDial.ts) named by
+ * `HARNESSD_TEST_DIAL_PORT`: they are not on the USB bus that discovery reads, and they are the only ports
+ * then looked at. A path is one dial; a `.json` file lists several, `[{ path, serial }]`, read at every scan,
+ * so a test can plug and unplug them. Nothing otherwise: a real daemon finds its dials on USB.
*/
-export function testDialDiscovery(path: string | undefined): Pick<CableFleetOptions, 'discover'> {
+export function testDialDiscovery(path: string | undefined, read: (file: string) => string = (file) => readFileSync(file, 'utf8')): Pick<CableFleetOptions, 'discover'> {
if (!path) return {}
- return { discover: async () => [{ path, vendorId: 0x303a, productId: 0x1001, serialNumber: 'E2E-DIAL' }] }
+ const dial = (at: string, serialNumber: string): DialPort => ({ path: at, vendorId: 0x303a, productId: 0x1001, serialNumber })
+ if (!path.endsWith('.json')) return { discover: async () => [dial(path, 'E2E-DIAL')] }
+ return {
+ discover: async () => {
+ let listed: unknown
+ try { listed = JSON.parse(read(path)) } catch { return [] }
+ return (Array.isArray(listed) ? listed : [])
+ .filter((row): row is { path: string; serial: string } => typeof row?.path === 'string' && typeof row?.serial === 'string')
+ .map((row) => dial(row.path, row.serial))
+ },
+ }
}
export class CableFleet {
@@ -54,6 +79,8 @@ export class CableFleet {
/** For each board ruled out: when it was last checked for another program's use, and whether it was in use. */
private readonly watched = new Map<string, { at: number; wasBusy: boolean }>()
private readonly watchEveryMs: number
+ /** Dials dropped for their faults, by id: when their port is looked at again, and the wait after that. */
+ private readonly dropped = new Map<string, { until: number; backoffMs: number; at: number }>()
constructor(private readonly Session: SessionConstructor, private readonly host: CableHost,
private readonly logs: string, private readonly Log: typeof DialLog,
@@ -148,6 +175,8 @@ export class CableFleet {
if (this.stopped) return
for (const [id, port] of present) {
if (this.entries.has(id)) continue
+ // Dropped for its faults a moment ago: its port is left alone until its wait is over.
+ if ((this.dropped.get(id)?.until ?? 0) > Date.now()) continue
// A board somebody else has open is somebody's work in progress (a flash, a monitor, a console).
// Two readers on one tty interleave bytes, so it is not opened, and looked at again next scan.
if (await this.inUse(port.path)) {
@@ -157,7 +186,7 @@ export class CableFleet {
}
this.heldNotes.delete(port.path)
if (this.stopped) return
- const entry: Entry = { port, attached: false, status: { attached: false }, session: undefined! }
+ const entry: Entry = { port, attached: false, status: { attached: false }, session: undefined!, faults: [] }
const attached = () => {
if (entry.attached) return
const first = ![...this.entries.values()].some(e => e.attached)
@@ -195,8 +224,11 @@ export class CableFleet {
this.publish()
}
if (key === 'log') return (line: string) => this.host.log(`${line} [usb ${id}]`)
+ if (key === 'onFault') return (error: unknown, hostile?: boolean) => this.faulted(id, entry, error, hostile === true)
const value = Reflect.get(target, key, target)
- return typeof value === 'function' ? value.bind(target) : value
+ if (typeof value !== 'function') return value
+ if (this.options.faults?.has(`dial.${id}`)) return () => { throw new Error(`injected fault: dial.${id}`) }
+ return value.bind(target)
},
})
const opener: PortOpener = async (onData, onClosed) => {
@@ -214,6 +246,30 @@ export class CableFleet {
}
}
+ /**
+ * One dial's session failed, or its far end is flooding the port. The dial alone is dropped — its
+ * session stopped and its port let go — once it has failed five times in a minute, or at once for a
+ * flood, and its port is looked at again after a wait that doubles while it keeps failing. Every other
+ * dial goes on: a fault in one device is that device's, and the process they share must not end for it.
+ */
+ private faulted(id: string, entry: Entry, error: unknown, hostile: boolean): void {
+ const now = Date.now()
+ entry.faults = [...entry.faults.filter((at) => now - at < 60_000), now]
+ if (!hostile && entry.faults.length < FAULTS_TO_DROP) return
+ if (this.entries.get(id) !== entry) return
+ const last = this.dropped.get(id)
+ const first = this.options.dropBackoffMs ?? DROP_BACKOFF_MS
+ const backoffMs = !last || now - last.at > DROP_FORGIVEN_MS ? first : Math.min(last.backoffMs * 2, DROP_BACKOFF_MAX_MS)
+ this.dropped.set(id, { until: now + backoffMs, backoffMs, at: now })
+ this.host.log(`cable: ${entry.port.path} dropped (${hostile ? 'flooding the port' : `${entry.faults.length} faults in a minute`}: ${String(error instanceof Error ? error.message : error)}) — this dial alone; its port is looked at again in ${Math.round(backoffMs / 1000)} s [usb ${id}]`)
+ // Off this call stack: the session is in the middle of the call that failed, and stop() waits on it.
+ setTimeout(() => {
+ if (this.entries.get(id) !== entry) return
+ this.entries.delete(id)
+ void entry.session.stop().finally(() => this.publish())
+ }, 0)
+ }
+
/**
* One status out, carrying every device.
*
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index c9406bb38..718399169 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -16,7 +16,7 @@
// whenever the fleet cannot answer — off, or its call failed — as the dial did before the fleet was a
// service. Its tests give it a bare fleet to route over by itself.
import { join } from 'node:path'
-import { notificationReadToken, type UnreadNotification } from './notificationRead.js'
+import { notificationReadToken, type UnreadNotification } from '../lib/notificationRead.js'
import type { RegisteredSession } from '../lib/registry.js'
import { fetchRelease, loadImage, otaKeyForBoard, shouldOffer } from './fwPush.js'
@@ -52,7 +52,9 @@ export interface CableHostWiring {
/** Exact live terminal footer for a local agent; absent when no footer is visible. */
activityText?: (agentId: string) => Promise<string | null>
/** The person's own last questions to a LOCAL agent, newest first. */
- recentAsks: (agentId: string) => string[]
+ recentAsks: (agentId: string) => string[] | Promise<string[]>
+ /** Read the agents again before a list is built from them (see FleetLocal.refresh). */
+ refresh?: () => Promise<void>
machineName: () => string
/** This computer's machineId, or '' when the daemon has never resolved one (signed out). */
machineId: () => string
@@ -75,7 +77,7 @@ export interface CableHostWiring {
answer: (agentId: string, requestId: string, answers: Record<string, string>) => void
answerReviewed?: (answer: ReviewedAnswer) => Promise<boolean>
/** Recaps of an agent's last `n` completed turns — for routing, and for redrawing a reattached dial. */
- recent: (agentId: string, n: number) => RecentTurn[]
+ recent: (agentId: string, n: number) => RecentTurn[] | Promise<RecentTurn[]>
/** The opaque runtime-v1 profile, which is where the dial's Model/Effort chips come from. */
runtimeProfile?: (session: RegisteredSession) => string | null
updateAgent?: (agentId: string, model?: string, effort?: string) => void
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index de95fdd42..f6efca0e3 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -29,7 +29,7 @@ import { SerialLink, findDialPort } from './serial.js'
import { PassageCarry, withCarriedPassage, type CarryRead } from './passageCarry.js'
import { VoiceDraft, type DraftPin } from './voiceDraft.js'
import { QuestionInbox, type ReviewedAnswer, type AnswerReceipt, type QuestionSpeech } from './questionInbox.js'
-import { notificationReadToken, type UnreadNotification } from './notificationRead.js'
+import { notificationReadToken, type UnreadNotification } from '../lib/notificationRead.js'
/** Bumped when the VOCABULARY changes. Separate from the frame version, which is the envelope. */
export const CABLE_PROTO_VERSION = 3 // 3: + question.close (a question answered on another client)
@@ -344,6 +344,13 @@ export interface CableHost {
* Never called for a device that has been a dial.
*/
onForeignPort?(path: string, why: string): void
+ /**
+ * Something this session does threw, or the far end is flooding the port with what no dial sends. Told
+ * every time, so whoever owns the session can drop this dial alone, and look at its port again later,
+ * rather than let one device's fault reach every other one in the process. A dial is hardware speaking
+ * whatever its firmware says: a fault here is expected to happen, and to be this dial's alone.
+ */
+ onFault?(error: unknown, hostile?: boolean): void
/**
* The dial as a window would draw it: there or not, on which firmware, and whether an update is
* going over the cable right now. Fired on every change and never on a keepalive — the window
@@ -611,8 +618,8 @@ export class CableSession {
start(): void {
this.stopped = false
- this.timer = setInterval(() => void this.tick(), 1_000)
- void this.tick()
+ this.timer = setInterval(() => this.ticked(), 1_000)
+ this.ticked()
}
async stop(): Promise<void> {
@@ -623,6 +630,17 @@ export class CableSession {
this.link = null
}
+ /** One tick, its failure this dial's: a rejection left unhandled would end the whole devices process. */
+ private ticked(): void {
+ void this.tick().catch((error: unknown) => this.fault(error))
+ }
+
+ /** This dial's fault, told to whoever owns the session (CableHost.onFault). */
+ private fault(error: unknown, hostile = false): void {
+ this.log(`cable: ${hostile ? 'flooded' : 'fault'} · ${error instanceof Error ? error.message : String(error)}`)
+ this.host.onFault?.(error, hostile)
+ }
+
// ── port lifecycle ────────────────────────────────────────────────────────────────────────────────
private reportForeign(path: string, why: string): void {
@@ -840,10 +858,46 @@ export class CableSession {
// ── inbound ───────────────────────────────────────────────────────────────────────────────────────
+ /**
+ * What a dial may send in a second before it reads as hostile: a byte stream that is mostly not frames, a
+ * flood of frames, or bytes that take the decoder longer than it may spend. A dial sends a few dozen
+ * frames a second at most (voice is 16-bit PCM at 16 kHz, about 32 KB/s in frames of up to 8 KB), and its
+ * boot noise is a few hundred bytes; the decoder's worst case is a CRC over 8 KB for every eight bytes of
+ * a crafted stream, which at USB speed would hold the event loop for seconds at a time.
+ */
+ static readonly BUDGET = { garbageBytes: 64 * 1024, frames: 2_000, decodeMs: 500 }
+ private budget = { since: 0, garbage: 0, frames: 0, ms: 0 }
+
private onBytes(chunk: Buffer): void {
+ const started = performance.now()
+ const discarded = this.decoder.discardedBytes
+ let frames = 0
+ try {
+ this.decode(chunk, () => { frames++ })
+ } catch (error) {
+ // A throw inside the decoder's callback (the console log's write, the voice buffer) is this dial's
+ // fault: thrown out of the port's `data` event it would end the whole devices process.
+ this.fault(error)
+ }
+ const now = Date.now()
+ if (now - this.budget.since >= 1_000) this.budget = { since: now, garbage: 0, frames: 0, ms: 0 }
+ this.budget.garbage += this.decoder.discardedBytes - discarded
+ this.budget.frames += frames
+ this.budget.ms += performance.now() - started
+ const over = this.budget.garbage > CableSession.BUDGET.garbageBytes ? `${this.budget.garbage} B that are no frames`
+ : this.budget.frames > CableSession.BUDGET.frames ? `${this.budget.frames} frames`
+ : this.budget.ms > CableSession.BUDGET.decodeMs ? `${Math.round(this.budget.ms)} ms of decoding` : ''
+ if (over) {
+ this.budget = { since: now, garbage: 0, frames: 0, ms: 0 }
+ this.fault(new Error(`${over} in a second, more than a dial sends`), true)
+ }
+ }
+
+ private decode(chunk: Buffer, counted: () => void): void {
this.lastRx = Date.now()
this.bytesSinceOpen += chunk.length
this.decoder.feed(chunk, (frame) => {
+ counted()
this.framesSinceOpen += 1
if (frame.type === CableType.Json) {
let msg: Message
@@ -852,7 +906,8 @@ export class CableSession {
} catch {
return // unreadable payloads are counted by the decoder, never fatal
}
- void this.onMessage(msg)
+ // Its failure is this dial's: a rejection left unhandled would end the whole devices process.
+ void this.onMessage(msg).catch((error: unknown) => this.fault(error))
return
}
if (frame.type === CableType.Log) {
diff --git a/cli/src/cable/serial.real.spec.ts b/cli/src/cable/serial.real.spec.ts
index aca5aa9f6..c05d57dc7 100644
--- a/cli/src/cable/serial.real.spec.ts
+++ b/cli/src/cable/serial.real.spec.ts
@@ -68,3 +68,21 @@ it.skipIf(!hasPty).each(['duplex', 'disconnect', 'close'])(
}
}, 15_000,
)
+
+it.skipIf(!hasPty).each(['gone', 'early'])('opens a port whose far end is %s without waiting in open()', async (mode) => {
+ const scratch = await mkdtemp(join(tmpdir(), 'serial-gone-'))
+ try {
+ const worker = join(scratch, 'serial-gone.mjs')
+ await build({
+ entryPoints: [fileURLToPath(new URL('./__fixtures__/serialGone.ts', import.meta.url))],
+ outfile: worker, bundle: true, platform: 'node', format: 'esm', target: 'node20',
+ })
+ const driver = fileURLToPath(new URL('./__fixtures__/serialGone.py', import.meta.url))
+ const { stdout } = await promisify(execFile)('python3', [driver, process.execPath, worker, mode], { timeout: 12_000 })
+ const result = JSON.parse(stdout)
+ if (mode === 'gone') expect(result).toMatchObject({ mode, opened: false })
+ else expect(result).toEqual({ mode, opened: true, received: 'before after' })
+ } finally {
+ await rm(scratch, { recursive: true, force: true })
+ }
+}, 15_000)
diff --git a/cli/src/cable/serial.spec.ts b/cli/src/cable/serial.spec.ts
index 27fd30d2a..7421928ee 100644
--- a/cli/src/cable/serial.spec.ts
+++ b/cli/src/cable/serial.spec.ts
@@ -2,8 +2,8 @@ import { EventEmitter } from 'node:events'
import { constants } from 'node:fs'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-const io = vi.hoisted(() => ({ open: vi.fn(), close: vi.fn(), configure: vi.fn(), stream: vi.fn(), readdir: vi.fn(), lstat: vi.fn() }))
-vi.mock('node:fs', async (original) => ({ ...await original<typeof import('node:fs')>(), openSync: io.open, closeSync: io.close, readdirSync: io.readdir, lstatSync: io.lstat }))
+const io = vi.hoisted(() => ({ open: vi.fn(), close: vi.fn(), configure: vi.fn(), stream: vi.fn(), readdir: vi.fn(), lstat: vi.fn(), read: vi.fn() }))
+vi.mock('node:fs', async (original) => ({ ...await original<typeof import('node:fs')>(), openSync: io.open, closeSync: io.close, readdirSync: io.readdir, lstatSync: io.lstat, readSync: io.read }))
vi.mock('node:tty', () => ({ ReadStream: io.stream }))
vi.mock('node:child_process', () => ({ execFile: io.configure }))
@@ -15,6 +15,7 @@ function port(nativeFd = 43) {
destroyed: false,
write: vi.fn((_bytes: Uint8Array, done: (error?: Error) => void) => { queueMicrotask(() => done()); return true }),
destroy: vi.fn(() => { queueMicrotask(() => stream.emit('close')); return stream }),
+ unshift: vi.fn(),
})
io.stream.mockImplementation(function () { return stream })
return stream
@@ -28,9 +29,31 @@ describe('event-driven serial link', () => {
io.open.mockReturnValue(42)
if (claimsPort) io.open.mockReturnValueOnce(41)
io.configure.mockImplementation((_cmd, _args, callback) => callback(null, '', ''))
+ // The far end is there and has said nothing yet.
+ io.read.mockImplementation(() => { throw Object.assign(new Error('EAGAIN'), { code: 'EAGAIN' }) })
})
afterEach(() => { vi.useRealTimers(); vi.resetAllMocks() })
+ it('refuses a port whose far end is gone before the stream reopens it, which would wait for it forever', async () => {
+ port()
+ io.read.mockReturnValueOnce(0)
+ await expect(SerialLink.open('/dev/fake', vi.fn(), vi.fn())).rejects.toMatchObject({ code: 'EOF' })
+ expect(io.stream).not.toHaveBeenCalled()
+ expect(io.close).toHaveBeenCalledWith(42)
+ io.open.mockReturnValue(42)
+ if (claimsPort) io.open.mockReturnValueOnce(41)
+ io.read.mockImplementationOnce(() => { throw Object.assign(new Error('EIO'), { code: 'EIO' }) })
+ await expect(SerialLink.open('/dev/fake', vi.fn(), vi.fn())).rejects.toMatchObject({ code: 'EIO' })
+ expect(io.stream).not.toHaveBeenCalled()
+ })
+
+ it('hands the stream what the dial said before the port opened, ahead of the rest', async () => {
+ const stream = port()
+ io.read.mockImplementationOnce((_fd: number, buffer: Buffer) => buffer.write('hello', 0))
+ await SerialLink.open('/dev/fake', vi.fn(), vi.fn())
+ expect(stream.unshift).toHaveBeenCalledWith(Buffer.from('hello'))
+ })
+
it('stays idle without a timer, preserves raw bytes, and closes the duplicate descriptor', async () => {
const stream = port(), received = vi.fn(), closed = vi.fn()
const link = await SerialLink.open('/dev/fake', received, closed)
diff --git a/cli/src/cable/serial.ts b/cli/src/cable/serial.ts
index 236170891..21cd69922 100644
--- a/cli/src/cable/serial.ts
+++ b/cli/src/cable/serial.ts
@@ -5,7 +5,7 @@
// a per-platform release matrix into a distribution that is currently a download. A tty is a file, `stty`
// puts it in raw mode, and that is the whole of what this needs.
import { execFile } from 'node:child_process'
-import { closeSync, constants, existsSync, lstatSync, openSync, readFileSync, readdirSync } from 'node:fs'
+import { closeSync, constants, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync } from 'node:fs'
import { basename } from 'node:path'
import { ReadStream } from 'node:tty'
import { promisify } from 'node:util'
@@ -281,9 +281,27 @@ export class SerialLink {
// uses libuv readiness instead, including short writes/backpressure, without a polling timer.
// ReadStream is a net.Socket; opening O_RDWR and enabling both sides makes it full duplex.
const fd = openSync(path, constants.O_RDWR | constants.O_NOCTTY | constants.O_NONBLOCK)
+ // THE FAR END MUST STILL BE THERE, OR THE NEXT LINE NEVER RETURNS. libuv reopens a tty by its name
+ // with a plain, blocking open() (uv_tty_init), and a terminal whose other end has closed blocks such an
+ // open until something opens that end again: measured 2026-10-06, a fake dial on a pseudo-terminal
+ // unplugged while its port was being opened (during `stty` above) held the devices' process in that
+ // open for 40 s, until the master killed it as hung, and the other dial with it. A dial on USB is a
+ // callout device (cu.*) that does not wait, but nothing here should rest on that. So one read first,
+ // without waiting: it ends (0) or fails, other than with "nothing yet", when the far end is gone, and
+ // what it read is the dial's and is handed to the stream ahead of the rest.
+ let early: Buffer | null = null
+ try {
+ const probe = Buffer.alloc(4096)
+ const read = readSync(fd, probe, 0, probe.length, null)
+ if (read === 0) throw Object.assign(new Error('the port has no far end'), { code: 'EOF' })
+ early = probe.subarray(0, read)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EAGAIN') { closeSync(fd); throw error }
+ }
let stream: ReadStream
try { stream = new ReadStream(fd, { readable: true, writable: true }) }
catch (error) { closeSync(fd); throw error }
+ if (early) stream.unshift(early)
// On POSIX libuv normally reopens the tty and owns a duplicate. On its fallback path it owns
// the supplied fd itself. Check the native handle exactly once so neither path leaks a
// descriptor or closes it twice. The managed Node runtime's real-PTY tests cover ownership.
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index 1e6d36acb..194385230 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -54,4 +54,6 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
`gatewayLink.ts`: the relay and its E2EE in their own process (src/gateway/), as the core sees them:
the link's state and the remote clients it reads in line, the frames it hands over in the clear, a
window's sessions to another machine or a shared harness, and the fleet's lane's sealing
- (`core.account.lane`).
+ (`core.account.lane`). `devicesLink.ts`: the devices in their own process (the dials, the window
+ bridges, the fleet): what the core tells them, what it asks with a deadline and a fallback, and what it
+ answers them.
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index c5a08956a..b456b454c 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -65,7 +65,7 @@ describe('the core API services stand on', () => {
daemon: { command: 'harness', port: 18473, machineId: () => 'machine-1', autonomousEnv: 'prod' },
observerKey: OBSERVER_KEY_OFF,
observer: vi.fn(() => true),
- turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(() => []), asks: vi.fn(() => []), deliver: vi.fn(), cancelDelivery: vi.fn(() => true), onDelivery: vi.fn(() => () => {}) },
+ turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(async () => []), asks: vi.fn(async () => []), deliver: vi.fn(), cancelDelivery: vi.fn(() => true), onDelivery: vi.fn(() => () => {}) },
questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => true) },
machine: { id: vi.fn(() => 'machine-1'), computerId: vi.fn(() => 'computer-1'), name: vi.fn(() => 'Studio') },
activityText: vi.fn(async () => 'Reading 3 files'),
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index d8a9ecf06..ccc527e60 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -14,7 +14,7 @@ import type { RecentTurn } from '../cable/cableHost.js'
import type { ReviewedAnswer } from '../cable/questionInbox.js'
import type { AgentEngine } from '../engines/types.js'
import type { AppSwarms } from '../cable/cableSession.js'
-import type { UnreadNotification } from '../cable/notificationRead.js'
+import type { UnreadNotification } from '../lib/notificationRead.js'
import type { AgentDshContext } from '../lib/agentFrame.js'
import type { GridAccess } from '../lib/gridAttach.js'
import type { createHarnessResourcesReader } from '../lib/harnessResources.js'
@@ -123,10 +123,11 @@ export interface CoreApi {
send(agentId: string, text: string): void
/** Stop a live agent's turn. */
stop(agentId: string): void
- /** A live agent's last `n` completed turns, newest first. */
- recent(agentId: string, n: number): RecentTurn[]
+ /** A live agent's last `n` completed turns, newest first. A promise, so that the devices in their own
+ * process ask it of the core when they need it. */
+ recent(agentId: string, n: number): Promise<RecentTurn[]>
/** The person's own last questions to a live agent, newest first. */
- asks(agentId: string): string[]
+ asks(agentId: string): Promise<string[]>
/** Deliver text into a live agent under a delivery id of the caller's own, as the Wi-Fi device, a team
* and the orchestrator deliver their turns: one path for the three. What becomes of it is heard through
* `onDelivery`, under the same id. */
diff --git a/cli/src/core/devicesLink.spec.ts b/cli/src/core/devicesLink.spec.ts
new file mode 100644
index 000000000..ae5e46574
--- /dev/null
+++ b/cli/src/core/devicesLink.spec.ts
@@ -0,0 +1,202 @@
+// The devices in their own process, as the core sees them (core/devicesLink.ts): what it tells them, what it
+// asks and what it does when they do not answer, and what it answers them.
+import { describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../lib/registry.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { createDevicesLink, DEVICES_WAIT_MS, ROUTE_TASK_WAIT_MS, type DevicesState } from './devicesLink.js'
+
+const STATE: DevicesState = {
+ desk: ['a1'], foreground: true, swarms: null, unread: [], focus: { voice: null, form: null }, engines: ['claude'], commanders: false,
+}
+
+function link(answer: Record<string, unknown> = {}) {
+ const core = fakeCore()
+ const sent: Array<{ type: string; payload?: Record<string, unknown> }> = []
+ const call = vi.fn(async (_type: string, _payload: Record<string, unknown>, _waitMs: number) => answer)
+ const log = vi.fn()
+ const devices = createDevicesLink({ core, notify: (frame) => { sent.push(frame); return true }, call, state: () => STATE, log })
+ return { core, sent, call, log, devices, port: devices.port }
+}
+
+describe('what the core tells the devices', () => {
+ it('is a notice for each, by kind, carrying what the windows said', () => {
+ const { sent, port } = link()
+ port.card({ type: 'commander_event', agentId: 'a1' })
+ port.desk(['a1'], false)
+ port.swarms(null)
+ port.unread([])
+ port.appFocus('m1', 'a1')
+ port.seen('a1')
+ port.seen('a1', 'tok')
+ port.settings('usb', { brightness: 3 })
+ port.windowFocus({ voice: null, form: null })
+ port.windowReply('form', 'w1', 'm1', { ok: true })
+ port.voiceReply('v1', { t: 'taken' })
+ port.windowGone('w1')
+ port.scroll('move', 2, 9)
+ port.engines(['codex'])
+ port.commanders(true)
+ expect(sent.map((frame) => frame.payload)).toEqual([
+ { kind: 'card', frame: { type: 'commander_event', agentId: 'a1' } },
+ { kind: 'desk', agentIds: ['a1'], foreground: false },
+ { kind: 'swarms', swarms: null },
+ { kind: 'unread', items: [] },
+ { kind: 'appFocus', machineId: 'm1', agentId: 'a1' },
+ { kind: 'seen', agentId: 'a1' },
+ { kind: 'seen', agentId: 'a1', readToken: 'tok' },
+ { kind: 'settings', id: 'usb', patch: { brightness: 3 } },
+ { kind: 'windowFocus', focus: { voice: null, form: null } },
+ { kind: 'windowReply', which: 'form', connId: 'w1', machineId: 'm1', reply: { ok: true } },
+ { kind: 'voiceReply', voiceId: 'v1', reply: { t: 'taken' } },
+ { kind: 'windowGone', connId: 'w1' },
+ { kind: 'scroll', phase: 'move', dy: 2, velocity: 9 },
+ { kind: 'engines', engines: ['codex'] },
+ { kind: 'commanders', connected: true },
+ ])
+ expect(sent.every((frame) => frame.type === 'service_event')).toBe(true)
+ })
+
+ it('tells devices started in the core\'s own process the same, as calls on their port', () => {
+ const { devices, sent } = link()
+ const started = { desk: vi.fn(), swarms: vi.fn(), unread: vi.fn(), windowFocus: vi.fn(), engines: vi.fn(), commanders: vi.fn() }
+ devices.started(started as never)
+ expect(started.desk).toHaveBeenCalledWith(['a1'], true)
+ expect(started.swarms).toHaveBeenCalledWith(null)
+ expect(started.unread).toHaveBeenCalledWith([])
+ expect(started.windowFocus).toHaveBeenCalledWith({ voice: null, form: null })
+ expect(started.engines).toHaveBeenCalledWith(['claude'])
+ expect(started.commanders).toHaveBeenCalledWith(false)
+ expect(sent).toEqual([])
+ })
+
+ it('says everything again when they connect, and nothing to stop: the master stops their process', async () => {
+ const { sent, devices, port } = link()
+ devices.connected()
+ expect(sent).toEqual([{ type: 'service_event', payload: { ...STATE, kind: 'state' } }])
+ await expect(port.stop()).resolves.toBeUndefined()
+ })
+})
+
+describe('what the core asks of the devices', () => {
+ it('asks ⌘K and the Wi-Fi device\'s step under their own types, with deadlines', async () => {
+ const answer = { agentId: 'a1', machineId: 'm1', name: 'api', confidence: 1, reason: 'r', candidates: [], weighed: 1, machines: 1, via: 'model' }
+ const { call, port } = link(answer)
+ expect(await port.routeTask('fix it')).toEqual(answer)
+ expect(call).toHaveBeenLastCalledWith('routeTask', { text: 'fix it' }, ROUTE_TASK_WAIT_MS)
+ call.mockResolvedValueOnce({ ok: false, machine: 'mac-mini', reason: 'gone' })
+ expect(await port.routeSend('a1', 'go')).toEqual({ ok: false, machine: 'mac-mini', reason: 'gone' })
+ expect(call).toHaveBeenLastCalledWith('routeSend', { agentId: 'a1', text: 'go' }, DEVICES_WAIT_MS)
+ call.mockResolvedValueOnce({ machineId: 'm1', agentId: 'a2' })
+ expect(await port.stepFocus('next', 'a1')).toEqual({ machineId: 'm1', agentId: 'a2' })
+ expect(call).toHaveBeenLastCalledWith('stepFocus', { direction: 'next', currentAgentId: 'a1' }, DEVICES_WAIT_MS)
+ call.mockResolvedValueOnce({ step: 'no_agents' })
+ expect(await port.stepFocus('previous')).toBe('no_agents')
+ expect(call).toHaveBeenLastCalledWith('stepFocus', { direction: 'previous' }, DEVICES_WAIT_MS)
+ call.mockResolvedValueOnce({ machineId: 7 })
+ expect(await port.stepFocus('next')).toEqual({ machineId: '', agentId: '' })
+ })
+
+ it('answers with the port\'s fallbacks when they are down, slow or failing: ⌘K says so, the walk finds no desk', async () => {
+ const { port } = link({ error: 'SERVICE_UNAVAILABLE', service: 'devices', retryable: true })
+ expect(await port.routeTask('fix it')).toMatchObject({ agentId: '', reason: 'the devices service is unavailable', candidates: [] })
+ expect(await port.routeSend('a1', 'go')).toEqual({ ok: false, machine: '', reason: 'the devices service is unavailable' })
+ expect(await port.stepFocus('next')).toBe('no_agents')
+ })
+})
+
+describe('what the devices ask of the core', () => {
+ it('is this computer\'s agents as the dial lists them, with what the dial reads in line', async () => {
+ const agent = { agentId: 'a1', engine: 'claude' } as RegisteredSession
+ const { core, devices } = link()
+ vi.mocked(core.agents.advertised).mockReturnValue([agent])
+ vi.mocked(core.agents.displayName).mockReturnValue('api')
+ vi.mocked(core.agents.runtimeProfile).mockReturnValue('runtime-v1:s:claude:opus@high')
+ expect(await devices.answer('view', {})).toEqual({
+ agents: [{ ...agent, displayName: 'api', runtimeProfile: 'runtime-v1:s:claude:opus@high' }],
+ machine: { id: 'machine-1', computerId: 'computer-1', name: 'This machine' },
+ signedIn: true, environment: 'prod', hasWindow: true,
+ })
+ })
+
+ it('is the core\'s own doors and the sign-in, asked when they need them', async () => {
+ const { core, devices } = link()
+ vi.mocked(core.agents.activityText).mockResolvedValue('Reading')
+ vi.mocked(core.turns.recent).mockResolvedValue([{ recap: 'done' }])
+ vi.mocked(core.turns.asks).mockResolvedValue(['why?'])
+ vi.mocked(core.questions.answerReviewed).mockResolvedValue(true)
+ vi.mocked(core.agents.runtimeModels).mockResolvedValue([{ id: 'opus' } as never])
+ vi.mocked(core.agents.fork).mockResolvedValue({ ok: true, agentId: 'a2' })
+ expect(await devices.answer('activityText', { agentId: 'a1' })).toEqual({ text: 'Reading' })
+ expect(await devices.answer('recent', { agentId: 'a1', n: 2 })).toEqual({ turns: [{ recap: 'done' }] })
+ expect(core.turns.recent).toHaveBeenLastCalledWith('a1', 2)
+ await devices.answer('recent', { agentId: 7 })
+ expect(core.turns.recent).toHaveBeenLastCalledWith('', 3)
+ expect(await devices.answer('asks', { agentId: 'a1' })).toEqual({ asks: ['why?'] })
+ expect(await devices.answer('answerReviewed', { answer: { agentId: 'a1' } })).toEqual({ ok: true })
+ expect(await devices.answer('models', { agentId: 'a1' })).toEqual({ models: [{ id: 'opus' }] })
+ expect(await devices.answer('fork', { agentId: 'a1' })).toEqual({ ok: true, agentId: 'a2' })
+ // The account, as every service in its own process asks it (core/accountQueries.ts).
+ expect(await devices.answer('access_token', {})).toEqual({ token: 'token' })
+ expect(await devices.answer('access_token', { force: true, failedToken: 'old' })).toEqual({ token: 'token' })
+ expect(core.account.accessToken).toHaveBeenLastCalledWith({ force: true, failedToken: 'old' })
+ expect(await devices.answer('lane', { op: 'seal', machineId: 'm2', frame: { type: 'message' } })).toEqual({ frame: { type: 'message' } })
+ expect(core.account.lane.seal).toHaveBeenCalledWith('m2', { type: 'message' })
+ expect(await devices.answer('machines', {})).toEqual({ status: 200, body: { success: true, data: { machines: [] } } })
+ expect(await devices.answer('nothing', {})).toEqual({ error: 'UNKNOWN_QUERY' })
+ expect(await devices.answer('constructor', {})).toEqual({ error: 'UNKNOWN_QUERY' })
+ })
+})
+
+describe('what the devices tell the core', () => {
+ it('is a turn, a stop, an answer, a model, the windows\' frames and the device status', () => {
+ const { core, devices } = link()
+ devices.notice({ kind: 'turn', agentId: 'a1', text: 'hello' })
+ devices.notice({ kind: 'stop', agentId: 'a1' })
+ devices.notice({ kind: 'answer', agentId: 'a1', requestId: 'r1', answers: { q: 'Coffee' } })
+ devices.notice({ kind: 'answer', agentId: 'a1', requestId: 'r1', answers: 'nonsense' })
+ devices.notice({ kind: 'setRuntime', agentId: 'a1', model: 'opus', effort: 'high' })
+ devices.notice({ kind: 'setRuntime', agentId: 'a1' })
+ devices.notice({ kind: 'sendLocal', frame: { type: 'dial_focus', payload: { agentId: 'a1' } } })
+ devices.notice({ kind: 'sendLocal', frame: 'not a frame' })
+ devices.notice({ kind: 'sendLocal', frame: { type: 'dial_focus' } })
+ devices.notice({ kind: 'sendToWindow', connId: 'w1', frame: { type: 'dial_form', payload: {} } })
+ devices.notice({ kind: 'sendToWindow', connId: 'w1', frame: null })
+ devices.notice({ kind: 'devicesChanged', status: { attached: true }, revision: 2 })
+ expect(core.turns.send).toHaveBeenCalledWith('a1', 'hello')
+ expect(core.turns.stop).toHaveBeenCalledWith('a1')
+ expect(vi.mocked(core.questions.answer).mock.calls).toEqual([['a1', 'r1', { q: 'Coffee' }], ['a1', 'r1', {}]])
+ expect(vi.mocked(core.agents.setRuntime).mock.calls).toEqual([['a1', 'opus', 'high'], ['a1', undefined, undefined]])
+ expect(vi.mocked(core.clients.sendLocal).mock.calls).toEqual([[{ type: 'dial_focus', payload: { agentId: 'a1' } }]])
+ expect(vi.mocked(core.clients.sendToWindow).mock.calls).toEqual([['w1', { type: 'dial_form', payload: {} }]])
+ expect(core.clients.devicesChanged).toHaveBeenCalledWith({ status: { attached: true }, revision: 2 })
+ })
+
+ it('is a dial on the wire, and none once their process is gone', () => {
+ const { core, devices } = link()
+ // Gone with no dial on the wire: nothing to take back.
+ devices.disconnected()
+ expect(core.clients.dialWatching).not.toHaveBeenCalled()
+ devices.notice({ kind: 'dialWatching', watching: true })
+ expect(core.clients.dialWatching).toHaveBeenLastCalledWith(true)
+ devices.disconnected()
+ expect(core.clients.dialWatching).toHaveBeenLastCalledWith(false)
+ devices.notice({ kind: 'dialWatching', watching: 'yes' })
+ expect(core.clients.dialWatching).toHaveBeenLastCalledWith(false)
+ })
+
+ it('logs what it does not hear, by kind, and to the console by default', () => {
+ const { devices, log } = link()
+ devices.notice({ kind: 'shout' })
+ devices.notice({})
+ devices.notice({ kind: 'hasOwnProperty' })
+ expect(log.mock.calls).toEqual([
+ ['[services] devices said shout, which the core does not hear'],
+ ['[services] devices said nothing, which the core does not hear'],
+ ['[services] devices said hasOwnProperty, which the core does not hear'],
+ ])
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ createDevicesLink({ core: fakeCore(), notify: () => true, call: async () => ({}), state: () => STATE }).notice({ kind: 'shout' })
+ expect(warn).toHaveBeenCalledWith('[services] devices said shout, which the core does not hear')
+ warn.mockRestore()
+ })
+})
diff --git a/cli/src/core/devicesLink.ts b/cli/src/core/devicesLink.ts
new file mode 100644
index 000000000..4a4f6e9b5
--- /dev/null
+++ b/cli/src/core/devicesLink.ts
@@ -0,0 +1,172 @@
+/**
+ * The devices in a process of their own (services/devicesProcess.ts), as the core sees them: the port the
+ * core calls (`DevicesPort`) and what the core answers when the devices ask (docs/design/2026-10-06-core-
+ * boundary-next.md, step 9, D2).
+ *
+ * The core never waits on them. What it tells them (a card, the desk, a window's answer) is a notice on
+ * their link, dropped while they are down, since the core keeps the state they need and says it again
+ * when they connect. What it asks of them (⌘K, the Wi-Fi device's step along the desk) is a request on
+ * the link with a deadline and an answer for when they do not give one: a hung devices process costs ⌘K
+ * its answer, never a window's typing or an agent's turn.
+ *
+ * What they ask of the core is the core's API, as a service in the core's process would call it: this
+ * computer's agents as the dial lists them (asked as the dial's tick or ⌘K needs them, and with them this
+ * computer, the sign-in and whether a window is there), a turn, a stop, an answer, a pane's activity line,
+ * a token for the transcriber and the fleet's lane, the lane's sealing (the gateway's), the machine list,
+ * and the frames for the windows.
+ * The one-way ones come as notices, the rest as queries.
+ */
+import type { AppSwarms } from '../cable/cableSession.js'
+import type { UnreadNotification } from '../lib/notificationRead.js'
+import type { ReviewedAnswer } from '../cable/questionInbox.js'
+import { DEVICES_FALLBACKS, readFallback, type CoreApi, type DeviceBridgeFrame, type DevicesPort, type DeviceWindowFrame, type RouteAnswer, type SendResult, type WindowFocus } from './api.js'
+import { answerAccountQuery } from './accountQueries.js'
+import type { ServiceFrame } from './serviceLinks.js'
+
+/** What the core keeps for the devices, and says again whenever they connect. */
+export interface DevicesState {
+ desk: string[]
+ foreground: boolean
+ swarms: AppSwarms | null
+ unread: UnreadNotification[]
+ focus: WindowFocus
+ engines: string[]
+ commanders: boolean
+}
+
+export interface DevicesLinkDeps {
+ core: CoreApi
+ /** A notice for the devices' process; false when it is not connected to hear it. */
+ notify(frame: ServiceFrame): boolean
+ /** A request to the devices' process, answered SERVICE_UNAVAILABLE when it is down or slow. */
+ call(type: string, payload: Record<string, unknown>, waitMs: number): Promise<Record<string, unknown>>
+ /** What the windows last said: the desk, the tabs, what is unread, which window has the person's
+ * attention; and the engines here and whether a device watches through the backend. */
+ state(): DevicesState
+ log?: (line: string) => void
+}
+
+/** How long ⌘K waits for the devices to pick an agent: the classifier has 20 s (services/fleet.ts). */
+export const ROUTE_TASK_WAIT_MS = 25_000
+/** How long anything else waits for them: a send, a step along the desk. */
+export const DEVICES_WAIT_MS = 5_000
+
+const fallback = <T>(member: keyof typeof DEVICES_FALLBACKS): T => readFallback(DEVICES_FALLBACKS[member]).value as T
+const text = (value: unknown): string => (typeof value === 'string' ? value : '')
+const isFrame = (value: unknown): value is { type: string; payload: Record<string, unknown> } =>
+ !!value && typeof value === 'object' && typeof (value as { type?: unknown }).type === 'string'
+ && !!(value as { payload?: unknown }).payload && typeof (value as { payload?: unknown }).payload === 'object'
+
+export function createDevicesLink(deps: DevicesLinkDeps) {
+ const { core } = deps
+ const log = deps.log ?? ((line: string) => console.warn(line))
+ const event = (kind: string, payload: Record<string, unknown> = {}): void => { deps.notify({ type: 'service_event', payload: { ...payload, kind } }) }
+ /** An answer from the devices, or the port's fallback when there was none (down, slow, or failed). */
+ const answered = <T>(answer: Record<string, unknown>, member: keyof typeof DEVICES_FALLBACKS, read: (answer: Record<string, unknown>) => T): T =>
+ typeof answer.error === 'string' ? fallback<T>(member) : read(answer)
+ let dialWatching = false
+
+ const port: DevicesPort = {
+ card: (frame) => event('card', { frame }),
+ desk: (agentIds, foreground) => event('desk', { agentIds, foreground }),
+ swarms: (swarms) => event('swarms', { swarms }),
+ unread: (items) => event('unread', { items }),
+ appFocus: (machineId, agentId) => event('appFocus', { machineId, agentId }),
+ seen: (agentId, readToken) => event('seen', { agentId, ...(readToken === undefined ? {} : { readToken }) }),
+ settings: (id, patch) => event('settings', { id, patch }),
+ windowFocus: (focus) => event('windowFocus', { focus }),
+ windowReply: (which, connId, machineId, reply) => event('windowReply', { which, connId, machineId, reply }),
+ voiceReply: (voiceId, reply) => event('voiceReply', { voiceId, reply }),
+ windowGone: (connId) => event('windowGone', { connId }),
+ routeTask: async (task) => answered(await deps.call('routeTask', { text: task }, ROUTE_TASK_WAIT_MS), 'routeTask', (answer) => answer as unknown as RouteAnswer),
+ routeSend: async (agentId, task) => answered(await deps.call('routeSend', { agentId, text: task }, DEVICES_WAIT_MS), 'routeSend',
+ (answer) => answer as unknown as SendResult),
+ stepFocus: async (direction, currentAgentId) => answered(await deps.call('stepFocus', { direction, ...(currentAgentId ? { currentAgentId } : {}) }, DEVICES_WAIT_MS),
+ 'stepFocus', (answer) => (answer.step === 'no_agents' ? 'no_agents' : { machineId: text(answer.machineId), agentId: text(answer.agentId) })),
+ scroll: (phase, dy, velocity) => event('scroll', { phase, dy, velocity }),
+ engines: (engines) => event('engines', { engines }),
+ commanders: (connected) => event('commanders', { connected }),
+ // Their own process: the master stops it, and a core that restarts leaves it running with the dial.
+ stop: async () => {},
+ }
+
+ /** A dial on the wire, or none any more, as the devices said last: the core makes the cards for it. */
+ const watching = (on: boolean): void => {
+ dialWatching = on
+ core.clients.dialWatching(on)
+ }
+
+ /** What the devices may ask of the core (`service_query`), by name. */
+ const queries: Record<string, (payload: Record<string, unknown>) => Record<string, unknown> | Promise<Record<string, unknown>>> = {
+ // This computer's agents as the dial lists them, and what else the dial reads in line: asked as its
+ // tick or ⌘K builds a list, so the devices read the registry as it is then.
+ view: () => ({
+ agents: core.agents.advertised().map((session) => ({ ...session, displayName: core.agents.displayName(session), runtimeProfile: core.agents.runtimeProfile(session) })),
+ machine: { id: core.machine.id(), computerId: core.machine.computerId(), name: core.machine.name() },
+ signedIn: core.account.signedIn(),
+ environment: core.account.environment(),
+ hasWindow: core.clients.hasWindow(),
+ }),
+ activityText: async ({ agentId }) => ({ text: await core.agents.activityText(text(agentId)) }),
+ recent: async ({ agentId, n }) => ({ turns: await core.turns.recent(text(agentId), typeof n === 'number' ? n : 3) }),
+ asks: async ({ agentId }) => ({ asks: await core.turns.asks(text(agentId)) }),
+ answerReviewed: async ({ answer }) => ({ ok: await core.questions.answerReviewed(answer as ReviewedAnswer) }),
+ models: async ({ agentId }) => ({ models: await core.agents.runtimeModels(text(agentId)) }),
+ fork: async ({ agentId }) => ({ ...await core.agents.fork(text(agentId)) }),
+ machines: () => core.account.machines(),
+ // The transcriber's and the fleet's lane's sign-in, and the lane's sealing, asked of the core at every
+ // use as every service in its own process asks them (core/accountQueries.ts): the devices hold no
+ // credential and no E2EE identity.
+ access_token: async (payload) => (await answerAccountQuery(core.account, 'access_token', payload))!,
+ lane: async (payload) => (await answerAccountQuery(core.account, 'lane', payload))!,
+ }
+
+ /** What the devices tell the core without asking (`service_notice`), by kind. */
+ const notices: Record<string, (payload: Record<string, unknown>) => void> = {
+ turn: ({ agentId, text: said }) => core.turns.send(text(agentId), text(said)),
+ stop: ({ agentId }) => core.turns.stop(text(agentId)),
+ answer: ({ agentId, requestId, answers }) => core.questions.answer(text(agentId), text(requestId), (answers && typeof answers === 'object' ? answers : {}) as Record<string, string>),
+ setRuntime: ({ agentId, model, effort }) => core.agents.setRuntime(text(agentId), typeof model === 'string' ? model : undefined, typeof effort === 'string' ? effort : undefined),
+ sendLocal: ({ frame }) => { if (isFrame(frame)) core.clients.sendLocal(frame as DeviceWindowFrame) },
+ // A bridge's ask for one window: told, not asked, since the bridge answers a window that has gone by its
+ // own deadline either way.
+ sendToWindow: ({ connId, frame }) => { if (isFrame(frame)) core.clients.sendToWindow(text(connId), frame as DeviceBridgeFrame) },
+ devicesChanged: ({ status, revision }) => core.clients.devicesChanged({ status, revision }),
+ dialWatching: ({ watching: on }) => watching(on === true),
+ }
+
+ return {
+ port,
+ answer(query: string, payload: Record<string, unknown>): Record<string, unknown> | Promise<Record<string, unknown>> {
+ const ask = Object.hasOwn(queries, query) ? queries[query] : undefined
+ return ask ? ask(payload) : { error: 'UNKNOWN_QUERY' }
+ },
+ notice(payload: Record<string, unknown>): void {
+ const kind = text(payload.kind)
+ const tell = Object.hasOwn(notices, kind) ? notices[kind] : undefined
+ if (!tell) { log(`[services] devices said ${kind.slice(0, 40) || 'nothing'}, which the core does not hear`); return }
+ tell(payload)
+ },
+ /** The devices connected (again): told everything the windows said meanwhile, and what the machine runs. */
+ connected(): void {
+ const state = deps.state()
+ event('state', { ...state })
+ },
+ /** Their process is gone, and every dial with it: no cards are made for a dial that is not there. */
+ disconnected(): void {
+ if (dialWatching) watching(false)
+ },
+ /** The devices started in the core's process instead: told the same, as calls on their port. */
+ started(started: DevicesPort): void {
+ const state = deps.state()
+ started.desk(state.desk, state.foreground)
+ started.swarms(state.swarms)
+ started.unread(state.unread)
+ started.windowFocus(state.focus)
+ started.engines(state.engines)
+ started.commanders(state.commanders)
+ },
+ }
+}
+
+export type DevicesLink = ReturnType<typeof createDevicesLink>
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index f33bbb66b..e1debef91 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -22,7 +22,7 @@ import { VERSION } from '../version.js'
import { sqlitePreflightMessage } from '../lib/sqliteAvailability.js'
import { warmLoginShellEnvironment } from '../lib/loginShellEnv.js'
import type { AppSwarms } from '../cable/cableSession.js'
-import type { UnreadNotification } from '../cable/notificationRead.js'
+import type { UnreadNotification } from '../lib/notificationRead.js'
import { terminalActivity } from '../lib/terminalActivity.js'
import { MachineListCache, withStaleMarker } from '../device/machineList.js'
import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from '../lib/registry.js'
@@ -140,7 +140,7 @@ import { createOrchestratorLink } from './orchestratorLink.js'
import { daemonCommand } from '../lib/daemonCommand.js'
import { KNOWN_SERVICES, servicesTheMasterRuns } from '../harnessd/services.js'
import { createTeamsLink, teamsOutOfProcess } from './teamsLink.js'
-import { startDevices } from '../services/devices.js'
+import { createDevicesLink } from './devicesLink.js'
import { CORE_EXIT_STOP, CORE_EXIT_UPDATE, PROBE_COMMAND, PROBE_TIMEOUT_MS } from '../harnessd/protocol.js'
import { localSocketPath, refuseServedDataFolder, type LocalSocketServer } from '../lib/localSocket.js'
import { saveDaemonPort } from '../lib/daemonEndpoint.js'
@@ -688,7 +688,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
sendToWindow: (connId, frame) => localWsServerRef?.sendToWindow(connId, frame) ?? false,
hasWindow: () => backendRef?.hasLocalClient() ?? false,
devicesChanged: (payload) => backendRef?.send({ type: 'harness_devices_changed', payload }),
- dialWatching: (watching) => { dialWatching = watching },
+ dialWatching: (watching) => {
+ const attached = watching && !dialWatching
+ dialWatching = watching
+ // A dial attaching is shown what is still being asked and what is still working, as a device joining
+ // through the backend is (onCommanderJoin): one whose devices' process restarted comes back to tiles
+ // mid-turn, and to a question nobody has answered yet.
+ if (attached) for (const frame of [...openQuestions.values(), ...mirror.liveCards()]) ports.devices?.card(frame)
+ },
// What a device or another machine asks of an agent here: the SAME handlers the backend socket
// drives, called directly — the slash-command adaptation and the turn and question plumbing live there.
runtimeProfile: (session) => runtimeProfiles.selectedModel(session),
@@ -714,8 +721,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
turns: {
send: (agentId, text) => backendRef?.onMessage?.(agentId, text),
stop: (agentId) => backendRef?.onCancel?.(agentId),
- recent: (agentId, n) => mirror.recent(registry.resolve(agentId)?.sessionId || agentId, n),
- asks: (agentId) => mirror.recentAsks(registry.resolve(agentId)?.sessionId || agentId),
+ recent: async (agentId, n) => mirror.recent(registry.resolve(agentId)?.sessionId || agentId, n),
+ asks: async (agentId) => mirror.recentAsks(registry.resolve(agentId)?.sessionId || agentId),
...deliveries.turns,
},
questions: {
@@ -1112,6 +1119,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The requests each service that can run in its own process answers, as core/api.ts declares them.
const requestsOf: Record<string, readonly string[]> = {
search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS,
+ devices: DEVICES_REQUESTS,
...Object.fromEntries(Object.entries(EXPERIMENTS).map(([name, experiment]) => [name, experiment.requests])),
}
// The experiments (core/api.ts `EXPERIMENTS`): each may act on the core through the hooks an experiment has.
@@ -1135,6 +1143,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const storeLink = createStoreLink(coreApi, invalidateInstalledDsh)
// What the core keeps of models in its own process for frames and keystrokes, and how it asks it the rest (core/modelsLink.ts).
const modelsLink = createModelsLink(coreApi, (type, payload) => serviceLinks.call('models', type, payload), (frame) => serviceLinks.notify('models', frame))
+ // The devices in their own process (core/devicesLink.ts): told what the windows say, asked ⌘K, and told it
+ // all again whenever they connect, from what the core keeps.
+ const devicesLink = createDevicesLink({
+ core: coreApi,
+ notify: (frame) => serviceLinks.notify('devices', frame),
+ call: (type, payload, waitMs) => serviceLinks.call('devices', type, payload, waitMs),
+ state: () => ({ desk: appPaneAgents, foreground: appWindowForeground, swarms: appSwarmsLatest, unread: appUnreadLatest,
+ focus: windowFocus(), engines: registry.active().map((agent) => agent.engine), commanders: backend.hasCommander() }),
+ })
const serviceLinks = createServiceLinks({
token: serviceToken,
owned: Object.fromEntries([...outOfProcess].map((name) => [name, requestsOf[name] ?? []])),
@@ -1151,16 +1168,20 @@ async function runForeground(session: AuthSession | null): Promise<void> {
: service === 'store' ? storeLink.answer(query, payload)
: service === 'models' ? modelsLink.answer(query, payload)
: service === 'teams' || service === 'collaboration' ? teamsLink.answer(query, payload)
+ : service === 'devices' ? devicesLink.answer(query, payload)
: service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : answerAgentQuery(coreApi, query)),
- // The gateway's own traffic: its remote clients and what they sent, and its comings and goings.
- notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload) },
+ // The gateway's own traffic: its remote clients and what they sent, and its comings and goings; and what
+ // the devices tell the core (a turn, a frame for the windows, a dial on the wire).
+ notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload); else if (service === 'devices') devicesLink.notice(payload) },
binary: (service, bytes) => { if (service === 'gateway') gatewayLink?.binary(bytes) },
connected: (service) => {
if (service === 'gateway') gatewayLink?.connected()
if (service === 'teams') teamsLink.on()
+ if (service === 'devices') devicesLink.connected()
},
disconnected: (service) => {
if (service === 'gateway') gatewayLink?.disconnected()
+ if (service === 'devices') devicesLink.disconnected()
void terminalWatch.gone(service)
},
})
@@ -2492,20 +2513,18 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// (⌘K's too) with the lane to the owner's other machines, the voice router and the Devices tab. Behind
// their port: a device that fails costs the devices, never a session. Deliberately not fatal and not
// blocking: an unplugged cable is this daemon's ordinary state.
- serviceHost.start('devices', (core, started) => startDevices(core, started, {
- logsDir: env.HARNESS_LOGS_DIR,
- dialSerials: process.env.HARNESS_DIAL_SERIALS?.split(',').map((serial) => serial.trim()).filter(Boolean),
- testDialPort: process.env.HARNESSD_TEST_DIAL_PORT,
- cableDisabled: env.CABLE_DISABLE,
- faults: testFaults(process.env.HARNESSD_TEST_FAULTS),
- }), coreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS)
- // Everything the windows said while the devices were being built, and what the machine runs.
- ports.devices?.desk(appPaneAgents, appWindowForeground)
- ports.devices?.swarms(appSwarmsLatest)
- ports.devices?.unread(appUnreadLatest)
- ports.devices?.windowFocus(windowFocus())
- ports.devices?.engines(registry.active().map((agent) => agent.engine))
- ports.devices?.commanders(backend.hasCommander())
+ // In their own process they are told everything the windows said as they connect (core/devicesLink.ts):
+ // said here too, it reached a dial still opening its port, before its greeting.
+ if (outOfProcess.has('devices')) ports.devices = devicesLink.port
+ else {
+ serviceHost.start('devices', (core, started) => inline!.startDevices(core, started, {
+ logsDir: env.HARNESS_LOGS_DIR, testDialPort: process.env.HARNESSD_TEST_DIAL_PORT,
+ dialSerials: process.env.HARNESS_DIAL_SERIALS?.split(',').map((serial) => serial.trim()).filter(Boolean),
+ cableDisabled: env.CABLE_DISABLE, faults: testFaults(process.env.HARNESSD_TEST_FAULTS),
+ }), coreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS)
+ // Everything the windows said while the devices were being built, and what the machine runs.
+ if (ports.devices) devicesLink.started(ports.devices)
+ }
const deviceStore = createDeviceStore({ dataDir: env.ADAPTER_DATA_DIR, machineId: backend.machineId,
create: input => backend.onCreateAgent!(input),
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index d89d2b412..789e2b594 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -353,6 +353,11 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// Grid's pictures, the Model Manager's catalog and the models found on this machine. Its downloads, model
// servers and `grid` commands run in processes of their own, outside this budget.
models: { services: ['models'], heapLimitMiB: 512, rssLimitMiB: 1_024 },
+ // The devices (services/devicesProcess.ts): the dials on USB (pure-JS serial, a frame decoder whose buffer
+ // is bounded per dial), the window bridges, the fleet's router and its lane, the voice router's engine
+ // worker (a process of its own, outside this budget). Hardware that speaks whatever its firmware says:
+ // what it costs, it costs here, never a session.
+ devices: { services: ['devices'], heapLimitMiB: 256, rssLimitMiB: 512 },
}
/** Every service this build can run outside the core's process: what `HARNESSD_SERVICES` names. */
diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.ts
index 14d9dcfe0..3f0f2e12e 100644
--- a/cli/src/lib/commander.ts
+++ b/cli/src/lib/commander.ts
@@ -776,6 +776,28 @@ export class CommanderMirror {
* device that missed it is stuck "Working…" forever. A bare `done` clears that stale busy WITHOUT a beep or
* recap card, and is a harmless no-op on a tile that isn't busy; the device's recent-poll restores the
* stored summary text afterwards. */
+ /**
+ * What a dial attaching now must be shown of the turns in progress: the cards `heartbeat` would send for
+ * each busy session, returned rather than sent, and not gated on a device watching (the dial is). The
+ * devices restart in a process of their own and come back to a dial whose tiles were mid-turn; without
+ * these the tile reads idle until the next heartbeat, or the next turn.
+ */
+ liveCards(): Array<Record<string, unknown>> {
+ const cards: Array<Record<string, unknown>> = []
+ for (const [sessionId, st] of this.states) {
+ const card = (payload: Record<string, unknown>) =>
+ cards.push({ type: 'commander_event', agentId: this.opts.agentIdFor?.(sessionId) ?? sessionId, dbSessionId: sessionId, payload })
+ if (st.turnOpen) {
+ if (this.opts.verifiedWorking?.(sessionId) === false) continue
+ card(st.lastTodos ? { kind: 'processing', text: 'Processing', todos: st.lastTodos } : { kind: 'processing', text: 'Processing' })
+ if (st.lastTool) card(st.lastTool)
+ } else if (st.summarizing) {
+ card({ kind: 'processing', text: 'Summarizing…' })
+ }
+ }
+ return cards
+ }
+
replayAll(): void {
for (const sessionId of this.states.keys()) {
// Busy session → re-assert its live processing/summarizing state (shared with heartbeat()).
diff --git a/cli/src/cable/notificationRead.ts b/cli/src/lib/notificationRead.ts
similarity index 100%
rename from cli/src/cable/notificationRead.ts
rename to cli/src/lib/notificationRead.ts
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 9efa4f335..a37a099cd 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto'
import type { AppSwarms } from './cable/cableSession.js'
-import { notificationReadToken, type UnreadNotification } from './cable/notificationRead.js'
+import { notificationReadToken, type UnreadNotification } from './lib/notificationRead.js'
import type http from 'node:http'
import type { Socket } from 'node:net'
import { WebSocket, WebSocketServer, type RawData } from 'ws'
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index f0bea8545..2fbdd15d4 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -38,6 +38,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M
['orchestrator', async () => (await import('./services/orchestratorProcess.js')).runOrchestratorService],
['gateway', async () => (await import('./gateway/gatewayProcess.js')).runGatewayService],
['models', async () => (await import('./services/modelsProcess.js')).runModelsService],
+ ['devices', async () => (await import('./services/devicesProcess.js')).runDevicesService],
])
export interface ServiceProcessDeps {
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 5adc9e0de..3d8da5bb1 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -44,7 +44,8 @@ let several people build features at once without touching the core or each othe
A service that can crash natively, hang or leak should run in a process of its own, where it costs only
that process. A process per risk, not per feature: search (native `node:sqlite`), the viewers (their
servers) with the Store (its minutes-long installs), each experiment (below), models (grid's installs,
-downloads and commands), and the edge host, one process for the light services that only answer requests
+downloads and commands), the devices (the dials' serial ports, the fleet's lane, the voice router's
+worker), and the edge host, one process for the light services that only answer requests
(workspaces, usage, the monitor, the project readers). A fault in one of the edge host's services can
cost the others in it, never the core. Every service in `KNOWN_SERVICES` runs out of the core's process
by default, unless `HARNESSD_SERVICES` names a subset, by service (`search,usage`) or by process
@@ -113,6 +114,14 @@ way back).
takes one back with `cancelDelivery` (core/deliveries.ts). In its own process `services/turnsLink.ts`
asks the core over its link, in order, and hears only its own deliveries; the core lets a process deliver
only when it is an experiment (below).
+- A service that drives hardware: the devices (src/services/devicesProcess.ts, src/core/devicesLink.ts).
+ The dial reads a dozen facts in line while it builds each frame, so the process keeps a copy of what it
+ reads (this computer's agents, its name, the sign-in, whether a window is there), asked of the core as
+ the dial's tick or ⌘K builds a list; the core keeps what the windows said and says it again each time
+ the process connects, and a dial attaching is shown the open questions and the working tiles. Inside,
+ one device failing is that device's alone: its session's faults and a flood on its port drop it, and
+ its port is looked at again later (src/cable/cableFleet.ts). `e2e/devicesProcess.e2e.ts` proves it,
+ with fake dials on pseudo-terminals.
- State built from every change must get every change exactly once. The teams show how
(`src/services/teamsProcess.ts`, `src/core/teamsLink.ts`): the core numbers each change and keeps it
until the process acknowledges it; on each connection the process says what it applied and gets
diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.ts
index 9d90f578a..a09fe7217 100644
--- a/cli/src/services/devices.ts
+++ b/cli/src/services/devices.ts
@@ -51,6 +51,9 @@ export interface DevicesDeps {
log?: (line: string) => void
/** How the voice router's worker is stopped when the process exits: an engine process of its own. */
onExit?: (run: () => void) => void
+ /** Read this computer's agents again before a list is built from them: in their own process the devices
+ * keep a copy, asked of the core as the dial's tick or ⌘K needs it (services/devicesProcess.ts). */
+ refresh?: () => Promise<void>
/** For this service's tests: the dial's session, and how dials are found and opened. */
Session?: ConstructorParameters<typeof CableFleet>[0]
cable?: Partial<CableFleetOptions>
@@ -87,7 +90,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
// the trust group read; this copy writes no file of its own, so `machines.json` has one writer.
const machines = new MachineListCache(() => core.account.machines(), () => core.machine.computerId(),
(line) => log(`[cable] ${line}`), core.dataDir, () => null, false)
- const fleet: Fleet | null = part.start('fleet', () => startFleet(core, { machines, desk: () => desk }).fleet, FLEET_FALLBACKS)
+ const fleet: Fleet | null = part.start('fleet', () => startFleet(core, { machines, desk: () => desk, refresh: deps.refresh }).fleet, FLEET_FALLBACKS)
// ── the window bridges ─────────────────────────────────────────────────────────────────────────────
//
@@ -127,6 +130,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
let revision = 0
const cableHost = new DaemonCableHost({
sessions: () => core.agents.advertised(),
+ refresh: deps.refresh,
displayName: (session) => core.agents.displayName(session),
activityText: (agentId) => core.agents.activityText(agentId),
machineName: () => core.machine.name(),
@@ -191,6 +195,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
const cable = new CableFleet(deps.Session ?? CableSession, cableHost, deps.logsDir, DialLog, {
serials: deps.dialSerials,
verdicts: new DialVerdicts(join(core.dataDir, 'dial-ports.json')),
+ faults: deps.faults,
...testDialDiscovery(deps.testDialPort),
...deps.cable,
})
diff --git a/cli/src/services/devicesProcess.spec.ts b/cli/src/services/devicesProcess.spec.ts
new file mode 100644
index 000000000..42cbe3df8
--- /dev/null
+++ b/cli/src/services/devicesProcess.spec.ts
@@ -0,0 +1,335 @@
+// The devices in a process of their own (services/devicesProcess.ts): the core API they run on across their
+// link, what the core tells them reaching the devices' port, and what the core asks answered from it.
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { CoreApi, CorePorts, DevicesPort, ServiceRequests } from '../core/api.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { DevicesDeps } from './devices.js'
+import { runDevicesService } from './devicesProcess.js'
+import type { CoreConnection, ServiceProcessOptions } from './process.js'
+
+// The real devices and the real link, as a process started by the master runs them: stood in for here.
+const real = vi.hoisted(() => ({ started: [] as unknown[], linked: [] as unknown[] }))
+vi.mock('./devices.js', () => ({
+ startDevices: (_core: unknown, ports: { devices: unknown }) => { real.started.push(ports); ports.devices = { stop: async () => {} }; return {} },
+}))
+vi.mock('./process.js', () => ({
+ runServiceProcess: (options: unknown) => { real.linked.push(options); return { stop: () => {} } },
+}))
+
+/** A devices' port that records what reached it. */
+function devicesPort() {
+ const calls: Array<[string, unknown[]]> = []
+ const record = (name: string) => (...args: unknown[]) => { calls.push([name, args]) }
+ const port = {
+ card: record('card'), desk: record('desk'), swarms: record('swarms'), unread: record('unread'), appFocus: record('appFocus'),
+ seen: record('seen'), settings: record('settings'), windowFocus: record('windowFocus'), windowReply: record('windowReply'),
+ voiceReply: record('voiceReply'), windowGone: record('windowGone'), scroll: record('scroll'), engines: record('engines'),
+ commanders: record('commanders'),
+ routeTask: vi.fn(async (text: string) => ({ agentId: 'a1', machineId: 'm1', name: 'api', confidence: 1, reason: text, candidates: [], weighed: 1, machines: 1, via: 'model' })),
+ routeSend: vi.fn(async () => ({ ok: true as const })),
+ stepFocus: vi.fn(async (): Promise<{ machineId: string; agentId: string } | 'no_agents'> => ({ machineId: 'm1', agentId: 'a2' })),
+ stop: vi.fn(async () => {}),
+ } satisfies DevicesPort
+ return { port, calls }
+}
+
+function setup(over: { processEnv?: NodeJS.ProcessEnv } = {}) {
+ const { port, calls } = devicesPort()
+ let api!: CoreApi
+ let deps!: DevicesDeps
+ const tab = { harness_devices_list: vi.fn(async () => ({ protocol: 1 })) }
+ const start = vi.fn((core: CoreApi, ports: CorePorts, given: DevicesDeps): ServiceRequests => {
+ api = core
+ deps = given
+ ports.devices = port
+ return tab
+ })
+ let options!: ServiceProcessOptions
+ const stop = vi.fn()
+ const run = vi.fn((given: ServiceProcessOptions) => { options = given; return { stop } })
+ const service = runDevicesService({
+ dataDir: '/data', socketPath: '/sock', machineId: 'computer-9', token: 't',
+ start, run, processEnv: over.processEnv ?? {},
+ })
+ const queries: Array<[string, Record<string, unknown> | undefined]> = []
+ const notices: Array<[string, Record<string, unknown> | undefined]> = []
+ let answers: Record<string, unknown> = {}
+ const connection: CoreConnection = {
+ query: vi.fn(async (query: string, payload?: Record<string, unknown>) => {
+ queries.push([query, payload])
+ const answer = answers[query]
+ if (answer instanceof Error) throw answer
+ return (answer ?? {}) as Record<string, unknown>
+ }),
+ notice: (kind, payload) => { notices.push([kind, payload]) },
+ }
+ return {
+ service, port, calls, api: () => api, deps: () => deps, options: () => options, stop, tab, queries, notices, connection,
+ answer: (query: string, value: unknown) => { answers = { ...answers, [query]: value } },
+ connect: () => options.onConnected!(connection),
+ event: (payload: Record<string, unknown>) => options.onEvent!(payload),
+ }
+}
+
+afterEach(() => vi.restoreAllMocks())
+
+describe('the devices in their own process', () => {
+ it('start the devices on a link of their own, with what their process\'s environment says', () => {
+ const f = setup({ processEnv: { HARNESS_DIAL_SERIALS: ' AA, ,BB ', HARNESSD_TEST_DIAL_PORT: '/dev/ttys042', HARNESSD_TEST_FAULTS: 'dial, fleet.knows ,' } })
+ expect(f.options()).toMatchObject({ name: 'devices', socketPath: '/sock', machineId: 'computer-9', token: 't' })
+ expect(f.deps()).toMatchObject({ dialSerials: ['AA', 'BB'], testDialPort: '/dev/ttys042' })
+ // No credential and no E2EE identity: the account is asked of the core.
+ expect(Object.keys(f.deps())).not.toContain('identity')
+ expect([...f.deps().faults!]).toEqual(['dial', 'fleet.knows'])
+ // The Devices tab's requests are the devices' own, beside what only the core asks.
+ expect(Object.keys(f.options().requests).sort()).toEqual(['harness_devices_list', 'routeSend', 'routeTask', 'stepFocus'])
+ })
+
+ it('read no serials, dial or faults without them', () => {
+ const f = setup({ processEnv: {} })
+ expect(f.deps().dialSerials).toBeUndefined()
+ expect([...f.deps().faults!]).toEqual([])
+ // Their own process's environment by default.
+ const was = process.env.HARNESSD_TEST_DIAL_PORT
+ process.env.HARNESSD_TEST_DIAL_PORT = '/dev/ttys777'
+ try {
+ let deps!: DevicesDeps
+ runDevicesService({ dataDir: '/data', socketPath: '/sock', machineId: 'c', token: 't',
+ start: (_core, ports, given) => { deps = given; ports.devices = devicesPort().port; return {} }, run: () => ({ stop: () => {} }) })
+ expect(deps.testDialPort).toBe('/dev/ttys777')
+ } finally {
+ if (was === undefined) delete process.env.HARNESSD_TEST_DIAL_PORT
+ else process.env.HARNESSD_TEST_DIAL_PORT = was
+ }
+ })
+
+ it('run the devices and their link as the master starts them', () => {
+ runDevicesService({ dataDir: '/data', socketPath: '/sock', machineId: 'c', token: 't' })
+ expect(real.started).toHaveLength(1)
+ expect(real.linked).toEqual([expect.objectContaining({ name: 'devices', socketPath: '/sock', token: 't' })])
+ })
+
+ it('stop their link, then the devices, serial ports first', async () => {
+ const f = setup()
+ await f.service.stop()
+ expect(f.stop).toHaveBeenCalled()
+ expect(f.port.stop).toHaveBeenCalled()
+ })
+})
+
+describe('the core\'s view, read in line by the dial', () => {
+ const agent = { agentId: 'a1', sessionId: 's1', engine: 'claude', displayName: 'api', runtimeProfile: 'runtime-v1:s1:claude:opus@high' }
+
+ it('is nothing but this computer\'s id before the core is asked', async () => {
+ const f = setup()
+ const api = f.api()
+ expect(api.agents.advertised()).toEqual([])
+ expect(api.machine.computerId()).toBe('computer-9')
+ expect(api.machine.name()).toBe('This machine')
+ expect(api.account.signedIn()).toBe(false)
+ // Not connected: refreshing asks nothing, and a question to the core fails at once.
+ await f.deps().refresh!()
+ expect(f.queries).toEqual([])
+ await expect(api.agents.activityText('a1')).rejects.toThrow('the devices are not connected to the core')
+ })
+
+ it('is asked as the core connects, and again as the dial\'s tick or ⌘K needs it, one ask at a time', async () => {
+ const f = setup()
+ f.answer('view', { agents: [agent], machine: { id: 'machine-1', computerId: 'computer-1', name: 'Studio' }, signedIn: true, environment: 'prod', hasWindow: true })
+ f.connect()
+ await vi.waitFor(() => expect(f.api().agents.advertised()).toHaveLength(1))
+ const api = f.api()
+ const session = api.agents.advertised()[0]
+ expect(api.agents.all()).toEqual([agent])
+ expect(api.agents.live()).toEqual([agent])
+ expect(api.agents.displayName(session)).toBe('api')
+ expect(api.agents.displayName({ agentId: 'x' } as RegisteredSession)).toBe('')
+ expect(api.agents.runtimeProfile(session)).toBe('runtime-v1:s1:claude:opus@high')
+ expect(api.agents.runtimeProfile({ agentId: 'x' } as RegisteredSession)).toBeNull()
+ expect(api.agents.byAgent('a1')).toEqual(agent)
+ expect(api.agents.resolve('s1')).toEqual(agent)
+ expect(api.agents.terminalAvailable('a1')).toBe(true)
+ api.agents.sync(session)
+ expect([api.machine.id(), api.machine.computerId(), api.machine.name()]).toEqual(['machine-1', 'computer-1', 'Studio'])
+ expect(api.account.signedIn()).toBe(true)
+ expect(api.account.environment()).toBe('prod')
+ expect(api.clients.hasWindow()).toBe(true)
+ // Asked twice at once: one ask.
+ const before = f.queries.length
+ await Promise.all([f.deps().refresh!(), f.deps().refresh!()])
+ expect(f.queries.length).toBe(before + 1)
+ // An answer that is not a view changes nothing; one that is missing names keeps the defaults.
+ f.answer('view', { error: 'QUERY_FAILED' })
+ await f.deps().refresh!()
+ expect(api.agents.advertised()).toHaveLength(1)
+ f.answer('view', { agents: [], machine: 'nothing' })
+ await f.deps().refresh!()
+ expect([api.machine.id(), api.machine.computerId(), api.machine.name()]).toEqual(['', 'computer-9', 'This machine'])
+ // An ask the core never answers (it went away) leaves the last view.
+ f.answer('view', new Error('the core went away'))
+ await f.deps().refresh!()
+ expect(api.machine.computerId()).toBe('computer-9')
+ })
+})
+
+describe('the core\'s doors, across the link', () => {
+ it('ask the core for what needs an answer, and tell it the rest', async () => {
+ const f = setup()
+ f.connect()
+ const api = f.api()
+ f.answer('models', { models: [{ id: 'opus' }] })
+ expect(await api.agents.runtimeModels('a1')).toEqual([{ id: 'opus' }])
+ f.answer('models', {})
+ expect(await api.agents.runtimeModels('a1')).toEqual([])
+ f.answer('fork', { requestId: 'r', ok: true, agentId: 'a2' })
+ expect(await api.agents.fork('a1')).toEqual({ ok: true, agentId: 'a2' })
+ f.answer('activityText', { text: 'Reading' })
+ expect(await api.agents.activityText('a1')).toBe('Reading')
+ f.answer('activityText', { text: null })
+ expect(await api.agents.activityText('a1')).toBeNull()
+ f.answer('recent', { turns: [{ recap: 'done' }] })
+ expect(await api.turns.recent('a1', 2)).toEqual([{ recap: 'done' }])
+ f.answer('recent', {})
+ expect(await api.turns.recent('a1', 2)).toEqual([])
+ f.answer('asks', { asks: ['why?', 7] })
+ expect(await api.turns.asks('a1')).toEqual(['why?'])
+ f.answer('answerReviewed', { ok: true })
+ expect(await api.questions.answerReviewed({ agentId: 'a1' } as never)).toBe(true)
+ // The account through the link every service in its own process uses (services/accountLink.ts).
+ f.answer('access_token', { token: 'secret' })
+ expect(await api.account.accessToken({ force: true })).toBe('secret')
+ expect(f.queries.at(-1)).toEqual(['access_token', { force: true }])
+ f.answer('lane', { frame: { type: 'message', sealed: true } })
+ expect(await api.account.lane.seal('m2', { type: 'message' })).toEqual({ frame: { type: 'message', sealed: true } })
+ expect(f.queries.at(-1)).toEqual(['lane', { machineId: 'm2', frame: { type: 'message' }, op: 'seal' }])
+ f.answer('machines', { status: 200, body: { data: { machines: [] } } })
+ expect(await api.account.machines()).toEqual({ status: 200, body: { data: { machines: [] } } })
+ f.answer('machines', { body: 'broken' })
+ expect(await api.account.machines()).toEqual({ status: 502, body: {} })
+ api.agents.setRuntime('a1', 'opus', 'high')
+ api.turns.send('a1', 'hello')
+ api.turns.stop('a1')
+ api.questions.answer('a1', 'r1', { q: 'Coffee' })
+ api.clients.sendLocal({ type: 'dial_focus', payload: {} })
+ expect(api.clients.sendToWindow('w1', { type: 'dial_form', payload: {} })).toBe(true)
+ api.clients.devicesChanged({ revision: 1 })
+ api.clients.dialWatching(true)
+ // What an experiment acts on the core through, the devices never do.
+ api.clients.windows({ type: 'orchestrator_changed', payload: {} })
+ expect(api.daemon.port).toBe(0)
+ expect(f.notices).toEqual([
+ ['setRuntime', { agentId: 'a1', model: 'opus', effort: 'high' }],
+ ['turn', { agentId: 'a1', text: 'hello' }],
+ ['stop', { agentId: 'a1' }],
+ ['answer', { agentId: 'a1', requestId: 'r1', answers: { q: 'Coffee' } }],
+ ['sendLocal', { frame: { type: 'dial_focus', payload: {} } }],
+ ['sendToWindow', { connId: 'w1', frame: { type: 'dial_form', payload: {} } }],
+ ['devicesChanged', { revision: 1 }],
+ ['dialWatching', { watching: true }],
+ ])
+ // What the devices never ask answers as every other service's does.
+ expect(api.transcripts.databaseHistory({} as RegisteredSession)).toBeUndefined()
+ expect(api.external.sessions.list()).toEqual([])
+ await expect(api.account.mintGridName()).resolves.toBeNull()
+ // Gone from the core: told nothing, and a bridge's ask says it did not go.
+ f.options().onDisconnected!()
+ api.turns.send('a1', 'lost')
+ expect(api.clients.sendToWindow('w1', { type: 'dial_form', payload: {} })).toBe(false)
+ expect(f.notices).toHaveLength(8)
+ })
+})
+
+describe('what the core tells the devices, reaching their port', () => {
+ it('is each kind of notice, read as the port takes it', () => {
+ const f = setup()
+ const focus = { voice: { machineId: 'm1', agentId: 'a1', connId: 'w1' }, form: { machineId: 'm1', connId: 'w1' } }
+ for (const payload of [
+ { kind: 'card', frame: { type: 'commander_event' } },
+ { kind: 'card', frame: 'not one' },
+ { kind: 'desk', agentIds: ['a1', 7], foreground: false },
+ { kind: 'desk', agentIds: 'nonsense' },
+ { kind: 'swarms', swarms: { active: 't1', swarms: [], tiles: [] } },
+ { kind: 'swarms', swarms: null },
+ { kind: 'unread', items: [{ agentId: 'a1' }] },
+ { kind: 'unread', items: 'nonsense' },
+ { kind: 'appFocus', machineId: 'm1', agentId: 'a1' },
+ { kind: 'seen', agentId: 'a1', readToken: 'tok' },
+ { kind: 'seen', agentId: 'a1' },
+ { kind: 'settings', id: 'usb', patch: { brightness: 3 } },
+ { kind: 'settings', id: 'usb', patch: [1] },
+ { kind: 'windowFocus', focus },
+ { kind: 'windowFocus', focus: { voice: { connId: 'w2' }, form: 'nonsense' } },
+ { kind: 'windowReply', which: 'form', connId: 'w1', machineId: 'm1', reply: { ok: true } },
+ { kind: 'windowReply', which: 'visit', connId: 'w1', machineId: 'm1', reply: null },
+ { kind: 'windowReply', which: 'anything', connId: 'w1', machineId: 'm1', reply: {} },
+ { kind: 'voiceReply', voiceId: 'v1', reply: { t: 'taken' } },
+ { kind: 'windowGone', connId: 'w1' },
+ { kind: 'scroll', phase: 'move', dy: 2, velocity: Infinity },
+ { kind: 'scroll', phase: 'sideways', dy: 2, velocity: 1 },
+ { kind: 'engines', engines: ['claude'] },
+ { kind: 'commanders', connected: true },
+ { kind: 'nothing it knows' },
+ { kind: 'constructor' },
+ ]) f.event(payload)
+ expect(f.calls).toEqual([
+ ['card', [{ type: 'commander_event' }]],
+ ['card', [{}]],
+ ['desk', [['a1'], false]],
+ ['desk', [[], true]],
+ ['swarms', [{ active: 't1', swarms: [], tiles: [] }]],
+ ['swarms', [null]],
+ ['unread', [[{ agentId: 'a1' }]]],
+ ['unread', [[]]],
+ ['appFocus', ['m1', 'a1']],
+ ['seen', ['a1', 'tok']],
+ ['seen', ['a1', undefined]],
+ ['settings', ['usb', { brightness: 3 }]],
+ ['settings', ['usb', {}]],
+ ['windowFocus', [focus]],
+ ['windowFocus', [{ voice: { machineId: '', agentId: '', connId: 'w2' }, form: null }]],
+ ['windowReply', ['form', 'w1', 'm1', { ok: true }]],
+ ['windowReply', ['visit', 'w1', 'm1', {}]],
+ ['windowReply', ['selection', 'w1', 'm1', {}]],
+ ['voiceReply', ['v1', { t: 'taken' }]],
+ ['windowGone', ['w1']],
+ ['scroll', ['move', 2, 0]],
+ ['engines', [['claude']]],
+ ['commanders', [true]],
+ ])
+ })
+
+ it('is everything the windows said at once when the devices connect, and nothing they did not', () => {
+ const f = setup()
+ f.event({ kind: 'state', desk: ['a1'], foreground: true, swarms: { active: 't1', swarms: [], tiles: [] }, unread: [{ agentId: 'a1' }], focus: null, engines: ['codex'], commanders: true })
+ expect(f.calls).toEqual([
+ ['desk', [['a1'], true]],
+ ['swarms', [{ active: 't1', swarms: [], tiles: [] }]],
+ ['unread', [[{ agentId: 'a1' }]]],
+ ['windowFocus', [{ voice: null, form: null }]],
+ ['engines', [['codex']]],
+ ['commanders', [true]],
+ ])
+ // No window yet: the dial is told nothing about one.
+ f.calls.length = 0
+ f.event({ kind: 'state', desk: [], swarms: null, unread: 'nonsense' })
+ expect(f.calls.map(([name]) => name)).toEqual(['windowFocus', 'engines', 'commanders'])
+ })
+})
+
+describe('what the core asks of the devices', () => {
+ it('is ⌘K and the Wi-Fi device\'s step, answered from the devices\' port', async () => {
+ const f = setup()
+ const asker = { local: true, owner: true }
+ const { requests } = f.options()
+ expect(await requests.routeTask({ text: 'fix it' }, asker)).toMatchObject({ agentId: 'a1', reason: 'fix it' })
+ expect(await requests.routeTask({}, asker)).toMatchObject({ reason: '' })
+ expect(await requests.routeSend({ agentId: 'a1', text: 'go' }, asker)).toEqual({ ok: true })
+ expect(f.port.routeSend).toHaveBeenCalledWith('a1', 'go')
+ expect(await requests.stepFocus({ direction: 'previous', currentAgentId: 'a1' }, asker)).toEqual({ machineId: 'm1', agentId: 'a2' })
+ expect(f.port.stepFocus).toHaveBeenLastCalledWith('previous', 'a1')
+ f.port.stepFocus.mockResolvedValueOnce('no_agents')
+ expect(await requests.stepFocus({ direction: 'sideways', currentAgentId: 7 }, asker)).toEqual({ step: 'no_agents' })
+ expect(f.port.stepFocus).toHaveBeenLastCalledWith('next', undefined)
+ expect(await requests.harness_devices_list({}, asker)).toEqual({ protocol: 1 })
+ })
+})
diff --git a/cli/src/services/devicesProcess.ts b/cli/src/services/devicesProcess.ts
new file mode 100644
index 000000000..a4d354b95
--- /dev/null
+++ b/cli/src/services/devicesProcess.ts
@@ -0,0 +1,254 @@
+/**
+ * The devices in a process of their own (`harness __service devices`, harnessd/services.ts): the dials on
+ * this computer's USB ports, the window bridges they speak through, the fleet's router and its lane to the
+ * owner's other machines, the voice router and the Devices tab (services/devices.ts), on a link to the core
+ * (docs/design/2026-10-06-core-boundary-next.md, step 9, D2).
+ *
+ * A device is hardware speaking whatever its firmware says, a lane to the backend and a voice router's
+ * engine worker: here a device that hangs the event loop, leaks or crashes costs the devices, and the
+ * master starts them again, while every agent and window goes on. The serial ports are this process's,
+ * one owner each (`O_EXLOCK`, cable/serial.ts).
+ *
+ * It runs on a core API of its own, over its link (core/devicesLink.ts): what the dial reads in line while
+ * it builds a frame (this computer's agents, their names and models, this computer, the sign-in, whether a
+ * window is there) is the core's answer to `view`, asked again as the dial's tick or ⌘K builds a list;
+ * everything else is asked of the core when it is needed, or told to it. The core keeps what the windows
+ * said and tells it again each time this process connects.
+ */
+import { env } from '../config/env.js'
+import type { AppSwarms } from '../cable/cableSession.js'
+import type { RecentTurn } from '../cable/cableHost.js'
+import type { UnreadNotification } from '../lib/notificationRead.js'
+import { AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, resolveAgent, TERMINALS_OFF, type CoreApi, type CorePorts, type DevicesPort, type ForkResult, type ServiceRequests, type VoiceRouteReply, type WindowFocus } from '../core/api.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { RuntimeModelOption } from '../lib/runtimeProfile.js'
+import { accountLink } from './accountLink.js'
+import { startDevices, type DevicesDeps } from './devices.js'
+import { runServiceProcess, type CoreConnection, type ServiceProcess, type ServiceProcessOptions } from './process.js'
+import { processCoreApi } from './processCoreApi.js'
+
+/** An agent as the core lists it for the dial: with the name the apps show and the model it runs. */
+type Viewed = RegisteredSession & { displayName?: string; runtimeProfile?: string | null }
+
+/** What the core last said of this computer: what the dial reads in line. */
+interface View {
+ agents: Viewed[]
+ machine: { id: string; computerId: string; name: string }
+ signedIn: boolean
+ environment: string
+ hasWindow: boolean
+}
+
+export interface DevicesServiceOptions {
+ dataDir: string
+ socketPath: string
+ machineId: string
+ token: string
+ /** For this service's tests: its start and its link. */
+ start?: typeof startDevices
+ run?: (options: ServiceProcessOptions) => ServiceProcess
+ processEnv?: NodeJS.ProcessEnv
+}
+
+const text = (value: unknown): string => (typeof value === 'string' ? value : '')
+const strings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [])
+const object = (value: unknown): Record<string, unknown> => (value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {})
+const number = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
+
+/** The window that has the person's attention, as the core sent it; nothing for anything else. */
+function focusOf(value: unknown): WindowFocus {
+ const focus = object(value)
+ const voice = object(focus.voice)
+ const form = object(focus.form)
+ return {
+ voice: voice.connId ? { machineId: text(voice.machineId), agentId: text(voice.agentId), connId: text(voice.connId) } : null,
+ form: form.connId ? { machineId: text(form.machineId), connId: text(form.connId) } : null,
+ }
+}
+
+/** `HARNESSD_TEST_FAULTS`, as the devices read it for their own parts (services/devicesGuard.ts). */
+function faultsOf(value: string | undefined): ReadonlySet<string> {
+ return new Set((value ?? '').split(',').map((entry) => entry.trim()).filter(Boolean))
+}
+
+export function runDevicesService(options: DevicesServiceOptions): ServiceProcess {
+ const processEnv = options.processEnv ?? process.env
+ let core: CoreConnection | null = null
+ let view: View = { agents: [], machine: { id: '', computerId: options.machineId, name: 'This machine' }, signedIn: false, environment: '', hasWindow: false }
+ /** One ask of the core's view at a time: the dial's tick and ⌘K asking together share it. */
+ let viewing: Promise<void> | null = null
+ const refresh = (): Promise<void> => {
+ if (viewing) return viewing
+ if (!core) return Promise.resolve()
+ const asking = core.query('view').then((answer) => {
+ if (!Array.isArray(answer.agents)) return
+ const machine = object(answer.machine)
+ view = {
+ agents: answer.agents as Viewed[],
+ machine: { id: text(machine.id), computerId: text(machine.computerId) || options.machineId, name: text(machine.name) || 'This machine' },
+ signedIn: answer.signedIn === true,
+ environment: text(answer.environment),
+ hasWindow: answer.hasWindow === true,
+ }
+ }).catch(() => { /* the core went away; its next connection is asked again */ }).finally(() => { viewing = null })
+ viewing = asking
+ return asking
+ }
+ const ask = async (query: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> => {
+ if (!core) throw new Error('the devices are not connected to the core')
+ return core.query(query, payload)
+ }
+ const tell = (kind: string, payload: Record<string, unknown> = {}): void => { core?.notice?.(kind, payload) }
+
+ // What the devices never ask of the core, answered as every service in its own process answers it.
+ const unasked = processCoreApi(options.dataDir, 'devices')
+ const account = accountLink((query, payload) => ask(query, payload))
+ const api: CoreApi = {
+ dataDir: options.dataDir,
+ // Terminals are launched by the core alone (#893).
+ terminals: TERMINALS_OFF,
+ machine: { id: () => view.machine.id, computerId: () => view.machine.computerId, name: () => view.machine.name },
+ agents: {
+ all: () => view.agents,
+ live: () => view.agents,
+ advertised: () => view.agents,
+ displayName: (session) => (session as Viewed).displayName ?? '',
+ byAgent: (agentId) => view.agents.find((agent) => agent.agentId === agentId),
+ resolve: (id) => resolveAgent(view.agents, id),
+ terminalAvailable: () => true,
+ sync: () => {},
+ runtimeModels: async (agentId) => ((await ask('models', { agentId })).models ?? []) as RuntimeModelOption[],
+ runtimeProfile: (session) => (session as Viewed).runtimeProfile ?? null,
+ setRuntime: (agentId, model, effort) => tell('setRuntime', { agentId, model, effort }),
+ fork: async (agentId) => {
+ const { requestId: _id, ...result } = await ask('fork', { agentId })
+ return result as unknown as ForkResult
+ },
+ activityText: async (agentId) => {
+ const said = (await ask('activityText', { agentId })).text
+ return typeof said === 'string' ? said : null
+ },
+ // The devices make no agent of their own and show no harness's viewer.
+ ...AGENT_ACTIONS_OFF,
+ },
+ turns: {
+ send: (agentId, said) => tell('turn', { agentId, text: said }),
+ stop: (agentId) => tell('stop', { agentId }),
+ recent: async (agentId, n) => ((await ask('recent', { agentId, n })).turns ?? []) as RecentTurn[],
+ asks: async (agentId) => strings((await ask('asks', { agentId })).asks),
+ // The devices deliver no turns of their own under an id: a dial's turn is `send`.
+ ...DELIVERIES_OFF,
+ },
+ questions: {
+ answer: (agentId, requestId, answers) => tell('answer', { agentId, requestId, answers }),
+ answerReviewed: async (answer) => (await ask('answerReviewed', { answer })).ok === true,
+ },
+ transcripts: unasked.transcripts,
+ external: unasked.external,
+ account: {
+ ...unasked.account,
+ // The core's sign-in and the gateway's seal, asked at every use: this process holds no credential and
+ // no E2EE identity (services/accountLink.ts).
+ ...account,
+ signedIn: () => view.signedIn,
+ environment: () => view.environment,
+ machines: async () => {
+ const answer = await ask('machines')
+ return { status: typeof answer.status === 'number' ? answer.status : 502, body: object(answer.body) }
+ },
+ },
+ clients: {
+ ...unasked.clients,
+ sendLocal: (frame) => tell('sendLocal', { frame }),
+ // Told, not asked: a bridge answers a window that has gone by its own deadline either way.
+ sendToWindow: (connId, frame) => { tell('sendToWindow', { connId, frame }); return core !== null },
+ hasWindow: () => view.hasWindow,
+ devicesChanged: (payload) => tell('devicesChanged', payload),
+ dialWatching: (watching) => tell('dialWatching', { watching }),
+ windows: () => {},
+ },
+ daemon: DAEMON_UNKNOWN,
+ }
+
+ const ports: CorePorts = emptyPorts()
+ const deps: DevicesDeps = {
+ logsDir: env.HARNESS_LOGS_DIR,
+ dialSerials: processEnv.HARNESS_DIAL_SERIALS?.split(',').map((serial) => serial.trim()).filter(Boolean),
+ testDialPort: processEnv.HARNESSD_TEST_DIAL_PORT,
+ cableDisabled: env.CABLE_DISABLE,
+ faults: faultsOf(processEnv.HARNESSD_TEST_FAULTS),
+ refresh,
+ }
+ const requests = (options.start ?? startDevices)(api, ports, deps)
+ const port = ports.devices as DevicesPort
+
+ /** What the core tells the devices (`service_event`), by kind: the port's own calls, across the link. */
+ const heard: Record<string, (payload: Record<string, unknown>) => void> = {
+ card: ({ frame }) => port.card(object(frame)),
+ desk: ({ agentIds, foreground }) => port.desk(strings(agentIds), foreground !== false),
+ swarms: ({ swarms }) => port.swarms(swarms && typeof swarms === 'object' ? swarms as AppSwarms : null),
+ unread: ({ items }) => port.unread(Array.isArray(items) ? items as UnreadNotification[] : []),
+ appFocus: ({ machineId, agentId }) => port.appFocus(text(machineId), text(agentId)),
+ seen: ({ agentId, readToken }) => port.seen(text(agentId), typeof readToken === 'string' ? readToken : undefined),
+ settings: ({ id, patch }) => port.settings(text(id), object(patch)),
+ windowFocus: ({ focus }) => port.windowFocus(focusOf(focus)),
+ windowReply: ({ which, connId, machineId, reply }) =>
+ port.windowReply(which === 'form' ? 'form' : which === 'visit' ? 'visit' : 'selection', text(connId), text(machineId), object(reply)),
+ voiceReply: ({ voiceId, reply }) => port.voiceReply(text(voiceId), object(reply) as unknown as VoiceRouteReply),
+ windowGone: ({ connId }) => port.windowGone(text(connId)),
+ scroll: ({ phase, dy, velocity }) => { if (phase === 'down' || phase === 'move' || phase === 'up') port.scroll(phase, number(dy), number(velocity)) },
+ engines: ({ engines }) => port.engines(strings(engines)),
+ commanders: ({ connected }) => port.commanders(connected === true),
+ // Everything at once, as the core keeps it: this process (re)connected, and starts where the windows are.
+ // What a window has not said is not said to the dial: a fresh process holds nothing yet, and a dial still
+ // attached through a core's restart keeps its tab until the windows, reconnecting, say theirs again.
+ // Pushed regardless, an empty tab reached a dial still opening its port, before its greeting, which no
+ // build before this one sent (e2e/deviceCompat.e2e.ts).
+ state: (state) => {
+ const desk = strings(state.desk)
+ if (desk.length) port.desk(desk, state.foreground !== false)
+ if (state.swarms && typeof state.swarms === 'object') port.swarms(state.swarms as AppSwarms)
+ if (Array.isArray(state.unread) && state.unread.length) port.unread(state.unread as UnreadNotification[])
+ port.windowFocus(focusOf(state.focus))
+ port.engines(strings(state.engines))
+ port.commanders(state.commanders === true)
+ },
+ }
+
+ const devices: ServiceRequests = {
+ ...requests,
+ // What the core asks of the devices (core/devicesLink.ts), under types only the core sends: no client's
+ // request is routed here under these names (core/serviceLinks.ts routes the Devices tab's alone).
+ routeTask: async ({ text: task }) => ({ ...await port.routeTask(text(task)) }),
+ routeSend: async ({ agentId, text: task }) => ({ ...await port.routeSend(text(agentId), text(task)) }),
+ stepFocus: async ({ direction, currentAgentId }) => {
+ const step = await port.stepFocus(direction === 'previous' ? 'previous' : 'next', typeof currentAgentId === 'string' ? currentAgentId : undefined)
+ return step === 'no_agents' ? { step } : { ...step }
+ },
+ }
+
+ const service = (options.run ?? runServiceProcess)({
+ name: 'devices',
+ socketPath: options.socketPath,
+ machineId: options.machineId,
+ token: options.token,
+ requests: devices,
+ onEvent: (payload) => {
+ const kind = text(payload.kind)
+ if (Object.hasOwn(heard, kind)) heard[kind](payload)
+ },
+ onConnected: (connection) => {
+ core = connection
+ void refresh()
+ },
+ onDisconnected: () => { core = null },
+ })
+ return {
+ stop: async () => {
+ service.stop()
+ // The serial ports first and on the way out: a port this process still held would make the next
+ // devices process, and esptool, fail as if the hardware had died.
+ await port.stop()
+ },
+ }
+}
diff --git a/cli/src/services/fleet.spec.ts b/cli/src/services/fleet.spec.ts
index e7137e0b6..0eb6b0a8e 100644
--- a/cli/src/services/fleet.spec.ts
+++ b/cli/src/services/fleet.spec.ts
@@ -179,7 +179,7 @@ describe('this computer’s side of every route', () => {
fork: vi.fn(async () => ({ ok: true as const, agentId: 'a1-fork' })),
runtimeModels: vi.fn(async () => [{ id: 'opus', displayName: 'Opus' }]),
},
- turns: { recent: vi.fn(() => [{ recap: 'Done', text: 'Done' }]), asks: vi.fn(() => ['what next?']) },
+ turns: { recent: vi.fn(async () => [{ recap: 'Done', text: 'Done' }]), asks: vi.fn(async () => ['what next?']) },
questions: { answerReviewed: vi.fn(async () => true) },
})
// Asked as the dial asks it: through the port, the router's own answers.
@@ -250,7 +250,7 @@ describe('⌘K: which agent a typed task belongs to', () => {
it('weighs every agent it knows with the person’s own questions, and remembers who they were just talking to', async () => {
const core = fakeCore({
agents: { advertised: vi.fn(() => [session('a1'), session('a2', 2, 'codex')]), displayName: vi.fn((s: RegisteredSession) => `name-${s.agentId}`) },
- turns: { asks: vi.fn((agentId: string) => (agentId === 'a1' ? [' fix the\nparser '] : [])) },
+ turns: { asks: vi.fn(async (agentId: string) => (agentId === 'a1' ? [' fix the\nparser '] : [])) },
})
const { fleet } = setup({}, core)
route.mockResolvedValue(decision({ agentId: 'a2', confidence: 0.8, reason: 'parser work', via: 'claude' }))
diff --git a/cli/src/services/fleet.ts b/cli/src/services/fleet.ts
index 99ece81a4..a9ef507fb 100644
--- a/cli/src/services/fleet.ts
+++ b/cli/src/services/fleet.ts
@@ -115,6 +115,8 @@ export interface FleetDeps {
machines: MachineListCache
/** The window's tiles on its active tab, in tile order, as it last reported them. */
desk(): string[]
+ /** Read this computer's agents again before a list is built from them (FleetLocal.refresh). */
+ refresh?: () => Promise<void>
}
/** Start the fleet: what ⌘K and the dial reach it through. The router itself is returned beside it, for
@@ -164,6 +166,7 @@ export function startFleet(core: CoreApi, deps: FleetDeps): { fleet: Fleet; rout
machineId: () => core.machine.id(),
computerId: () => core.machine.computerId(),
sessions: () => core.agents.advertised(),
+ refresh: deps.refresh,
displayName: (session) => core.agents.displayName(session),
runtimeProfile: (session) => core.agents.runtimeProfile(session),
desk: () => deps.desk(),
diff --git a/cli/src/services/fleetRouter.ts b/cli/src/services/fleetRouter.ts
index bc3b84652..c4384e141 100644
--- a/cli/src/services/fleetRouter.ts
+++ b/cli/src/services/fleetRouter.ts
@@ -49,9 +49,12 @@ export interface FleetLocal {
answer: (agentId: string, requestId: string, answers: Record<string, string>) => void
answerReviewed?: (answer: ReviewedAnswer) => Promise<boolean>
/** Recaps of a local agent's last `n` completed turns. */
- recent: (agentId: string, n: number) => RecentTurn[]
+ recent: (agentId: string, n: number) => RecentTurn[] | Promise<RecentTurn[]>
/** The person's own last questions to a LOCAL agent, newest first. */
- recentAsks: (agentId: string) => string[]
+ recentAsks: (agentId: string) => string[] | Promise<string[]>
+ /** Read this computer's agents again before a list is built from them: the devices in their own process
+ * keep a copy of them, asked of the core when the dial's tick or ⌘K needs it. */
+ refresh?: () => Promise<void>
updateAgent?: (agentId: string, model?: string, effort?: string) => void
listModels?: (agentId: string) => Promise<Array<{ id: string }>>
/** Fork a LOCAL agent — see lib/forkAgent.ts. Resolves to the new agent's id. */
@@ -230,6 +233,7 @@ export class FleetRouter implements FleetRouting {
* `refreshRemotes()` does the asking, off to the side, on its own slower clock.
*/
async listAgentsFlat(): Promise<CableAgent[]> {
+ await this.local.refresh?.()
const out = this.localAgents()
const { machines } = await this.listMachines()
this.machineNames = new Map(machines.map((m) => [m.id, m.name]))
@@ -527,7 +531,7 @@ export class FleetRouter implements FleetRouting {
/** The last few turns, newest first, in the shape the dial's tile draws: a headline and a body. */
async recentSummaries(agentId: string): Promise<Array<{ recap: string; text: string; ask: string }>> {
const raw = this.isLocalAgent(agentId)
- ? this.local.recent(agentId, 3)
+ ? await this.local.recent(agentId, 3)
: await this.fleet!.recentSummaries(this.machineOf(agentId), agentId)
return raw
.map((r) => ({ recap: extendShortRecap(r?.recap ?? '', r?.text ?? ''), text: r?.text ?? '', ask: r?.ask ?? '' }))
@@ -544,7 +548,7 @@ export class FleetRouter implements FleetRouting {
*/
async recentAsks(agentId: string): Promise<string[]> {
const raw = this.isLocalAgent(agentId)
- ? this.local.recentAsks(agentId)
+ ? await this.local.recentAsks(agentId)
: await this.fleet!.recentAsks(this.machineOf(agentId), agentId)
return raw.map((a) => (a || '').replace(/\s+/g, ' ').trim()).filter(Boolean)
}
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index 0489ee559..64f6e590b 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { startGateway } from '../gateway/start.js'
+import { startDevices } from './devices.js'
import * as inline from './inline.js'
import { startModels } from './models.js'
import { startTeamsInCore } from './collaboration.js'
@@ -15,6 +16,6 @@ import { startWorkspaces } from './workspaces.js'
describe('the services the core runs in its own process only when they do not run in theirs', () => {
it('are their own starts, unchanged: the same services either way', () => {
- expect({ ...inline }).toEqual({ startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWorkspaces })
+ expect({ ...inline }).toEqual({ startDevices, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index 051e1abba..1810938dd 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -13,6 +13,7 @@
* declared in core/api.ts, which it loads either way.
*/
export { startGateway } from '../gateway/start.js'
+export { startDevices } from './devices.js'
export { startModels } from './models.js'
export { startTeamsInCore } from './collaboration.js'
export { startMonitor } from './monitor.js'
diff --git a/cli/src/services/modelsProcess.spec.ts b/cli/src/services/modelsProcess.spec.ts
index a42da13ee..668d937f7 100644
--- a/cli/src/services/modelsProcess.spec.ts
+++ b/cli/src/services/modelsProcess.spec.ts
@@ -236,7 +236,7 @@ describe('the core API models runs on in its own process', () => {
expect(await api.agents.fork('a1')).toEqual({ ok: false, error: 'UNSUPPORTED' })
api.turns.send('a1', 'x')
api.turns.stop('a1')
- expect([api.turns.recent('a1', 1), api.turns.asks('a1')]).toEqual([[], []])
+ expect(await Promise.all([api.turns.recent('a1', 1), api.turns.asks('a1')])).toEqual([[], []])
api.questions.answer('a1', 'r', {})
expect(await api.questions.answerReviewed({} as never)).toBe(false)
expect(api.transcripts.databaseHistory({} as never)).toBeUndefined()
diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.ts
index dd3fe5848..661e779b1 100644
--- a/cli/src/services/modelsProcess.ts
+++ b/cli/src/services/modelsProcess.ts
@@ -78,7 +78,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: Pa
...AGENT_ACTIONS_OFF,
activityText: UNASKED.activityText,
},
- turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },
+ turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },
questions: { answer: () => {}, answerReviewed: async () => false },
transcripts: { databaseHistory: () => undefined },
external: {
diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.ts
index ef310de41..a4188e898 100644
--- a/cli/src/services/processCoreApi.spec.ts
+++ b/cli/src/services/processCoreApi.spec.ts
@@ -34,8 +34,8 @@ describe('the core API a light service runs on in its own process', () => {
await expect(api.agents.fork('a1')).resolves.toEqual({ ok: false, error: 'UNSUPPORTED' })
api.turns.send('a1', 'text')
api.turns.stop('a1')
- expect(api.turns.recent('a1', 3)).toEqual([])
- expect(api.turns.asks('a1')).toEqual([])
+ expect(await api.turns.recent('a1', 3)).toEqual([])
+ expect(await api.turns.asks('a1')).toEqual([])
api.questions.answer('a1', 'q', {})
await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)
expect(api.transcripts.databaseHistory(agent('a1'))).toBeUndefined()
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index b2eaa4378..13eee8233 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -114,8 +114,8 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
turns: {
send: () => {},
stop: (agentId) => { void ask?.('stop_turn', { agentId }).catch(() => {}) },
- recent: () => [],
- asks: () => [],
+ recent: async () => [],
+ asks: async () => [],
...(view.deliveries?.turns ?? DELIVERIES_OFF),
},
questions: { answer: () => {}, answerReviewed: async () => false },
diff --git a/cli/src/services/searchProcess.spec.ts b/cli/src/services/searchProcess.spec.ts
index 43051daf3..1af49673a 100644
--- a/cli/src/services/searchProcess.spec.ts
+++ b/cli/src/services/searchProcess.spec.ts
@@ -128,8 +128,8 @@ describe('search in its own process', () => {
await expect(api.agents.fork('live')).resolves.toEqual({ ok: false, error: 'UNSUPPORTED' })
api.turns.send('live', 'text')
api.turns.stop('live')
- expect(api.turns.recent('live', 3)).toEqual([])
- expect(api.turns.asks('live')).toEqual([])
+ expect(await api.turns.recent('live', 3)).toEqual([])
+ expect(await api.turns.asks('live')).toEqual([])
api.questions.answer('live', 'q', {})
await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)
expect(api.transcripts.databaseHistory({ engine: 'claude' } as never)).toBeUndefined()
diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.ts
index c79755349..4ae80f73b 100644
--- a/cli/src/services/searchProcess.ts
+++ b/cli/src/services/searchProcess.ts
@@ -60,7 +60,7 @@ export function searchCoreApi(
activityText: UNASKED.activityText,
},
// Search drives no agent: these are never asked of it.
- turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },
+ turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },
questions: { answer: () => {}, answerReviewed: async () => false },
transcripts: { databaseHistory },
external: {
diff --git a/cli/src/services/viewersProcess.spec.ts b/cli/src/services/viewersProcess.spec.ts
index 97c29286b..41c67cfdf 100644
--- a/cli/src/services/viewersProcess.spec.ts
+++ b/cli/src/services/viewersProcess.spec.ts
@@ -230,8 +230,8 @@ describe('the viewers in their own process', () => {
await expect(api.agents.fork('a1')).resolves.toEqual({ ok: false, error: 'UNSUPPORTED' })
api.turns.send('a1', 'text')
api.turns.stop('a1')
- expect(api.turns.recent('a1', 3)).toEqual([])
- expect(api.turns.asks('a1')).toEqual([])
+ expect(await api.turns.recent('a1', 3)).toEqual([])
+ expect(await api.turns.asks('a1')).toEqual([])
api.questions.answer('a1', 'q', {})
await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)
api.clients.gridNamed('grid')
diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.ts
index 4554b56a8..945acb9aa 100644
--- a/cli/src/services/viewersProcess.ts
+++ b/cli/src/services/viewersProcess.ts
@@ -67,7 +67,7 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, Re
activityText: UNASKED.activityText,
},
// The viewers drive no agent: these are never asked of them.
- turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },
+ turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },
questions: { answer: () => {}, answerReviewed: async () => false },
transcripts: { databaseHistory: () => undefined },
external: {
diff --git a/cli/src/services/workspacesProcess.spec.ts b/cli/src/services/workspacesProcess.spec.ts
index c2498338a..8c34a926e 100644
--- a/cli/src/services/workspacesProcess.spec.ts
+++ b/cli/src/services/workspacesProcess.spec.ts
@@ -173,8 +173,8 @@ describe('workspaces in their own process', () => {
await expect(api.agents.fork('a1')).resolves.toEqual({ ok: false, error: 'UNSUPPORTED' })
api.turns.send('a1', 'text')
api.turns.stop('a1')
- expect(api.turns.recent('a1', 3)).toEqual([])
- expect(api.turns.asks('a1')).toEqual([])
+ expect(await api.turns.recent('a1', 3)).toEqual([])
+ expect(await api.turns.asks('a1')).toEqual([])
api.questions.answer('a1', 'q', {})
await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)
api.clients.gridModelsChanged()
diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.ts
index da094c21d..80c59cedd 100644
--- a/cli/src/services/workspacesProcess.ts
+++ b/cli/src/services/workspacesProcess.ts
@@ -69,7 +69,7 @@ export function workspacesCoreApi(
activityText: UNASKED.activityText,
},
// The workspaces drive no agent: these are never asked of them.
- turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },
+ turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },
questions: { answer: () => {}, answerReviewed: async () => false },
transcripts: { databaseHistory: () => undefined },
external: {
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index 29a566c6f..56e7260b0 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -36,7 +36,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {
...over.agents,
},
turns: {
- send: vi.fn(), stop: vi.fn(), recent: vi.fn(() => []), asks: vi.fn(() => []),
+ send: vi.fn(), stop: vi.fn(), recent: vi.fn(async () => []), asks: vi.fn(async () => []),
deliver: vi.fn(), cancelDelivery: vi.fn(() => false), onDelivery: vi.fn(() => () => {}),
...over.turns,
},
diff --git a/cli/src/testing/teamFixture.ts b/cli/src/testing/teamFixture.ts
index 23b8b3498..69e129022 100644
--- a/cli/src/testing/teamFixture.ts
+++ b/cli/src/testing/teamFixture.ts
@@ -50,7 +50,7 @@ export function attachTeams<T extends BackendSocket>(socket: T): T & TeamFixture
activityText: UNASKED.activityText,
},
turns: {
- send: () => {}, stop: () => {}, recent: () => [], asks: () => [],
+ send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [],
...DELIVERIES_OFF,
deliver: (agentId, text, deliveryId) => socket.onMessage?.(agentId, text, deliveryId),
cancelDelivery: (deliveryId) => socket.onCancelOrchestratorMessage?.(deliveryId) ?? false,
diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.md
index bb73cdfe3..db62655ea 100644
--- a/docs/design/2026-10-03-harnessd.md
+++ b/docs/design/2026-10-03-harnessd.md
@@ -270,7 +270,18 @@ The steps, each a pull request with its end-to-end proof:
for itself (`services/devicesGuard.ts`): a dial throwing costs ⌘K nothing, a fleet that cannot start
costs the dial nothing. ⌘K's answers are sent off the window's ordered chain, so they can come from
another process without holding the window's typing.
-- **D2, the dial in its own process.** Sized on 2026-10-05 against the viewers' process (#775): it
+- **D2, the dial in its own process (done, 6 October).** `harness __service devices`
+ (services/devicesProcess.ts; the core's side is core/devicesLink.ts) runs the dials, the window bridges,
+ the fleet's router and lane, the voice router and the Devices tab. The ten routing reads stay in line:
+ the router is in the same process as the dial, and what it reads of the core (the agents with their
+ names and models, this computer, the sign-in, whether a window is there) is a copy asked of the core as
+ the dial's tick or ⌘K builds a list. The core never waits on the process: what it tells it is a notice,
+ what it asks (⌘K, the Wi-Fi device's walk) has a deadline and a fallback, and ⌘K is answered off the
+ window's ordered chain. The core keeps what the windows said, says it again when the process connects,
+ and keeps whether a dial is watching; a dial attaching is shown the open questions and the working
+ tiles. One device failing is that device's alone: its session's faults and a flood on its port drop it,
+ with a wait before its port is looked at again (cable/cableFleet.ts). The original sizing:
+ Sized on 2026-10-05 against the viewers' process (#775): it
is several times larger. Viewers cross the link in about five calls; the dial needs about fifteen
from the core (the desk, swarms, unread, focus, seen, settings, status, the six kinds of turn and
question card teed to it, the remote cards) and about twenty-five back (the local doors, seven