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.

feat(cable): one carousel across every machine, routed per agent

0xdiego25e7b73cc5577f
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index c2910e845..dc00b39d9 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -198,3 +198,110 @@ describe('the cloud lane follows the CABLE, not the selection', () => {
await new Promise((r) => setTimeout(r, 0)) // let the rejection land on its catch
})
})
+
+describe('DaemonCableHost.listAgents across machines', () => {
+ /** A fleet whose remote agent lists are scripted per machine. */
+ function crossFleet(byMachine: Record<string, Array<{ id: string; name: string }>>, machines = [REMOTE]): MachineFleet {
+ const fleet = fleetOf(machines)
+ fleet.listAgents = vi.fn(async (machineId: string) => (byMachine[machineId] ?? []) as never)
+ fleet.sendTurn = vi.fn()
+ fleet.stopTurn = vi.fn()
+ fleet.recentSummaries = vi.fn(async () => [])
+ return fleet
+ }
+
+ /** Two ticks: the first kicks the background refresh off, the second reads what it wrote. */
+ async function settled(host: DaemonCableHost): Promise<Awaited<ReturnType<DaemonCableHost['listAgents']>>> {
+ await host.listAgents()
+ await new Promise((r) => setTimeout(r, 0))
+ return host.listAgents()
+ }
+
+ it('puts this computer first and every other machine after it, in wheel order', async () => {
+ // The order IS the contract: the dial swipes through it and the desktop app's rail reads top to
+ // bottom in the same order, so the two surfaces can be compared by eye.
+ AGENTS.length = 0
+ AGENTS.push({ agentId: 'local-1', registeredAt: 1, active: true, engine: 'claude' })
+ const second: FleetMachine = { machineId: 'third', name: 'studio', state: 'ready', authMode: 'remote' }
+ const host = new DaemonCableHost(
+ wiring(),
+ crossFleet({ other: [{ id: 'r1', name: 'api' }], third: [{ id: 'r2', name: 'ui' }] }, [REMOTE, second]),
+ )
+ const agents = await settled(host)
+ expect(agents.map((a) => a.id)).toEqual(['local-1', 'r1', 'r2'])
+ expect(agents.map((a) => a.machine)).toEqual(['MacbookPro.local', 'office-imac', 'studio'])
+ expect(agents.map((a) => a.machineId)).toEqual(['mine', 'other', 'third'])
+ })
+
+ it('sends a turn to the agent’s OWN machine, not to the selected one', async () => {
+ // The single worst outcome this feature can produce is a turn delivered to a different computer, so
+ // the routing is asserted with the wheel deliberately pointed somewhere else.
+ AGENTS.length = 0
+ const fleet = crossFleet({ other: [{ id: 'r1', name: 'api' }] })
+ const host = new DaemonCableHost(wiring(), fleet)
+ await settled(host)
+ expect(host.isLocalSelected()).toBe(true) // the wheel never moved
+
+ host.sendTurn('r1', 'ship it')
+ expect(fleet.sendTurn).toHaveBeenCalledWith('other', 'r1', 'ship it')
+ })
+
+ it('keeps a local agent local even while another machine is selected', async () => {
+ AGENTS.length = 0
+ AGENTS.push({ agentId: 'local-1', registeredAt: 1, active: true, engine: 'claude' })
+ const sendTurn = vi.fn()
+ const fleet = crossFleet({ other: [] })
+ const host = new DaemonCableHost(wiring({ sendTurn }), fleet)
+ await settled(host)
+ await host.selectMachine('other')
+
+ host.sendTurn('local-1', 'hello')
+ expect(sendTurn).toHaveBeenCalledWith('local-1', 'hello')
+ expect(fleet.sendTurn).not.toHaveBeenCalled()
+ })
+
+ it('drops a turn for an agent it has never listed rather than guessing a machine', async () => {
+ // Falling back to the selected machine here is how a turn lands on the wrong computer. The local
+ // wiring is the only safe default: it is the machine the cable can vouch for.
+ AGENTS.length = 0
+ const sendTurn = vi.fn()
+ const fleet = crossFleet({ other: [{ id: 'r1', name: 'api' }] })
+ const host = new DaemonCableHost(wiring({ sendTurn }), fleet)
+ await settled(host)
+ await host.selectMachine('other')
+
+ host.sendTurn('ghost', 'where does this go?')
+ expect(fleet.sendTurn).not.toHaveBeenCalled()
+ expect(sendTurn).toHaveBeenCalledWith('ghost', 'where does this go?')
+ })
+
+ it('holds a machine’s last good list through a failure instead of blanking its tiles', async () => {
+ AGENTS.length = 0
+ const fleet = crossFleet({ other: [{ id: 'r1', name: 'api' }] })
+ const host = new DaemonCableHost(wiring(), fleet)
+ expect((await settled(host)).map((a) => a.id)).toEqual(['r1'])
+
+ ;(fleet.listAgents as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('cloud blip'))
+ // Date.now rather than fake timers: the refresh is paced by wall-clock comparisons, and faking the
+ // whole timer wheel would also freeze the `setTimeout(0)` this test uses to let the refresh land.
+ const real = Date.now
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => real() + 6_000)
+ try {
+ const agents = await settled(host) // past the refresh cadence, well inside the grace period
+ expect(agents.map((a) => a.id)).toEqual(['r1'])
+ } finally {
+ nowSpy.mockRestore()
+ }
+ })
+
+
+ it('asks nothing of a machine that is not ready, and shows none of its agents', async () => {
+ // An offline or unlinked machine costs a 15-second RPC timeout per round to learn nothing.
+ AGENTS.length = 0
+ const unlinked: FleetMachine = { machineId: 'other', name: 'office-imac', state: 'needs-link', authMode: 'remote' }
+ const fleet = crossFleet({ other: [{ id: 'r1', name: 'api' }] }, [unlinked])
+ const host = new DaemonCableHost(wiring(), fleet)
+ expect(await settled(host)).toEqual([])
+ expect(fleet.listAgents).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index 182d5f344..3fa305547 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -62,6 +62,12 @@ function placeholderId(computerId: string): string {
return `cable:${computerId}`
}
+/** How often another machine's agent list is re-asked. Far slower than the dial's one-second tick: the
+ * list changes when a person starts an agent, not continuously. */
+const REMOTE_REFRESH_MS = 5_000
+/** How long a machine's last good list survives failures before its tiles leave the carousel. */
+const REMOTE_GRACE_MS = 30_000
+
/** Whether an id is that placeholder rather than a machine the backend has heard of. */
function isPlaceholder(id: string): boolean {
return id.startsWith('cable:')
@@ -93,6 +99,13 @@ export class DaemonCableHost implements CableHost {
*/
private selected = ''
+ /** Each other machine's agents, as last read. `asked` throttles the round; `at` ages the answer. */
+ private readonly remoteAgents = new Map<string, { agents: CableAgent[]; at: number; asked: number }>()
+ /** Machines with a list RPC in flight, so a slow machine is asked once rather than every tick. */
+ private readonly inFlight = new Set<string>()
+ /** agentId → machineId, rebuilt from the snapshot last handed to the dial. */
+ private agentMachine = new Map<string, string>()
+
/** `undefined` = no lane to any other machine exists; the wheel is the local row and nothing else. */
constructor(private readonly wiring: CableHostWiring, private readonly fleet?: MachineFleet) {}
@@ -229,8 +242,8 @@ export class DaemonCableHost implements CableHost {
return locale.startsWith('vi') ? 'vi' : 'en'
}
- async listAgents(): Promise<CableAgent[]> {
- if (!this.isLocalSelected()) return this.fleet!.listAgents(this.selectedMachine())
+ /** This computer's own agents, in the order every other surface reads them in. */
+ private localAgents(): CableAgent[] {
// `active()`, not `list()` — the SAME set `agents_list` answers the web and the desktop app with. They
// read one registry and must not disagree about what is on it: a dead agent holding a tile on the dial
// and nowhere else is a tile that cannot be driven and cannot be explained.
@@ -239,38 +252,135 @@ export class DaemonCableHost implements CableHost {
// which is Map insertion order and differs between daemon runs. Both producers sort identically, so
// the dial and the app cannot drift apart while reading the same registry.
sessions.sort((a, b) => a.registeredAt - b.registeredAt || a.agentId.localeCompare(b.agentId))
+ const machineId = this.localId()
+ const machine = this.wiring.machineName()
return sessions.map((s) => ({
id: s.agentId,
name: projectDisplayName(s),
engine: s.engine ?? '',
+ machineId,
+ machine,
...chipsFromProfile(this.wiring.runtimeProfile?.(s)),
}))
}
+ /**
+ * EVERY agent on EVERY machine, in the order the desktop app's rail reads them: this computer first,
+ * then each other machine in wheel order, and within a machine whatever order that machine returns.
+ *
+ * Read from a CACHE, never from a live RPC. This is called on the session's one-second tick, and a
+ * naive implementation would fire one cloud round trip per machine per second — the dial would spend
+ * its whole life waiting on the network to answer a question whose answer changes every few minutes.
+ * `refreshRemotes()` does the asking, off to the side, on its own slower clock.
+ */
+ async listAgents(): Promise<CableAgent[]> {
+ const out = this.localAgents()
+ const { machines } = await this.listMachines()
+ for (const m of machines) {
+ if (m.local) continue
+ const entry = this.remoteAgents.get(m.id)
+ if (entry) for (const a of entry.agents) out.push({ ...a, machineId: m.id, machine: m.name })
+ }
+ void this.refreshRemotes(machines)
+ // Rebuilt from the SAME snapshot that is about to be pushed, so the map can never name a machine an
+ // agent has already left. Every action the dial can take is routed through it.
+ const next = new Map<string, string>()
+ for (const a of out) if (a.machineId) next.set(a.id, a.machineId)
+ this.agentMachine = next
+ return out
+ }
+
+ /**
+ * Which machine an agent lives on, or '' if the dial named one this daemon has never listed.
+ *
+ * NEVER falls back to the selected machine. A wrong answer here does not fail — it delivers the user's
+ * turn to a different computer, which is the worst outcome this whole feature can produce.
+ */
+ private machineOf(agentId: string): string {
+ return this.agentMachine.get(agentId) ?? ''
+ }
+
+ /** True when the agent belongs to this computer (or is unknown, which is handled at the call site). */
+ private isLocalAgent(agentId: string): boolean {
+ const machineId = this.machineOf(agentId)
+ return !machineId || machineId === this.localId()
+ }
+
+ /**
+ * Refresh the other machines' agent lists, on their own clock.
+ *
+ * Only `ready` machines are asked. An offline one has nothing to say and an unlinked one cannot be
+ * read at all (no pinned key), and asking either costs a 15-second RPC timeout per machine per round.
+ *
+ * A machine that fails keeps its LAST GOOD list for `REMOTE_GRACE_MS` and only then goes empty. A cloud
+ * blip is the common case, and dropping every one of a machine's tiles off the carousel for a few
+ * seconds — then putting them back — is a far worse lie than briefly showing a list that is a minute
+ * old.
+ */
+ private refreshRemotes(machines: CableMachine[]): void {
+ if (!this.fleet) return
+ const now = Date.now()
+ for (const m of machines) {
+ if (m.local) continue
+ const entry = this.remoteAgents.get(m.id)
+ if (m.state !== 'ready') {
+ // Not an error and not worth a grace period: the machine itself says it has nothing to offer.
+ if (entry && entry.agents.length) this.remoteAgents.set(m.id, { agents: [], at: now, asked: entry.asked })
+ continue
+ }
+ if (entry && now - entry.asked < REMOTE_REFRESH_MS) continue
+ if (this.inFlight.has(m.id)) continue
+ this.inFlight.add(m.id)
+ this.remoteAgents.set(m.id, { agents: entry?.agents ?? [], at: entry?.at ?? 0, asked: now })
+ void this.fleet.listAgents(m.id)
+ .then((agents) => {
+ const before = this.remoteAgents.get(m.id)
+ this.remoteAgents.set(m.id, { agents, at: Date.now(), asked: Date.now() })
+ // One line per TRANSITION, not per round: this runs every few seconds forever, and a healthy
+ // machine that logs each time buries everything else in the file.
+ if (!before || before.agents.length !== agents.length) {
+ this.wiring.log(`cable: ${m.name} → ${agents.length} agents`)
+ }
+ })
+ .catch((err) => {
+ const before = this.remoteAgents.get(m.id)
+ const stale = before && Date.now() - before.at > REMOTE_GRACE_MS
+ if (stale) this.remoteAgents.set(m.id, { agents: [], at: Date.now(), asked: Date.now() })
+ if (before?.agents.length && stale) {
+ this.wiring.log(`cable: ${m.name} dropped off the carousel (${(err as Error).message})`)
+ }
+ })
+ .finally(() => this.inFlight.delete(m.id))
+ }
+ }
+
sendTurn(agentId: string, text: string): void {
- if (!this.isLocalSelected()) { this.fleet!.sendTurn(this.selectedMachine(), agentId, text); return }
+ if (!this.isLocalAgent(agentId)) { this.fleet!.sendTurn(this.machineOf(agentId), agentId, text); return }
this.wiring.sendTurn(agentId, text)
}
stopTurn(agentId: string): void {
- if (!this.isLocalSelected()) { this.fleet!.stopTurn(this.selectedMachine(), agentId); return }
+ if (!this.isLocalAgent(agentId)) { this.fleet!.stopTurn(this.machineOf(agentId), agentId); return }
this.wiring.stopTurn(agentId)
}
answer(agentId: string, requestId: string, answers: Record<string, string>): void {
- if (!this.isLocalSelected()) { this.fleet!.answer(this.selectedMachine(), agentId, requestId, answers); return }
+ if (!this.isLocalAgent(agentId)) { this.fleet!.answer(this.machineOf(agentId), agentId, requestId, answers); return }
this.wiring.answer(agentId, requestId, answers)
}
+
focus(agentId: string): void {
// A statement about where the user is looking, and the desktop window follows it: turning the dial to
// an agent switches the terminal on screen to the same one. The daemon still has no window of its own
// — it forwards, and the app decides what following means for it.
- // Local only, and not an oversight: this says where a hand at THIS desk is looking. There is no
- // window here to move for an agent running on another computer, and moving one there is not what the
- // person turning the dial asked for.
- if (!this.isLocalSelected()) return
+ // FORWARDED FOR EVERY AGENT, including one running on another computer. That used to be refused on
+ // the grounds that there was no window here to move — which stopped being true when the desktop app
+ // grew panes for remote machines. The hand is still at THIS desk; the pane it wants in front of it
+ // may simply belong to a machine somewhere else, and the app is the side that decides what it can do
+ // about an agent it does not have.
this.wiring.log(`cable: focus ${agentId}`)
+
this.wiring.focused?.(agentId)
}
@@ -280,28 +390,29 @@ export class DaemonCableHost implements CableHost {
// protocol is most exposed to is a stroke that never CLOSES — the far side then holds a drag forever
// and its list stops answering the mouse — and that failure is invisible without a matching pair to
// look for. Two lines per swipe buys the one thing worth seeing.
- if (!this.isLocalSelected()) return // same reasoning as focus(): a finger on this glass, this desk
if (phase !== 'move') {
+
this.wiring.log(phase === 'down' ? 'cable: scroll ↓' : `cable: scroll ↑ (v=${velocity})`)
}
this.wiring.scrolled?.(phase, dy, velocity)
}
updateAgent(agentId: string, model?: string, effort?: string): void {
- if (!this.isLocalSelected()) { this.fleet!.updateAgent(this.selectedMachine(), agentId, model, effort); return }
+ if (!this.isLocalAgent(agentId)) { this.fleet!.updateAgent(this.machineOf(agentId), agentId, model, effort); return }
this.wiring.updateAgent?.(agentId, model, effort)
}
/** The last few turns, newest first, in the shape the dial's tile draws: a headline and a body. */
async recentSummaries(agentId: string): Promise<Array<{ recap: string; text: string }>> {
- const raw = this.isLocalSelected()
+ const raw = this.isLocalAgent(agentId)
? this.wiring.recent(agentId, 3)
- : await this.fleet!.recentSummaries(this.selectedMachine(), agentId)
+ : await this.fleet!.recentSummaries(this.machineOf(agentId), agentId)
return raw.map((r) => ({ recap: r?.recap ?? '', text: r?.text ?? '' })).filter((s) => s.recap || s.text)
}
async listModels(agentId: string): Promise<string[]> {
- if (!this.isLocalSelected()) return this.fleet!.listModels(this.selectedMachine(), agentId)
+ if (!this.isLocalAgent(agentId)) return this.fleet!.listModels(this.machineOf(agentId), agentId)
+
const models = (await this.wiring.listModels?.(agentId)) ?? []
return models.map((m) => m.id).filter(Boolean)
}
@@ -330,13 +441,17 @@ export class DaemonCableHost implements CableHost {
* which is the whole reason voice on the cable does not inherit the hosted path's failure modes.
*/
async route(transcript: string, agents: CableAgent[]): Promise<RouteDecision> {
- // The recaps must come from the SELECTED machine. Scored against this computer's history instead, a
- // spoken turn meant for a remote agent is routed by what the agents HERE were last doing — which is
- // both wrong and completely invisible, because the router always answers with something.
+ // Each agent's recaps come from ITS OWN machine — recentSummaries routes by agentId. Scored against
+ // the wrong machine's history, a spoken turn is routed by what some other computer's agents were last
+ // doing, which is both wrong and completely invisible, because the router always answers with
+ // something. The machine name travels too, so two agents with the same name on two computers are
+ // distinguishable by the only thing that separates them.
const candidates: RouterAgent[] = await Promise.all(agents.map(async (a) => ({
id: a.id,
name: a.name,
engine: a.engine,
+ machine: a.machine,
+
recentSummary: (await this.recentSummaries(a.id))
.map((r) => r.recap || r.text || '')
.filter(Boolean)
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index a9f8ec9f9..3632a20e7 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -81,8 +81,20 @@ export interface CableAgent {
engine?: string
model?: string
effort?: string
+ /**
+ * The machine this agent lives on, and that machine's name.
+ *
+ * THE CAROUSEL IS NO LONGER ONE MACHINE'S. Every agent on every machine is on it at once, so an agent
+ * that does not say where it lives cannot be driven: the daemon routes each turn, stop and answer by
+ * this id, and the dial prints the name on the switcher's second line where the engine used to be.
+ *
+ * Optional because the WIRE is: a firmware that predates the field simply does not draw it.
+ */
+ machineId?: string
+ machine?: string
}
+
/**
* One row of the dial's machine wheel.
*
@@ -788,9 +800,12 @@ export class CableSession {
*/
/** What the dial has been told, as one comparable string. */
private static agentsKey(agents: CableAgent[]): string {
- return agents.map((a) => `${a.id}:${a.name}:${a.engine ?? ''}:${a.model ?? ''}:${a.effort ?? ''}`).join('|')
+ // `machine` is in the key, not just `machineId`: the dial DRAWS the name, so a machine being renamed
+ // has to reach the screen even though not one agent has changed.
+ return agents.map((a) => `${a.id}:${a.name}:${a.engine ?? ''}:${a.model ?? ''}:${a.effort ?? ''}:${a.machineId ?? ''}:${a.machine ?? ''}`).join('|')
}
+
/**
* Send the agent list IF it differs from what the dial was last told.
*
@@ -813,7 +828,19 @@ export class CableSession {
await this.send({ t: 'agents.begin' })
for (const a of agents) {
- await this.send({ t: 'agent', id: a.id, name: a.name, engine: a.engine ?? '', model: a.model ?? '', effort: a.effort ?? '' })
+ await this.send({
+ t: 'agent',
+ id: a.id,
+ name: a.name,
+ engine: a.engine ?? '',
+ model: a.model ?? '',
+ effort: a.effort ?? '',
+ // Where it lives. The id is what the dial sends back for every action, the name is what it draws
+ // on the switcher's second line, and the id is also how a machine row finds its first agent.
+ machineId: a.machineId ?? '',
+ machine: a.machine ?? '',
+ })
+
}
await this.send({ t: 'agents.end' })
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index d061e8186..361f2f3c6 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -1036,10 +1036,12 @@ async function runForeground(session: AuthSession): Promise<void> {
* backend-only meant a dial plugged into a machine with no WiFi device saw a turn start in its tmux
* pane and then nothing at all: the daemon skipped GENERATING the cards, so there was nothing to send.
*/
- // The cable half is gated on the dial actually LOOKING at this computer. A dial turned to another
- // machine is watching that machine's cards, not ours, so generating recaps here would spend an LLM call
- // per turn on something nobody renders.
- const cableWatchingLocal = (): boolean => cableRef?.isConnected === true && cableHostRef?.isLocalSelected() === true
+ // A PLUGGED-IN DIAL IS ALWAYS WATCHING THIS COMPUTER. It used to be gated on the dial having this
+ // machine selected, because the carousel held one machine's agents at a time; it now holds every
+ // machine's at once, so this computer's tiles are on screen whichever machine the wheel last landed on
+ // and skipping the recap here would leave them permanently blank.
+ const cableWatchingLocal = (): boolean => cableRef?.isConnected === true
+
const deviceIsWatching = (): boolean => backend.hasCommander() || cableWatchingLocal()
const terminalStreams = new TerminalStreamManager({
terminals,
@@ -3000,8 +3002,12 @@ async function runForeground(session: AuthSession): Promise<void> {
// Read FRESH on every attach: `harness link import` runs as a separate process, so a value captured
// at daemon start would keep answering "not linked" until the next restart.
peer: (machineId) => machinePeers.get(machineId),
+ // Read fresh for the same reason `machineId` above is a thunk: it is '' until the daemon has resolved
+ // this computer's machine, and the echo guard must start working the moment it is not.
+ localMachineId: () => backend.machineId,
log: (line) => console.log(`[device] ${line}`),
})
+
deviceLinkRef = deviceLink
const fleet = new DeviceFleet({
@@ -3049,11 +3055,11 @@ async function runForeground(session: AuthSession): Promise<void> {
// Every card bound for the WiFi device goes down the cable too, translated once. Teeing beats emitting
// again at each call site: a new event kind reaches the dial the day it reaches the socket.
backend.onOutboundCommander = (frame) => {
- // THIS COMPUTER'S cards, by definition. When the dial is showing another machine they must not be
- // painted: agent ids are bare local UUIDs with no machine component, so the tile they land on is
- // either the wrong agent's or nobody's.
- if (!cableHost.isLocalSelected()) return
- const question = cableQuestionFor(frame as { type?: string; agentId?: string; payload?: { requestId?: string; questions?: unknown } })
+ // THIS COMPUTER'S cards, by definition — and every one of them belongs to a tile that is on the
+ // carousel, because the carousel now spans machines. The old guard dropped them whenever the wheel
+ // was pointed elsewhere, which would now silence this machine's own agents.
+ const question = cableQuestionFor
+(frame as { type?: string; agentId?: string; payload?: { requestId?: string; questions?: unknown } })
if (question) { void cable.question(question.agentId, question.requestId, question.questions); return }
const event = cableEventFor(frame as { type?: string; agentId?: string; payload?: { kind?: string; text?: string; recap?: string } })
// Logged at the fork, not at the send: this is the one place that can answer "did the daemon even
@@ -3076,7 +3082,10 @@ async function runForeground(session: AuthSession): Promise<void> {
// 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-flight
+ // No selection guard. Every machine's agents are on the carousel at once, so a card from a machine
+ // the wheel is not pointed at still belongs to a tile the user can see — and dropping it is what a
+ // tile that never leaves "Working…" looks like from the outside.
+
if (event.kind === 'question') { void cable.question(event.agentId, event.requestId, event.questions); return }
if (event.kind === 'processing') void cable.turnStarted(event.agentId, event.text)
else if (event.kind === 'done') void cable.turnDone(event.agentId)
diff --git a/cli/src/device/deviceFleet.spec.ts b/cli/src/device/deviceFleet.spec.ts
index 6b36ceb40..8fd226f44 100644
--- a/cli/src/device/deviceFleet.spec.ts
+++ b/cli/src/device/deviceFleet.spec.ts
@@ -101,19 +101,21 @@ describe('DeviceFleet', () => {
expect(agents[0]).toMatchObject({ id: 'a1', name: 'api refactor', engine: 'codex', model: 'opus', effort: 'high' })
})
- it('drops a card tagged for a machine the dial is not showing', () => {
- // Agent ids are bare UUIDs with no machine component, so a stray card either paints the wrong tile or
- // none at all — and both look like the dial simply missing a turn.
+ it('delivers a card from a machine the wheel is not pointed at, tagged with its own machine', () => {
+ // The carousel spans machines, so a card from a background machine belongs to a tile that is on
+ // screen. This used to be DROPPED — which, once every machine's agents share one carousel, is what a
+ // tile stuck on "Working…" for a turn that finished minutes ago looks like from the outside.
const { fleet, say } = make()
const seen: FleetEvent[] = []
fleet.onEvent((e) => seen.push(e))
- say({ type: 'commander_event', machineId: 'other', agentId: 'a1', payload: { kind: 'summary', recap: 'nope' } })
- expect(seen).toHaveLength(0)
+ say({ type: 'commander_event', machineId: 'other', agentId: 'a1', payload: { kind: 'summary', recap: 'nope', text: 'b' } })
+ expect(seen).toEqual([{ machineId: 'other', kind: 'summary', agentId: 'a1', text: 'b', recap: 'nope' }])
say({ type: 'commander_event', machineId: 'm1', agentId: 'a1', payload: { kind: 'summary', recap: 'yes', text: 'body' } })
- expect(seen).toEqual([{ machineId: 'm1', kind: 'summary', agentId: 'a1', text: 'body', recap: 'yes' }])
+ expect(seen[1]).toEqual({ machineId: 'm1', kind: 'summary', agentId: 'a1', text: 'body', recap: 'yes' })
})
+
it('ignores card kinds the dial has no use for', () => {
const { fleet, say } = make()
const seen: FleetEvent[] = []
diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.ts
index 9f52dbfa1..71fe7f8ae 100644
--- a/cli/src/device/deviceFleet.ts
+++ b/cli/src/device/deviceFleet.ts
@@ -95,7 +95,10 @@ export class DeviceFleet implements MachineFleet {
const message = (err as Error).message
throw new FleetError(this.codeFor(message), this.messageFor(message, row.name))
}
- this.recapCache.clear()
+ // ONLY this machine's recaps. Clearing the whole cache was right when a select meant "throw away the
+ // machine you were reading and pick up another one"; now every other machine's tiles are still on the
+ // dial's carousel, and blanking them would make a select look like N agents forgetting their work.
+ for (const key of [...this.recapCache.keys()]) if (key.startsWith(`${machineId}:`)) this.recapCache.delete(key)
// 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
@@ -107,79 +110,82 @@ export class DeviceFleet implements MachineFleet {
}
/**
- * `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.
+ * `immediate` = the dial is gone, so the socket goes with it. Anything else is a NO-OP, and the reason
+ * is worth stating because this used to detach after a linger.
+ *
+ * Detaching sent `machine_deselect`, which drops the backend's ACTIVE machine pointer — and the backend
+ * refuses `agents_list`/`message` outright while there is no active machine, tagged for another machine
+ * or not (deviceWs's ensureActiveReady). So the linger would have quietly killed the carousel a minute
+ * after the user went back to the local machine. There is also nothing left for it to buy: with the
+ * `multi_machine` cap the backend holds a commander on every machine for as long as the socket lives,
+ * so detaching one of them frees nothing.
*/
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.detach()
- this.recapCache.clear()
- }, LINGER_MS)
+ if (!immediate) return
+ this.opts.link.release()
+ this.recapCache.clear()
}
+
+ // ── EVERY method below NAMES ITS MACHINE ────────────────────────────────────────────────────────
+ // These used to `void machineId` and let the frame land on whatever machine was attached, because
+ // exactly one ever was. The dial now holds every machine's agents in one carousel, so the machine is
+ // no longer implied by the selection and has to travel with the frame: the backend routes a device
+ // frame by its outer `machineId` tag (deviceWs.handleFrame) and answers from THAT machine's node.
+ // Dropping the tag would not fail loudly — it would quietly ask the wrong computer.
+
async listAgents(machineId: string): Promise<CableAgent[]> {
- const res = await this.opts.link.rpc('agents_list', {})
- void machineId
+ const res = await this.opts.link.rpc('agents_list', {}, machineId)
const raw = Array.isArray(res.agents) ? res.agents : []
return raw.map(toCableAgent).filter((a) => a.id)
}
sendTurn(machineId: string, agentId: string, text: string): void {
- void machineId
// `resumeLatest` matches what the backend's own voice path dispatches, so a dial turn and a spoken
// turn land on the same session rather than one of them starting a new one.
- this.opts.link.send({ type: 'message', payload: { content: text, agentId, mode: 'auto', resumeLatest: true } })
+ this.tagged(machineId, { type: 'message', payload: { content: text, agentId, mode: 'auto', resumeLatest: true } })
}
stopTurn(machineId: string, agentId: string): void {
- void machineId
- this.opts.link.send({ type: 'cancel', payload: { agentId } })
+ this.tagged(machineId, { type: 'cancel', payload: { agentId } })
}
answer(machineId: string, agentId: string, requestId: string, answers: Record<string, string>): void {
- void machineId
- this.opts.link.send({ type: 'question_response', payload: { agentId, requestId, answers } })
+ this.tagged(machineId, { type: 'question_response', payload: { agentId, requestId, answers } })
}
updateAgent(machineId: string, agentId: string, model?: string, effort?: string): void {
- void machineId
if (!model) return
// The far end owns what the profile means; this only reassembles the opaque string it round-trips.
- const row = this.opts.list.find(this.opts.link.selectedMachine)
- void row
const selectedModel = `runtime-v1:${agentId}:claude:${model}@${effort || 'auto'}`
- void this.opts.link.rpc('agent_update', { agentId, selectedModel })
+ void this.opts.link.rpc('agent_update', { agentId, selectedModel }, machineId)
.catch((err) => this.opts.log(`device: agent_update failed (${(err as Error).message})`))
}
async listModels(machineId: string, agentId: string): Promise<string[]> {
- void machineId
+
// `compact` is what keeps the catalog inside the dial's picker; the backend trims to ≤24 entries.
- const res = await this.opts.link.rpc('models_list', { agentId, compact: true })
+ const res = await this.opts.link.rpc('models_list', { agentId, compact: true }, machineId)
+
const raw = Array.isArray(res.models) ? res.models : []
return raw.map((m) => (typeof m === 'string' ? m : String((m as Record<string, unknown>)?.id ?? ''))).filter(Boolean)
}
async recentSummaries(machineId: string, agentId: string): Promise<RecentTurn[]> {
- void machineId
- const cached = this.recapCache.get(agentId)
+ const key = `${machineId}:${agentId}`
+ const cached = this.recapCache.get(key)
if (cached) return cached
try {
- const res = await this.opts.link.rpc('agent_recent', { agentId, n: 3 })
+ const res = await this.opts.link.rpc('agent_recent', { agentId, n: 3 }, machineId)
+
const events = Array.isArray(res.events) ? res.events : []
const turns = events.map((e) => {
const r = (e ?? {}) as Record<string, unknown>
return { recap: typeof r.recap === 'string' ? r.recap : '', text: typeof r.text === 'string' ? r.text : '' }
})
- this.recapCache.set(agentId, turns)
+ this.recapCache.set(key, turns)
+
return turns
} catch (err) {
this.opts.log(`device: agent_recent ${agentId} failed (${(err as Error).message})`)
@@ -194,7 +200,13 @@ export class DeviceFleet implements MachineFleet {
// ── internals ───────────────────────────────────────────────────────────────────────────────────
+ /** Send a frame addressed to one machine. The tag is what the backend routes on. */
+ private tagged(machineId: string, frame: DeviceFrame): void {
+ this.opts.link.send({ ...frame, machineId })
+ }
+
private async prefetchRecaps(machineId: string): Promise<void> {
+
try {
const agents = await this.listAgents(machineId)
for (const a of agents) await this.recentSummaries(machineId, a.id)
@@ -205,14 +217,15 @@ export class DeviceFleet implements MachineFleet {
private onFrame(frame: DeviceFrame): void {
const selected = this.opts.link.selectedMachine
- // `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
- }
+ // WHICH MACHINE SENT IT. The hub stamps `machineId` on every frame it fans out to a commander
+ // client, and since the dial's carousel spans machines, that tag is the answer rather than a filter:
+ // a card from a machine the user is not looking at still belongs to a tile that is on screen.
+ //
+ // This used to DROP anything not wearing the selected machine's tag. That was right when one machine
+ // was attached at a time and is exactly wrong now — it would silence every tile but one, and the
+ // silence would look like agents that simply never finish a turn.
+ const from = typeof frame.machineId === 'string' && frame.machineId ? frame.machineId : selected
+
// 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
@@ -225,8 +238,9 @@ export class DeviceFleet implements MachineFleet {
const kind = payload.kind
if (kind !== 'processing' && kind !== 'done' && kind !== 'summary' && kind !== 'error') return
this.emit({
- machineId: selected,
+ machineId: from,
kind,
+
agentId: frame.agentId,
text: typeof payload.text === 'string' ? payload.text : '',
recap: typeof payload.recap === 'string' ? payload.recap : '',
@@ -236,11 +250,13 @@ export class DeviceFleet implements MachineFleet {
if (frame.type === 'commander_question' && frame.agentId) {
const requestId = payload.requestId
if (typeof requestId !== 'string' || !Array.isArray(payload.questions)) return
- this.emit({ machineId: selected, kind: 'question', agentId: frame.agentId, requestId, questions: payload.questions })
+ this.emit({ machineId: from, kind: 'question', agentId: frame.agentId, requestId, questions: payload.questions })
+
return
}
if (frame.type === 'node_status') {
- this.emit({ machineId: selected, kind: 'state', state: payload.online === true ? 'ready' : 'offline' })
+ this.emit({ machineId: from, 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
@@ -248,7 +264,8 @@ export class DeviceFleet implements MachineFleet {
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' })
+ this.emit({ machineId: from, kind: 'state', state: 'ready' })
+
}
}
}
diff --git a/cli/src/device/deviceLink.ts b/cli/src/device/deviceLink.ts
index 802927ed1..34f66f945 100644
--- a/cli/src/device/deviceLink.ts
+++ b/cli/src/device/deviceLink.ts
@@ -59,6 +59,15 @@ export interface DeviceLinkOpts {
identity: Identity
/** The pinned key for a machine, read FRESH: `harness link import` runs as a separate process. */
peer: (machineId: string) => MachinePeer | null
+ /**
+ * THIS computer's machineId, or '' before the daemon has resolved one.
+ *
+ * Needed because `multi_machine` attaches a commander to every machine INCLUDING this one, so this
+ * socket is subscribed to its own node's cards. They are already delivered in-process; the copy that
+ * comes back around through the cloud is dropped by machineId, and this is how it is recognised.
+ */
+ localMachineId: () => string
+
log: (line: string) => void
}
@@ -77,14 +86,24 @@ export class DeviceLink {
/** Resolves when `machine_selected` lands, so callers can await the attach rather than poll for it. */
private selectWaiter: { resolve: () => void; reject: (e: Error) => void; timer: NodeJS.Timeout } | null = null
/**
- * The session for the attached machine, or null when none is needed.
+ * One session PER MACHINE, keyed by machineId.
*
* Only REMOTE machines (another computer running this same daemon) require one: a cloud machine's RPCs
* are answered by the backend itself and its cards are plaintext, so there is nothing to establish and
* nobody at the far end to establish it with.
+ *
+ * A MAP RATHER THAN A FIELD because the dial's carousel is no longer one machine's: it holds every
+ * agent on every machine at once, so this daemon is talking to N far ends concurrently and each one
+ * has its own key. Every frame in and out therefore has to say WHICH machine it belongs to before it
+ * can be encrypted or read — which is exactly what the backend's outer `machineId` tag is for
+ * (hub.ts deliverUpLocal tags every commander frame with it).
*/
- private crypto: RelaySessionCrypto | null = null
- private cryptoWaiter: { resolve: () => void; reject: (e: Error) => void; timer: NodeJS.Timeout } | null = null
+ private readonly sessions = new Map<string, RelaySessionCrypto>()
+ private readonly cryptoWaiters = new Map<string, { resolve: () => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>()
+ /** In-flight handshakes, so N concurrent callers for one machine send exactly ONE hello. */
+ private readonly handshakes = new Map<string, Promise<void>>()
+
+
constructor(private readonly opts: DeviceLinkOpts) {}
@@ -123,29 +142,45 @@ export class DeviceLink {
}
/**
- * Bring up the E2EE session for a machine that needs one.
+ * Bring up the E2EE session for a machine that needs one, IF it does not already have a live one.
*
* The trust anchor is the PINNED key from `harness link import`, never anything the backend hands over:
* a key directory would make the relay the trust anchor, which is the exact property end-to-end
* encryption exists to deny it.
+ *
+ * Idempotent and safe to call before every RPC: a machine whose session is already up returns without
+ * a frame. That is what lets the caller stop tracking handshake state — the aggregated agent list talks
+ * to whichever machines it needs, whenever it needs them, and each one is established on first use.
*/
- private async establish(machineId: string): Promise<void> {
- this.crypto = null
+ async establish(machineId: string): Promise<void> {
+ if (!machineId) return
+ if (this.sessions.get(machineId)?.ready) return
+ // A second caller JOINS the first handshake rather than starting a rival one: two `e2e_hello`s for
+ // the same machine race, and the welcome for the loser would resolve against a session that has
+ // already been replaced in the map.
+ const inflight = this.handshakes.get(machineId)
+ if (inflight) return inflight
const peer = this.opts.peer(machineId)
if (!peer) return // a cloud machine, or one whose RPCs the backend answers itself
const crypto = new RelaySessionCrypto({ machineId, selfIdentity: this.opts.identity, peerPub: b64d(peer.pub) })
- this.crypto = crypto
- await new Promise<void>((resolve, reject) => {
+ this.sessions.set(machineId, crypto)
+ const handshake = new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
- this.cryptoWaiter = null
+ this.cryptoWaiters.delete(machineId)
reject(new Error('the machine did not answer the E2EE hello'))
}, RPC_TIMEOUT_MS)
- this.cryptoWaiter = { resolve, reject, timer }
- this.send(crypto.helloFrame() as DeviceFrame)
- })
+ this.cryptoWaiters.set(machineId, { resolve, reject, timer })
+ // The hello goes in clear AND tagged: the backend routes a device frame by its outer machineId, so
+ // without the tag the handshake for a background machine would be delivered to the active one.
+ this.send({ ...(crypto.helloFrame() as DeviceFrame), machineId })
+ }).finally(() => { this.handshakes.delete(machineId) })
+ this.handshakes.set(machineId, handshake)
+ await handshake
this.opts.log(`device: e2e session ready ${machineId}`)
}
+
+
/** Let go of whatever is attached. The socket is closed: nothing else on it is being watched. */
/** Detach from the machine but KEEP the socket: the dial is still plugged in. */
detach(): void {
@@ -176,20 +211,34 @@ export class DeviceLink {
this.opts.log(`device: dropped ${frame.type ?? '?'} — no link`)
return
}
- // Wrapped only once the session is up. `e2e_*` frames are the handshake itself and must go in clear,
- // or the far end would need the key to learn the key.
- const out = this.crypto?.ready && !String(frame.type ?? '').startsWith('e2e_')
- ? (this.crypto.wrapOutgoing(frame as Record<string, unknown>) as DeviceFrame)
+ // Wrapped only once THAT MACHINE's session is up. `e2e_*` frames are the handshake itself and must go
+ // in clear, or the far end would need the key to learn the key.
+ //
+ // The key is picked by the frame's own `machineId`, falling back to the attached machine for the
+ // frames that predate multi-machine (machine_select, ping). Encrypting with the wrong machine's key
+ // is the one failure here that looks like nothing at all: the far end drops it silently.
+ const session = this.sessions.get(frame.machineId || this.attached)
+ const out = session?.ready && !String(frame.type ?? '').startsWith('e2e_')
+ ? (session.wrapOutgoing(frame as Record<string, unknown>) as DeviceFrame)
: frame
+
try { this.ws.send(JSON.stringify(out)) } catch (err) {
this.opts.log(`device: send ${frame.type ?? '?'} failed (${(err as Error).message})`)
}
}
- /** One request/response, correlated by `requestId`. Rejects on timeout or an `error` in the reply. */
- async rpc(type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> {
+ /**
+ * One request/response, correlated by `requestId`. Rejects on timeout or an `error` in the reply.
+ *
+ * `machineId` names the machine to ask; omitted means the attached one. Passing it is what makes an RPC
+ * to a machine the dial is not currently rendering possible at all — the backend routes a device frame
+ * by its outer tag and answers from that machine's node.
+ */
+ async rpc(type: string, payload: Record<string, unknown> = {}, machineId = ''): Promise<Record<string, unknown>> {
if (this.ws?.readyState !== WebSocket.OPEN) throw new Error('not connected')
+ if (machineId) await this.establish(machineId)
const requestId = randomUUID()
+
return new Promise<Record<string, unknown>>((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(requestId)
@@ -197,7 +246,8 @@ export class DeviceLink {
reject(new Error(`${type} timed out`))
}, RPC_TIMEOUT_MS)
this.pending.set(requestId, { resolve, reject, timer })
- this.send({ type, payload: { ...payload, requestId } })
+ this.send(machineId ? { type, machineId, payload: { ...payload, requestId } } : { type, payload: { ...payload, requestId } })
+
})
}
@@ -238,13 +288,20 @@ export class DeviceLink {
// RelaySessionCrypto below. Advertising it before that was true would turn a clean
// E2EE_REQUIRED error into a hang, which is why it went in only once the session did.
//
- // `multi_machine` is deliberately NOT advertised: it would attach a commander to EVERY machine,
- // including this computer's own, whose daemon would then burn an LLM recap on turns nobody is
- // watching and echo its own cards back to itself through the cloud.
+ // `multi_machine` is what makes the dial's carousel span machines: the backend then holds a
+ // commander client on EVERY machine at once, so each one's node runs its recap and every frame
+ // it sends arrives tagged with its machineId. Without it only the selected machine is attached
+ // and an RPC aimed at any other is answered by the wrong node.
+ //
+ // It also attaches a commander to THIS computer's own machine, which is the reason it was held
+ // back before. Two guards make that harmless: the local machine's own cards are dropped on
+ // arrival (see onMessage), and nothing local is ever ASKED for over this lane — cableHost reads
+ // this computer's agents in-process, exactly as it did.
this.send({
type: 'device_hello',
- payload: { chip: 'harness-cli', firmwareVersion: VERSION, caps: ['e2ee_data'] },
+ payload: { chip: 'harness-cli', firmwareVersion: VERSION, caps: ['e2ee_data', 'multi_machine'] },
})
+
this.armPing()
resolve()
}
@@ -279,17 +336,21 @@ export class DeviceLink {
})
}
- private onWelcome(payload: Record<string, unknown>): void {
- if (!this.crypto) return
- if (!this.crypto.handleWelcome(payload)) { this.failCrypto(new Error('E2EE_HANDSHAKE_FAILED')); return }
- if (this.cryptoWaiter) { clearTimeout(this.cryptoWaiter.timer); this.cryptoWaiter.resolve(); this.cryptoWaiter = null }
+ private onWelcome(machineId: string, payload: Record<string, unknown>): void {
+ const crypto = this.sessions.get(machineId)
+ if (!crypto) return
+ if (!crypto.handleWelcome(payload)) { this.failCrypto(machineId, new Error('E2EE_HANDSHAKE_FAILED')); return }
+ const waiter = this.cryptoWaiters.get(machineId)
+ if (waiter) { clearTimeout(waiter.timer); this.cryptoWaiters.delete(machineId); waiter.resolve() }
}
- private failCrypto(err: Error): void {
- this.crypto = null
- if (this.cryptoWaiter) { clearTimeout(this.cryptoWaiter.timer); this.cryptoWaiter.reject(err); this.cryptoWaiter = null }
+ private failCrypto(machineId: string, err: Error): void {
+ this.sessions.delete(machineId)
+ const waiter = this.cryptoWaiters.get(machineId)
+ if (waiter) { clearTimeout(waiter.timer); this.cryptoWaiters.delete(machineId); waiter.reject(err) }
}
+
private armPing(): void {
if (this.pingTimer) clearInterval(this.pingTimer)
// App-level, not a WS ping: the backend refreshes device presence on any inbound frame, and a socket
@@ -303,7 +364,13 @@ export class DeviceLink {
for (const [, p] of this.pending) { clearTimeout(p.timer); p.reject(new Error(why)) }
this.pending.clear()
if (this.selectWaiter) { clearTimeout(this.selectWaiter.timer); this.selectWaiter.reject(new Error(why)); this.selectWaiter = null }
- this.failCrypto(new Error(why))
+ // EVERY session, not just the attached machine's. The socket is what carried all of them; a session
+ // left in the map after it dies would encrypt the first frame of the next connection with a key the
+ // far end has already forgotten, and that frame is dropped in silence at the other end.
+ for (const machineId of [...this.cryptoWaiters.keys(), ...this.sessions.keys()]) {
+ this.failCrypto(machineId, new Error(why))
+ }
+
const ws = this.ws
this.ws = null
this.attached = ''
@@ -337,17 +404,31 @@ export class DeviceLink {
let frame: DeviceFrame
try { frame = JSON.parse(raw.toString()) as DeviceFrame } catch { return }
- if (frame.type === 'e2e_welcome') { this.onWelcome((frame.payload ?? {}) as Record<string, unknown>); return }
- if (frame.type === 'e2e_rekey') { this.crypto?.handleRekey((frame.payload ?? {}) as Record<string, unknown>); return }
+ // WHICH MACHINE THIS CAME FROM. The backend tags every commander frame with it (hub.ts
+ // deliverUpLocal), and with N machines attached at once it is the only thing that says which key
+ // opens the payload. Empty means a backend-authored frame with no machine behind it.
+ const from = typeof frame.machineId === 'string' ? frame.machineId : ''
+ // THE ECHO GUARD. `multi_machine` subscribes this socket to this computer's own machine, so every
+ // card its node publishes comes back down here. Every one of them was already delivered in-process
+ // by the local path, and forwarding the cloud copy too would double every turn card on the dial.
+ // RPC replies are exempt: nothing ever ASKS this lane about the local machine, so a `_result` tagged
+ // with it can only be a reply this daemon is genuinely waiting for.
+ if (from && from === this.opts.localMachineId() && !String(frame.type ?? '').endsWith('_result')) return
+
+
+ if (frame.type === 'e2e_welcome') { this.onWelcome(from, (frame.payload ?? {}) as Record<string, unknown>); return }
+ if (frame.type === 'e2e_rekey') { this.sessions.get(from)?.handleRekey((frame.payload ?? {}) as Record<string, unknown>); return }
if (frame.type === 'e2e_denied') {
// The far end knows this daemon's key and rejected it — the pin is stale, not merely missing.
- this.opts.log('device: e2e denied — re-run `harness link import` for this machine')
- this.failCrypto(new Error('E2EE_DENIED'))
+ this.opts.log(`device: e2e denied ${from} — re-run \`harness link import\` for this machine`)
+ this.failCrypto(from, new Error('E2EE_DENIED'))
return
}
- if (this.crypto?.ready) {
- const plain = this.crypto.unwrapIncoming(frame as Record<string, unknown>)
+ const session = this.sessions.get(from)
+ if (session?.ready) {
+ const plain = session.unwrapIncoming(frame as Record<string, unknown>)
+
if (!plain) {
// The single most misleading failure this lane has: an undecryptable card is indistinguishable
// from no card at all, and the dial just sits through a whole turn showing nothing.
diff --git a/cli/src/lib/voiceRouter.ts b/cli/src/lib/voiceRouter.ts
index 60ea4ecf9..58a5ee165 100644
--- a/cli/src/lib/voiceRouter.ts
+++ b/cli/src/lib/voiceRouter.ts
@@ -20,6 +20,11 @@ export interface RouterAgent {
/** Recaps of the agent's last few completed turns (up to 3), joined — a broader, less skewed picture
* of what it's working on than a single turn. */
recentSummary?: string
+ /** The machine it runs on. The candidate list spans every machine the owner has, so this is the only
+ * thing that separates two agents with the same name on two computers — and it is how a spoken "the
+ * one on the mac mini" can be answered at all. */
+ machine?: string
+
}
export interface RouteDecision {
@@ -161,7 +166,8 @@ function logDecision(via: string, agents: RouterAgent[], decision: RouteDecision
export function buildRouterPrompt(transcript: string, agents: RouterAgent[]): string {
const lines = agents
- .map((a) => `- id=${a.id} | name="${a.name}" | recent: ${a.recentSummary?.trim() || '(no activity yet)'}`)
+ .map((a) => `- id=${a.id} | name="${a.name}"${a.machine ? ` | machine="${a.machine}"` : ''} | recent: ${a.recentSummary?.trim() || '(no activity yet)'}`)
+
.join('\n')
return (
`You are a ROUTER. Assign ONE incoming voice task to the single best-fit agent from the fixed list ` +