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): two overlapping machine selects both settle, instead of one failing 15 s later as "Can't reach" (#2400)
0xken1585b8b87de097
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.tsindex bd91044da..a2ea2ad36 100644--- a/cli/src/cable/cableHost.spec.ts+++ b/cli/src/cable/cableHost.spec.ts@@ -6,6 +6,9 @@ import type { FleetMachine, MachineFleet } from './machineFleet.js'import type { FleetRouting } from '../services/fleet.js'import { ServiceUnavailableError } from '../core/serviceHost.js'import type { RegisteredSession } from '../lib/registry.js'+import { WebSocketServer, type WebSocket } from 'ws'+import { DeviceFleet } from '../device/deviceFleet.js'+import { DeviceLink } from '../device/deviceLink.js'const AGENTS: Array<{ agentId: string; registeredAt: number; active: boolean; terminalAvailable: boolean; engine: string; lastHookAt?: number }> = []@@ -1106,3 +1109,114 @@ describe('firmware release lookup', () => {expect(fetch).toHaveBeenCalledTimes(4)})})++/**+ * The two announces of a plug-in, over the real lane (deviceLink.ts) and fleet (deviceFleet.ts), against a fake device+ * socket that answers only the newest select, as the backend does (deviceWs.ts bindMachine). Diego's Mac, 10-30: 13+ * "could not announce" lines in a day, each about 15 s after a select the backend had answered.+ */+describe('announcing over the real lane', () => {+ const CLOUD_ROW = { machineId: 'cloud-1', name: 'cloud-box', state: 'ready', authMode: 'managed', local: false }+ const stops: Array<() => Promise<void> | void> = []+ afterEach(async () => {+ vi.useRealTimers()+ for (const stop of stops.splice(0)) await stop()+ })++ /** Wait on the lane without a timer (they are faked): it reads each frame through promises alone. */+ const soon = async (what: string, check: () => boolean): Promise<void> => {+ for (let turn = 0; turn < 50_000; turn++) {+ if (check()) return+ await new Promise((resolve) => setImmediate(resolve))+ }+ throw new Error(`never: ${what}`)+ }++ async function plugged() {+ const selects: string[] = []+ let socket: WebSocket | null = null+ const wss = new WebSocketServer({ port: 0, host: '127.0.0.1', handleProtocols: (protocols) => [...protocols][0] ?? false })+ await new Promise<void>((resolve) => wss.once('listening', () => resolve()))+ wss.on('connection', (ws) => {+ socket = ws+ ws.on('message', (raw) => {+ const frame = JSON.parse(raw.toString()) as { type?: string; payload?: { machineId?: string } }+ if (frame.type === 'machine_select') selects.push(String(frame.payload?.machineId))+ })+ })+ stops.push(() => new Promise<void>((resolve) => { for (const client of wss.clients) client.terminate(); wss.close(() => resolve()) }))+ /** The backend has read every select so far: only the newest is answered. */+ const answerNewest = () => socket?.send(JSON.stringify({ type: 'machine_selected', payload: { machineId: selects.at(-1) } }))+ const lines: string[] = []+ const seal = { hello: vi.fn(), welcome: vi.fn(), rekey: vi.fn(), seal: vi.fn(), open: vi.fn(), drop: vi.fn() }+ const link = new DeviceLink({+ auth: { accessToken: async () => 'token' }, backendWsBase: `ws://127.0.0.1:${(wss.address() as { port: number }).port}`,+ computerId: 'this-computer', autonomousEnv: 'test', seal: seal as never, peer: () => null,+ localMachineId: () => 'mine', log: (line) => { lines.push(line) },+ })+ stops.push(() => link.stop())+ const rows = [{ machineId: 'mine', name: 'MacbookPro.local', state: 'ready', authMode: 'remote', local: true }, CLOUD_ROW]+ const fleet = new DeviceFleet({ list: { list: () => ({ machines: rows, source: 'backend' as const }), find: (id: string) => rows.find((r) => r.machineId === id) } as never,+ link, hasPeerLink: () => false, log: (line) => { lines.push(line) } })+ // The lane is up from before (the dial was plugged in already): what overlaps is the announces.+ await link.online()+ const host = new DaemonCableHost(wiring({ log: (line: string) => { lines.push(line) } }), fleet)+ const announced = () => lines.filter((line) => line.includes('could not announce'))+ return { host, selects, answerNewest, lines, announced }+ }++ it('logs no "could not announce" for a plug-in that announces through both paths when the backend answers', async () => {+ const { host, selects, answerNewest, announced, lines } = await plugged()+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ host.onDialAttached() // announces where the dial is, once the lane is up+ const picked = host.selectMachine('mine') // the dial's own pick on hello, announced too+ expect(await picked).toEqual({ ok: true })+ await soon('the announce', () => selects.length >= 1)+ for (let turn = 0; turn < 50; turn++) await new Promise((resolve) => setImmediate(resolve))+ answerNewest()+ await soon('its answer', () => lines.includes('device: machine_selected mine'))+ await vi.advanceTimersByTimeAsync(15_000)+ for (let turn = 0; turn < 50; turn++) await new Promise((resolve) => setImmediate(resolve))+ expect(announced()).toEqual([])+ expect(selects).toEqual(['mine'])+ })++ it('announces the machine a select is on its way to, instead of replacing it with the one before', async () => {+ const { host, selects, answerNewest, announced, lines } = await plugged()+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ const picked = host.selectMachine('cloud-1')+ await soon('the pick', () => selects.length === 1)+ host.onDialAttached()+ for (let turn = 0; turn < 50; turn++) await new Promise((resolve) => setImmediate(resolve))+ answerNewest()+ await soon('its answer', () => lines.some((line) => line.startsWith('device: machine_selected')))+ await vi.advanceTimersByTimeAsync(15_000)+ expect(await picked).toEqual({ ok: true })+ for (let turn = 0; turn < 50; turn++) await new Promise((resolve) => setImmediate(resolve))+ expect(host.selectedMachine()).toBe('cloud-1')+ expect(announced()).toEqual([])+ expect(selects).toEqual(['cloud-1'])+ })++ it('says nothing of an announce a newer pick replaced, and the pick lands', async () => {+ const { host, selects, answerNewest, announced, lines } = await plugged()+ const first = host.selectMachine('cloud-1')+ await soon('the first pick', () => selects.length === 1)+ answerNewest()+ expect(await first).toEqual({ ok: true })+ host.onDialGone() // unplugged: the lane goes with it+ await soon('the old socket to close', () => lines.some((line) => line.startsWith('device: closed')))+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ host.onDialAttached() // and back: announces cloud-1, where the dial was+ await soon('the announce', () => selects.length === 2)+ expect(await host.selectMachine('mine')).toEqual({ ok: true }) // and the person picks this computer+ await soon('the pick', () => selects.length === 3)+ answerNewest()+ await soon('its answer', () => lines.includes('device: machine_selected mine'))+ await vi.advanceTimersByTimeAsync(15_000)+ for (let turn = 0; turn < 50; turn++) await new Promise((resolve) => setImmediate(resolve))+ expect(announced()).toEqual([])+ expect(selects).toEqual(['cloud-1', 'cloud-1', 'mine'])+ expect(host.selectedMachine()).toBe('mine')+ })+})diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex b0ada2562..e34723798 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -167,6 +167,11 @@ export class DaemonCableHost implements CableHost {* remember across a daemon restart either — that is when the registry reloads anyway.*/private selected = ''+ /**+ * The remote machine a select is on its way to, until it settles. The announce on plug-in names it rather than+ * `selected`: announcing the older machine would replace the newer choice at the lane (deviceLink.ts select).+ */+ private selecting = ''/** The last good manifest read per OTA key, for keepalives — see firmwareFor. */private readonly releases = new Map<string, { release: FirmwareRelease; at: number }>()@@ -233,6 +238,7 @@ export class DaemonCableHost implements CableHost {async selectMachine(machineId: string): Promise<{ ok: true } | { ok: false; code: string; message: string }> {if (machineId === this.localId()) {this.selected = machineId+ this.selecting = ''// Let go of the REMOTE machine after a linger, keeping the socket — then announce where the dial// actually is. `activeMachineId` on the account is then true for this machine too, instead of// silently going stale on whatever was selected last.@@ -243,7 +249,13 @@ export class DaemonCableHost implements CableHost {if (!this.viaFleet((r) => r.hasLane())) {return { ok: false, code: 'UNAVAILABLE', message: 'Sign in on this computer to reach other machines' }}- const selected = await this.viaFleet((r) => r.select(machineId))+ this.selecting = machineId+ let selected: Awaited<ReturnType<FleetRouting['select']>>+ try {+ selected = await this.viaFleet((r) => r.select(machineId))+ } finally {+ if (this.selecting === machineId) this.selecting = ''+ }if (!selected.ok) return selectedthis.selected = machineIdreturn { ok: true }@@ -288,12 +300,13 @@ export class DaemonCableHost implements CableHost {*/private async announceSelection(): Promise<void> {if (!this.viaFleet((r) => r.hasLane())) return- const machineId = this.selectedMachine()+ const machineId = this.selecting || this.selectedMachine()if (isPlaceholder(machineId)) returnconst selected = await this.viaFleet((r) => r.select(machineId))// Never fatal. The local machine in particular must stay usable with no backend at all — it is the- // one machine the cable can vouch for on its own.- if (!selected.ok) this.wiring.log(`cable: could not announce ${machineId} (${selected.message})`)+ // one machine the cable can vouch for on its own. Replaced by a newer select is not a failure: that+ // one tells the backend where the dial is.+ if (!selected.ok && selected.code !== 'SUPERSEDED') this.wiring.log(`cable: could not announce ${machineId} (${selected.message})`)}/**diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.tsindex 1a13b209a..9067e9392 100644--- a/cli/src/device/deviceFleet.ts+++ b/cli/src/device/deviceFleet.ts@@ -10,7 +10,7 @@ import { FleetError, type FleetEvent, type FleetMachine, type MachineFleet } froimport type { CableAgent } from '../cable/cableSession.js'import type { RecentTurn } from '../cable/cableHost.js'import type { MachineListCache } from './machineList.js'-import { SESSION_GONE, type DeviceFrame, type DeviceLink, type Undelivered } from './deviceLink.js'+import { SELECT_SUPERSEDED, SESSION_GONE, type DeviceFrame, type DeviceLink, type Undelivered } from './deviceLink.js'/** How long the socket lingers after the dial goes back to local, so flicking between two machines does* not pay a full dial each way. Mirrors RemoteRelayPool's own linger for the same reason. */@@ -472,6 +472,8 @@ export class DeviceFleet implements MachineFleet {/** Map the far end's words onto a code the dial can act on. Unknown reasons stay unreachable. */private codeFor(message: string): string {+ // Replaced by a select of another machine: nothing is wrong with this one (deviceLink.ts SELECT_SUPERSEDED).+ if (message === SELECT_SUPERSEDED) return 'SUPERSEDED'if (message.includes('NOT_YOUR_MACHINE')) return 'NOT_YOURS'if (message.includes('MACHINE_ENV_MISMATCH')) return 'NOT_YOURS'if (message.includes('PAYMENT') || message.includes('SUBSCRIPTION')) return 'BILLING'@@ -480,6 +482,7 @@ export class DeviceFleet implements MachineFleet {}private messageFor(message: string, name: string): string {+ if (message === SELECT_SUPERSEDED) return 'Another machine was chosen'if (message.includes('NOT_YOUR_MACHINE') || message.includes('MACHINE_ENV_MISMATCH')) {return `${name} is not on this account`}diff --git a/cli/src/device/deviceLink.spec.ts b/cli/src/device/deviceLink.spec.tsindex fa657190f..afef22d79 100644--- a/cli/src/device/deviceLink.spec.ts+++ b/cli/src/device/deviceLink.spec.ts@@ -952,3 +952,158 @@ describe('a late reply from a slow machine', () => {await vi.waitFor(() => expect(gone).toEqual([LINKED, LINKED_2]))})})++/**+ * Overlapping machine selects. The backend answers only the newest select on a socket: an older one still being read+ * when a newer arrives gets no answer at all (deviceWs.ts bindMachine, selectGen). Diego's Mac, 10-30: every plug-in+ * announced its machine twice, and one of the two failed 15 s later as "Can't reach" although the backend had selected+ * it, 13 times in a day.+ */+describe('overlapping machine selects', () => {+ const CLOUD_2 = 'second-cloud-machine'++ /** A lane whose fake backend answers each select after a moment, unless a newer one came meanwhile (as the real one). */+ async function selecting(answerMs = 50) {+ const up = await lane()+ let gen = 0+ const selects = () => up.server.received.filter((frame) => frame.type === 'machine_select')+ up.server.on((frame) => {+ if (frame.type !== 'machine_select') return+ const mine = ++gen+ const machineId = (frame.payload as { machineId: string }).machineId+ setTimeout(() => { if (mine === gen) up.server.send({ type: 'machine_selected', payload: { machineId } }) }, answerMs)+ })+ await up.link.online()+ return { ...up, selects }+ }+ const settled = (promise: Promise<void>) => promise.then(() => 'ok', (error: Error) => error.message)+ /** Wait on the lane without a timer, which some of these tests fake: it reads each frame through promises alone. */+ const soon = async (what: string, check: () => boolean): Promise<void> => {+ for (let turn = 0; turn < 50_000; turn++) {+ if (check()) return+ await new Promise((resolve) => setImmediate(resolve))+ }+ throw new Error(`never: ${what}`)+ }++ it('settles two overlapping attaches to one machine with its one answer, and sends one select', async () => {+ const { link, selects, lines } = await selecting()+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ try {+ const first = settled(link.attach(CLOUD))+ const second = settled(link.attach(CLOUD))+ await soon('the select to reach the backend', () => selects().length >= 1)+ await vi.advanceTimersByTimeAsync(100) // the backend answers+ await soon('its answer', () => lines.includes(`device: machine_selected ${CLOUD}`))+ await vi.advanceTimersByTimeAsync(15_000)+ expect(await first).toBe('ok')+ expect(await second).toBe('ok')+ expect(selects()).toHaveLength(1)+ expect(lines).toContain(`device: machine_selected ${CLOUD}`)+ } finally { vi.useRealTimers() }+ })++ it('lets a select of another machine replace the older one at once, and an old timer clear nothing of the new one', async () => {+ // The newer select's answer lands after the older one's 15 s are up: that timer used to clear the newer waiter.+ const { link, server, selects, lines } = await selecting(60_000)+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ try {+ const older = settled(link.attach(CLOUD))+ await soon('the first select', () => selects().length === 1)+ await vi.advanceTimersByTimeAsync(5_000)+ const newer = settled(link.attach(CLOUD_2))+ await soon('the second select', () => selects().length === 2)+ await vi.advanceTimersByTimeAsync(12_000) // past the older select's 15 s+ server.send({ type: 'machine_selected', payload: { machineId: CLOUD_2 } })+ await soon('its answer', () => lines.includes(`device: machine_selected ${CLOUD_2}`))+ await vi.advanceTimersByTimeAsync(15_000)+ expect(await older).toBe('SELECT_SUPERSEDED')+ expect(await newer).toBe('ok')+ } finally { vi.useRealTimers() }+ })++ it('counts an answer only for the machine it names, and one that names none for the select in flight', async () => {+ const { link, server, selects, lines } = await selecting(60_000)+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ try {+ const older = settled(link.attach(CLOUD))+ await soon('the first select', () => selects().length === 1)+ let newerSettled = ''+ const newer = link.attach(CLOUD_2)+ void settled(newer).then((how) => { newerSettled = how })+ await soon('the second select', () => selects().length === 2)+ // The older select's answers, sent before the backend read the newer one: neither settles the newer.+ server.send({ type: 'machine_selected', payload: { machineId: CLOUD } })+ server.send({ type: 'machine_select_error', payload: { machineId: CLOUD, error: 'NOT_YOUR_MACHINE' } })+ await soon('both read', () => lines.includes('device: machine_select_error NOT_YOUR_MACHINE'))+ for (let turn = 0; turn < 20; turn++) await new Promise((resolve) => setImmediate(resolve))+ expect(newerSettled).toBe('')+ // An older backend names no machine: its answer is the select in flight's.+ server.send({ type: 'machine_select_error', payload: { error: 'MACHINE_START_FAILED' } })+ await soon('the unnamed answer', () => lines.includes('device: machine_select_error MACHINE_START_FAILED'))+ await vi.advanceTimersByTimeAsync(15_000)+ expect(await settled(newer)).toBe('MACHINE_START_FAILED')+ expect(await older).toBe('SELECT_SUPERSEDED')+ // And nothing is left waiting: the next select is sent and settled by its own answer.+ const again = settled(link.attach(CLOUD_2))+ await soon('the third select', () => selects().length === 3)+ server.send({ type: 'machine_selected', payload: {} })+ await soon('its answer', () => lines.filter((line) => line === `device: machine_selected ${CLOUD_2}`).length === 1)+ await vi.advanceTimersByTimeAsync(15_000)+ expect(await again).toBe('ok')+ } finally { vi.useRealTimers() }+ })++ it('fails both callers of one select with its error', async () => {+ const { link, server, selects, lines } = await selecting(60_000)+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ try {+ const first = settled(link.attach(CLOUD))+ const second = settled(link.attach(CLOUD))+ await soon('the select', () => selects().length >= 1)+ server.send({ type: 'machine_select_error', payload: { machineId: CLOUD, error: 'MACHINE_PAYMENT_PENDING' } })+ await soon('its answer', () => lines.includes('device: machine_select_error MACHINE_PAYMENT_PENDING'))+ await vi.advanceTimersByTimeAsync(15_000)+ expect([await first, await second]).toEqual(['MACHINE_PAYMENT_PENDING', 'MACHINE_PAYMENT_PENDING'])+ expect(selects()).toHaveLength(1)+ } finally { vi.useRealTimers() }+ })++ it('sends a select back to the attached machine while one to another is in flight, instead of skipping it', async () => {+ const { link, selects } = await selecting()+ await link.attach(CLOUD)+ const away = settled(link.attach(CLOUD_2))+ await soon('the select away', () => selects().length === 2)+ const back = settled(link.attach(CLOUD))+ expect(await away).toBe('SELECT_SUPERSEDED')+ expect(await back).toBe('ok')+ expect(selects().map((frame) => (frame.payload as { machineId: string }).machineId)).toEqual([CLOUD, CLOUD_2, CLOUD])+ })++ it('sends nothing for an attach overtaken by a newer one while it waited for the socket', async () => {+ const { link, selects } = await selecting()+ await link.attach(CLOUD)+ // Both asked in one go: the select away has not gone out when the dial comes back.+ const away = settled(link.attach(CLOUD_2))+ const back = settled(link.attach(CLOUD))+ expect(await away).toBe('SELECT_SUPERSEDED')+ expect(await back).toBe('ok')+ expect(selects().map((frame) => (frame.payload as { machineId: string }).machineId)).toEqual([CLOUD])+ // And the backend was left where the dial is: the next select of the other machine is sent.+ expect(await settled(link.attach(CLOUD_2))).toBe('ok')+ expect(selects()).toHaveLength(2)+ })++ it('fails a select in flight when the lane is revoked, and starts the next one fresh', async () => {+ const { link, server, selects, lines } = await selecting(60_000)+ const pending = settled(link.attach(CLOUD))+ await soon('the select', () => selects().length === 1)+ server.send({ type: 'device_revoked' })+ expect(await pending).toBe('revoked')+ await soon('the revoked socket to close', () => lines.some((line) => line.startsWith('device: closed')))+ const next = settled(link.attach(CLOUD))+ await soon('a select on a new socket', () => selects().length === 2)+ server.send({ type: 'machine_selected', payload: { machineId: CLOUD } })+ expect(await next).toBe('ok')+ })+})diff --git a/cli/src/device/deviceLink.ts b/cli/src/device/deviceLink.tsindex 5dba2a32a..927635b07 100644--- a/cli/src/device/deviceLink.ts+++ b/cli/src/device/deviceLink.ts@@ -45,6 +45,12 @@ export interface DeviceFrame {}const RPC_TIMEOUT_MS = 15_000+/**+ * What a select replaced by a select of another machine fails with, at once. Not "the machine did not answer": the+ * backend answers only the newest select on a socket, so the older one would otherwise wait out its 15 s and read as+ * a machine nobody could reach. Callers say nothing of it as a failure (deviceFleet.ts, cableHost.ts).+ */+export const SELECT_SUPERSEDED = 'SELECT_SUPERSEDED'/*** How long an agent list may take: a background read nobody is watching a spinner for, refreshed every few seconds* (fleetRouter.ts). Diego, 10-30: a slow but working Mac answered its lists 5 to 25 s after the 15 s every request had,@@ -162,8 +168,14 @@ export class DeviceLink {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+ /**+ * The select in flight, for the machine it asked: settled when `machine_selected` or `machine_select_error` for that+ * machine lands, so callers can await the attach rather than poll for it. One at a time, because the backend answers+ * only the newest select on a socket (deviceWs.ts bindMachine): a second select of the same machine JOINS this one+ * (as `establish()` joins handshakes) and sends nothing, and a select of another machine replaces it, failing it with+ * SELECT_SUPERSEDED at once. Each timer clears only its own select.+ */+ private selecting: { machineId: string; done: Promise<void>; resolve: () => void; reject: (e: Error) => void; timer: NodeJS.Timeout } | null = null/*** One session PER MACHINE, keyed by machineId.*@@ -277,8 +289,11 @@ export class DeviceLink {async attach(machineId: string): Promise<void> {if (!machineId) throw new Error('no machine to attach to')this.wanted = machineId- if (this.attached === machineId && this.ws?.readyState === WebSocket.OPEN) return+ // Not while a select of another machine is in flight: the backend ends on that one unless this is sent after it.+ if (this.attached === machineId && !this.selecting && this.ws?.readyState === WebSocket.OPEN) returnawait this.connect()+ // Another attach came while this one waited for the socket: it is the newer choice, and this one sends nothing.+ if (this.wanted !== machineId) throw new Error(SELECT_SUPERSEDED)await this.select(machineId)await this.establish(machineId)}@@ -681,14 +696,47 @@ export class DeviceLink {}private select(machineId: string): Promise<void> {- return new Promise<void>((resolve, reject) => {- const timer = setTimeout(() => {- this.selectWaiter = null+ const current = this.selecting+ if (current?.machineId === machineId) return current.done+ if (current) {+ this.opts.log(`device: machine_select ${current.machineId} replaced by ${machineId}`)+ this.settleSelect(new Error(SELECT_SUPERSEDED))+ }+ let resolve!: () => void+ let reject!: (e: Error) => void+ const done = new Promise<void>((res, rej) => { resolve = res; reject = rej })+ const entry = {+ machineId, done, resolve, reject,+ timer: setTimeout(() => {+ if (this.selecting === entry) this.selecting = nullreject(new Error('the machine did not answer'))- }, RPC_TIMEOUT_MS)- this.selectWaiter = { resolve, reject, timer }- this.send({ type: 'machine_select', payload: { machineId } })- })+ }, RPC_TIMEOUT_MS),+ }+ this.selecting = entry+ this.send({ type: 'machine_select', payload: { machineId } })+ return done+ }++ /** Settle the select in flight, if any: resolved, or failed with [err]. */+ private settleSelect(err?: Error): void {+ const entry = this.selecting+ if (!entry) return+ this.selecting = null+ clearTimeout(entry.timer)+ if (err) entry.reject(err)+ else entry.resolve()+ }++ /**+ * Whether an answer to a select is the one in flight's. It names the machine it answers; one for another machine is+ * the answer to a select already replaced (sent before the backend read the newer one), and settles nothing. One+ * that names none, from a backend older than the name, is taken as the select in flight's, as before.+ */+ private answersSelect(type: string, machineId: string): boolean {+ if (!this.selecting) return false+ if (!machineId || machineId === this.selecting.machineId) return true+ this.opts.log(`device: ${type} ${machineId} for a select no longer waited on — the one in flight is ${this.selecting.machineId}`)+ return false}/**@@ -805,7 +853,7 @@ export class DeviceLink {if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null }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.settleSelect(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.@@ -846,7 +894,8 @@ export class DeviceLink {// Re-select only if a machine was selected. A socket held open purely for presence comes back the// same way it went up — connected and attached to nothing.const retry = wanted ? this.attach(wanted) : this.online()- void retry.catch((err) => this.opts.log(`device: reconnect failed (${(err as Error).message})`))+ // Replaced by a newer select meanwhile is not a failed reconnect: the newer one carries on.+ void retry.catch((err) => { if ((err as Error).message !== SELECT_SUPERSEDED) this.opts.log(`device: reconnect failed (${(err as Error).message})`) })}, delay)}@@ -1013,15 +1062,17 @@ export class DeviceLink {const payload = (frame.payload ?? {}) as Record<string, unknown>if (type === 'machine_selected') {- this.attached = typeof payload.machineId === 'string' ? payload.machineId : this.wanted+ const named = typeof payload.machineId === 'string' ? payload.machineId : ''+ this.attached = named || this.wantedthis.opts.log(`device: machine_selected ${this.attached}`)- if (this.selectWaiter) { clearTimeout(this.selectWaiter.timer); this.selectWaiter.resolve(); this.selectWaiter = null }+ if (this.answersSelect(type, named)) this.settleSelect()return}if (type === 'machine_select_error') {+ const named = typeof payload.machineId === 'string' ? payload.machineId : ''const code = typeof payload.error === 'string' ? payload.error : 'SELECT_FAILED'this.opts.log(`device: machine_select_error ${code}`)- if (this.selectWaiter) { clearTimeout(this.selectWaiter.timer); this.selectWaiter.reject(new Error(code)); this.selectWaiter = null }+ if (this.answersSelect(type, named)) this.settleSelect(new Error(code))return}if (type === 'device_revoked') {