The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: maintain persistent device socket for machine presence tracking even when unattached
0xken153d5de672ee73
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.tsindex 8b5849d78..c2910e845 100644--- a/cli/src/cable/cableHost.spec.ts+++ b/cli/src/cable/cableHost.spec.ts@@ -30,6 +30,7 @@ function wiring(over: Partial<CableHostWiring> = {}): CableHostWiring {function fleetOf(machines: FleetMachine[]): MachineFleet {return {list: async () => ({ machines, source: 'backend' as const }),+ online: async () => {},select: async () => {},release: vi.fn(),listAgents: async () => [],@@ -76,9 +77,10 @@ describe('DaemonCableHost.listMachines', () => {expect(machines[0].local).toBe(true)})- it('falls back to a cable: id when the daemon has never resolved a machineId', async () => {- // Signed out, or offline before the first resolve. The row must still exist and still be selectable —- // it is the one machine that is certainly reachable.+ it('falls back to a placeholder id rather than an empty one', async () => {+ // A belt, not a mode: `harness start` refuses to run signed out and resolves the machineId before the+ // daemon spawns, so this should never happen. It is guarded because the alternative is silent — an+ // empty id renders a row that is tappable and can never be selected.const host = new DaemonCableHost(wiring({ machineId: () => '' }))const { machines } = await host.listMachines()expect(machines[0].id).toBe('cable:abc-123')@@ -117,3 +119,82 @@ describe('DaemonCableHost.listAgents', () => {expect((await new DaemonCableHost(wiring()).listAgents()).map((a) => a.id)).toEqual(['aa', 'zz'])})})++describe('the cloud lane follows the CABLE, not the selection', () => {+ const remoteFleet = () => {+ const f = fleetOf([REMOTE])+ f.online = vi.fn(async () => {})+ f.select = vi.fn(async () => {})+ f.release = vi.fn()+ return f+ }++ it('drops the lane the moment the dial goes away', async () => {+ // Held on the dial's behalf and used by nothing else here. Keeping it open leaves the account showing+ // a device attached to a machine while the dial sits unplugged in a drawer, with that machine's cards+ // relayed to a screen that is not there.+ const fleet = remoteFleet()+ const host = new DaemonCableHost(wiring(), fleet)+ await host.selectMachine('other')++ host.onDialGone()+ expect(fleet.release).toHaveBeenCalledWith(true) // true = now, not after the linger+ })++ it('drops it even when the dial was on the local machine — cancelling a linger', () => {+ const fleet = remoteFleet()+ const host = new DaemonCableHost(wiring(), fleet)+ host.onDialGone()+ expect(fleet.release).toHaveBeenCalledWith(true)+ })++ it('opens the socket the moment the dial appears, whatever is selected', async () => {+ // The whole point: plugged in means online. The wheel's dots are live from that moment, instead of+ // waiting for the user to pick a machine that is not this computer.+ const fleet = remoteFleet()+ const host = new DaemonCableHost(wiring(), fleet)+ host.onDialAttached()+ await new Promise((r) => setTimeout(r, 0))+ expect(fleet.online).toHaveBeenCalled()+ })++ it('announces the selected machine on attach — including the local one', async () => {+ // `DeviceBinding.activeMachineId` is what the web and the mobile app read to say where a dial is.+ // Skipping the local machine leaves it naming whatever was selected last, forever.+ const fleet = remoteFleet()+ const host = new DaemonCableHost(wiring(), fleet)+ host.onDialAttached()+ await new Promise((r) => setTimeout(r, 0))+ expect(fleet.select).toHaveBeenCalledWith('mine')+ })++ it('announces a remote selection after a replug', async () => {+ const fleet = remoteFleet()+ const host = new DaemonCableHost(wiring(), fleet)+ await host.selectMachine('other')+ ;(fleet.select as ReturnType<typeof vi.fn>).mockClear()++ host.onDialAttached()+ await new Promise((r) => setTimeout(r, 0))+ expect(fleet.select).toHaveBeenCalledWith('other')+ })++ it('announces nothing for the placeholder id — it is not a machineId', async () => {+ const fleet = remoteFleet()+ const host = new DaemonCableHost(wiring({ machineId: () => '' }), fleet)+ host.onDialAttached()+ await new Promise((r) => setTimeout(r, 0))+ expect(fleet.online).toHaveBeenCalled()+ expect(fleet.select).not.toHaveBeenCalled()+ })++ it('survives a lane that will not reopen, instead of rejecting into the greeting', async () => {+ const fleet = remoteFleet()+ const host = new DaemonCableHost(wiring(), fleet)+ await host.selectMachine('other')+ ;(fleet.select as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('unreachable'))++ expect(() => host.onDialAttached()).not.toThrow()+ await new Promise((r) => setTimeout(r, 0)) // let the rejection land on its catch+ })+})diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 5a57bcc05..182d5f344 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -49,11 +49,24 @@ export interface CableHostWiring {log: (line: string) => void}-/** How the local row names itself before the daemon has ever resolved a machineId for this computer. */-function localFallbackId(computerId: string): string {+/**+ * A placeholder id for a machine this daemon does not know the real id of.+ *+ * A BELT, not a mode. `harness start` refuses to run without an SSO session and awaits+ * `resolveComputerMachine()` before it spawns the daemon, so by the time anything here runs the machineId+ * is real. The guard exists because the alternative failure is silent: an empty id makes a row that+ * renders, is tappable, and can never be selected. `cable:` is deliberately not machineId-shaped, so+ * nothing downstream mistakes it for one and announces it to the backend.+ */+function placeholderId(computerId: string): string {return `cable:${computerId}`}+/** Whether an id is that placeholder rather than a machine the backend has heard of. */+function isPlaceholder(id: string): boolean {+ return id.startsWith('cable:')+}+/** A fleet row as the wire carries it. `authMode` does not travel: the dial has no use for the word, and* `remote` is just `!local`, which the row already says. */function toCableMachine(m: FleetMachine): CableMachine {@@ -89,7 +102,7 @@ export class DaemonCableHost implements CableHost {}private localId(): string {- return this.wiring.machineId() || localFallbackId(this.wiring.computerId())+ return this.wiring.machineId() || placeholderId(this.wiring.computerId())}/** Whether the dial is looking at THIS computer. Everything forks on this one question. */@@ -126,8 +139,12 @@ export class DaemonCableHost implements CableHost {async selectMachine(machineId: string): Promise<{ ok: true } | { ok: false; code: string; message: string }> {if (machineId === this.localId()) {- this.fleet?.release()this.selected = machineId+ // Let go of the REMOTE machine after a linger, keeping the socket — then announce where the dial+ // actually is. `activeMachineId` on the account is then true for this machine too, instead of+ // silently going stale on whatever was selected last.+ this.fleet?.release()+ void this.announceSelection()return { ok: true }}if (!this.fleet) {@@ -143,6 +160,60 @@ export class DaemonCableHost implements CableHost {return { ok: true }}+ /**+ * The dial is on the wire again.+ *+ * If it left looking at another machine, the cloud lane has to be back UP before the state push that+ * follows — that push calls listAgents(), which for a remote machine is an RPC over exactly this lane.+ * Awaiting it here would block the greeting, so it is fired and the push retries on the next tick if+ * it loses the race; a failure marks the machine unreachable rather than pretending it has no agents.+ */+ onDialAttached(): void {+ if (!this.fleet) return+ const fleet = this.fleet+ this.wiring.log('cable: dial on the wire — opening the cloud lane')+ void (async () => {+ // The socket first, and unconditionally: it is what makes the machine wheel's dots live, and it is+ // held for as long as the dial is plugged in whether or not anything is selected.+ await fleet.online()+ await this.announceSelection()+ })().catch((err) => this.wiring.log(`cable: could not open the lane (${(err as Error).message})`))+ }++ /**+ * Tell the backend which machine the dial is on.+ *+ * Sent for the LOCAL machine too. It costs one frame and it is the only thing that makes+ * `DeviceBinding.activeMachineId` true rather than "whatever was selected last" — which is what the web+ * and the mobile app read to say where a dial is.+ *+ * Skipped only for the placeholder id, which is not a machineId and means nothing to the backend.+ */+ private async announceSelection(): Promise<void> {+ if (!this.fleet) return+ const machineId = this.selectedMachine()+ if (isPlaceholder(machineId)) return+ try {+ await this.fleet.select(machineId)+ } catch (err) {+ // Never fatal. The local machine in particular must stay usable with no backend at all — it is the+ // one machine the cable can vouch for on its own.+ this.wiring.log(`cable: could not announce ${machineId} (${(err as Error).message})`)+ }+ }++ /**+ * The dial is gone — cable pulled, or the far end stopped answering.+ *+ * Drop the lane NOW rather than lingering. The daemon holds it on the dial's behalf and nothing else in+ * this process uses it, so keeping it open leaves the account showing a device attached to a machine+ * while the dial sits unplugged in a drawer — and every card that machine produces would be relayed to+ * a screen that is not there.+ */+ onDialGone(): void {+ this.fleet?.release(true)+ }+machineName(): string {return this.wiring.machineName()}diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex a4a0bc497..2fc66335e 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -26,7 +26,10 @@ class LoopbackPort implements CablePort {private decoder = new CableDecoder()- constructor(private readonly onData: (chunk: Buffer) => void) {}+ constructor(+ private readonly onData: (chunk: Buffer) => void,+ private readonly onClosed: (why: string) => void = () => {},+ ) {}async write(bytes: Uint8Array): Promise<void> {this.frames.push(bytes)@@ -38,8 +41,11 @@ class LoopbackPort implements CablePort {}async close(why = 'closed'): Promise<void> {+ if (!this.isOpen) returnthis.isOpen = falsethis.closedWith = why+ // SerialLink announces its own close; a fake that stays quiet makes "the dial went away" untestable.+ this.onClosed(why)}/** Speak as the dial. */@@ -97,8 +103,8 @@ function makeHost(over: Partial<CableHost> = {}) {/** Start a session on a loopback and hand back both ends. Never touches the real serial layer. */async function connect(host: CableHost = makeHost(), logPath = '/dev/null') {let port!: LoopbackPort- const session = new CableSession(host, logPath, async (onData) => {- port = new LoopbackPort(onData)+ const session = new CableSession(host, logPath, async (onData, onClosed) => {+ port = new LoopbackPort(onData, onClosed)return port})session.start()@@ -586,4 +592,24 @@ describe('cable session', () => {expect(open, 'a begin was never closed').toBe(false)await session.stop()})+ it('tells the host when the dial arrives and when it goes', async () => {+ // The daemon's cloud lane is held on the dial's behalf, so these two are what open and close it. A+ // port that goes silent must look identical to a cable that was pulled — both are "no dial".+ const host = makeHost()+ host.onDialAttached = vi.fn()+ host.onDialGone = vi.fn()+ const { session, port } = await connect(host)++ port.say({ t: 'hello', mac: 'aa:bb' })+ await vi.waitFor(() => expect(host.onDialAttached).toHaveBeenCalledTimes(1))++ // A keepalive greeting from the same dial is not a new arrival — re-opening the lane on every one+ // would dial the cloud every fifteen seconds for as long as the dial sits there.+ port.say({ t: 'hello', mac: 'aa:bb' })+ await settle()+ expect(host.onDialAttached).toHaveBeenCalledTimes(1)++ await session.stop()+ expect(host.onDialGone).toHaveBeenCalled()+ })})diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex 5b960c8bf..dc95cb9af 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -123,6 +123,15 @@ export interface CableHost {* dial that is current, a dev build that must not be touched, and an unreachable manifest.*/firmwareFor?(runningVersion: string): Promise<{ version: string; image: Buffer; sha256: string } | null>+ /**+ * A dial greeted us, or the port went away.+ *+ * The daemon holds its cloud lane ON THE DIAL'S BEHALF — nothing else in this process uses it. So with+ * no dial there is nobody to hold it for, and holding it anyway leaves the account showing a device+ * that is attached to a machine while sitting unplugged in a drawer.+ */+ onDialAttached?(): void+ onDialGone?(): voidlog(line: string): void}@@ -234,6 +243,8 @@ export class CableSession {// Rule 2. The read never fails on a dead handle, so silence is the only symptom there is.if (Date.now() - this.lastRx > SILENCE_MS) {this.host.log('cable: silent, reopening the port')+ // close() runs onClosed, which is where onDialGone fires — one path for "the dial is not there",+ // whether the cable was pulled or the far end simply stopped answering.await this.link.close('silence')this.link = nullreturn@@ -324,6 +335,7 @@ export class CableSession {private onClosed(why: string): void {this.host.log(`cable: closed (${why})`)+ this.host.onDialGone?.()this.link = nullthis.greetedMac = nullthis.greetedFw = null@@ -397,6 +409,9 @@ export class CableSession {this.greetedMac = macthis.greetedFw = fwthis.host.log(`cable: dial ${mac} ${returning ? 'back ' : ''}on fw ${fw} proto ${msg.proto}`)+ // BEFORE the state push, not after: the push reads the selected machine, and for a remote one+ // that means an RPC over a lane this is what re-opens.+ this.host.onDialAttached?.()// Both halves of the test above mean the same thing to this line: a dial with nothing on its// screen. A repeat greeting from the same dial on the same image is a keepalive and is skipped,// which is the whole reason the branch exists.diff --git a/cli/src/cable/machineFleet.ts b/cli/src/cable/machineFleet.tsindex e03158db1..e9f1fa620 100644--- a/cli/src/cable/machineFleet.ts+++ b/cli/src/cable/machineFleet.ts@@ -48,10 +48,24 @@ export interface MachineFleet {* explains itself, and a dial whose daemon is offline still has one machine that works perfectly.*/list(): Promise<{ machines: FleetMachine[]; source: 'backend' | 'local' | 'signed-out' }>- /** Attach to a machine. Throws `FleetError` on refusal. */+ /**+ * Come online for the dial: hold a socket to the backend, attached to no machine.+ *+ * Connecting and attaching are different things. A held socket buys device presence and a LIVE machine+ * list — the wheel's dots stop being a REST snapshot up to a minute old — without making any machine+ * believe a commander is watching it.+ */+ online(): Promise<void>+ /** Attach to a machine, which is also how the backend learns where the dial is. Throws on refusal. */select(machineId: string): Promise<void>- /** Release whatever `select` acquired. Called when the dial goes back to the local machine. */- release(): void+ /**+ * Let go of whatever `select` acquired.+ *+ * `immediate` is the difference between "the user looked away" and "the dial is gone". Going back to+ * the local machine lingers, so flicking between two machines does not pay a dial each way; the cable+ * dropping closes the lane now, because the thing it was being held for is no longer there.+ */+ release(immediate?: boolean): voidlistAgents(machineId: string): Promise<CableAgent[]>sendTurn(machineId: string, agentId: string, text: string): voidstopTurn(machineId: string, agentId: string): voiddiff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 6c170b9a1..5868f76f7 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -2910,9 +2910,12 @@ async function runForeground(session: AuthSession): Promise<void> {// A remote machine's cards reach the dial through the SAME four calls the local tee uses, so a new// event kind lands on both surfaces the day it lands on either.fleet.onEvent((event) => {+ // A `state` event is about the WHEEL, not about a turn — live machine presence, which matters+ // whichever machine is selected. Filtering it with the guard below would freeze the dots the moment+ // the dial came back to this computer, which is where it sits most of the time.+ if (event.kind === 'state') { void cable.syncMachines(); return }if (cableHost.isLocalSelected()) return // the dial came back to this computer mid-flightif (event.kind === 'question') { void cable.question(event.agentId, event.requestId, event.questions); return }- if (event.kind === 'state') { void cable.syncMachines(true); return }if (event.kind === 'processing') void cable.turnStarted(event.agentId, event.text)else if (event.kind === 'done') void cable.turnDone(event.agentId)else if (event.kind === 'summary') void cable.summary(event.agentId, event.recap || event.text, event.text)diff --git a/cli/src/device/deviceFleet.spec.ts b/cli/src/device/deviceFleet.spec.tsindex 0221847df..6b36ceb40 100644--- a/cli/src/device/deviceFleet.spec.ts+++ b/cli/src/device/deviceFleet.spec.ts@@ -25,6 +25,8 @@ function make(over: { rows?: Partial<Listed>[]; linked?: string[]; rpc?: (t: strselectedMachine: 'm1',onFrame: (cb: (f: DeviceFrame) => void) => { frameCb = cb; return () => {} },attach: vi.fn(async () => {}),+ online: vi.fn(async () => {}),+ detach: vi.fn(),release: vi.fn(),send: (f: DeviceFrame) => { sent.push(f) },rpc: over.rpc ?? (async () => ({})),@@ -141,4 +143,84 @@ describe('DeviceFleet', () => {const { fleet } = make({ rpc: async () => { throw new Error('timed out') } })await expect(fleet.recentSummaries('m1', 'a1')).resolves.toEqual([])})++ it('selects THIS computer without asking for a pinned key', async () => {+ // Our own machine is `authMode: 'remote'` like any other computer-backed one and has no pin for+ // itself — nor does it need one: its agents are read in-process, never over the relay.+ const { fleet, link } = make({ rows: [{ machineId: 'mine', local: true, authMode: 'remote' }], linked: [] })+ await expect(fleet.select('mine')).resolves.toBeUndefined()+ expect(link.attach).toHaveBeenCalledWith('mine')+ })++ it('keeps the socket when the dial goes back to local, and drops it when the dial goes', () => {+ // Two different events. "Looked away" detaches from the machine but the wheel's dots must stay live;+ // "unplugged" takes the socket with it, because it was only ever held for the dial.+ const { fleet, link } = make()+ // Lingering: nothing happens yet, and when it does it DETACHES rather than closing.+ fleet.release(false)+ expect(link.release).not.toHaveBeenCalled()++ // Unplugged: the socket goes now.+ fleet.release(true)+ expect(link.release).toHaveBeenCalled()+ expect(link.detach).not.toHaveBeenCalled()+ })++ it('folds a live machines_status into the list and reports the change', () => {+ const rows = [{ machineId: 'm1', name: 'a', state: 'offline', authMode: 'remote', local: false }]+ const applied: unknown[] = []+ let frameCb!: (f: { type?: string; payload?: Record<string, unknown> }) => void+ const fleet = new DeviceFleet({+ list: {+ list: () => ({ machines: rows, source: 'backend' as const }),+ find: (id: string) => rows.find((r) => r.machineId === id),+ applyLive: (r: unknown) => { applied.push(r); return true },+ } as never,+ link: { selectedMachine: 'm1', onFrame: (cb: never) => { frameCb = cb; return () => {} } } as never,+ hasPeerLink: () => true,+ log: () => {},+ })+ const seen: string[] = []+ fleet.onEvent((e) => seen.push(e.kind))++ frameCb({ type: 'machines_status', payload: { statuses: [{ machineId: 'm1', online: true }] } })+ expect(applied).toHaveLength(1)+ expect(seen).toEqual(['state'])+ })++ it('does not filter machines_status by the selected machine', () => {+ // It is about the whole account, and it arrives while nothing at all is selected.+ let frameCb!: (f: { type?: string; machineId?: string; payload?: Record<string, unknown> }) => void+ const fleet = new DeviceFleet({+ list: { list: () => ({ machines: [], source: 'backend' as const }), find: () => undefined, applyLive: () => true } as never,+ link: { selectedMachine: 'm1', onFrame: (cb: never) => { frameCb = cb; return () => {} } } as never,+ hasPeerLink: () => true,+ log: () => {},+ })+ const seen: string[] = []+ fleet.onEvent((e) => seen.push(e.kind))+ frameCb({ type: 'machines_status', machineId: 'someone-else', payload: { statuses: [] } })+ expect(seen).toEqual(['state'])+ })++ it('reads nothing over the lane for THIS computer', async () => {+ // Selecting the local machine is an announcement, not an attach-to-read: its agents are in-process.+ // Asking the cloud round-trips to ourselves and is refused with E2EE_REQUIRED, because a+ // computer-backed machine is `authMode: 'remote'` — which is exactly what happened on hardware.+ const rpc = vi.fn(async () => ({ agents: [] }))+ const { fleet } = make({ rows: [{ machineId: 'mine', local: true, authMode: 'remote' }], linked: [], rpc })+ await fleet.select('mine')+ await new Promise((r) => setTimeout(r, 0))+ expect(rpc).not.toHaveBeenCalled()+ })++ it('drops our own cards when they come back the long way', () => {+ // Selecting the local machine attaches a commander to it, so everything this daemon emits is fanned+ // back down the socket — after the dial already had it in-process.+ const { fleet, say } = make({ rows: [{ machineId: 'mine', local: true }, { machineId: 'm1' }] })+ const seen: string[] = []+ fleet.onEvent((e) => seen.push(e.kind))+ say({ type: 'commander_event', machineId: 'mine', agentId: 'a1', payload: { kind: 'summary', recap: 'echo' } })+ expect(seen).toHaveLength(0)+ })})diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.tsindex 3cf146d5f..9f52dbfa1 100644--- a/cli/src/device/deviceFleet.ts+++ b/cli/src/device/deviceFleet.ts@@ -67,10 +67,23 @@ export class DeviceFleet implements MachineFleet {}}+ /**+ * The dial is plugged in: hold a socket for presence, attached to nothing.+ *+ * Cheap on purpose — see DeviceLink.online for why a held socket does not make any machine think a+ * commander is watching it.+ */+ async online(): Promise<void> {+ await this.opts.link.online()+ }+async select(machineId: string): Promise<void> {const row = this.opts.list.find(machineId)if (!row) throw new FleetError('UNKNOWN_MACHINE', 'That machine is not on your account')- if (row.authMode === 'remote' && !this.opts.hasPeerLink(machineId)) {+ // THIS computer is `authMode: 'remote'` like any other computer-backed machine, and it has no pinned+ // key for itself — nor does it need one. Selecting it announces where the dial is; the agents behind+ // it are read in-process, never over the relay, so there is nothing to encrypt and nothing to link.+ if (!row.local && row.authMode === 'remote' && !this.opts.hasPeerLink(machineId)) {// Checked HERE, locally and for free, so the guide appears instantly instead of after a connect// that was always going to fail.throw new FleetError('NEEDS_LINK', `Link ${row.name} to this computer first`)@@ -83,16 +96,31 @@ export class DeviceFleet implements MachineFleet {throw new FleetError(this.codeFor(message), this.messageFor(message, row.name))}this.recapCache.clear()+ // NOTHING is read over the lane for this computer. Selecting it is an ANNOUNCEMENT — it tells the+ // backend where the dial is — and its agents, turns and recaps all come from this process. Asking the+ // cloud for them instead round-trips to ourselves and, because a computer-backed machine is+ // `authMode: 'remote'`, is refused outright with E2EE_REQUIRED.+ if (row.local) return// Prefetch the recaps SERIALLY. Not caution — the contract: the agent list stays metadata-only and// recaps are fetched one at a time precisely so no giant frame is ever built.void this.prefetchRecaps(machineId)}- release(): void {- if (this.lingerTimer) clearTimeout(this.lingerTimer)+ /**+ * `immediate` = the dial is gone, so the socket goes with it. Otherwise the dial merely went back to the+ * local machine: DETACH from the remote one after a linger, but keep the socket — it is still what+ * keeps the machine wheel's dots live.+ */+ release(immediate = false): void {+ if (this.lingerTimer) { clearTimeout(this.lingerTimer); this.lingerTimer = null }+ if (immediate) {+ this.opts.link.release()+ this.recapCache.clear()+ return+ }this.lingerTimer = setTimeout(() => {this.lingerTimer = null- this.opts.link.release()+ this.opts.link.detach()this.recapCache.clear()}, LINGER_MS)}@@ -177,10 +205,20 @@ export class DeviceFleet implements MachineFleet {private onFrame(frame: DeviceFrame): void {const selected = this.opts.link.selectedMachine- // The hub stamps `machineId` on every frame it fans out to a commander client. Anything wearing- // another machine's tag is a card for a machine the dial is not showing — dropped at the source, which- // is what keeps the agent id space flat and unscoped everywhere else.- if (frame.machineId && selected && frame.machineId !== selected) return+ // `machines_status` is about the whole account, not one machine, so it must not be filtered by the+ // selection — it arrives while nothing at all is selected.+ if (frame.type !== 'machines_status') {+ // The hub stamps `machineId` on every frame it fans out to a commander client. Anything wearing+ // another machine's tag is a card for a machine the dial is not showing — dropped at the source,+ // which is what keeps the agent id space flat and unscoped everywhere else.+ if (frame.machineId && selected && frame.machineId !== selected) return+ }++ // OUR OWN cards, come back to us the long way. Selecting the local machine attaches a commander to+ // it, so everything this daemon emits for the dial is fanned back down this socket — and the dial has+ // already had it, in-process, milliseconds earlier. Dropping it here rather than at the consumer+ // keeps the echo out of the event stream entirely.+ if (frame.machineId && this.opts.list.find(frame.machineId)?.local) returnconst payload = (frame.payload ?? {}) as Record<string, unknown>if (frame.type === 'commander_event' && frame.agentId) {@@ -203,6 +241,15 @@ export class DeviceFleet implements MachineFleet {}if (frame.type === 'node_status') {this.emit({ machineId: selected, kind: 'state', state: payload.online === true ? 'ready' : 'offline' })+ return+ }+ // The live machine list. This is what the held socket buys: without it the wheel's dots are a REST+ // snapshot up to a minute old, and a machine that just came up stays grey while the user looks at it.+ if (frame.type === 'machines_status') {+ const rows = Array.isArray(payload.statuses) ? payload.statuses : []+ if (this.opts.list.applyLive(rows as Array<{ machineId?: unknown; online?: unknown }>)) {+ this.emit({ machineId: selected, kind: 'state', state: 'ready' })+ }}}diff --git a/cli/src/device/deviceLink.ts b/cli/src/device/deviceLink.tsindex 8cce832b3..802927ed1 100644--- a/cli/src/device/deviceLink.ts+++ b/cli/src/device/deviceLink.ts@@ -70,6 +70,8 @@ export class DeviceLink {private reconnectTimer: NodeJS.Timeout | null = nullprivate pingTimer: NodeJS.Timeout | null = nullprivate state: DeviceLinkStatus = 'idle'+ /** The dial is plugged in, so this socket should exist even with no machine selected. */+ private held = falseprivate readonly pending = new Map<string, { resolve: (v: Record<string, unknown>) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>()private readonly listeners = new Set<(frame: DeviceFrame) => void>()/** Resolves when `machine_selected` lands, so callers can await the attach rather than poll for it. */@@ -94,6 +96,22 @@ export class DeviceLink {return () => this.listeners.delete(cb)}+ /**+ * Open the socket WITHOUT attaching to any machine, and start watching the machine list.+ *+ * Connecting and attaching are different things, and the difference is the whole reason this can be+ * held for as long as the dial is plugged in. The backend's relay starts UNATTACHED: a commander client+ * is created by `machine_select`, or by `machines_watch` when a device advertises `multi_machine` —+ * which this one deliberately does not. So the socket costs presence and a live machine list, and+ * nothing else: no machine sees a commander, no daemon starts generating recap cards for a screen+ * nobody is looking at.+ */+ async online(): Promise<void> {+ this.held = true+ await this.connect()+ this.send({ type: 'machines_watch' })+ }+/** Dial if needed, then select `machineId`. Rejects with a plain Error the caller maps to a code. */async attach(machineId: string): Promise<void> {if (!machineId) throw new Error('no machine to attach to')@@ -129,8 +147,16 @@ export class DeviceLink {}/** Let go of whatever is attached. The socket is closed: nothing else on it is being watched. */+ /** Detach from the machine but KEEP the socket: the dial is still plugged in. */+ detach(): void {+ this.wanted = ''+ this.attached = ''+ if (this.ws?.readyState === WebSocket.OPEN) this.send({ type: 'machine_deselect' })+ }+release(): void {this.wanted = ''+ this.held = falsethis.attached = ''if (this.ws?.readyState === WebSocket.OPEN) {this.send({ type: 'machine_deselect' })@@ -140,6 +166,7 @@ export class DeviceLink {stop(): void {this.wanted = ''+ this.held = falsethis.teardown('daemon stopping')}@@ -287,8 +314,9 @@ export class DeviceLink {private onClose(code: number): void {this.opts.log(`device: closed (${code})`)const wanted = this.wanted+ const held = this.heldthis.teardown(`socket closed (${code})`)- if (!wanted) return+ if (!wanted && !held) return// 401/403 after the one refresh above is a decision, not a hiccup: stop, and let the cabled machine// carry on. Clearing the session here is NOT this class's call — see rule 2 in the header.if (code === 4401 || code === 4403) {@@ -298,7 +326,10 @@ export class DeviceLink {}const delay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.min(this.attempts++, 5))this.reconnectTimer = setTimeout(() => {- void this.attach(wanted).catch((err) => this.opts.log(`device: reattach failed (${(err as Error).message})`))+ // Re-select only if a machine was selected. A socket held open purely for presence comes back the+ // same way it went up — connected and attached to nothing.+ const retry = wanted ? this.attach(wanted) : this.online()+ void retry.catch((err) => this.opts.log(`device: reconnect failed (${(err as Error).message})`))}, delay)}diff --git a/cli/src/device/machineList.ts b/cli/src/device/machineList.tsindex 5cc3f8974..1756eb210 100644--- a/cli/src/device/machineList.ts+++ b/cli/src/device/machineList.ts@@ -116,6 +116,34 @@ export class MachineListCache {}}+ /**+ * Overlay live presence from a `machines_status` frame.+ *+ * The REST list is a SNAPSHOT — it is re-read on a timer, so on its own a machine that just came up+ * stays grey for up to a minute. This is the stream that fixes that, and it is why the socket is worth+ * holding while the dial is plugged in.+ *+ * Presence only: the name, the auth mode and which row is local all keep coming from REST, which is the+ * source that knows them. Returns true when something actually changed, so the caller can push a wheel+ * that differs and stay silent about one that does not.+ */+ applyLive(rows: Array<{ machineId?: unknown; online?: unknown }>): boolean {+ let changed = false+ let unknown = false+ for (const r of rows) {+ const id = typeof r.machineId === 'string' ? r.machineId : ''+ if (!id) continue+ const row = this.machines.find((m) => m.machineId === id)+ if (!row) { unknown = true; continue }+ const next = r.online === true ? 'ready' : 'offline'+ if (row.state !== next) { row.state = next; changed = true }+ }+ // A machine nobody has heard of means the account gained one since the last read. Go and find out+ // what it is called rather than inventing a row from a presence frame.+ if (unknown) void this.refresh()+ return changed+ }+/** The list is stale but not wrong: keep the rows, stop claiming they are live. */private degrade(why: string): void {if (this.source !== 'local') this.log(`machines: ${why} — showing the last known list`)