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.

Device lane: a machine pick the person left can't land late and move the check mark (Diego) (#2504)

0xken1566240dd822a9
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index f5422d2b8..e2f7e43c8 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -2,7 +2,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { DaemonCableHost, cableEventFor, cableStepFor, type CableHostWiring } from './cableHost.js'
-import type { FleetMachine, MachineFleet } from './machineFleet.js'
+import { FleetError, type FleetMachine, type MachineFleet } from './machineFleet.js'
import type { FleetRouting } from '../services/fleet.js'
import { ServiceUnavailableError } from '../core/serviceHost.js'
import type { RegisteredSession } from '../lib/registry.js'
@@ -1132,12 +1132,14 @@ describe('announcing over the real lane', () => {
throw new Error(`never: ${what}`)
}
- async function plugged() {
+ async function plugged(over: { linked?: string } = {}) {
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()))
+ let connections = 0
wss.on('connection', (ws) => {
+ connections++
socket = ws
ws.on('message', (raw) => {
const frame = JSON.parse(raw.toString()) as { type?: string; payload?: { machineId?: string } }
@@ -1148,21 +1150,26 @@ describe('announcing over the real lane', () => {
/** 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 seal = { hello: vi.fn(async () => ({ type: 'e2e_hello', payload: {} })), welcome: vi.fn(async () => true), 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,
+ computerId: 'this-computer', autonomousEnv: 'test', seal: seal as never,
+ peer: (machineId) => (machineId === over.linked ? { machineId, pub: 'PUB', label: 'linked', linkedAt: 1 } as never : 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 rows = [{ machineId: 'mine', name: 'MacbookPro.local', state: 'ready', authMode: 'remote', local: true }, CLOUD_ROW,
+ { machineId: 'unlinked', name: 'not-linked', state: 'ready', authMode: 'remote', local: false }]
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 }
+ const welcome = (machineId: string) => socket?.send(JSON.stringify({ type: 'e2e_welcome', machineId, payload: {} }))
+ const revoke = () => socket?.send(JSON.stringify({ type: 'device_revoked' }))
+ const closeWith = (code: number) => socket?.close(code)
+ return { host, selects, answerNewest, lines, announced, seal, welcome, revoke, closeWith, connections: () => connections }
}
it('logs no "could not announce" for a plug-in that announces through both paths when the backend answers', async () => {
@@ -1198,6 +1205,72 @@ describe('announcing over the real lane', () => {
expect(selects).toEqual(['cloud-1'])
})
+ it('refuses a pick whose session was still being made when the person picked this computer, end to end over the lane', async () => {
+ const { host, selects, answerNewest, lines, seal, welcome, announced } = await plugged({ linked: 'cloud-1' })
+ const late = host.selectMachine('cloud-1')
+ await soon('the pick', () => selects.length === 1)
+ answerNewest()
+ await soon('its hello', () => seal.hello.mock.calls.length === 1)
+ expect(await host.selectMachine('mine')).toEqual({ ok: true })
+ await soon('the announce', () => selects.length === 2)
+ answerNewest()
+ await soon('its answer', () => lines.includes('device: machine_selected mine'))
+ welcome('cloud-1')
+ expect(await late).toMatchObject({ ok: false, code: 'SUPERSEDED' })
+ expect(host.selectedMachine()).toBe('mine')
+ expect(announced()).toEqual([])
+ })
+
+ it('puts the lane back where the dial is when a refused pick replaced a slow one', async () => {
+ // Refused before the lane is asked, so the lane would stay on the machine the person left, and a reconnect return there.
+ const { host, selects, answerNewest, lines, seal, welcome, announced } = await plugged({ linked: 'cloud-1' })
+ const late = host.selectMachine('cloud-1')
+ await soon('the pick', () => selects.length === 1)
+ answerNewest()
+ await soon('its hello', () => seal.hello.mock.calls.length === 1)
+ expect(await host.selectMachine('unlinked')).toMatchObject({ ok: false, code: 'NEEDS_LINK' })
+ await soon('the lane told again', () => selects.length === 2)
+ answerNewest()
+ await soon('its answer', () => lines.includes('device: machine_selected mine'))
+ welcome('cloud-1')
+ expect(await late).toMatchObject({ ok: false, code: 'SUPERSEDED' })
+ expect(selects).toEqual(['cloud-1', 'mine'])
+ expect(host.selectedMachine()).toBe('mine')
+ expect(announced()).toEqual([])
+ })
+
+ describe('a lane that ends during a pick stays ended (review of #2504)', () => {
+ /** A pick in its handshake, on a lane about to end. */
+ const inHandshake = async () => {
+ const up = await plugged({ linked: 'cloud-1' })
+ const first = up.host.selectMachine('cloud-1')
+ await soon('the pick', () => up.selects.length === 1)
+ up.answerNewest()
+ await soon('its hello', () => up.seal.hello.mock.calls.length === 1)
+ return { ...up, first }
+ }
+
+ it('sends no select on the way out of a revoke', async () => {
+ const { host, selects, revoke, first } = await inHandshake()
+ revoke()
+ expect(await first).toMatchObject({ ok: false, code: 'UNREACHABLE' })
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ expect(selects).toEqual(['cloud-1'])
+ expect(host.selectedMachine()).toBe('mine')
+ })
+
+ it('dials nothing after the backend refuses the lane with 4403, whatever is picked next', async () => {
+ const { host, selects, closeWith, connections, lines, first } = await inHandshake()
+ closeWith(4403)
+ expect(await first).toMatchObject({ ok: false })
+ await soon('the refusal', () => lines.some((line) => line.includes('not authorized')))
+ expect(await host.selectMachine('unlinked')).toMatchObject({ code: 'NEEDS_LINK' })
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ expect(connections()).toBe(1)
+ 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')
@@ -1220,6 +1293,180 @@ describe('announcing over the real lane', () => {
})
})
+/**
+ * Diego's Buddy, 11-02: a pick waiting on a slow machine lands after the person left it. The late answer used to set
+ * `selected`, so the check mark moved to a machine nobody had asked for any more. The newest pick decides.
+ */
+describe('a pick a newer pick replaced', () => {
+ const SECOND: FleetMachine = { machineId: 'second', name: 'second-mac', state: 'ready', authMode: 'remote' }
+ /** A fleet whose selects wait until the test settles them, in the order they were asked. */
+ const slow = () => {
+ const asked: Array<{ machineId: string; ok: () => void; fail: (error: Error) => void }> = []
+ const fleet = fleetOf([REMOTE, SECOND])
+ fleet.select = vi.fn((machineId: string) => new Promise<void>((ok, fail) => { asked.push({ machineId, ok, fail }) }))
+ return { fleet, asked }
+ }
+ const SUPERSEDED = { ok: false, code: 'SUPERSEDED', message: 'Another machine was chosen' }
+
+ it('keeps this computer selected when a pick of another machine lands after a pick of this one', async () => {
+ const { fleet, asked } = slow()
+ // No machine id yet: nothing is announced, so the lane never hears of the newer pick. The host alone knows of it.
+ const host = new DaemonCableHost(wiring({ machineId: () => '' }), fleet)
+ const here = host.localMachine().id
+ const late = host.selectMachine('other')
+ expect(host.pendingPick()).toBe('other')
+ expect(await host.selectMachine(here)).toEqual({ ok: true })
+ expect(host.pendingPick()).toBe('')
+ asked[0]!.ok()
+ expect(await late).toEqual(SUPERSEDED)
+ expect(host.selectedMachine()).toBe(here)
+ })
+
+ it('reports a late failure of a replaced pick as replaced, not as the machine failing', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring({ machineId: () => '' }), fleet)
+ const late = host.selectMachine('other')
+ await host.selectMachine(host.localMachine().id)
+ asked[0]!.fail(new Error('the machine did not answer'))
+ expect(await late).toEqual(SUPERSEDED)
+ })
+
+ it('lets only the newest of two remote picks move the selection, whichever lands first', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring(), fleet)
+ const older = host.selectMachine('other')
+ const newer = host.selectMachine('second')
+ expect(host.pendingPick()).toBe('second')
+ asked[0]!.ok()
+ expect(await older).toEqual(SUPERSEDED)
+ // Still on its way: the older one's end does not clear it, or a plug-in now would announce the machine before.
+ expect(host.pendingPick()).toBe('second')
+ expect(host.selectedMachine()).toBe('mine')
+ asked[1]!.ok()
+ expect(await newer).toEqual({ ok: true })
+ expect(host.selectedMachine()).toBe('second')
+ expect(host.pendingPick()).toBe('')
+ })
+
+ it('answers a person going away and back with the last pick\'s outcome: the first one landing proves nothing', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring({ machineId: () => '' }), fleet)
+ const first = host.selectMachine('other')
+ await host.selectMachine(host.localMachine().id)
+ const third = host.selectMachine('other')
+ asked[0]!.ok()
+ await new Promise((resolve) => setImmediate(resolve))
+ expect(host.selectedMachine()).toBe(host.localMachine().id)
+ expect(host.pendingPick()).toBe('other')
+ asked[1]!.fail(new Error('the machine did not answer'))
+ expect(await third).toMatchObject({ ok: false, code: 'UNREACHABLE' })
+ expect(await first).toMatchObject({ ok: false, code: 'UNREACHABLE' })
+ expect(host.selectedMachine()).toBe(host.localMachine().id)
+ })
+
+ it('answers a first pick ok when the same machine\'s last pick landed before it', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring({ machineId: () => '' }), fleet)
+ const first = host.selectMachine('other')
+ await host.selectMachine(host.localMachine().id)
+ const third = host.selectMachine('other')
+ asked[1]!.ok()
+ expect(await third).toEqual({ ok: true })
+ asked[0]!.ok()
+ expect(await first).toEqual({ ok: true })
+ expect(host.selectedMachine()).toBe('other')
+ })
+
+ it('asks once for two picks of one machine, and gives both its answer', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring(), fleet)
+ const first = host.selectMachine('other')
+ const second = host.selectMachine('other')
+ expect(asked).toHaveLength(1)
+ asked[0]!.ok()
+ expect([await first, await second]).toEqual([{ ok: true }, { ok: true }])
+ expect(host.selectedMachine()).toBe('other')
+ })
+
+ it('says where the dial is when a machine refuses a pick that replaced another, and not for a replaced pick failing', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring(), fleet)
+ const older = host.selectMachine('other')
+ const newest = host.selectMachine('second')
+ asked[0]!.fail(new Error('the machine did not answer'))
+ await older
+ expect(asked.map((a) => a.machineId)).toEqual(['other', 'second'])
+ asked[1]!.fail(new FleetError('BILLING', 'second-mac needs a subscription'))
+ expect(await newest).toMatchObject({ ok: false, code: 'BILLING' })
+ expect(asked.map((a) => a.machineId)).toEqual(['other', 'second', 'mine'])
+ asked[2]!.ok()
+ })
+
+ it('tells the lane nothing after a refusal with no pick replaced: it never moved', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring(), fleet)
+ const pick = host.selectMachine('other')
+ asked[0]!.fail(new FleetError('NEEDS_LINK', 'Link it first'))
+ expect(await pick).toMatchObject({ code: 'NEEDS_LINK' })
+ expect(asked).toHaveLength(1)
+ })
+
+ it('tells the lane nothing after a failure that is not a refusal: it may be the lane\'s end', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring(), fleet)
+ const older = host.selectMachine('other')
+ const newest = host.selectMachine('second')
+ asked[1]!.fail(new Error('socket closed (4403)'))
+ expect(await newest).toMatchObject({ code: 'UNREACHABLE' })
+ asked[0]!.ok()
+ await older
+ expect(asked).toHaveLength(2)
+ })
+
+ it('opens nothing again when a pick fails because the dial was unplugged', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring(), fleet)
+ const older = host.selectMachine('other')
+ const pick = host.selectMachine('second')
+ host.onDialGone()
+ asked[1]!.fail(new Error('released'))
+ await pick
+ asked[0]!.fail(new Error('released'))
+ await older
+ expect(asked).toHaveLength(2)
+ expect(fleet.release).toHaveBeenCalledWith(true)
+ })
+
+ it('leaves the lane alone when it says a newer select replaced the pick', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring(), fleet)
+ const older = host.selectMachine('other')
+ const pick = host.selectMachine('second')
+ asked[1]!.fail(new FleetError('SUPERSEDED', 'Another machine was chosen'))
+ expect(await pick).toMatchObject({ ok: false, code: 'SUPERSEDED' })
+ asked[0]!.ok()
+ await older
+ expect(asked).toHaveLength(2)
+ })
+
+ it('leaves nothing pending when the fleet call fails at once', async () => {
+ const { fleet } = slow()
+ fleet.select = vi.fn(() => { throw new Error('broken fleet') })
+ const host = new DaemonCableHost(wiring(), fleet)
+ expect(await host.selectMachine('other')).toMatchObject({ ok: false, code: 'UNREACHABLE' })
+ expect(host.pendingPick()).toBe('')
+ })
+
+ it('still reports the newest pick\'s own refusal', async () => {
+ const { fleet, asked } = slow()
+ const host = new DaemonCableHost(wiring(), fleet)
+ const pick = host.selectMachine('other')
+ asked[0]!.fail(new Error('the machine did not answer'))
+ expect(await pick).toMatchObject({ ok: false, code: 'UNREACHABLE' })
+ expect(host.pendingPick()).toBe('')
+ })
+})
+
/**
* A plug-in whose first lane open fails — Diego, 11-01: the sign-in refresh failed in a network blip, nothing tried
* again, and the wheel lost every other Mac until the dial was replugged.
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index 700ce1c33..6c4165003 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -158,6 +158,15 @@ const RELEASE_KEEP_MS = 30 * 60_000
const LANE_RETRY_MS = 1_000
const LANE_RETRY_MAX_MS = 30_000
+/** How a pick of a machine ended: `code` is the daemon's, `message` is shown to a person (CableHost.selectMachine). */
+type MachinePick = { ok: true } | { ok: false; code: string; message: string }
+
+/** A pick on its way; `replaced` when it took over from another still running. */
+interface PendingPick { machineId: string; replaced: boolean; done: Promise<MachinePick> }
+
+/** A pick's end that says no about that machine and nothing about the lane (deviceFleet.ts select and codeFor). */
+const REFUSALS = new Set(['NEEDS_LINK', 'UNKNOWN_MACHINE', 'NOT_YOURS', 'BILLING'])
+
export class DaemonCableHost implements CableHost {
/**
* This host's own router: over the bare fleet it is given (its tests), or over none, for this computer
@@ -175,10 +184,13 @@ export class DaemonCableHost implements CableHost {
*/
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).
+ * The newest pick still on its way to a remote machine, until it settles. Only it may move `selected`: a pick waiting on
+ * a slow machine lands up to 15 s later, by when the person may be elsewhere (Diego's Buddy, 11-02). Which pick it is, not
+ * just which machine: going away and back to one machine looks the same by name, and the first landing says nothing of
+ * the last. 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 = ''
+ private pending: PendingPick | null = null
/** Counts plug-ins: a lane open that lands after an unplug or a replug belongs to an older one and does nothing. */
private plugIn = 0
@@ -248,10 +260,15 @@ export class DaemonCableHost implements CableHost {
return this.viaFleet((r) => r.listMachines())
}
- async selectMachine(machineId: string): Promise<{ ok: true } | { ok: false; code: string; message: string }> {
+ /** The machine the newest pick is still on its way to, or '' when none is. */
+ pendingPick(): string {
+ return this.pending?.machineId ?? ''
+ }
+
+ async selectMachine(machineId: string): Promise<MachinePick> {
if (machineId === this.localId()) {
this.selected = machineId
- this.selecting = ''
+ this.pending = null
// 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.
@@ -262,14 +279,44 @@ 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' }
}
- this.selecting = machineId
+ // A second pick of the machine already on its way shares its one answer, as the lane's select does. Each caller may be
+ // the only one left to tell the dial: an app follow's answer is dropped once a newer focus arrives (reviews of #2504).
+ if (this.pending?.machineId === machineId) return this.pending.done
+ // Set before the select starts, so a fleet call that fails at once still finds it and clears it.
+ const entry: PendingPick = { machineId, replaced: this.pending !== null, done: null as unknown as Promise<MachinePick> }
+ this.pending = entry
+ entry.done = this.pickMachine(entry)
+ return entry.done
+ }
+
+ private async pickMachine(entry: PendingPick): Promise<MachinePick> {
+ const { machineId } = entry
let selected: Awaited<ReturnType<FleetRouting['select']>>
+ let newest = false
try {
selected = await this.viaFleet((r) => r.select(machineId))
} finally {
- if (this.selecting === machineId) this.selecting = ''
+ newest = this.pending === entry
+ if (newest) this.pending = null
+ }
+ if (!newest) {
+ // Replaced, however it ended: a machine the person left failing late is no news to them. A newer pick of this same
+ // machine (away and back) speaks for this one too: the dial waits on that machine, and an error would end its wait.
+ if (this.pending?.machineId === machineId) return this.pending.done
+ if (this.selected === machineId) return { ok: true }
+ return { ok: false, code: 'SUPERSEDED', message: 'Another machine was chosen' }
+ }
+ if (!selected.ok) {
+ // The lane may still be where the pick this one replaced took it: the fleet refuses an unlinked machine before asking
+ // the lane, so the dial stayed here while the backend and any reconnect stayed on the machine the person left (reviews
+ // of #2504). Said again now, as picking this machine again would not: it is already selected. Only for a refusal, and
+ // only with a pick replaced: that one was still running, so the lane is up. Any other failure may be the lane's end (a
+ // revoke, a 4403, an unplug), and telling it anything would dial straight back past what it decided.
+ if (entry.replaced && REFUSALS.has(selected.code)) {
+ void this.announceSelection().catch((err) => this.wiring.log(`cable: could not announce (${(err as Error).message})`))
+ }
+ return selected
}
- if (!selected.ok) return selected
this.selected = machineId
return { ok: true }
}
@@ -355,7 +402,7 @@ export class DaemonCableHost implements CableHost {
*/
private async announceSelection(): Promise<void> {
if (!this.viaFleet((r) => r.hasLane())) return
- const machineId = this.selecting || this.selectedMachine()
+ const machineId = this.pendingPick() || this.selectedMachine()
if (isPlaceholder(machineId)) return
const 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
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.ts
index d9289b13f..731e43e68 100644
--- a/cli/src/cable/cableSession.spec.ts
+++ b/cli/src/cable/cableSession.spec.ts
@@ -12,6 +12,8 @@ import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { CABLE_MAX_FRAME, CableDecoder, CableType, encodeCableFrame } from './cableFrame.js'
+import { DaemonCableHost } from './cableHost.js'
+import type { MachineFleet } from './machineFleet.js'
import { CableSession, recapFrame, type CableAgent, type CableHost, type CableMachine, type CablePort } from './cableSession.js'
import { DialLog } from './dialLog.js'
import { leadsOf, type SaidOnCard, type SwarmCard, type SwarmLead } from '../superTabs/cards.js'
@@ -2363,6 +2365,163 @@ describe('cable session', () => {
await session.stop()
})
+ /**
+ * Diego's Buddy, 11-02. The dial's picks are not queued: a slow one is still out when the next arrives. Picking the
+ * machine the dial is already on took the "already selected" shortcut, so the host never heard of it, the slow pick
+ * landed, and `machine.selected` moved the dial's check mark away. On the real host, because the bug is between the two.
+ */
+ describe('a slow pick left behind', () => {
+ async function slowPick() {
+ const asked: Array<{ machineId: string; ok: () => void }> = []
+ const rows = [{ machineId: 'm2', name: 'office', state: 'ready', authMode: 'remote' }]
+ const fleet = {
+ list: async () => ({ machines: rows, source: 'backend' as const }),
+ recentAsks: async () => [],
+ online: async () => {},
+ // This computer's own select only announces where the dial is, and is answered at once here: the slow one is the pick.
+ select: (machineId: string) => machineId === 'mac-local' ? Promise.resolve() : new Promise<void>((ok) => { asked.push({ machineId, ok }) }),
+ release: vi.fn(),
+ listAgents: async () => [],
+ } as unknown as MachineFleet
+ const host = new DaemonCableHost({
+ sessions: () => [], displayName: () => '', machineName: () => 'this-mac', machineId: () => 'mac-local', computerId: () => 'abc',
+ sendTurn: vi.fn(), stopTurn: vi.fn(), answer: vi.fn(), recent: () => [], recentAsks: () => [], log: vi.fn(),
+ }, fleet)
+ const { session, port } = await connect(host)
+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })
+ await vi.waitFor(() => expect(port.types()).toContain('agents.end'))
+ port.sent.length = 0
+ const told = (type: string) => port.sent.filter((m) => m.t === type).map((m) => m.machineId)
+ return { host, session, port, asked, told }
+ }
+ /** What the dial is told takes a few sends after a pick settles; let them all out. */
+ const drained = async () => { for (let turn = 0; turn < 20; turn++) await settle() }
+
+ it('tells the dial nothing of the slow machine once the person picked the one the dial is on', async () => {
+ const { host, session, port, asked, told } = await slowPick()
+ port.say({ t: 'machine.select', machineId: 'm2' })
+ await vi.waitFor(() => expect(asked.map((a) => a.machineId)).toEqual(['m2']))
+ port.say({ t: 'machine.select', machineId: 'mac-local' })
+ await vi.waitFor(() => expect(told('machine.selected')).toEqual(['mac-local']))
+ asked[0]!.ok()
+ await drained()
+ expect(told('machine.selected')).toEqual(['mac-local'])
+ expect(host.selectedMachine()).toBe('mac-local')
+ await session.stop()
+ })
+
+ it('follows the app back to the machine the dial is on, which replaces a slow pick the same way', async () => {
+ const { host, session, port, asked, told } = await slowPick()
+ port.say({ t: 'machine.select', machineId: 'm2' })
+ await vi.waitFor(() => expect(asked.map((a) => a.machineId)).toEqual(['m2']))
+ await session.followApp('mac-local', 'a1')
+ asked[0]!.ok()
+ await drained()
+ expect(told('machine.selected')).toEqual(['mac-local'])
+ expect(host.selectedMachine()).toBe('mac-local')
+ await session.stop()
+ })
+
+ it('leaves a pick running when the window re-announces the focus it already had', async () => {
+ // Desktop re-sends its focus whenever its visible panes change: nobody chose anything (review of #2504).
+ const { host, session, port, asked, told } = await slowPick()
+ await session.followApp('mac-local', 'a1')
+ await drained()
+ port.sent.length = 0
+ port.say({ t: 'machine.select', machineId: 'm2' })
+ await vi.waitFor(() => expect(asked).toHaveLength(1))
+ await session.followApp('mac-local', 'a1')
+ expect(host.pendingPick!()).toBe('m2')
+ asked[0]!.ok()
+ await drained()
+ expect(told('machine.error')).toEqual([])
+ expect(told('machine.selected')).toEqual(['m2'])
+ expect(host.selectedMachine()).toBe('m2')
+ await session.stop()
+ })
+
+ it('leaves a pick running when the window echoes a turn of the dial', async () => {
+ const { host, session, port, asked, told } = await slowPick()
+ port.say({ t: 'machine.select', machineId: 'm2' })
+ await vi.waitFor(() => expect(asked).toHaveLength(1))
+ port.say({ t: 'focus', agentId: 'a7' })
+ await drained()
+ await session.followApp('mac-local', 'a7')
+ expect(host.pendingPick!()).toBe('m2')
+ asked[0]!.ok()
+ await drained()
+ expect(told('machine.selected')).toEqual(['m2'])
+ await session.stop()
+ })
+
+ it('answers the dial when an app follow joins its pick and a newer focus drops the follow\'s answer', async () => {
+ // Both reviews of #2504: the dial's wait has only its own pick left to end it, or it says "No response" at 6 s.
+ const { host, session, port, asked, told } = await slowPick()
+ port.say({ t: 'machine.select', machineId: 'm2' })
+ await vi.waitFor(() => expect(asked).toHaveLength(1))
+ const follow = session.followApp('m2', 'r1')
+ await drained()
+ const newer = session.followApp('m2', 'r2')
+ await drained()
+ expect(asked).toHaveLength(1)
+ asked[0]!.ok()
+ await Promise.all([follow, newer])
+ await drained()
+ expect(told('machine.error')).toEqual([])
+ expect(told('machine.selected')).toContain('m2')
+ expect(host.selectedMachine()).toBe('m2')
+ await session.stop()
+ })
+
+ it('shows no error when the dial gives up on a slow machine and the person picks it again', async () => {
+ // The firmware shows a machine.error for the machine it still waits on, so one here would read as a failure.
+ const { host, session, port, asked, told } = await slowPick()
+ port.say({ t: 'machine.select', machineId: 'm2' })
+ await vi.waitFor(() => expect(asked).toHaveLength(1))
+ port.say({ t: 'machine.select', machineId: 'm2' })
+ await drained()
+ expect(asked).toHaveLength(1)
+ asked[0]!.ok()
+ await drained()
+ expect(told('machine.error')).toEqual([])
+ expect(told('machine.selected')).toEqual(['m2', 'm2'])
+ expect(host.selectedMachine()).toBe('m2')
+ await session.stop()
+ })
+
+ it('shows no error when a person goes away and back: the last pick answers for the first', async () => {
+ // The dial shows a machine.error for the machine it still waits on, and a false one would clear its wait.
+ const { host, session, port, asked, told } = await slowPick()
+ port.say({ t: 'machine.select', machineId: 'm2' })
+ await vi.waitFor(() => expect(asked).toHaveLength(1))
+ port.say({ t: 'machine.select', machineId: 'mac-local' })
+ await vi.waitFor(() => expect(told('machine.selected')).toEqual(['mac-local']))
+ port.say({ t: 'machine.select', machineId: 'm2' })
+ await vi.waitFor(() => expect(asked).toHaveLength(2))
+ asked[0]!.ok()
+ await drained()
+ expect(told('machine.error')).toEqual([])
+ expect(told('machine.selected')).toEqual(['mac-local'])
+ asked[1]!.ok()
+ await drained()
+ expect(told('machine.selected')).toEqual(['mac-local', 'm2', 'm2'])
+ expect(host.selectedMachine()).toBe('m2')
+ await session.stop()
+ })
+
+ it('tells a dial its pick was replaced when something else chose another machine', async () => {
+ // The dial still waits on its pick here, and only this ends the wait before its own "No response".
+ const { session, port, asked, told } = await slowPick()
+ port.say({ t: 'machine.select', machineId: 'm2' })
+ await vi.waitFor(() => expect(asked).toHaveLength(1))
+ await session.followApp('mac-local', 'a1')
+ asked[0]!.ok()
+ await drained()
+ expect(told('machine.error')).toEqual(['m2'])
+ await session.stop()
+ })
+ })
+
it('shows one row and says why when there is no lane to anywhere else', async () => {
const host = makeHost({ listMachines: async () => ({ machines: [LOCAL_ROW], source: 'signed-out' as const }) })
const { session, port } = await connect(host)
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index b0a608778..3e7bf4229 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -387,6 +387,8 @@ export interface CableHost {
* so the dial needs no table for a set it does not own.
*/
selectMachine(machineId: string): Promise<{ ok: true } | { ok: false; code: string; message: string }>
+ /** The machine a pick is still on its way to, or '' when none is. Picking the selected machine then has to replace it. */
+ pendingPick?(): string
/** The window's swarms and which is on screen. Empty with no window: the dial then draws no swarm line. */
listSwarms(): { selected: string; swarms: CableSwarm[]; tiles: CableTile[] }
/** The dial picked a swarm. Relayed to the window, which switches and re-describes its desk. */
@@ -3227,7 +3229,9 @@ export class CableSession {
*/
private async selectMachine(machineId: string, isCurrent = () => true): Promise<void> {
if (!machineId) return
- if (machineId === this.host.selectedMachine()) {
+ // Not while a pick is on its way elsewhere: this one replaces it, so the host has to hear of it. Answered here alone,
+ // the slow pick landed afterwards and moved the check mark to a machine the person had left (Diego's Buddy, 11-02).
+ if (machineId === this.host.selectedMachine() && !this.host.pendingPick?.()) {
await this.send({ t: 'machine.selected', machineId })
await this.syncAgents()
this.restoreInBackground()
@@ -3589,6 +3593,9 @@ export class CableSession {
if (!this.link?.isOpen || this.greetedMac === null) return
if (!agentId) return
+ // Read now: the focus step below writes the record. Desktop re-sends the same focus whenever its visible panes change,
+ // and a dial's own turn comes back as an echo: neither is anyone choosing anything (review of #2504).
+ const moved = agentId !== this.desiredFocus || this.appFocusUnsent
const generation = ++this.appFocusGeneration
const task = this.appFocusTail.then(async () => {
// A newer desktop selection made this queued one obsolete before it started.
@@ -3636,7 +3643,8 @@ export class CableSession {
await focused
const isCurrent = () => generation === this.appFocusGeneration
if (!isCurrent() || !machineId) return
- if (machineId === this.host.selectedMachine()) {
+ // Only a focus that really moved replaces a pick on its way elsewhere (see selectMachine).
+ if (machineId === this.host.selectedMachine() && !(moved && this.host.pendingPick?.())) {
// An older attachment to this same machine may have finished without acknowledging it,
// because a newer pane superseded that request. The wheel still needs its selection.
await this.syncMachines()
diff --git a/cli/src/device/deviceLink.spec.ts b/cli/src/device/deviceLink.spec.ts
index ee21654b4..04ba6b8af 100644
--- a/cli/src/device/deviceLink.spec.ts
+++ b/cli/src/device/deviceLink.spec.ts
@@ -1100,6 +1100,67 @@ describe('overlapping machine selects', () => {
expect(selects()).toHaveLength(2)
})
+ /**
+ * Diego's Buddy, 11-02: a select is answered, then the machine's handshake may take its whole 15 s. A newer pick in those
+ * seconds found nothing to replace (the select had settled), so the older attach still resolved and the dial was told it
+ * had landed on a machine the person had already left.
+ */
+ describe('a newer pick during the handshake', () => {
+ /** A lane whose machines answer no hello until told to: every select is answered at once. */
+ async function slowHello() {
+ const up = await lane({ welcome: false })
+ up.server.on((frame) => {
+ if (frame.type === 'machine_select') up.server.send({ type: 'machine_selected', payload: { machineId: (frame.payload as { machineId: string }).machineId } })
+ })
+ await up.link.online()
+ const hello = () => up.server.received.filter((frame) => frame.type === 'e2e_hello').length
+ const welcome = (machineId: string) => up.server.send({ type: 'e2e_welcome', machineId, payload: { ephPub: 'E' } })
+ return { ...up, hello, welcome }
+ }
+
+ it('fails the older attach once its handshake ends, and leaves the lane on the newer machine', async () => {
+ const { link, hello, welcome, lines } = await slowHello()
+ const older = settled(link.attach(LINKED))
+ await soon('the hello', () => hello() === 1)
+ expect(await settled(link.attach(CLOUD))).toBe('ok')
+ welcome(LINKED)
+ expect(await older).toBe('SELECT_SUPERSEDED')
+ expect(link.selectedMachine).toBe(CLOUD)
+ await soon('the session', () => lines.includes(`device: e2e session ready ${LINKED}`))
+ })
+
+ it('fails the older attach the same way when its handshake fails instead', async () => {
+ const { link, server, hello } = await slowHello()
+ const older = settled(link.attach(LINKED))
+ await soon('the hello', () => hello() === 1)
+ expect(await settled(link.attach(CLOUD))).toBe('ok')
+ server.send({ type: 'e2e_denied', machineId: LINKED, payload: {} })
+ // Its own failure is what it reports: the caller that made a newer pick decides what it means (cableHost.ts).
+ expect(await older).toBe('E2EE_DENIED')
+ expect(link.selectedMachine).toBe(CLOUD)
+ })
+
+ it('still resolves both attaches of one machine through one handshake', async () => {
+ const { link, server, hello, welcome } = await slowHello()
+ const first = settled(link.attach(LINKED))
+ await soon('the hello', () => hello() === 1)
+ const second = settled(link.attach(LINKED))
+ welcome(LINKED)
+ expect([await first, await second]).toEqual(['ok', 'ok'])
+ expect(hello()).toBe(1)
+ expect(server.received.filter((frame) => frame.type === 'machine_select')).toHaveLength(1)
+ })
+
+ it('fails the attach when the lane is revoked during its handshake', async () => {
+ const { link, server, hello } = await slowHello()
+ const pending = settled(link.attach(LINKED))
+ await soon('the hello', () => hello() === 1)
+ server.send({ type: 'device_revoked' })
+ expect(await pending).toBe('revoked')
+ expect(link.selectedMachine).toBe('')
+ })
+ })
+
it('fails a select in flight when the lane is revoked, and starts the next one fresh', async () => {
const { link, server, selects } = await selecting(60_000)
const pending = settled(link.attach(CLOUD))
diff --git a/cli/src/device/deviceLink.ts b/cli/src/device/deviceLink.ts
index 02d264f56..c3f2a5522 100644
--- a/cli/src/device/deviceLink.ts
+++ b/cli/src/device/deviceLink.ts
@@ -309,6 +309,10 @@ export class DeviceLink {
if (this.wanted !== machineId) throw new Error(SELECT_SUPERSEDED)
await this.select(machineId)
await this.establish(machineId)
+ // Again, because the handshake can take its whole 15 s with its select already settled, so a newer pick found nothing
+ // to replace: this attach resolved, and the dial was told it had landed on a machine the person had left (Diego's
+ // Buddy, 11-02). The session it made is kept: the carousel holds this machine's agents whichever is selected.
+ if (this.wanted !== machineId) throw new Error(SELECT_SUPERSEDED)
}
/**