The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(cli): a linked machine that refuses every agent list drops off the dial after 30 s (#2387)
harness-for-autonomous[bot]5228589d0961
diff --git a/cli/src/services/fleetRouter.spec.ts b/cli/src/services/fleetRouter.spec.tsindex f03c1678a..56186fab7 100644--- a/cli/src/services/fleetRouter.spec.ts+++ b/cli/src/services/fleetRouter.spec.ts@@ -52,6 +52,21 @@ function fleetOf(machines: FleetMachine[], byMachine: Record<string, Array<{ id:const flush = () => new Promise((resolve) => setTimeout(resolve, 0))+/** The real fleet over a scripted lane that lists r1; `alive` is a reply of the machine's own under its session. */+function laneOf() {+ const rows = [{ ...REMOTE, local: false, agentCount: 1 }]+ let heard: (machineId: string) => void = () => {}+ const link = {+ selectedMachine: '', onFrame: () => () => {}, onUndelivered: () => () => {},+ onAlive: (cb: (machineId: string) => void) => { heard = cb; return () => {} },+ rpc: vi.fn(async (): Promise<Record<string, unknown>> => ({ agents: [{ id: 'r1', name: 'api', engine: 'claude' }] })),+ resetSession: vi.fn(() => true), sendSealed: vi.fn(async () => {}),+ }+ const fleet = new DeviceFleet({ list: { list: () => ({ machines: rows, source: 'backend' as const }), find: (id: string) => rows.find((r) => r.machineId === id) } as never,+ link: link as never, hasPeerLink: () => true, log: () => {} })+ return { link, fleet, alive: (machineId: string) => heard(machineId) }+}+/** Two reads: the first starts the background refresh, the second reads what it wrote. */async function settled(router: FleetRouter) {await router.listAgentsFlat()@@ -207,6 +222,130 @@ describe('which machine an agent is on', () => {expect(fleet.reachable('other')).toMatchObject({ ok: false })})+ // #2381's second review: a machine that answers every list with an error answers under its own session too, so the+ // rule above kept its last good tiles for ever (before #2381, 30 s). A refusal is an answer, not lateness: its tiles+ // keep the same grace, counted from its first refusal after the last good list.+ it('drops the tiles of a machine that answers every list with an error, 30 s after its first refusal, and takes them back when it lists again', async () => {+ const { link, fleet, alive } = laneOf()+ const log = vi.fn()+ const router = new FleetRouter(localOf({ log }), fleet)+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])+ link.rpc.mockImplementation(async () => { alive('other'); throw new Error('UNSUPPORTED') })+ const now = Date.now()+ for (const later of [60_000, 70_000, 85_000]) {+ vi.spyOn(Date, 'now').mockReturnValue(now + later)+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])+ }+ vi.spyOn(Date, 'now').mockReturnValue(now + 95_000)+ await settled(router)+ expect(log).toHaveBeenCalledWith('cable: office-imac dropped off the carousel (UNSUPPORTED)')+ expect(await router.listAgentsFlat()).toEqual([])+ // It answers, so it is up: its session stays, and nothing about it is called unreachable.+ expect(link.resetSession).not.toHaveBeenCalled()+ expect(fleet.reachable('other')).toMatchObject({ ok: true })+ // A good list again: its tiles are back, and a later refusal has its whole grace once more.+ link.rpc.mockImplementation(async () => ({ agents: [{ id: 'r1', name: 'api', engine: 'claude' }] }))+ vi.spyOn(Date, 'now').mockReturnValue(now + 101_000)+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])+ link.rpc.mockImplementation(async () => { alive('other'); throw new Error('UNSUPPORTED') })+ vi.spyOn(Date, 'now').mockReturnValue(now + 200_000)+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])+ })++ it('shows a machine whose first list was refused once it lists, with no clock left over from the refusals', async () => {+ const { link, fleet, alive } = laneOf()+ link.rpc.mockImplementation(async () => { alive('other'); throw new Error('UNSUPPORTED') })+ const router = new FleetRouter(localOf(), fleet)+ expect(await settled(router)).toEqual([])+ const now = Date.now()+ vi.spyOn(Date, 'now').mockReturnValue(now + 60_000)+ expect(await settled(router)).toEqual([])+ link.rpc.mockImplementation(async () => ({ agents: [{ id: 'r1', name: 'api', engine: 'claude' }] }))+ vi.spyOn(Date, 'now').mockReturnValue(now + 66_000)+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])+ link.rpc.mockImplementation(async () => { alive('other'); throw new Error('UNSUPPORTED') })+ vi.spyOn(Date, 'now').mockReturnValue(now + 72_000)+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])+ })++ it('keeps a slow machine whose lists come back good, however late each one is', async () => {+ let answer: (res: Record<string, unknown>) => void = () => {}+ const { link, fleet } = laneOf()+ const log = vi.fn()+ const router = new FleetRouter(localOf({ log }), fleet)+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])+ link.rpc.mockImplementation(() => new Promise((resolve) => { answer = resolve }))+ const now = Date.now()+ for (let round = 1; round <= 4; round++) {+ vi.spyOn(Date, 'now').mockReturnValue(now + round * 50_000)+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1']) // asked, and still out+ vi.spyOn(Date, 'now').mockReturnValue(now + round * 50_000 + 40_000)+ expect((await router.listAgentsFlat()).map((a) => a.id)).toEqual(['r1'])+ answer({ agents: [{ id: 'r1', name: 'api', engine: 'claude' }] })+ await flush()+ }+ expect(link.rpc).toHaveBeenCalledTimes(5)+ expect(log).not.toHaveBeenCalledWith(expect.stringContaining('dropped off the carousel'))+ })++ it('restarts the refusal clock on each good list', async () => {+ const { link, fleet, alive } = laneOf()+ const log = vi.fn()+ const router = new FleetRouter(localOf({ log }), fleet)+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])+ const refuse = () => link.rpc.mockImplementation(async () => { alive('other'); throw new Error('UNSUPPORTED') })+ const list = () => link.rpc.mockImplementation(async () => ({ agents: [{ id: 'r1', name: 'api', engine: 'claude' }] }))+ const now = Date.now()+ const at = async (later: number) => { vi.spyOn(Date, 'now').mockReturnValue(now + later); return (await settled(router)).map((a) => a.id) }+ refuse()+ expect(await at(10_000)).toEqual(['r1']) // its first refusal: the clock starts+ expect(await at(35_000)).toEqual(['r1'])+ list()+ expect(await at(41_000)).toEqual(['r1']) // a good list: the clock stops+ refuse()+ expect(await at(50_000)).toEqual(['r1']) // and starts again here, not at 10 s+ expect(await at(75_000)).toEqual(['r1'])+ expect(log).not.toHaveBeenCalledWith(expect.stringContaining('dropped off the carousel'))+ await at(85_000)+ expect(log).toHaveBeenCalledWith('cable: office-imac dropped off the carousel (UNSUPPORTED)')+ expect(await router.listAgentsFlat()).toEqual([])+ })++ it('never puts back the tiles of a machine that went offline, lost its link or left the list while its list was out', async () => {+ const cases = [['offline', ['r1'], 'list'], ['needs-link', ['r1'], 'refusal'], ['removed', ['r1'], 'list'], ['removed', ['r1'], 'refusal'],+ ['offline', [], 'refusal'], ['needs-link', [], 'list']] as const+ for (const [gone, first, lands] of cases) {+ const machines: FleetMachine[] = [{ ...REMOTE }]+ const fleet = fleetOf(machines, { other: first.map((id) => ({ id, name: 'api' })) })+ const router = new FleetRouter(localOf(), fleet)+ expect((await settled(router)).map((a) => a.id)).toEqual(first)+ const out: Array<{ resolve: (agents: never) => void; reject: (err: Error) => void }> = []+ ;(fleet.listAgents as ReturnType<typeof vi.fn>).mockImplementation(() => new Promise<never>((resolve, reject) => { out.push({ resolve, reject }) }))+ const now = Date.now()+ vi.spyOn(Date, 'now').mockReturnValue(now + 6_000)+ await router.listAgentsFlat()+ expect(out).toHaveLength(1)+ if (gone === 'removed') machines.length = 0+ else machines[0].state = gone+ expect(await settled(router)).toEqual([])+ // Its answer lands after, a list or a refusal, whether it had tiles or none: it changes nothing the dial now shows.+ if (lands === 'list') out[0].resolve([{ id: 'r1', name: 'api' }] as never)+ else out[0].reject(new Error('UNSUPPORTED'))+ await flush()+ expect(await router.listAgentsFlat()).toEqual([])+ // Back, ready: its tiles come from a list asked now, never from the one asked before it went.+ machines.length = 0+ machines.push({ ...REMOTE })+ vi.spyOn(Date, 'now').mockReturnValue(now + 12_000)+ expect(await router.listAgentsFlat()).toEqual([])+ expect(out).toHaveLength(2)+ out[1].resolve([{ id: 'r2', name: 'web' }] as never)+ await flush()+ expect((await router.listAgentsFlat()).map((a) => a.id)).toEqual(['r2'])+ vi.restoreAllMocks()+ }+ })+it('keeps a machine’s agents while the backend cannot be asked, and drops them when the machine says offline', async () => {const machines: FleetMachine[] = [{ ...REMOTE }]const fleet = fleetOf(machines, { other: [{ id: 'r1', name: 'api' }] })diff --git a/cli/src/services/fleetRouter.ts b/cli/src/services/fleetRouter.tsindex 073ed3ec6..4f0444eb8 100644--- a/cli/src/services/fleetRouter.ts+++ b/cli/src/services/fleetRouter.ts@@ -81,6 +81,13 @@ function placeholderId(computerId: string): string {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+/** How the lane says an agent list went unanswered (DeviceLink.rpc). Every other failure of a list the machine+ * answered during is its answer: a refusal. */+const LIST_TIMED_OUT = 'agents_list timed out'++/** Each other machine's agents, as last read. `asked` throttles the round; `at` ages the answer; `refusedSince` is the+ * machine's first refusal of a list since its last good one. */+interface RemoteList { agents: CableAgent[]; at: number; asked: number; refusedSince?: number }/** 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. */@@ -102,8 +109,8 @@ export class FleetRouter implements FleetRouting {* daemon restart is not one the five-minute window would have carried anyway. */private lastTurn?: { agentId: string; at: number }- /** 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 }>()+ /** Each other machine's agents, as last read (RemoteList). */+ private readonly remoteAgents = new Map<string, RemoteList>()/** 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. */@@ -397,6 +404,14 @@ export class FleetRouter implements FleetRouting {* seconds — then putting them back — is a far worse lie than briefly showing a list that is a minute* old.*+ * A machine that answers under its own session is up, and how its list failed says why. Timed out: it is+ * slow, and its tiles stay however long that lasts (Diego, 10-30, #2381). Answered with an error: it is+ * refusing, and its tiles keep the same grace, counted from its first refusal since its last good list+ * (#2381's second review: without that, a machine that refuses every list kept its tiles for ever).+ *+ * A list still out when its machine goes offline, loses its link or leaves the list changes nothing when it+ * lands: the tiles that machine had are gone, and only a list asked after it is back brings them again.+ ** `unknown` is NOT a reason to drop anything, and reading it as one cost a morning. It means the* backend could not be asked — `MachineListCache.degrade()` sets every machine to it in one go when* the list cannot be refreshed, on the stated principle that the rows are "stale but not wrong". The@@ -409,6 +424,9 @@ export class FleetRouter implements FleetRouting {if (!this.fleet) returnconst fleet = this.fleetconst now = Date.now()+ // Gone from the list (unlinked, its access revoked, signed out): what it said is not kept for its return.+ const listed = new Set(machines.map((m) => m.id))+ for (const id of [...this.remoteAgents.keys()]) if (!listed.has(id)) this.remoteAgents.delete(id)for (const m of machines) {if (m.local) continueconst entry = this.remoteAgents.get(m.id)@@ -416,8 +434,9 @@ export class FleetRouter implements FleetRouting {// The machine ITSELF says it has nothing to offer, which is different from not being able to// ask it. No grace period, but never silently: an agent leaving the carousel is exactly the// event that is impossible to diagnose after the fact from its absence.- if (entry && entry.agents.length) {- this.remoteAgents.set(m.id, { agents: [], at: now, asked: entry.asked })+ // Replaced even when empty, so a list still out from before it went cannot fill it when it lands.+ if (entry) this.remoteAgents.set(m.id, { agents: [], at: now, asked: entry.asked })+ if (entry?.agents.length) {this.local.log(`cable: ${m.name} is ${m.state} — its ${entry.agents.length} agents left the carousel`)}continue@@ -427,25 +446,36 @@ export class FleetRouter implements FleetRouting {if (entry && now - entry.asked < REMOTE_REFRESH_MS) continueif (this.inFlight.has(m.id)) continuethis.inFlight.add(m.id)- this.remoteAgents.set(m.id, { agents: entry?.agents ?? [], at: entry?.at ?? 0, asked: now })+ // This entry, replaced only when the machine goes offline, loses its link or leaves the list, is what its+ // answer may change: one that lands after is about tiles no longer shown.+ const asking: RemoteList = { agents: entry?.agents ?? [], at: entry?.at ?? 0, asked: now, refusedSince: entry?.refusedSince }+ this.remoteAgents.set(m.id, asking)void fleet.listAgents(m.id).then((agents) => {- const before = this.remoteAgents.get(m.id)+ if (this.remoteAgents.get(m.id) !== asking) returnthis.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) {+ if (asking.agents.length !== agents.length) {this.local.log(`cable: ${m.name} → ${agents.length} agents`)}}).catch((err) => {- const before = this.remoteAgents.get(m.id)- // A machine that answered under its own session while this list was out is slow, not gone (Diego, 10-30:- // 15 carousel drops in a day of a Mac whose late replies kept arriving): its last good list stays.- const stale = before && Date.now() - before.at > REMOTE_GRACE_MS && fleet.reachable?.(m.id)?.ok !== true- if (stale) this.remoteAgents.set(m.id, { agents: [], at: Date.now(), asked: Date.now() })- if (before?.agents.length && stale) {- this.local.log(`cable: ${m.name} dropped off the carousel (${(err as Error).message})`)+ if (this.remoteAgents.get(m.id) !== asking) return+ const failedAt = Date.now()+ const message = (err as Error).message+ let stale: boolean+ if (fleet.reachable?.(m.id)?.ok !== true) stale = failedAt - asking.at > REMOTE_GRACE_MS+ // Answered under its own session while this list was out, and the list timed out: slow, not gone (Diego,+ // 10-30: 15 carousel drops in a day of a Mac whose late replies kept arriving). Its last good list stays.+ else if (message === LIST_TIMED_OUT) stale = false+ else {+ asking.refusedSince ??= failedAt+ stale = failedAt - asking.refusedSince > REMOTE_GRACE_MS+ }+ if (stale) this.remoteAgents.set(m.id, { agents: [], at: failedAt, asked: failedAt })+ if (asking.agents.length && stale) {+ this.local.log(`cable: ${m.name} dropped off the carousel (${message})`)}}).finally(() => this.inFlight.delete(m.id))