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.

fix(cli): a turn to a linked Mac that just went away is refused, not lost (#2395)

harness-for-autonomous[bot]316c5fea7308
diff --git a/cli/src/device/deviceFleet.spec.ts b/cli/src/device/deviceFleet.spec.ts
index 24d50b1f0..7e1143071 100644
--- a/cli/src/device/deviceFleet.spec.ts
+++ b/cli/src/device/deviceFleet.spec.ts
@@ -6,6 +6,7 @@
import { describe, expect, it, vi } from 'vitest'
import { DeviceFleet } from './deviceFleet.js'
+import { FleetRouter } from '../services/fleetRouter.js'
import { FleetError, type FleetEvent } from '../cable/machineFleet.js'
import { SESSION_GONE, type DeviceFrame, type Undelivered } from './deviceLink.js'
@@ -22,6 +23,7 @@ function make(over: { rows?: Partial<Listed>[]; linked?: string[]; rpc?: (t: str
let frameCb: ((f: DeviceFrame) => void) | null = null
let undeliveredCb: ((what: Undelivered) => void) | null = null
let aliveCb: ((machineId: string) => void) | null = null
+ let goneCb: ((machineId: string) => void) | null = null
const sent: DeviceFrame[] = []
const resets: string[] = []
const link = {
@@ -29,6 +31,7 @@ function make(over: { rows?: Partial<Listed>[]; linked?: string[]; rpc?: (t: str
onFrame: (cb: (f: DeviceFrame) => void) => { frameCb = cb; return () => {} },
onUndelivered: (cb: (what: Undelivered) => void) => { undeliveredCb = cb; return () => {} },
onAlive: (cb: (machineId: string) => void) => { aliveCb = cb; return () => {} },
+ onGone: (cb: (machineId: string) => void) => { goneCb = cb; return () => {} },
attach: vi.fn(async () => {}),
online: vi.fn(async () => {}),
detach: vi.fn(),
@@ -48,7 +51,7 @@ function make(over: { rows?: Partial<Listed>[]; linked?: string[]; rpc?: (t: str
log: () => {},
})
return { fleet, link, sent, resets, say: (f: DeviceFrame) => frameCb?.(f), undelivered: (what: Undelivered) => undeliveredCb?.(what),
- alive: (machineId: string) => aliveCb?.(machineId) }
+ alive: (machineId: string) => aliveCb?.(machineId), gone: (machineId: string) => goneCb?.(machineId) }
}
describe('DeviceFleet', () => {
@@ -125,6 +128,26 @@ describe('DeviceFleet', () => {
expect(resets).toEqual([])
})
+ // #2387's review: B's daemon gone, a turn to its agent was sent to be lost for up to 50 s, while a list to it waited out
+ // its time. Told it went away (DeviceLink.onGone), the router refuses the turn at once, and sends again once it answers.
+ it('refuses a turn to a machine the lane says went away at once, and sends to it again once it answers', async () => {
+ const { fleet, sent, resets, alive, gone } = make({ rpc: async () => ({ agents: [{ id: 'r1', name: 'api', engine: 'claude' }] }) })
+ const log = vi.fn()
+ const router = new FleetRouter({ machineName: () => 'here', machineId: () => 'this-one', computerId: () => 'c', sessions: () => [],
+ displayName: () => '', desk: () => [], sendTurn: vi.fn(), stopTurn: vi.fn(), answer: vi.fn(), recent: () => [], recentAsks: () => [], log }, fleet)
+ await router.listAgentsFlat()
+ await vi.waitFor(async () => expect((await router.listAgentsFlat()).map((a) => a.id)).toEqual(['r1']))
+ expect(router.sendTurn('r1', 'before')).toEqual({ ok: true })
+ gone('m1')
+ expect(fleet.reachable('m1')).toMatchObject({ ok: false })
+ expect(router.sendTurn('r1', 'while it is away')).toMatchObject({ ok: false, machine: 'office-imac', reason: 'the last request to it did not come back' })
+ expect(sent.filter((frame) => frame.type === 'message').map((frame) => (frame.payload as { content?: string }).content)).toEqual(['before'])
+ // The word may be the relay's: it throws no session away and counts no miss.
+ expect(resets).toEqual([])
+ alive('m1')
+ expect(router.sendTurn('r1', 'back')).toEqual({ ok: true })
+ })
+
it('counts no miss for a request its machine proved alive during, however it ended', async () => {
let fail!: (error: Error) => void
const { fleet, resets, alive } = make({ rpc: () => new Promise((_resolve, reject) => { fail = reject }) })
@@ -337,7 +360,7 @@ describe('DeviceFleet', () => {
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 () => {} }, onUndelivered: () => () => {}, onAlive: () => () => {} } as never,
+ link: { selectedMachine: 'm1', onFrame: (cb: never) => { frameCb = cb; return () => {} }, onUndelivered: () => () => {}, onAlive: () => () => {}, onGone: () => () => {} } as never,
hasPeerLink: () => true,
log: () => {},
})
@@ -354,7 +377,7 @@ describe('DeviceFleet', () => {
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 () => {} }, onUndelivered: () => () => {}, onAlive: () => () => {} } as never,
+ link: { selectedMachine: 'm1', onFrame: (cb: never) => { frameCb = cb; return () => {} }, onUndelivered: () => () => {}, onAlive: () => () => {}, onGone: () => () => {} } as never,
hasPeerLink: () => true,
log: () => {},
})
diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.ts
index 203379cf4..1a13b209a 100644
--- a/cli/src/device/deviceFleet.ts
+++ b/cli/src/device/deviceFleet.ts
@@ -100,6 +100,7 @@ export class DeviceFleet implements MachineFleet {
this.opts.link.onFrame((frame) => this.onFrame(frame))
this.opts.link.onUndelivered((what) => this.onUndelivered(what))
this.opts.link.onAlive((machineId) => this.alive(machineId))
+ this.opts.link.onGone((machineId) => this.gone(machineId))
}
async list(): Promise<{ machines: FleetMachine[]; source: 'backend' | 'local' | 'signed-out' }> {
@@ -246,6 +247,17 @@ export class DeviceFleet implements MachineFleet {
this.misses.delete(machineId)
}
+ /**
+ * A machine went away (DeviceLink.onGone): the backend said it went offline, or the lane under its session closed. A
+ * turn to it is refused from now, not sent to be lost, until it answers again under a new session (`alive`). Its misses
+ * stay as they were: the word may be the relay's, so it throws nothing more away (#2387's review: a turn to a Mac that
+ * had just gone was lost for up to 50 s while a list to it waited out its time).
+ */
+ private gone(machineId: string): void {
+ this.health.set(machineId, { ok: false, at: Date.now() })
+ this.opts.log(`device: ${machineId.slice(0, 8)} went away — turns to it are refused until it answers again`)
+ }
+
/**
* Whether the last thing we asked this machine came back.
*
diff --git a/cli/src/device/deviceLink.spec.ts b/cli/src/device/deviceLink.spec.ts
index 66d05f45f..fa657190f 100644
--- a/cli/src/device/deviceLink.spec.ts
+++ b/cli/src/device/deviceLink.spec.ts
@@ -55,6 +55,8 @@ async function fakeDeviceWs(opts: { refuseToken?: string } = {}) {
/** Frames for machines, as the lane sent them: its own control frames left out. */
forMachines: () => received.filter((frame) => frame.type !== 'device_hello' && frame.type !== 'machines_watch' && frame.type !== 'ping'),
send: (frame: Frame) => socket?.send(JSON.stringify(frame)),
+ /** The socket to this lane closing under it, as a relay restart or a network change does. */
+ drop: () => socket?.terminate(),
on: (listener: (frame: Frame) => void) => { listeners.add(listener) },
close: () => new Promise<void>((resolve) => { for (const client of wss.clients) client.terminate(); wss.close(() => resolve()) }),
}
@@ -843,14 +845,34 @@ describe('a late reply from a slow machine', () => {
expect(seal.hello).toHaveBeenCalledTimes(2)
})
- it('has longer to answer an agent list, a background read, than anything a person waits on', async () => {
- const { link, lines } = await upWithAlive()
+ /** Wait for a frame over the real socket without moving the faked timers (vi.waitFor moves them). */
+ const heardOver = async (check: () => boolean): Promise<void> => {
+ for (let i = 0; i < 2_000 && !check(); i++) await new Promise((resolve) => setImmediate(resolve))
+ expect(check()).toBe(true)
+ }
+
+ /** A lane on a clock of the test's own, with LINKED's session up (its welcome heard at 1 000). */
+ async function upOnClock() {
+ let clock = 1_000
+ const lane$ = await lane({ now: () => clock })
+ await lane$.link.online()
+ await lane$.link.establish(LINKED)
+ return { ...lane$, tick: (ms: number) => { clock += ms } }
+ }
+
+ it('has longer to answer an agent list, a background read, than anything a person waits on, while its machine answers meanwhile', async () => {
+ const { server, seal, link, lines, tick } = await upOnClock()
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
try {
const list = link.rpc('agents_list', {}, LINKED).catch((error: Error) => error)
const models = link.rpc('models_list', {}, LINKED).catch((error: Error) => error)
await vi.advanceTimersByTimeAsync(15_000)
+ tick(15_000)
expect(await models).toEqual(new Error('models_list timed out'))
+ // Its late answer to something else: the machine is slow, not gone, and the list waits on.
+ seal.open.mockResolvedValueOnce({ frame: { type: 'models_list_result', machineId: LINKED, payload: { requestId: 'late', models: [] } } })
+ server.send({ type: 'models_list_result', machineId: LINKED, payload: { __e2e: { n: 3 } } })
+ await heardOver(() => lines.includes('device: unmatched models_list_result'))
await vi.advanceTimersByTimeAsync(29_999)
expect(lines.some((line) => line.includes('agents_list timed out'))).toBe(false)
await vi.advanceTimersByTimeAsync(1)
@@ -858,4 +880,75 @@ describe('a late reply from a slow machine', () => {
expect(lines).toContain('device: agents_list timed out after 45000 ms')
} finally { vi.useRealTimers() }
})
+
+ // #2387's review: B's daemon killed and nothing telling this lane, a list to it waited 45 s, and a turn sent meanwhile
+ // was lost instead of refused. Heard from: a reply that proves the machine (as onAlive), or its welcome to our hello.
+ it('fails a list to a machine nothing has been heard from for 30 s then, and the next after 15 s', async () => {
+ const { link, lines, tick } = await upOnClock()
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ tick(5_000)
+ const list = link.rpc('agents_list', {}, LINKED).catch((error: Error) => error)
+ await vi.advanceTimersByTimeAsync(24_999)
+ expect(lines.some((line) => line.includes('agents_list timed out'))).toBe(false)
+ await vi.advanceTimersByTimeAsync(1)
+ tick(25_000)
+ expect(lines).toContain('device: agents_list timed out after 25000 ms')
+ expect(await list).toEqual(new Error('agents_list timed out'))
+ // Still nothing: the next list has the 15 s anything else has.
+ const next = link.rpc('agents_list', {}, LINKED).catch((error: Error) => error)
+ await vi.advanceTimersByTimeAsync(15_000)
+ expect(lines).toContain('device: agents_list timed out after 15000 ms')
+ expect(await next).toEqual(new Error('agents_list timed out'))
+ } finally { vi.useRealTimers() }
+ })
+
+ it('a reply in the clear or under the group key is not hearing from it: the list still fails when it went quiet', async () => {
+ const { server, seal, link, lines, tick } = await upOnClock()
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ const list = link.rpc('agents_list', {}, LINKED).catch((error: Error) => error)
+ // 10 s on, so a reply counted as heard would be news: the list would wait on to 45 s (#2395's security review 2).
+ await vi.advanceTimersByTimeAsync(10_000)
+ tick(10_000)
+ server.send({ type: 'agents_list_result', machineId: LINKED, payload: { requestId: 'forged', agents: [] } })
+ seal.open.mockResolvedValueOnce({ frame: { type: 'agents_list_result', machineId: LINKED, payload: { requestId: 'group', agents: [] } } })
+ server.send({ type: 'agents_list_result', machineId: LINKED, payload: { __e2e: { k: 'g', n: 1, epoch: 'e' } } })
+ await heardOver(() => lines.filter((line) => line.includes('unmatched agents_list_result')).length === 2)
+ await vi.advanceTimersByTimeAsync(20_000)
+ expect(lines).toContain('device: agents_list timed out after 30000 ms')
+ expect(await list).toEqual(new Error('agents_list timed out'))
+ } finally { vi.useRealTimers() }
+ })
+
+ // Both security reviews of #2395: a machine with no sealed session is never heard from, so its list failed at 15 s.
+ it('gives a list to a machine with no sealed session (a cloud machine) its full 45 s: it can prove nothing either way', async () => {
+ const { link, lines } = await upOnClock()
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ const list = link.rpc('agents_list', {}, CLOUD).catch((error: Error) => error)
+ await vi.advanceTimersByTimeAsync(44_999)
+ expect(lines.some((line) => line.includes('agents_list timed out'))).toBe(false)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(lines).toContain('device: agents_list timed out after 45000 ms')
+ expect(await list).toEqual(new Error('agents_list timed out'))
+ } finally { vi.useRealTimers() }
+ })
+
+ it('says a machine went away when the backend says it went offline, once per half minute, and when the lane closes under its session', async () => {
+ const { server, link } = await upOnClock()
+ await link.establish(LINKED_2)
+ const gone: string[] = []
+ link.onGone((machineId) => { gone.push(machineId) })
+ server.send({ type: 'node_status', machineId: LINKED, payload: { online: false } })
+ await vi.waitFor(() => expect(gone).toEqual([LINKED]))
+ // Again at once: the relay's word, within the limit, changes nothing. A machine this lane never spoke to is no news.
+ server.send({ type: 'machines_status', payload: { statuses: [{ machineId: LINKED, online: false }, { machineId: CLOUD, online: false }] } })
+ server.send({ type: 'node_status', machineId: LINKED_2, payload: { online: true } })
+ await new Promise((resolve) => setTimeout(resolve, 50))
+ expect(gone).toEqual([LINKED])
+ // The lane's socket closing takes every session it carried: LINKED_2's.
+ server.drop()
+ await vi.waitFor(() => expect(gone).toEqual([LINKED, LINKED_2]))
+ })
})
diff --git a/cli/src/device/deviceLink.ts b/cli/src/device/deviceLink.ts
index 5d3f0d730..5dba2a32a 100644
--- a/cli/src/device/deviceLink.ts
+++ b/cli/src/device/deviceLink.ts
@@ -52,6 +52,20 @@ const RPC_TIMEOUT_MS = 15_000
* is still found: two lists it never answers throw its session away (deviceFleet.ts).
*/
const LIST_TIMEOUT_MS = 45_000
+/**
+ * But not for a machine that has gone quiet: an agent list fails once nothing has been heard from its machine for this
+ * long (and never before RPC_TIMEOUT_MS), unless the machine answers something while it waits. #2387's review: B's
+ * daemon killed, and nothing tells this lane (the relay's list still says running), so a list to it was the only way to
+ * learn it was gone, and at 45 s a turn sent meanwhile was lost instead of refused. A dead machine's last answer was the
+ * list before, a few seconds before it died. Diego's slow Mac answered 5 to 25 s after the 15 s its requests then waited,
+ * so 20 to 40 s after each was sent (#2381's log gives no spread beyond that): one answering past 30 s has a turn refused
+ * for the few seconds until its answer lands, never lost, and keeps its tiles (#2395's security review 2 measured 31 to
+ * 40 s answers: refused for 2 to 11 s per list).
+ *
+ * Only a machine under a sealed session can be heard from (onAlive). Any other (a cloud machine, whose requests the
+ * backend answers) proves nothing either way, and its list keeps the full LIST_TIMEOUT_MS.
+ */
+const QUIET_MS = 30_000
const PING_EVERY_MS = 15_000
const BASE_DELAY_MS = 1_000
const MAX_DELAY_MS = 30_000
@@ -147,6 +161,7 @@ export class DeviceLink {
private readonly listeners = new Set<(frame: DeviceFrame) => void>()
private readonly undeliveredListeners = new Set<(what: Undelivered) => void>()
private readonly aliveListeners = new Set<(machineId: string) => void>()
+ private readonly goneListeners = new Set<(machineId: string) => void>()
/** Resolves when `machine_selected` lands, so callers can await the attach rather than poll for it. */
private selectWaiter: { resolve: () => void; reject: (e: Error) => void; timer: NodeJS.Timeout } | null = null
/**
@@ -190,6 +205,9 @@ export class DeviceLink {
private readonly renewLater = new Map<string, NodeJS.Timeout>()
/** Whether each machine is linked, read for frames that arrive with no session; kept a few seconds. */
private readonly linkedCache = new Map<string, { linked: boolean; at: number }>()
+ /** When each machine was last heard from under its current session: a reply that proves it (`onAlive`), or its welcome
+ * to this daemon's hello. Gone with the session. One entry per machine this lane holds a session with. */
+ private readonly heardAt = new Map<string, number>()
/** What the person sent under each machine's current session, and under the one before it. */
private readonly sent = new Map<string, SentUnder>()
private readonly sentBefore = new Map<string, SentUnder>()
@@ -223,6 +241,16 @@ export class DeviceLink {
return () => this.aliveListeners.delete(cb)
}
+ /**
+ * Hear each machine that went away: the backend said it went offline (within the per-machine limit on drops on its
+ * word), or this lane's socket closed under its session. A turn to it now would be lost, not refused, until it answers
+ * again (deviceFleet.ts). Returns how to stop hearing.
+ */
+ onGone(cb: (machineId: string) => void): () => void {
+ this.goneListeners.add(cb)
+ return () => this.goneListeners.delete(cb)
+ }
+
/** Hear each turn, stop or answer that did not reach its machine. Returns how to stop hearing. */
onUndelivered(cb: (what: Undelivered) => void): () => void {
this.undeliveredListeners.add(cb)
@@ -330,6 +358,7 @@ export class DeviceLink {
if (!this.sessions.has(machineId)) return false
this.retire(machineId)
this.sessions.delete(machineId)
+ this.heardAt.delete(machineId)
this.opts.seal.drop(machineId)
return true
}
@@ -348,6 +377,7 @@ export class DeviceLink {
} else if (this.sessions.has(machineId)) {
this.retire(machineId)
this.sessions.delete(machineId)
+ this.heardAt.delete(machineId)
this.opts.seal.drop(machineId)
}
for (const [requestId, waiter] of [...this.pending]) {
@@ -366,6 +396,7 @@ export class DeviceLink {
return
}
this.sessionGone(machineId)
+ for (const cb of this.goneListeners) cb(machineId)
}
private hasPending(machineId: string): boolean {
@@ -547,14 +578,25 @@ export class DeviceLink {
if (machineId && this.opts.peer(machineId) && !this.sessions.get(machineId)?.ready) throw new Error(SESSION_GONE)
const requestId = randomUUID()
+ const target = machineId || this.attached
const waitMs = type === 'agents_list' ? LIST_TIMEOUT_MS : RPC_TIMEOUT_MS
+ // A list to a machine already quiet fails as soon as it has been quiet QUIET_MS; one heard from meanwhile waits on.
+ const heard = this.heardAt.get(target)
+ const quietMs = type === 'agents_list' && this.sessions.get(target)?.ready ? Math.ceil(Math.max(RPC_TIMEOUT_MS, (heard ?? -Infinity) + QUIET_MS - this.now())) : waitMs
return new Promise<Record<string, unknown>>((resolve, reject) => {
- const timer = setTimeout(() => {
+ const timedOut = (afterMs: number): void => {
this.pending.delete(requestId)
- this.opts.log(`device: ${type} timed out after ${waitMs} ms`)
+ this.opts.log(`device: ${type} timed out after ${afterMs} ms`)
reject(new Error(`${type} timed out`))
- }, waitMs)
- this.pending.set(requestId, { resolve, reject, timer, machineId: machineId || this.attached })
+ }
+ const quiet = (): void => {
+ const since = this.heardAt.get(target)
+ if (since === undefined || since === heard) return timedOut(quietMs)
+ const waiter = this.pending.get(requestId)
+ if (waiter) waiter.timer = setTimeout(() => timedOut(waitMs), waitMs - quietMs)
+ }
+ const timer = quietMs < waitMs ? setTimeout(quiet, quietMs) : setTimeout(() => timedOut(waitMs), waitMs)
+ this.pending.set(requestId, { resolve, reject, timer, machineId: target })
this.send(machineId ? { type, machineId, payload: { ...payload, requestId } } : { type, payload: { ...payload, requestId } })
})
@@ -672,6 +714,7 @@ export class DeviceLink {
return
}
session.ready = true
+ this.heardAt.set(machineId, this.now())
const waiter = this.cryptoWaiters.get(machineId)
if (waiter) { clearTimeout(waiter.timer); this.cryptoWaiters.delete(machineId); waiter.resolve() }
// Inside the inbound queue, so what was held is read before anything that came after the welcome.
@@ -680,6 +723,7 @@ export class DeviceLink {
private failCrypto(machineId: string, err: Error): void {
if (this.sessions.get(machineId)) this.retire(machineId)
+ this.heardAt.delete(machineId)
if (this.sessions.delete(machineId)) this.opts.seal.drop(machineId)
this.drop(machineId, 'its session could not be made')
const waiter = this.cryptoWaiters.get(machineId)
@@ -765,9 +809,11 @@ export class DeviceLink {
// 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.
+ const gone = [...this.sessions.keys()]
for (const machineId of [...this.cryptoWaiters.keys(), ...this.sessions.keys()]) {
this.failCrypto(machineId, new Error(why))
}
+ this.heardAt.clear()
this.drop(null, why)
// What was sent on this socket is unknowable now: none of it is named by a later refusal.
this.sent.clear()
@@ -778,6 +824,8 @@ export class DeviceLink {
this.attached = ''
this.state = 'idle'
try { ws?.close() } catch { /* already gone */ }
+ // Nothing reaches them until a new socket and session do: a turn meanwhile is refused, not lost.
+ for (const machineId of gone) for (const cb of this.goneListeners) cb(machineId)
}
private onClose(code: number): void {
@@ -997,7 +1045,10 @@ export class DeviceLink {
// Said before its waiter hears the answer, so a request that ends now in an error, or ended already in a timeout,
// is not counted against a machine that just answered. Only the machine that sealed it: the tag names whose keys
// opened it.
- if (answered && answered === from) for (const cb of this.aliveListeners) cb(answered)
+ if (answered && answered === from) {
+ this.heardAt.set(answered, this.now())
+ for (const cb of this.aliveListeners) cb(answered)
+ }
const requestId = typeof payload.requestId === 'string' ? payload.requestId : ''
const waiter = requestId ? this.pending.get(requestId) : undefined
if (!waiter) {
diff --git a/cli/src/device/slowMachine.spec.ts b/cli/src/device/slowMachine.spec.ts
index 8499b214a..d7f794956 100644
--- a/cli/src/device/slowMachine.spec.ts
+++ b/cli/src/device/slowMachine.spec.ts
@@ -16,6 +16,7 @@ import type { E2eeManager as Manager } from '../lib/e2ee/manager.js'
import { LaneSessions } from '../gateway/lane.js'
import { DeviceFleet } from './deviceFleet.js'
import { DeviceLink } from './deviceLink.js'
+import { FleetRouter } from '../services/fleetRouter.js'
type Frame = Record<string, unknown>
const MACHINE = 'b1b2c3d4e5f60718293a4b5c6d7e8f90'
@@ -47,7 +48,7 @@ async function until(what: string, check: () => boolean): Promise<void> {
throw new Error(`never: ${what}`)
}
-async function slowMachine() {
+async function slowMachine(over: { now?: () => number } = {}) {
const identity = C.newIdentity()
const lane = new LaneSessions(() => identity)
// The far machine, which trusts this one's key (as `harness link connect` leaves two machines).
@@ -88,6 +89,7 @@ async function slowMachine() {
computerId: 'this-computer', autonomousEnv: 'test', seal: lane,
peer: (machineId) => machineId === MACHINE ? { machineId, pub: farPub, label: 'far', linkedAt: 1 } as never : null,
localMachineId: () => 'this-machine', log: (line) => { lines.push(line) },
+ ...(over.now ? { now: over.now } : {}),
})
stops.push(async () => link.stop())
const rows = [{ machineId: MACHINE, name: 'slow-mac', state: 'ready', authMode: 'remote', local: false }]
@@ -105,9 +107,73 @@ async function slowMachine() {
return asked[before]!
}
const read = (what: string) => until(what, () => lines.some((line) => line.includes(what)))
- return { far, fleet, link, lines, toLane, timesOut, hellos, read, turns }
+ return { far, fleet, link, lines, toLane, timesOut, hellos, read, turns, asked }
}
+/** The router over that fleet, with the far machine's one agent listed: what ⌘K and the dial send a turn through. */
+async function routed(m: Awaited<ReturnType<typeof slowMachine>>, answer: () => Promise<void>) {
+ const router = new FleetRouter({ machineName: () => 'here', machineId: () => 'this-machine', computerId: () => 'c', sessions: () => [],
+ displayName: () => '', desk: () => [], sendTurn: vi.fn(), stopTurn: vi.fn(), answer: vi.fn(), recent: () => [], recentAsks: () => [],
+ log: (line) => { m.lines.push(line) } }, m.fleet)
+ await router.listAgentsFlat()
+ await answer()
+ expect((await router.listAgentsFlat()).map((a) => a.id)).toEqual(['agent-1'])
+ return router
+}
+
+/** The far machine answering the last list it was asked, sealed for this session alone. */
+function answerLast(m: Awaited<ReturnType<typeof slowMachine>>) {
+ return async () => {
+ await until('the far machine to read the list', () => m.asked.some((a) => a.type === 'agents_list'))
+ const last = m.asked.filter((a) => a.type === 'agents_list').at(-1)!
+ m.toLane(m.far.wrapRpcReply(CONN, 'agents_list_result', last.requestId, { agents: [{ id: 'agent-1', name: 'api', engine: 'claude' }] })!)
+ await until('its answer', () => m.fleet.reachable(MACHINE)?.ok === true)
+ }
+}
+
+// #2387's review: B's daemon killed, nothing told this machine (the relay's list still said running), and a list to it
+// waited 45 s, so a turn sent meanwhile was lost, not refused ('B going away' in e2e/fleet.e2e.ts). Now the list fails
+// once the machine has been quiet 30 s, and the turn is refused from then.
+it('refuses a turn to a machine gone quiet with nothing said, 30 s after it was last heard, not after a 45 s list', async () => {
+ let clock = 1_000_000
+ const m = await slowMachine({ now: () => clock })
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ const router = await routed(m, answerLast(m))
+ expect(router.sendTurn('agent-1', 'while it is up')).toEqual({ ok: true })
+ // It dies now. The next list, 5 s on, is read by nobody who answers.
+ clock += 5_000
+ const listed = m.fleet.listAgents(MACHINE).catch((error: Error) => error)
+ await until('the list to go out', () => m.asked.filter((a) => a.type === 'agents_list').length === 2)
+ await vi.advanceTimersByTimeAsync(24_999)
+ expect(router.sendTurn('agent-1', 'just after it went')).toEqual({ ok: true })
+ await vi.advanceTimersByTimeAsync(1)
+ clock += 25_000
+ expect(router.sendTurn('agent-1', 'to a machine gone 30 s')).toMatchObject({ ok: false, reason: 'the last request to it did not come back' })
+ expect(await listed).toEqual(new Error('agents_list timed out'))
+})
+
+// #2381's rule kept: a machine answering every list 20 s late is never quiet 30 s, keeps its tiles, and takes every turn.
+it('keeps a machine that answers every list 20 s late reachable, on the carousel, and taking turns', async () => {
+ let clock = 1_000_000
+ const m = await slowMachine({ now: () => clock })
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ const router = await routed(m, answerLast(m))
+ for (let round = 1; round <= 4; round++) {
+ const listed = m.fleet.listAgents(MACHINE)
+ await until('the list to go out', () => m.asked.filter((a) => a.type === 'agents_list').length === round + 1)
+ for (let second = 0; second < 20; second++) {
+ await vi.advanceTimersByTimeAsync(1_000)
+ clock += 1_000
+ expect(router.sendTurn('agent-1', `round ${round}, ${second + 1} s`)).toEqual({ ok: true })
+ }
+ await answerLast(m)()
+ expect((await listed).map((a) => a.id)).toEqual(['agent-1'])
+ expect((await router.listAgentsFlat()).map((a) => a.id)).toEqual(['agent-1'])
+ }
+ expect(m.lines.some((line) => line.includes('timed out'))).toBe(false)
+ expect(m.hellos()).toBe(1)
+})
+
it('keeps a slow machine reachable with its session on its own late reply, and on nothing the relay or a commander could make', async () => {
const { far, fleet, lines, toLane, timesOut, hellos, read, turns } = await slowMachine()
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
diff --git a/cli/src/services/fleet.spec.ts b/cli/src/services/fleet.spec.ts
index 566a43960..337d18acf 100644
--- a/cli/src/services/fleet.spec.ts
+++ b/cli/src/services/fleet.spec.ts
@@ -31,6 +31,7 @@ vi.mock('../device/deviceLink.js', () => ({
onFrame(cb: (frame: Record<string, unknown>) => void) { lane.frames = cb; return () => {} }
onUndelivered() { return () => {} }
onAlive() { return () => {} }
+ onGone() { return () => {} }
stop() { lane.stop() }
rpc(type: string) { return lane.rpc(type) }
sendSealed(...args: unknown[]) { return lane.sendSealed(...(args as [])) }
diff --git a/cli/src/services/fleetRouter.spec.ts b/cli/src/services/fleetRouter.spec.ts
index 56186fab7..d535aa0c2 100644
--- a/cli/src/services/fleetRouter.spec.ts
+++ b/cli/src/services/fleetRouter.spec.ts
@@ -58,7 +58,7 @@ function laneOf() {
let heard: (machineId: string) => void = () => {}
const link = {
selectedMachine: '', onFrame: () => () => {}, onUndelivered: () => () => {},
- onAlive: (cb: (machineId: string) => void) => { heard = cb; return () => {} },
+ onAlive: (cb: (machineId: string) => void) => { heard = cb; return () => {} }, onGone: () => () => {},
rpc: vi.fn(async (): Promise<Record<string, unknown>> => ({ agents: [{ id: 'r1', name: 'api', engine: 'claude' }] })),
resetSession: vi.fn(() => true), sendSealed: vi.fn(async () => {}),
}
@@ -190,7 +190,7 @@ describe('which machine an agent is on', () => {
let alive: (machineId: string) => void = () => {}
const link = {
selectedMachine: '', onFrame: () => () => {}, onUndelivered: () => () => {},
- onAlive: (cb: (machineId: string) => void) => { alive = cb; return () => {} },
+ onAlive: (cb: (machineId: string) => void) => { alive = cb; return () => {} }, onGone: () => () => {},
rpc: vi.fn(async (): Promise<Record<string, unknown>> => ({ agents: [{ id: 'r1', name: 'api', engine: 'claude' }] })),
resetSession: vi.fn(() => true), sendSealed: vi.fn(async () => {}),
}