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): probe an unknown USB board once, and leave it alone
jaylfc152e07e35f41
diff --git a/cli/src/cable/cableFleet.spec.ts b/cli/src/cable/cableFleet.spec.tsindex f218c9f3f..222cda444 100644--- a/cli/src/cable/cableFleet.spec.ts+++ b/cli/src/cable/cableFleet.spec.ts@@ -1,4 +1,5 @@-import { mkdtempSync, readdirSync } from 'node:fs'+import { spawn } from 'node:child_process'+import { mkdtempSync, readdirSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { pathToFileURL } from 'node:url'@@ -7,7 +8,8 @@ import { CableFleet as SourceFleet } from './cableFleet.js'import { CableSession, type CableHost, type CablePort } from './cableSession.js'import { CableDecoder, CableType, encodeCableFrame } from './cableFrame.js'import { DialLog } from './dialLog.js'-import { parseDarwinDialPorts, type DialPort } from './serial.js'+import { DialVerdicts } from './dialPortVerdicts.js'+import { parseDarwinDialPorts, portInUse, type DialPort } from './serial.js'// Run the same two-device scenarios against the staged helper before deployment.const CableFleet: typeof SourceFleet = process.env.HARNESS_TEST_USB_FLEET@@ -217,6 +219,142 @@ describe('USB dial fleet', () => {})})+describe('a board that is not a dial', () => {+ /**+ * Found on a desk with a second ESP32-S3 plugged in for its own work: it shares the dial's USB ids, so+ * the daemon opened it, heard nothing it understood, waited a minute and opened it again, for as long+ * as it ran. That corrupted an esptool flash read twice. A board is looked at once per attachment.+ */+ const scenario = (opts: { inUse?: (path: string) => Promise<boolean>; file?: string } = {}) => {+ const f = fixture()+ const foreign = { ...device('/dev/other', 'CC:03'), session: '100' }+ const dial = { ...device('/dev/tim', 'AA:01'), session: '200' }+ f.setPorts([foreign, dial])+ const options = { ...f.options, verdicts: new DialVerdicts(opts.file), watchEveryMs: 0, ...(opts.inUse ? { inUse: opts.inUse } : { inUse: async () => false }) }+ const fleet = new CableFleet(CableSession, f.host, f.logs, DialLog, options)+ const opens = () => f.options.open.mock.calls.map(c => c[0])+ const scan = async () => { await (fleet as unknown as { scan(): Promise<void> }).scan(); await new Promise(r => setTimeout(r, 5)) }+ return { f, fleet, foreign, dial, options, opens, scan }+ }++ it('is probed once, then left alone, while the dial beside it carries on', async () => {+ const s = scenario()+ try {+ s.fleet.start()+ await vi.waitFor(() => expect(s.f.ports).toHaveLength(2))+ const other = s.f.ports.find(p => p.path === '/dev/other')!+ const tim = s.f.ports.find(p => p.path === '/dev/tim')!+ other.say({ t: 'hello', product: 'grid', mac: 'other', fw: '1', proto: 1 })+ await s.f.greet([tim])+ await vi.waitFor(() => expect(other.isOpen).toBe(false))+ const after = s.opens().filter(p => p === '/dev/other').length+ for (let i = 0; i < 4; i++) await s.scan()+ expect(s.opens().filter(p => p === '/dev/other').length).toBe(after)+ expect(tim.isOpen).toBe(true)+ expect(s.f.host.log).toHaveBeenCalledWith(expect.stringContaining('leaving it alone until it is unplugged or reset'))+ } finally { await s.fleet.stop() }+ })++ it('is looked at again once it has been unplugged and plugged back in', async () => {+ const s = scenario()+ try {+ s.fleet.start()+ await vi.waitFor(() => expect(s.f.ports).toHaveLength(2))+ s.f.ports.find(p => p.path === '/dev/other')!.say({ t: 'hello', product: 'grid', mac: 'other', fw: '1', proto: 1 })+ await vi.waitFor(() => expect(s.f.ports.find(p => p.path === '/dev/other')!.isOpen).toBe(false))+ const before = s.opens().filter(p => p === '/dev/other').length+ // Unplugged and plugged back in: same board, new attachment.+ s.f.setPorts([{ ...s.foreign, session: '101' }, s.dial])+ // Scanning as the interval would: the old entry leaves on a timer of its own, so the first scan+ // may still find it there and the next one starts the new attachment.+ await vi.waitFor(async () => {+ await s.scan()+ expect(s.opens().filter(p => p === '/dev/other').length).toBeGreaterThan(before)+ }, { timeout: 5000 })+ } finally { await s.fleet.stop() }+ })++ it('is looked at again once a program has worked on it and let go, which is what a flash looks like', async () => {+ // A reset or a reflash over USB-Serial/JTAG leaves the attachment as it was (measured with esptool on+ // the desk), so the USB view cannot say a board became a dial. Somebody holding its port for a while,+ // and then not, can: that is esptool or idf.py. The board is looked at once more when they let go.+ let busy = false+ const s = scenario({ inUse: async path => path === '/dev/other' && busy })+ try {+ s.fleet.start()+ await vi.waitFor(() => expect(s.f.ports).toHaveLength(2))+ s.f.ports.find(p => p.path === '/dev/other')!.say({ t: 'hello', product: 'grid', mac: 'other', fw: '1', proto: 1 })+ await vi.waitFor(() => expect(s.f.ports.find(p => p.path === '/dev/other')!.isOpen).toBe(false))+ const before = s.opens().filter(p => p === '/dev/other').length++ // Still ruled out while nothing has touched it, and while it is being worked on.+ for (let i = 0; i < 3; i++) await s.scan()+ busy = true+ for (let i = 0; i < 3; i++) await s.scan()+ expect(s.opens().filter(p => p === '/dev/other').length).toBe(before)++ // They let go: it may be a different board now.+ busy = false+ await vi.waitFor(async () => {+ await s.scan()+ expect(s.opens().filter(p => p === '/dev/other').length).toBeGreaterThan(before)+ }, { timeout: 5000 })+ expect(s.f.host.log).toHaveBeenCalledWith(expect.stringContaining('was in use and is free again'))+ } finally { await s.fleet.stop() }+ })++ it('is not probed again by the next daemon either', async () => {+ const file = join(mkdtempSync(join(tmpdir(), 'fleet-verdicts-')), 'dial-ports.json')+ const first = scenario({ file })+ try {+ first.fleet.start()+ await vi.waitFor(() => expect(first.f.ports).toHaveLength(2))+ first.f.ports.find(p => p.path === '/dev/other')!.say({ t: 'hello', product: 'grid', mac: 'other', fw: '1', proto: 1 })+ await vi.waitFor(() => expect(first.f.ports.find(p => p.path === '/dev/other')!.isOpen).toBe(false))+ } finally { await first.fleet.stop() }++ const second = scenario({ file })+ try {+ second.fleet.start()+ await vi.waitFor(() => expect(second.opens()).toContain('/dev/tim'))+ for (let i = 0; i < 3; i++) await second.scan()+ expect(second.opens()).not.toContain('/dev/other')+ } finally { await second.fleet.stop() }+ })++ it('is never opened while another program has it, and only then once that program is done', async () => {+ let busy = true+ const s = scenario({ inUse: async path => path === '/dev/other' && busy })+ try {+ s.fleet.start()+ await vi.waitFor(() => expect(s.opens()).toContain('/dev/tim'))+ for (let i = 0; i < 3; i++) await s.scan()+ expect(s.opens()).not.toContain('/dev/other')+ expect(s.f.host.log).toHaveBeenCalledWith(expect.stringContaining('/dev/other is in use by another program'))+ busy = false+ await s.scan()+ await vi.waitFor(() => expect(s.opens()).toContain('/dev/other'))+ } finally { await s.fleet.stop() }+ })++ it('reads a port as held when a process other than this one has it open', async () => {+ // Skipped without lsof; the fleet treats "cannot tell" as free, so there is nothing to prove there.+ const file = join(mkdtempSync(join(tmpdir(), 'held-')), 'tty')+ writeFileSync(file, '')+ const holder = spawn('tail', ['-f', file], { stdio: 'ignore' })+ try {+ await new Promise(r => setTimeout(r, 300))+ const held = await portInUse(file)+ const lsofExists = await new Promise<boolean>(r => spawn('lsof', ['-v'], { stdio: 'ignore' }).on('error', () => r(false)).on('exit', () => r(true)))+ if (lsofExists) expect(held).toBe(true)+ } finally {+ holder.kill()+ await new Promise(r => holder.on('exit', r))+ }+ expect(await portInUse(file)).toBe(false)+ })+})+describe('macOS USB inventory', () => {it('associates each tty with its own matching USB parent and serial in either property order', () => {const dump = `+-o root@@ -236,11 +374,14 @@ describe('macOS USB inventory', () => {+-o Tux"idVendor" = 12346"idProduct" = 4097+ "sessionID" = 14351572441873"USB Serial Number" = "BB:02"+-o serial+ "sessionID" = 99"IOCalloutDevice" = "/dev/tux"+-o console"IOCalloutDevice" = "/dev/debug-console"`- expect(parseDarwinDialPorts(dump)).toEqual([device('/dev/tim', 'AA:01'), device('/dev/tux', 'BB:02')])+ // The attachment identity is the USB device's own sessionID, not one from a node below it.+ expect(parseDarwinDialPorts(dump)).toEqual([device('/dev/tim', 'AA:01'), { ...device('/dev/tux', 'BB:02'), session: '14351572441873' }])})})diff --git a/cli/src/cable/cableFleet.ts b/cli/src/cable/cableFleet.tsindex 1dcffcb31..e1bbece30 100644--- a/cli/src/cable/cableFleet.ts+++ b/cli/src/cable/cableFleet.ts@@ -1,7 +1,8 @@// One protocol session per USB dial, sharing the desktop's event source.// Voice buffers, decoding, firmware transfers and disconnects remain per dial.import { join } from 'node:path'-import { findDialPorts, SerialLink, type DialPort } from './serial.js'+import { DialVerdicts } from './dialPortVerdicts.js'+import { findDialPorts, portInUse, SerialLink, type DialPort } from './serial.js'import type { CableSession, CableHost, CablePort, DialStatus, PortOpener } from './cableSession.js'import type { DialLog } from './dialLog.js'@@ -15,6 +16,12 @@ export interface CableFleetOptions {/** Optional local selection. An empty list discovers all matching dials. */serials?: string[]intervalMs?: number+ /** Which boards have already been found not to be dials. In memory only unless it has a file. */+ verdicts?: DialVerdicts+ /** Does another process have this tty open? A port somebody else is using is not looked at. */+ inUse?: (path: string) => Promise<boolean>+ /** How often a board ruled out is checked for another program working on it. */+ watchEveryMs?: number}export class CableFleet {@@ -25,6 +32,13 @@ export class CableFleet {private readonly discover: () => Promise<DialPort[]>private readonly open: OpenPortprivate readonly serials: Set<string>+ private readonly verdicts: DialVerdicts+ private readonly inUse: (path: string) => Promise<boolean>+ /** Ports already reported as in use, so the log says it once rather than every scan. */+ private readonly heldNotes = new Set<string>()+ /** For each board ruled out: when it was last checked for another program's use, and whether it was in use. */+ private readonly watched = new Map<string, { at: number; wasBusy: boolean }>()+ private readonly watchEveryMs: numberconstructor(private readonly Session: SessionConstructor, private readonly host: CableHost,private readonly logs: string, private readonly Log: typeof DialLog,@@ -32,6 +46,9 @@ export class CableFleet {this.discover = options.discover ?? findDialPortsthis.open = options.open ?? SerialLink.openthis.serials = new Set((options.serials ?? []).map(s => s.toUpperCase()))+ this.verdicts = options.verdicts ?? new DialVerdicts()+ this.inUse = options.inUse ?? portInUse+ this.watchEveryMs = options.watchEveryMs ?? 8_000}get isConnected(): boolean { return [...this.entries.values()].some(e => e.session.isConnected) }@@ -61,6 +78,28 @@ export class CableFleet {return this.scanTask}+ /**+ * Has a program had this ruled-out board open and let go since it was ruled out?+ *+ * That is how a board becomes a dial: someone flashes it, with esptool or `idf.py`, and neither a+ * reset nor a reflash changes what USB says about it, so the flash itself is the only sign there is.+ * When the port goes from held to free the verdict is forgotten and the board is looked at once more.+ * Checked every few seconds, not every scan: `lsof` is a process, and the answer changes slowly.+ */+ private async workedOn(port: DialPort): Promise<boolean> {+ const key = (port.serialNumber ?? port.path).toUpperCase()+ const watch = this.watched.get(key) ?? { at: 0, wasBusy: false }+ this.watched.set(key, watch)+ if (Date.now() - watch.at < this.watchEveryMs) return false+ watch.at = Date.now()+ if (await this.inUse(port.path)) { watch.wasBusy = true; return false }+ if (!watch.wasBusy) return false+ watch.wasBusy = false+ this.verdicts.clear(port)+ this.host.log(`cable: ${port.path} was in use and is free again — looking at it once more`)+ return true+ }+private async reconcile(): Promise<void> {const ports = await this.discover()if (this.stopped) return@@ -68,6 +107,8 @@ export class CableFleet {for (const port of ports) {const serial = port.serialNumber?.toUpperCase()if (this.serials.size && (!serial || !this.serials.has(serial))) continue+ // Found not to be a dial already, and nobody seen working on it since: nothing to look at.+ if (this.verdicts.isForeign(port) && !(await this.workedOn(port))) continuepresent.set(serial || port.path, port)}let removed = false@@ -83,6 +124,15 @@ export class CableFleet {if (this.stopped) returnfor (const [id, port] of present) {if (this.entries.has(id)) continue+ // A board somebody else has open is somebody's work in progress (a flash, a monitor, a console).+ // Two readers on one tty interleave bytes, so it is not opened, and looked at again next scan.+ if (await this.inUse(port.path)) {+ if (!this.heldNotes.has(port.path)) this.host.log(`cable: ${port.path} is in use by another program — leaving it alone`)+ this.heldNotes.add(port.path)+ continue+ }+ this.heldNotes.delete(port.path)+ if (this.stopped) returnconst entry: Entry = { port, attached: false, status: { attached: false }, session: undefined! }const attached = () => {if (entry.attached) return@@ -106,6 +156,16 @@ export class CableFleet {get: (target, key) => {if (key === 'onDialAttached') return attachedif (key === 'onDialGone') return gone+ if (key === 'onForeignPort') return (path: string, why: string) => {+ this.verdicts.markForeign(port)+ this.host.log(`cable: ${path} is not a Harness dial (${why}) — leaving it alone until it is unplugged or reset [usb ${id}]`)+ // Off this call stack: the session is in the middle of deciding this, and stop() waits on it.+ setTimeout(() => {+ if (this.entries.get(id) !== entry) return+ this.entries.delete(id)+ void entry.session.stop()+ }, 0)+ }if (key === 'onDialStatus') return (status: DialStatus) => {entry.status = { ...status, id }this.publish()diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex 30ca5bf79..76962be8e 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -725,6 +725,42 @@ describe('cable session', () => {await session.stop()})+ it('says so when the port is another product\'s, or never speaks at all, and never of a real dial', async () => {+ // Told to whoever owns discovery, so a second ESP32 on the desk stops being opened every minute.+ // A port that has been a dial is never reported: a hung or rebooting dial goes quiet and comes back.+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] })+ try {+ const reports: Array<[string, string]> = []+ const host = makeHost({ onForeignPort: (path, why) => { reports.push([path, why]) } })++ // 1. Another product's greeting.+ const other = await connect(host)+ other.port.say({ t: 'hello', product: 'grid', fw: '0.1.2', proto: 1, mac: 'aa:bb' })+ await settle()+ expect(reports).toEqual([['/dev/loopback', "greeted as 'grid'"]])+ await other.session.stop()++ // 2. A port that never says anything.+ reports.length = 0+ const quiet = await connect(host)+ await settle()+ for (let sec = 0; sec < 25; sec++) { vi.advanceTimersByTime(1_000); await settle() }+ expect(reports).toEqual([['/dev/loopback', 'silent']])+ await quiet.session.stop()++ // 3. A real dial that then goes quiet is not written off.+ reports.length = 0+ const dial = await connect(host)+ dial.port.say({ t: 'hello', product: 'harness', fw: '0.1.0', proto: 1, mac: 'aa:bb' })+ await settle()+ for (let sec = 0; sec < 25; sec++) { vi.advanceTimersByTime(1_000); await settle() }+ expect(reports).toEqual([])+ await dial.session.stop()+ } finally {+ vi.useRealTimers()+ }+ })+it("refuses a dial that names another product, and lets go of its port", async () => {// The framing magic should already have made this greeting unreadable — reaching here means something// this code cannot see has changed (a re-unified magic, a fork of the firmware, a third product). Thediff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex 781955a50..e17aba51c 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -336,6 +336,13 @@ export interface CableHost {*/onDialAttached?(): voidonDialGone?(): void+ /**+ * The port this session opened turned out not to be a Harness dial: it talked in something else, or+ * never said anything at all. Told once, so whoever owns discovery can stop offering the port — a+ * second ESP32 board on the desk is somebody's work in progress, not ours to keep probing.+ * Never called for a device that has been a dial.+ */+ onForeignPort?(path: string, why: string): void/*** The dial as a window would draw it: there or not, on which firmware, and whether an update is* going over the cable right now. Fired on every change and never on a keepalive — the window@@ -468,6 +475,9 @@ export class CableSession {private decoder = new CableDecoder()private timer: NodeJS.Timeout | null = nullprivate greetedMac: string | null = null+ /** This session has spoken with a real dial at least once. Never reset: a port that has been a dial+ * can go quiet (a hung firmware, a reboot) without ever becoming somebody else's. */+ private everGreeted = false/** The board this device says it is (`hello.hw`). Decides which firmware it may be offered. */private greetedHw: string | undefined/** What the device last SAID its settings are. Never what this computer last asked for. */@@ -604,6 +614,11 @@ export class CableSession {// ── port lifecycle ────────────────────────────────────────────────────────────────────────────────+ private reportForeign(path: string, why: string): void {+ if (this.everGreeted) return+ this.host.onForeignPort?.(path, why)+ }+private async tick(): Promise<void> {if (this.stopped) return// The firmware beats once a minute; the gap is marked in the dial's own log, where it is read.@@ -627,12 +642,17 @@ export class CableSession {// dial if the user unplugged theirs and plugged ours into the same socket.this.foreignRetryAt = Date.now() + 60_000this.log(`cable: ${this.link.path} is not a Harness dial (${this.bytesSinceOpen} B, no frames) — releasing it`)+ this.reportForeign(this.link.path, `${this.bytesSinceOpen} B, no frames`)await this.link.close('not ours')this.link = nullreturn}// Rule 2. The read never fails on a dead handle, so silence is the only symptom there is.if (Date.now() - this.lastRx > SILENCE_MS) {+ // Silent since the moment it opened and never a dial: a board with nothing to say to us. Reopening+ // it every few seconds for ever is how a second ESP32 on the desk gets its serial port stolen+ // mid-flash, so say so instead of retrying.+ if (this.framesSinceOpen === 0 && !this.everGreeted) this.reportForeign(this.link.path, 'silent')this.log('cable: silent, reopening the port')// close() runs onClosed, which is where onDialGone fires — one path for "the dial is not there",// whether the cable was pulled or the far end simply stopped answering.@@ -860,6 +880,7 @@ export class CableSession {}this.foreignPort = this.link?.path ?? nullthis.foreignRetryAt = Date.now() + 60_000+ if (this.link) this.reportForeign(this.link.path, `greeted as '${product ?? 'nameless'}'`)await this.link?.close('another product')this.link = nullreturn@@ -908,6 +929,7 @@ export class CableSession {if (mac !== this.greetedMac || fw !== this.greetedFw) {const returning = mac === this.greetedMacthis.greetedMac = mac+ this.everGreeted = truethis.greetedFw = fwthis.log(`cable: dial ${mac} ${returning ? 'back ' : ''}on fw ${fw} proto ${msg.proto}${hw ? ` hw ${hw}` : ''}`)this.dialLog.greeted()diff --git a/cli/src/cable/dialPortVerdicts.spec.ts b/cli/src/cable/dialPortVerdicts.spec.tsnew file mode 100644index 000000000..c625f5f3d--- /dev/null+++ b/cli/src/cable/dialPortVerdicts.spec.ts@@ -0,0 +1,58 @@+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { DialVerdicts } from './dialPortVerdicts.js'+import type { DialPort } from './serial.js'++const board = (session?: string, serialNumber = 'AA:01'): DialPort =>+ ({ path: '/dev/board', serialNumber, vendorId: 0x303a, productId: 0x1001, ...(session ? { session } : {}) })++describe('verdicts on USB boards', () => {+ it('holds for one attachment of a board and lets go when it is unplugged or reset', () => {+ const verdicts = new DialVerdicts()+ expect(verdicts.isForeign(board('1'))).toBe(false)+ verdicts.markForeign(board('1'))+ expect(verdicts.isForeign(board('1'))).toBe(true)+ // A new attachment: the board may have been reflashed into a dial in between.+ expect(verdicts.isForeign(board('2'))).toBe(false)+ // Another board is another board.+ expect(verdicts.isForeign(board('1', 'BB:02'))).toBe(false)+ })++ it('expires on its own, as the safety net for a change the USB attachment did not show', () => {+ let now = 1_000_000+ const verdicts = new DialVerdicts(undefined, () => now)+ verdicts.markForeign(board('1'))+ now += 5 * 60 * 60_000+ expect(verdicts.isForeign(board('1'))).toBe(true)+ now += 2 * 60 * 60_000+ expect(verdicts.isForeign(board('1'))).toBe(false)+ })++ it('is only a short pause when nothing identifies the attachment', () => {+ let now = 1_000_000+ const verdicts = new DialVerdicts(undefined, () => now)+ verdicts.markForeign(board(undefined))+ now += 5 * 60_000+ expect(verdicts.isForeign(board(undefined))).toBe(true)+ now += 6 * 60_000+ expect(verdicts.isForeign(board(undefined))).toBe(false)+ })++ it('outlives the daemon: a restart does not cost another probe', () => {+ const file = join(mkdtempSync(join(tmpdir(), 'verdicts-')), 'nested', 'dial-ports.json')+ new DialVerdicts(file).markForeign(board('7'))+ expect(new DialVerdicts(file).isForeign(board('7'))).toBe(true)+ expect(new DialVerdicts(file).isForeign(board('8'))).toBe(false)+ })++ it('starts with no opinions from a file it cannot read, and writes a good one over it', () => {+ const file = join(mkdtempSync(join(tmpdir(), 'verdicts-')), 'dial-ports.json')+ writeFileSync(file, '{ not json')+ const verdicts = new DialVerdicts(file)+ expect(verdicts.isForeign(board('1'))).toBe(false)+ verdicts.markForeign(board('1'))+ expect(JSON.parse(readFileSync(file, 'utf8'))).toHaveProperty('AA:01')+ })+})diff --git a/cli/src/cable/dialPortVerdicts.ts b/cli/src/cable/dialPortVerdicts.tsnew file mode 100644index 000000000..e46fe8498--- /dev/null+++ b/cli/src/cable/dialPortVerdicts.ts@@ -0,0 +1,66 @@+// What this computer has learned about the USB boards that are not dials.+//+// Every ESP32-S3 shares one USB id, so the daemon cannot tell a dial from a developer's own board+// without opening the port and listening. It does that ONCE, writes down the answer, and leaves the+// board alone after that. The record outlives the daemon, which restarts often, so the answer does not+// cost another probe each time. It stops holding when the board is unplugged (a new attachment,+// DialPort.session), when someone worked on it and let go (the fleet clears it: a flash is exactly how a+// board becomes a dial, and a reset over USB-Serial/JTAG does NOT change the attachment, measured), or+// when it gets old.+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { dirname } from 'node:path'+import type { DialPort } from './serial.js'++/** A verdict about an attachment we can identify holds this long: the safety net for a board that+ * changed without its USB attachment changing and without anyone being seen working on it. */+const KNOWN_FOR_MS = 6 * 60 * 60_000+/** A verdict about a port with no attachment identity is only a pause, since nothing says when it changes. */+const UNKNOWN_FOR_MS = 10 * 60_000++interface Verdict { session?: string; at: number }++const keyOf = (port: DialPort) => (port.serialNumber ?? port.path).toUpperCase()++export class DialVerdicts {+ private readonly foreign = new Map<string, Verdict>()++ constructor(private readonly file?: string, private readonly now: () => number = Date.now) {+ if (!file || !existsSync(file)) return+ try {+ const raw = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>+ for (const [key, value] of Object.entries(raw)) {+ const v = value as Partial<Verdict> | null+ if (v && typeof v.at === 'number') this.foreign.set(key, { at: v.at, ...(typeof v.session === 'string' ? { session: v.session } : {}) })+ }+ } catch { /* unreadable: start with no opinions, and rewrite it on the next verdict */ }+ }++ /** Was this very attachment of this board already found not to be a dial? */+ isForeign(port: DialPort): boolean {+ const verdict = this.foreign.get(keyOf(port))+ if (!verdict) return false+ const age = this.now() - verdict.at+ if (verdict.session === undefined || port.session === undefined) return age < UNKNOWN_FOR_MS+ return verdict.session === port.session && age < KNOWN_FOR_MS+ }++ /** Forget the verdict: somebody worked on this board since it was made. */+ clear(port: DialPort): void {+ if (this.foreign.delete(keyOf(port))) this.save()+ }++ markForeign(port: DialPort): void {+ this.foreign.set(keyOf(port), { at: this.now(), ...(port.session ? { session: port.session } : {}) })+ this.save()+ }++ private save(): void {+ if (!this.file) return+ try {+ mkdirSync(dirname(this.file), { recursive: true })+ const tmp = `${this.file}.${process.pid}.tmp`+ writeFileSync(tmp, JSON.stringify(Object.fromEntries(this.foreign)))+ renameSync(tmp, this.file)+ } catch { /* a verdict that cannot be saved is still in memory for this run */ }+ }+}diff --git a/cli/src/cable/serial.ts b/cli/src/cable/serial.tsindex 1527e3f93..cf500cca9 100644--- a/cli/src/cable/serial.ts+++ b/cli/src/cable/serial.ts@@ -27,6 +27,14 @@ export interface DialPort {vendorId: numberproductId: numberserialNumber?: string+ /**+ * Which ATTACHMENT of that device this is: macOS's per-enumeration `sessionID`, Linux's bus:devnum.+ * It changes when the device is unplugged and plugged back in, and stays put while it sits there,+ * INCLUDING across a reset or a reflash over USB-Serial/JTAG (measured: esptool's hard reset leaves+ * the sessionID as it was). So it lets a verdict about a board ("not a dial") outlast a daemon restart+ * and end at an unplug, but it cannot say the board was reflashed; the fleet watches for that.+ */+ session?: string}/**@@ -52,6 +60,27 @@ export async function findDialPorts(): Promise<DialPort[]> {return []}+/**+ * Is another process holding this tty open right now?+ *+ * The daemon looks at every USB Espressif board on the desk, and most of them are not dials: they are+ * somebody's work in progress, with esptool, `idf.py monitor` or a serial console on the other end. Two+ * readers on one tty interleave bytes, and that corrupts a flash or a log, so a port somebody else has+ * open is left alone and looked at again later. Cannot tell (no `lsof`, a timeout) reads as free: a+ * daemon that never opens anything because a tool is missing would be worse than one that sometimes does.+ */+export async function portInUse(path: string): Promise<boolean> {+ const pids = (out: unknown) => String(out ?? '').split('\n').map(l => Number(l.trim())).filter(n => n > 0 && n !== process.pid)+ try {+ const { stdout } = await runFile('lsof', ['-t', '--', path], { timeout: 5000 })+ return pids(stdout).length > 0+ } catch (error) {+ // lsof exits 1 when nothing has the file open, but also when it lists holders and warns about+ // something else (a stale network mount is enough), so what it printed counts either way.+ return pids((error as { stdout?: unknown }).stdout).length > 0+ }+}+/** Indentation column of an ioreg line — the tree's only structure. */function depthOf(line: string): number {const m = line.match(/^[\s|+-]*/)@@ -75,6 +104,7 @@ export function parseDarwinDialPorts(dump: string): DialPort[] {const seen = new Set<string>()let armedAt: number | null = nulllet armedSerial: string | undefined+ let armedSession: string | undefinedlet serialNumber: string | undefinedlet sawVendor = falselet sawProduct = false@@ -84,7 +114,7 @@ export function parseDarwinDialPorts(dump: string): DialPort[] {// A new node resets what we have seen about the current one. `+-o` opens a node in this dump.if (line.includes('+-o')) {const d = depthOf(line)- if (armedAt !== null && d <= armedAt) { armedAt = null; armedSerial = undefined }+ if (armedAt !== null && d <= armedAt) { armedAt = null; armedSerial = undefined; armedSession = undefined }nodeDepth = dsawVendor = falsesawProduct = false@@ -98,12 +128,18 @@ export function parseDarwinDialPorts(dump: string): DialPort[] {serialNumber = line.split('=')[1]?.trim().replace(/^"|"$/g, '')if (armedAt === nodeDepth) armedSerial = serialNumber}+ // The USB device node's own sessionID (the interfaces below it carry ones of their own).+ if (line.includes('"sessionID"') && armedAt === nodeDepth) armedSession = line.split('=')[1]?.trim()if (sawVendor && sawProduct && armedAt === null) { armedAt = nodeDepth; armedSerial = serialNumber }if (armedAt !== null && line.includes('"IOCalloutDevice"')) {const path = line.split('=')[1]?.trim().replace(/^"|"$/g, '')if (path && !seen.has(path)) {- ports.push({ path, vendorId: DIAL_VENDOR_ID, productId: DIAL_PRODUCT_ID, ...(armedSerial ? { serialNumber: armedSerial } : {}) })+ ports.push({+ path, vendorId: DIAL_VENDOR_ID, productId: DIAL_PRODUCT_ID,+ ...(armedSerial ? { serialNumber: armedSerial } : {}),+ ...(armedSession ? { session: armedSession } : {}),+ })seen.add(path)}}@@ -127,7 +163,14 @@ function findLinux(): DialPort[] {if (vid === DIAL_VENDOR_ID && pid === DIAL_PRODUCT_ID) {let serialNumber: string | undefinedtry { serialNumber = readFileSync(`${dir}/serial`, 'utf8').trim() } catch { /* older USB descriptors */ }- ports.push({ path: `/dev/${name}`, vendorId: vid, productId: pid, ...(serialNumber ? { serialNumber } : {}) })+ let session: string | undefined+ try {+ session = `${readFileSync(`${dir}/busnum`, 'utf8').trim()}:${readFileSync(`${dir}/devnum`, 'utf8').trim()}`+ } catch { /* no attachment identity: verdicts on this port are short-lived */ }+ ports.push({+ path: `/dev/${name}`, vendorId: vid, productId: pid,+ ...(serialNumber ? { serialNumber } : {}), ...(session ? { session } : {}),+ })}break} catch {diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 4163e3f71..da3235083 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -43,6 +43,7 @@ import { DialLog } from './cable/dialLog.js'import { buildLogBundle, bundleFileName, redactSecretsInText } from './lib/logBundle.js'import { CableSession } from './cable/cableSession.js'import { CableFleet } from './cable/cableFleet.js'+import { DialVerdicts } from './cable/dialPortVerdicts.js'import { DaemonCableHost, cableEventFor, cableQuestionFor, cableQuestionCloseFor } from './cable/cableHost.js'import { terminalActivity } from './cable/terminalActivity.js'@@ -6792,7 +6793,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {try { writeFileSync(legacyDialLog, `moved to ${join(env.HARNESS_LOGS_DIR, 'dial-YYYYMMDD.log')}\n`) } catch { /* best effort */ }}const cable = new CableFleet(CableSession, cableHost, env.HARNESS_LOGS_DIR, DialLog,- { serials: process.env.HARNESS_DIAL_SERIALS?.split(',').map(s => s.trim()).filter(Boolean) })+ { serials: process.env.HARNESS_DIAL_SERIALS?.split(',').map(s => s.trim()).filter(Boolean),+ verdicts: new DialVerdicts(join(env.ADAPTER_DATA_DIR, 'dial-ports.json')) })cableRef = cableconst deviceStore = createDeviceStore({ dataDir: env.ADAPTER_DATA_DIR, machineId: backend.machineId,